From 318d2e578f3a2ff84dd9ea17ae0fc762864f0a6c Mon Sep 17 00:00:00 2001 From: rory Date: Tue, 3 Feb 2026 14:35:43 +0200 Subject: [PATCH] add local backups --- libs/html/_FromProd/401.pm | 99 + libs/html/_FromProd/_blank.pm | 42 + libs/html/_FromProd/_blank_3.pm | 32 + libs/html/_FromProd/_blank_4.pm | 88 + libs/html/_FromProd/_return.pm | 26 + libs/html/_FromProd/archive.pm | 95 + libs/html/_FromProd/calendar.pm | 37 + libs/html/_FromProd/fixedsystems.pm | 23 + libs/html/_FromProd/footer.pm | 103 + libs/html/_FromProd/header.pm | 618 ++ libs/html/_FromProd/index.pm | 65 + libs/html/_FromProd/login.pm | 18 +- libs/html/_FromProd/redirect.pm | 23 + libs/html/_FromProd/redirectcalibrator.pm | 23 + libs/html/_FromProd/redirectfixed.pm | 23 + libs/html/_FromProd/redirectlogistics.pm | 23 + libs/html/_FromProd/tickets.pm | 23 + libs/html/_FromProd/v1.0/401.pm | 99 + libs/html/_FromProd/v1.0/_blank.pm | 42 + libs/html/_FromProd/v1.0/_blank_3.pm | 32 + libs/html/_FromProd/v1.0/_blank_4.pm | 88 + libs/html/_FromProd/v1.0/_return.pm | 26 + libs/html/_FromProd/v1.0/archive.pm | 95 + libs/html/_FromProd/v1.0/calendar.pm | 37 + libs/html/_FromProd/v1.0/fixedsystems.pm | 23 + libs/html/_FromProd/v1.0/footer.pm | 103 + libs/html/_FromProd/v1.0/header.pm | 618 ++ libs/html/_FromProd/v1.0/index.pm | 65 + libs/html/_FromProd/v1.0/login.pm | 84 + libs/html/_FromProd/v1.0/redirect.pm | 23 + .../html/_FromProd/v1.0/redirectcalibrator.pm | 23 + libs/html/_FromProd/v1.0/redirectfixed.pm | 23 + libs/html/_FromProd/v1.0/redirectlogistics.pm | 23 + libs/html/_FromProd/v1.0/tickets.pm | 23 + libs/html/header.pm | 32 +- libs/html/redirectallfixtures.pm | 23 + libs/html/redirectanalytics.pm | 23 + .../_FromProd/analytics_event_booking_tabs.pm | 2029 ++++++ .../analytics_event_booking_tabs_test.pm | 0 libs/modules/_FromProd/calibration.pm | 797 +++ libs/modules/_FromProd/calibrator_payments.pm | 688 ++ libs/modules/_FromProd/cfg.pm | 159 + libs/modules/_FromProd/cfg_paths.pm | 17 +- libs/modules/_FromProd/common.pm | 1912 ++++++ libs/modules/_FromProd/common_min.pm | 3123 +++++++++ libs/modules/{ => _FromProd}/common_test.pm | 0 libs/modules/_FromProd/csv.pm | 54 + libs/modules/_FromProd/db.pm | 14 + libs/modules/_FromProd/db_min.pm | 269 + libs/modules/_FromProd/dcb.pm | 525 ++ libs/modules/_FromProd/dialog.pm | 34 + libs/modules/_FromProd/event_email.pm | 146 + libs/modules/_FromProd/event_tabs.pm | 5118 +++++++++++++++ .../event_tabs_test_demo_temp.pm | 0 libs/modules/_FromProd/fixedsystem.pm | 430 ++ libs/modules/_FromProd/getmail.pm | 287 + libs/modules/_FromProd/logistics.pm | 710 +++ libs/modules/_FromProd/mailsend.pm | 89 + .../_FromProd/match_event_production_time.pm | 603 ++ libs/modules/_FromProd/pdf.pm | 946 +++ libs/modules/_FromProd/production_time.pm | 603 ++ libs/modules/_FromProd/report.pm | 501 ++ libs/modules/_FromProd/schedule.pm | 1883 ++++++ libs/modules/_FromProd/schedule_test.pm | 1892 ++++++ libs/modules/_FromProd/session.pm | 51 + libs/modules/_FromProd/tabs.pm | 1971 ++++++ libs/modules/{ => _FromProd}/tabs_test.pm | 0 libs/modules/_FromProd/today.pm | 42 + libs/modules/_FromProd/uploader.pm | 30 + libs/modules/_FromProd/users.pm | 426 ++ .../v1.0/analytics_event_booking_tabs.pm | 2029 ++++++ .../v1.0/analytics_event_booking_tabs_test.pm | 2082 ++++++ libs/modules/_FromProd/v1.0/calibration.pm | 797 +++ .../_FromProd/v1.0/calibrator_payments.pm | 688 ++ libs/modules/_FromProd/v1.0/cfg.pm | 159 + libs/modules/_FromProd/v1.0/cfg_paths.pm | 246 + libs/modules/_FromProd/v1.0/common.pm | 1912 ++++++ libs/modules/_FromProd/v1.0/common_min.pm | 3123 +++++++++ libs/modules/_FromProd/v1.0/common_test.pm | 1428 +++++ libs/modules/_FromProd/v1.0/csv.pm | 54 + libs/modules/_FromProd/v1.0/db.pm | 98 + libs/modules/_FromProd/v1.0/db_min.pm | 269 + libs/modules/_FromProd/v1.0/dcb.pm | 525 ++ libs/modules/_FromProd/v1.0/dialog.pm | 34 + libs/modules/_FromProd/v1.0/event_email.pm | 146 + libs/modules/_FromProd/v1.0/event_tabs.pm | 5118 +++++++++++++++ .../v1.0/event_tabs_test_demo_temp.pm | 4978 +++++++++++++++ libs/modules/_FromProd/v1.0/fixedsystem.pm | 430 ++ libs/modules/_FromProd/v1.0/getmail.pm | 287 + libs/modules/_FromProd/v1.0/logistics.pm | 710 +++ libs/modules/_FromProd/v1.0/mailsend.pm | 89 + .../v1.0/match_event_production_time.pm | 603 ++ libs/modules/_FromProd/v1.0/pdf.pm | 946 +++ .../modules/_FromProd/v1.0/production_time.pm | 603 ++ libs/modules/_FromProd/v1.0/report.pm | 501 ++ libs/modules/_FromProd/v1.0/schedule.pm | 1883 ++++++ libs/modules/_FromProd/v1.0/schedule_test.pm | 1892 ++++++ libs/modules/_FromProd/v1.0/session.pm | 51 + libs/modules/_FromProd/v1.0/tabs.pm | 1971 ++++++ libs/modules/_FromProd/v1.0/tabs_test.pm | 2266 +++++++ libs/modules/_FromProd/v1.0/today.pm | 42 + libs/modules/_FromProd/v1.0/uploader.pm | 30 + libs/modules/_FromProd/v1.0/users.pm | 426 ++ libs/modules/_FromProd/v1.0/xlscreator.pm | 619 ++ libs/modules/_FromProd/v1.0/xlsxcreator.pm | 997 +++ libs/modules/_FromProd/xlscreator.pm | 619 ++ libs/modules/_FromProd/xlsxcreator.pm | 997 +++ libs/modules/analytics_event_booking_tabs.pm | 1089 +++- libs/modules/cfg.pm | 35 +- libs/modules/cfg_paths.pm | 25 +- libs/modules/common.pm | 8 +- libs/modules/common_min.pm | 11 +- libs/modules/db.pm | 11 +- libs/modules/schedule.pm | 280 +- libs/modules/session.pm | 56 +- libs/modules/tabs.pm | 2151 ++++--- scripts/_FromProd/XXX-monitoring_report.pl | 746 +++ scripts/_FromProd/XXX-troubleshoot_report.pl | 628 ++ .../v1.0/admin/oneoff/build_poc_table.pl | 328 + .../admin/oneoff/change_event_cost_items.pl | 92 + .../v1.0/admin/oneoff/cities_fix_db.pl | 57 + .../v1.0/admin/oneoff/compare_sss_aisa_poc.pl | 68 + .../admin/oneoff/compare_sss_aisa_synking.pl | 83 + .../oneoff/correct_event_quotes_min_table.pl | 430 ++ .../admin/oneoff/correct_linked_vpu_id.pl | 99 + .../admin/oneoff/dcb_create_waybill_test.pl | 199 + .../admin/oneoff/dcb_postalcode_lookup.pl | 195 + .../v1.0/admin/oneoff/dcb_soap_test.pl | 194 + .../v1.0/admin/oneoff/dcb_waybill_test.pl | 308 + .../v1.0/admin/oneoff/event_quotes_fix_db.pl | 245 + .../link_event_cost_items_to_event_systems.pl | 133 + .../v1.0/admin/oneoff/match_team_to_region.pl | 337 + .../v1.0/admin/oneoff/pixellot_api.pl | 165 + .../_FromProd/v1.0/admin/oneoff/sendmail.pl | 536 ++ .../_FromProd/v1.0/admin/oneoff/sendmailv2.pl | 478 ++ .../_FromProd/v1.0/admin/oneoff/sendmailv3.pl | 146 + .../_FromProd/v1.0/admin/oneoff/sendmailv4.pl | 215 + .../admin/oneoff/short_operator_dates_paid.pl | 66 + .../oneoff/transfer_changes_to_database.pl | 103 + .../oneoff/update_user_password_from_excel.pl | 102 + .../v1.0/allocate_credits.pl} | 0 scripts/_FromProd/v1.0/analytics_clients.pl | 124 + .../v1.0/analytics_event_bookings.pl | 1839 ++++++ .../_FromProd/v1.0/analytics_event_credits.pl | 1845 ++++++ .../v1.0}/analytics_eventbookings_test.pl | 0 scripts/_FromProd/v1.0/archive.pl | 540 ++ scripts/{ => _FromProd/v1.0}/audit_trial.pl | 0 .../v1.0/bank_transactions_report.pl | 406 ++ scripts/_FromProd/v1.0/calendar.pl | 73 + scripts/_FromProd/v1.0/calendar_test.pl | 73 + scripts/_FromProd/v1.0/calibration_report.pl | 722 +++ .../v1.0/calibration_status_report.pl | 1215 ++++ scripts/_FromProd/v1.0/calibrator_payments.pl | 566 ++ scripts/_FromProd/v1.0/camera_systems.pl | 204 + scripts/_FromProd/v1.0/cameras.pl | 1117 ++++ scripts/_FromProd/v1.0/cameras_report.pl | 300 + scripts/_FromProd/v1.0/casuals.pl | 209 + scripts/_FromProd/v1.0/cities.pl | 375 ++ scripts/_FromProd/v1.0/coding_providers.pl | 124 + .../v1.0/costings_detailed_report.pl | 456 ++ .../_FromProd/v1.0/costings_summary_report.pl | 342 + scripts/_FromProd/v1.0/credits_bought.pl | 381 ++ .../v1.0/cron/auto_get_next_day_events.pl | 171 + .../cron/auto_get_next_day_events_test.pl | 155 + ..._next_day_events_with_fixed_system_test.pl | 148 + scripts/_FromProd/v1.0/cron/auto_getmail.pl | 42 + .../_FromProd/v1.0/cron/email_sql_backup.pl | 138 + scripts/_FromProd/v1.0/cron/feed.dat | 3 + .../_FromProd/v1.0/cron/get_exchange_rates.pl | 135 + .../v1.0/cron/load_leave_settings.pl | 221 + scripts/_FromProd/v1.0/cron/mysql_backup.pl | 110 + .../cron/remove_expired_sessions_mysql.pl | 102 + .../v1.0/cron/sss_aisa_upload_check.pl | 93 + scripts/_FromProd/v1.0/customers.pl | 979 +++ .../v1.0/db/admin/admin_db_check_manifests.pl | 55 + .../v1.0/db/admin/admin_db_clients_table_1.pl | 62 + .../v1.0/db/admin/admin_db_shipper_details.pl | 89 + .../v1.0/db/admin/amend_db_clients_with_id.pl | 180 + .../db/admin/amend_db_clients_with_missing.pl | 193 + .../db/admin/amend_db_towns_airportcode.pl | 68 + .../db/admin/amend_db_waybills_add_address.pl | 133 + .../db/admin/amend_db_waybills_fix_address.pl | 98 + .../db/admin/amend_db_waybills_remove_f.pl | 135 + .../admin/amend_db_waybills_update_invno.pl | 96 + .../v1.0/db/admin/create_db_loc_table.pl | 73 + .../db/admin/create_db_other_service_table.pl | 76 + scripts/_FromProd/v1.0/delivered_report.pl | 276 + scripts/_FromProd/v1.0/demos.pl | 4402 +++++++++++++ .../v1.0/dialog/add_analytics_client.pl | 157 + scripts/_FromProd/v1.0/dialog/add_city.pl | 200 + .../_FromProd/v1.0/dialog/add_city_test.pl | 196 + scripts/_FromProd/v1.0/dialog/add_club.pl | 190 + scripts/_FromProd/v1.0/dialog/add_customer.pl | 168 + .../_FromProd/v1.0/dialog/add_event_poc.pl | 194 + .../v1.0/dialog/add_event_poc_or_recipient.pl | 210 + .../v1.0/dialog/add_existing_team.pl | 260 + .../_FromProd/v1.0/dialog/add_ht_colour.pl | 152 + .../v1.0/dialog/add_logistics_item.pl | 157 + scripts/_FromProd/v1.0/dialog/add_operator.pl | 157 + scripts/_FromProd/v1.0/dialog/add_poc.pl | 406 ++ .../_FromProd/v1.0/dialog/add_quote_type.pl | 139 + scripts/_FromProd/v1.0/dialog/add_region.pl | 196 + scripts/_FromProd/v1.0/dialog/add_school.pl | 190 + .../_FromProd/v1.0/dialog/add_sport_type.pl | 160 + scripts/_FromProd/v1.0/dialog/add_team.pl | 254 + scripts/_FromProd/v1.0/dialog/add_tenant.pl | 138 + .../v1.0/dialog/add_venue_address.pl | 182 + .../calibration_status_report_uploads.pl | 474 ++ .../_FromProd/v1.0/dialog/dcb_trackntrace.pl | 362 ++ scripts/_FromProd/v1.0/dialog/email.pl | 448 ++ scripts/_FromProd/v1.0/dialog/event_email.pl | 445 ++ scripts/_FromProd/v1.0/dialog/events.pl | 1870 ++++++ .../v1.0/dialog/get_bank_transactions.pl | 298 + scripts/_FromProd/v1.0/dialog/getmail.pl | 92 + scripts/_FromProd/v1.0/dialog/import.pl | 576 ++ .../v1.0/dialog/import_analytics_fixtures.pl | 676 ++ .../v1.0/dialog/import_bank_trans.pl | 492 ++ .../v1.0/dialog/import_bank_trans_cat.pl | 479 ++ .../v1.0/dialog/import_logistics_costs.pl | 483 ++ .../_FromProd/v1.0/dialog/import_unmatched.pl | 532 ++ .../v1.0/dialog/manually_match_csv_row.pl | 316 + scripts/_FromProd/v1.0/dialog/read_ticket.pl | 377 ++ scripts/_FromProd/v1.0/documents.pl | 624 ++ scripts/_FromProd/v1.0/event_cost_items.pl | 847 +++ .../_FromProd/v1.0/event_invoicing_report.pl | 1609 +++++ scripts/_FromProd/v1.0/event_quotes.pl | 5636 +++++++++++++++++ scripts/_FromProd/v1.0/event_quotes_report.pl | 547 ++ .../_FromProd/v1.0/event_summary_report.pl | 382 ++ scripts/_FromProd/v1.0/event_systems.pl | 351 + scripts/_FromProd/v1.0/event_types.pl | 201 + .../_FromProd/v1.0/events_detailed_report.pl | 417 ++ .../_FromProd/v1.0/events_pixellot_report.pl | 394 ++ .../_FromProd/v1.0/events_summary_report.pl | 399 ++ .../_FromProd/v1.0/fixed_systems_report.pl | 503 ++ scripts/_FromProd/v1.0/fixtures_report.pl | 612 ++ .../v1.0/get/add_event_system_hours.pl | 97 + .../v1.0/get/get_cities_from_country.pl | 83 + .../v1.0/get/get_cities_from_region.pl | 87 + .../v1.0/get/get_correct_camera_nr.pl | 131 + .../get/get_country_and_region_from_city.pl | 73 + .../v1.0/get/get_country_from_region.pl | 58 + .../v1.0/get/get_dates_from_event_quote.pl | 70 + .../_FromProd/v1.0/get/get_db_cal_events.pl | 741 +++ .../v1.0/get/get_db_cal_events_test.pl | 623 ++ .../v1.0/get/get_db_cal_events_test2.pl | 725 +++ scripts/_FromProd/v1.0/get/get_db_cameras.pl | 59 + .../v1.0/get/get_db_client_details.pl | 48 + .../v1.0/get/get_db_delete_client.pl | 83 + .../v1.0/get/get_db_delete_temp_support.pl | 60 + .../_FromProd/v1.0/get/get_db_delete_town.pl | 83 + .../v1.0/get/get_db_latest_cam_nr.pl | 65 + .../v1.0/get/get_db_latest_cam_nr_test.pl | 70 + .../_FromProd/v1.0/get/get_db_linked_vpu.pl | 116 + .../_FromProd/v1.0/get/get_delete_attach.pl | 100 + .../v1.0/get/get_delete_event_quote.pl | 62 + .../v1.0/get/get_event_cost_item_rates.pl | 71 + .../v1.0/get/get_event_quote_conflicts.pl | 166 + .../get/get_event_quote_conflicts_test.pl | 344 + .../_FromProd/v1.0/get/get_poc_contact_nr.pl | 67 + .../get/get_poc_or_recipient_contact_nr.pl | 41 + .../get/get_recipient_from_event_quote.pl | 60 + .../get/get_region_country_from_client.pl | 55 + .../v1.0/get/get_region_from_city.pl | 61 + .../v1.0/get/get_regions_from_country.pl | 70 + scripts/_FromProd/v1.0/get/get_roe.pl | 59 + scripts/_FromProd/v1.0/get/get_roe_test.pl | 61 + .../v1.0/get/get_sss_teams_from_client.pl | 62 + .../v1.0/get/get_sss_teams_from_region.pl | 81 + .../_FromProd/v1.0/get/get_typeahead_json.pl | 87 + .../v1.0/get/get_venues_from_region.pl | 86 + scripts/_FromProd/v1.0/index.pl | 68 + .../_FromProd/v1.0/installation_partners.pl | 124 + .../_FromProd/v1.0/integration_partners.pl | 124 + scripts/_FromProd/v1.0/leave.pl | 253 + scripts/_FromProd/v1.0/leave_report.pl | 596 ++ scripts/_FromProd/v1.0/leave_settings.pl | 219 + scripts/_FromProd/v1.0/live_reacon.pl | 380 ++ scripts/_FromProd/v1.0/login.pl | 96 + .../_FromProd/v1.0/logistics_costs_report.pl | 530 ++ scripts/_FromProd/v1.0/logistics_items.pl | 201 + scripts/_FromProd/v1.0/logistics_locations.pl | 200 + scripts/_FromProd/v1.0/logistics_payments.pl | 910 +++ scripts/_FromProd/v1.0/logistics_report.pl | 2893 +++++++++ .../v1.0/logistics_shipment_costs.pl | 295 + scripts/_FromProd/v1.0/logistics_suppliers.pl | 207 + scripts/_FromProd/v1.0/logout.pl | 43 + scripts/_FromProd/v1.0/management_report.pl | 590 ++ .../_FromProd/v1.0/match_credits_report.pl | 356 ++ .../v1.0/match_credits_report_test.pl | 356 ++ .../v1.0/mobile_site_surveys_report.pl | 702 ++ .../v1.0/mobile_system_tracking_report.pl | 647 ++ .../v1.0}/mobilesystemtracking_report_test.pl | 0 .../_FromProd/v1.0/monitor_payments_report.pl | 191 + .../{ => _FromProd/v1.0}/monitoring_report.pl | 0 .../v1.0}/monitoring_report_test.pl | 189 +- scripts/_FromProd/v1.0/operator_payments.pl | 736 +++ .../_FromProd/v1.0/operator_payments_test.pl | 810 +++ scripts/_FromProd/v1.0/operators.pl | 122 + .../v1.0/operators_booking_summary_report.pl | 405 ++ scripts/_FromProd/v1.0/operators_report.pl | 1056 +++ .../v1.0/operators_summary_report.pl | 317 + .../_FromProd/v1.0/pdf/delivery_note_pdf.pl | 478 ++ .../_FromProd/v1.0/pdf/event_details_pdf.pl | 1435 +++++ .../v1.0/pdf/event_details_pdf_orig.pl | 769 +++ scripts/_FromProd/v1.0/pdf/event_quote_pdf.pl | 1032 +++ .../v1.0/pdf/event_quote_pdf_test.pl | 1016 +++ scripts/_FromProd/v1.0/pdf/inv_pdf.pl | 356 ++ scripts/_FromProd/v1.0/pdf/label_pdf.pl | 220 + scripts/_FromProd/v1.0/pdf/mail_attach.pl | 72 + .../v1.0/pdf/operators_invoice_pdf.pl | 732 +++ scripts/_FromProd/v1.0/pdf/quote_pdf.pl | 1289 ++++ scripts/_FromProd/v1.0/pdf/vat_recon_pdf.pl | 121 + scripts/_FromProd/v1.0/pdf/warranty_pdf.pl | 599 ++ scripts/_FromProd/v1.0/pdf/warranty_report.pl | 290 + scripts/_FromProd/v1.0/pocs.pl | 316 + scripts/_FromProd/v1.0/price_list.pl | 606 ++ scripts/_FromProd/v1.0/quote_defaults.pl | 343 + scripts/_FromProd/v1.0/quote_notes.pl | 275 + scripts/_FromProd/v1.0/quotes.pl | 2578 ++++++++ scripts/_FromProd/v1.0/quotes_test.pl | 2787 ++++++++ scripts/_FromProd/v1.0/recipients.pl | 316 + scripts/_FromProd/v1.0/regions.pl | 299 + scripts/_FromProd/v1.0/rma.pl | 750 +++ scripts/_FromProd/v1.0/rma_test.pl | 654 ++ scripts/_FromProd/v1.0/school_managers.pl | 124 + .../_FromProd/v1.0/set_up_groups_report.pl | 653 ++ scripts/_FromProd/v1.0/sport_types.pl | 211 + scripts/_FromProd/v1.0/stock_report.pl | 307 + scripts/_FromProd/v1.0/storage.pl | 417 ++ scripts/_FromProd/v1.0/supplier_contacts.pl | 325 + scripts/_FromProd/v1.0/teams.pl | 391 ++ scripts/_FromProd/v1.0/teams_test.pl | 667 ++ .../v1.0/temp_calibrator_payments_report.pl | 211 + .../_FromProd/v1.0/temp_calibrator_report.pl | 498 ++ scripts/_FromProd/v1.0/tickets.pl | 784 +++ scripts/_FromProd/v1.0/towns.pl | 255 + .../troubleshoot_monitor_payments_report.pl | 189 + .../v1.0/troubleshoot_monitoring_report.pl | 624 ++ scripts/_FromProd/v1.0/users.pl | 115 + scripts/_FromProd/v1.0/venue.pl | 429 ++ scripts/_FromProd/v1.0/warranty_report.pl | 293 + scripts/_FromProd/v1.0/weekend.pl | 252 + scripts/_FromProd/v1.0/weekend_report.pl | 210 + scripts/admin/oneoff/find_saved_fixtures.pl | 59 + scripts/admin/oneoff/sendmailv5.pl | 78 + scripts/aisa_event_feedback.pl | 629 ++ scripts/all_fixtures_report.pl | 1284 ++++ scripts/allocate_credits.pl | 494 +- scripts/analytics_event_bookings.pl | 341 +- scripts/analytics_event_credits.pl | 827 +-- scripts/audit_trail.pl | 618 ++ scripts/calendar_test.pl | 2 +- scripts/cameras.pl | 6 +- scripts/credits_bought.pl | 496 +- scripts/cron/auto_get_next_day_events.pl | 6 +- scripts/cron/email_sql_backup.pl | 2 +- scripts/cron/get_exchange_rates.pl | 135 +- scripts/cron/mysql_backup.pl | 162 +- scripts/cron/remove_expired_sessions_mysql.pl | 2 +- scripts/cron/sss_aisa_upload_check.pl | 12 +- scripts/demos.pl | 24 +- scripts/dialog/add_fixtures_analyst.pl | 227 + .../dialog/add_fixtures_charge_free_reason.pl | 207 + .../add_fixtures_charge_free_table_reason.pl | 224 + scripts/dialog/add_team_test.pl | 266 + scripts/dialog/events.pl | 591 +- scripts/dialog/import_analytics_fixtures.pl | 281 +- scripts/event_quotes_test.pl | 4975 +++++++++++++++ scripts/eventinvoicing_report_test.pl | 1408 ++++ scripts/fixed_systems_report.pl | 1 - scripts/fixedsystems_report_test.pl | 607 ++ scripts/fixtures_report.pl | 105 +- .../get/get_analyst_from_coding_provider.pl | 56 + scripts/get/get_analytics_charge_client.pl | 68 + scripts/get/get_db_cal_events.pl | 64 +- scripts/get/get_db_cal_events_test.pl | 3 +- scripts/get/get_db_cal_events_test2.pl | 3 +- scripts/get/get_delete_event_quote.pl | 3 + scripts/get/get_sss_teams_from_client.pl | 12 +- scripts/get/get_sss_teams_from_typeahead.pl | 70 + scripts/get/get_venues_from_region_test.pl | 72 + scripts/index.pl | 8 +- scripts/live_recon.pl | 399 ++ scripts/logistics_payments.pl | 79 +- scripts/logistics_report.pl | 2 +- scripts/match_credits_report_test.pl | 3 +- scripts/operators_report.pl | 2 +- scripts/pdf/event_details_pdf.pl | 681 +- scripts/pod_report.pl | 251 + scripts/price_list.pl | 2 +- scripts/quotes.pl | 1713 ++--- scripts/quotes_test.pl | 1811 +++--- scripts/sss_event_feedback.pl | 745 +++ scripts/troubleshoot_monitoring_report.pl | 184 +- .../libs/modules/_FromProd/common_shared.pm | 502 ++ .../libs/modules/_FromProd/fixed_systems.pm | 952 +++ .../modules/_FromProd/fixed_systems_test.pm | 919 +++ shared/libs/modules/common_shared.pm | 151 + 398 files changed, 181239 insertions(+), 5068 deletions(-) create mode 100644 libs/html/_FromProd/401.pm create mode 100644 libs/html/_FromProd/_blank.pm create mode 100644 libs/html/_FromProd/_blank_3.pm create mode 100644 libs/html/_FromProd/_blank_4.pm create mode 100644 libs/html/_FromProd/_return.pm create mode 100644 libs/html/_FromProd/archive.pm create mode 100644 libs/html/_FromProd/calendar.pm create mode 100644 libs/html/_FromProd/fixedsystems.pm create mode 100644 libs/html/_FromProd/footer.pm create mode 100644 libs/html/_FromProd/header.pm create mode 100644 libs/html/_FromProd/index.pm create mode 100644 libs/html/_FromProd/redirect.pm create mode 100644 libs/html/_FromProd/redirectcalibrator.pm create mode 100644 libs/html/_FromProd/redirectfixed.pm create mode 100644 libs/html/_FromProd/redirectlogistics.pm create mode 100644 libs/html/_FromProd/tickets.pm create mode 100644 libs/html/_FromProd/v1.0/401.pm create mode 100644 libs/html/_FromProd/v1.0/_blank.pm create mode 100644 libs/html/_FromProd/v1.0/_blank_3.pm create mode 100644 libs/html/_FromProd/v1.0/_blank_4.pm create mode 100644 libs/html/_FromProd/v1.0/_return.pm create mode 100644 libs/html/_FromProd/v1.0/archive.pm create mode 100644 libs/html/_FromProd/v1.0/calendar.pm create mode 100644 libs/html/_FromProd/v1.0/fixedsystems.pm create mode 100644 libs/html/_FromProd/v1.0/footer.pm create mode 100644 libs/html/_FromProd/v1.0/header.pm create mode 100644 libs/html/_FromProd/v1.0/index.pm create mode 100644 libs/html/_FromProd/v1.0/login.pm create mode 100644 libs/html/_FromProd/v1.0/redirect.pm create mode 100644 libs/html/_FromProd/v1.0/redirectcalibrator.pm create mode 100644 libs/html/_FromProd/v1.0/redirectfixed.pm create mode 100644 libs/html/_FromProd/v1.0/redirectlogistics.pm create mode 100644 libs/html/_FromProd/v1.0/tickets.pm create mode 100644 libs/html/redirectallfixtures.pm create mode 100644 libs/html/redirectanalytics.pm create mode 100644 libs/modules/_FromProd/analytics_event_booking_tabs.pm rename libs/modules/{ => _FromProd}/analytics_event_booking_tabs_test.pm (100%) create mode 100644 libs/modules/_FromProd/calibration.pm create mode 100644 libs/modules/_FromProd/calibrator_payments.pm create mode 100644 libs/modules/_FromProd/cfg.pm create mode 100644 libs/modules/_FromProd/common.pm create mode 100644 libs/modules/_FromProd/common_min.pm rename libs/modules/{ => _FromProd}/common_test.pm (100%) create mode 100644 libs/modules/_FromProd/csv.pm create mode 100644 libs/modules/_FromProd/db_min.pm create mode 100644 libs/modules/_FromProd/dcb.pm create mode 100644 libs/modules/_FromProd/dialog.pm create mode 100644 libs/modules/_FromProd/event_email.pm create mode 100644 libs/modules/_FromProd/event_tabs.pm rename libs/modules/{ => _FromProd}/event_tabs_test_demo_temp.pm (100%) create mode 100644 libs/modules/_FromProd/fixedsystem.pm create mode 100644 libs/modules/_FromProd/getmail.pm create mode 100644 libs/modules/_FromProd/logistics.pm create mode 100644 libs/modules/_FromProd/mailsend.pm create mode 100644 libs/modules/_FromProd/match_event_production_time.pm create mode 100644 libs/modules/_FromProd/pdf.pm create mode 100644 libs/modules/_FromProd/production_time.pm create mode 100644 libs/modules/_FromProd/report.pm create mode 100644 libs/modules/_FromProd/schedule.pm create mode 100644 libs/modules/_FromProd/schedule_test.pm create mode 100644 libs/modules/_FromProd/session.pm create mode 100644 libs/modules/_FromProd/tabs.pm rename libs/modules/{ => _FromProd}/tabs_test.pm (100%) create mode 100644 libs/modules/_FromProd/today.pm create mode 100644 libs/modules/_FromProd/uploader.pm create mode 100644 libs/modules/_FromProd/users.pm create mode 100644 libs/modules/_FromProd/v1.0/analytics_event_booking_tabs.pm create mode 100644 libs/modules/_FromProd/v1.0/analytics_event_booking_tabs_test.pm create mode 100644 libs/modules/_FromProd/v1.0/calibration.pm create mode 100644 libs/modules/_FromProd/v1.0/calibrator_payments.pm create mode 100644 libs/modules/_FromProd/v1.0/cfg.pm create mode 100644 libs/modules/_FromProd/v1.0/cfg_paths.pm create mode 100644 libs/modules/_FromProd/v1.0/common.pm create mode 100644 libs/modules/_FromProd/v1.0/common_min.pm create mode 100644 libs/modules/_FromProd/v1.0/common_test.pm create mode 100644 libs/modules/_FromProd/v1.0/csv.pm create mode 100644 libs/modules/_FromProd/v1.0/db.pm create mode 100644 libs/modules/_FromProd/v1.0/db_min.pm create mode 100644 libs/modules/_FromProd/v1.0/dcb.pm create mode 100644 libs/modules/_FromProd/v1.0/dialog.pm create mode 100644 libs/modules/_FromProd/v1.0/event_email.pm create mode 100644 libs/modules/_FromProd/v1.0/event_tabs.pm create mode 100644 libs/modules/_FromProd/v1.0/event_tabs_test_demo_temp.pm create mode 100644 libs/modules/_FromProd/v1.0/fixedsystem.pm create mode 100644 libs/modules/_FromProd/v1.0/getmail.pm create mode 100644 libs/modules/_FromProd/v1.0/logistics.pm create mode 100644 libs/modules/_FromProd/v1.0/mailsend.pm create mode 100644 libs/modules/_FromProd/v1.0/match_event_production_time.pm create mode 100644 libs/modules/_FromProd/v1.0/pdf.pm create mode 100644 libs/modules/_FromProd/v1.0/production_time.pm create mode 100644 libs/modules/_FromProd/v1.0/report.pm create mode 100644 libs/modules/_FromProd/v1.0/schedule.pm create mode 100644 libs/modules/_FromProd/v1.0/schedule_test.pm create mode 100644 libs/modules/_FromProd/v1.0/session.pm create mode 100644 libs/modules/_FromProd/v1.0/tabs.pm create mode 100644 libs/modules/_FromProd/v1.0/tabs_test.pm create mode 100644 libs/modules/_FromProd/v1.0/today.pm create mode 100644 libs/modules/_FromProd/v1.0/uploader.pm create mode 100644 libs/modules/_FromProd/v1.0/users.pm create mode 100644 libs/modules/_FromProd/v1.0/xlscreator.pm create mode 100644 libs/modules/_FromProd/v1.0/xlsxcreator.pm create mode 100644 libs/modules/_FromProd/xlscreator.pm create mode 100644 libs/modules/_FromProd/xlsxcreator.pm create mode 100644 scripts/_FromProd/XXX-monitoring_report.pl create mode 100644 scripts/_FromProd/XXX-troubleshoot_report.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/build_poc_table.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/change_event_cost_items.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/cities_fix_db.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/compare_sss_aisa_poc.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/compare_sss_aisa_synking.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/correct_event_quotes_min_table.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/correct_linked_vpu_id.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/dcb_create_waybill_test.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/dcb_postalcode_lookup.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/dcb_soap_test.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/dcb_waybill_test.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/event_quotes_fix_db.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/link_event_cost_items_to_event_systems.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/match_team_to_region.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/pixellot_api.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/sendmail.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/sendmailv2.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/sendmailv3.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/sendmailv4.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/short_operator_dates_paid.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/transfer_changes_to_database.pl create mode 100644 scripts/_FromProd/v1.0/admin/oneoff/update_user_password_from_excel.pl rename scripts/{live_reacon.pl => _FromProd/v1.0/allocate_credits.pl} (100%) create mode 100644 scripts/_FromProd/v1.0/analytics_clients.pl create mode 100644 scripts/_FromProd/v1.0/analytics_event_bookings.pl create mode 100644 scripts/_FromProd/v1.0/analytics_event_credits.pl rename scripts/{ => _FromProd/v1.0}/analytics_eventbookings_test.pl (100%) create mode 100644 scripts/_FromProd/v1.0/archive.pl rename scripts/{ => _FromProd/v1.0}/audit_trial.pl (100%) create mode 100644 scripts/_FromProd/v1.0/bank_transactions_report.pl create mode 100644 scripts/_FromProd/v1.0/calendar.pl create mode 100644 scripts/_FromProd/v1.0/calendar_test.pl create mode 100644 scripts/_FromProd/v1.0/calibration_report.pl create mode 100644 scripts/_FromProd/v1.0/calibration_status_report.pl create mode 100644 scripts/_FromProd/v1.0/calibrator_payments.pl create mode 100644 scripts/_FromProd/v1.0/camera_systems.pl create mode 100644 scripts/_FromProd/v1.0/cameras.pl create mode 100644 scripts/_FromProd/v1.0/cameras_report.pl create mode 100644 scripts/_FromProd/v1.0/casuals.pl create mode 100644 scripts/_FromProd/v1.0/cities.pl create mode 100644 scripts/_FromProd/v1.0/coding_providers.pl create mode 100644 scripts/_FromProd/v1.0/costings_detailed_report.pl create mode 100644 scripts/_FromProd/v1.0/costings_summary_report.pl create mode 100644 scripts/_FromProd/v1.0/credits_bought.pl create mode 100644 scripts/_FromProd/v1.0/cron/auto_get_next_day_events.pl create mode 100644 scripts/_FromProd/v1.0/cron/auto_get_next_day_events_test.pl create mode 100644 scripts/_FromProd/v1.0/cron/auto_get_next_day_events_with_fixed_system_test.pl create mode 100644 scripts/_FromProd/v1.0/cron/auto_getmail.pl create mode 100644 scripts/_FromProd/v1.0/cron/email_sql_backup.pl create mode 100644 scripts/_FromProd/v1.0/cron/feed.dat create mode 100644 scripts/_FromProd/v1.0/cron/get_exchange_rates.pl create mode 100644 scripts/_FromProd/v1.0/cron/load_leave_settings.pl create mode 100644 scripts/_FromProd/v1.0/cron/mysql_backup.pl create mode 100644 scripts/_FromProd/v1.0/cron/remove_expired_sessions_mysql.pl create mode 100644 scripts/_FromProd/v1.0/cron/sss_aisa_upload_check.pl create mode 100644 scripts/_FromProd/v1.0/customers.pl create mode 100644 scripts/_FromProd/v1.0/db/admin/admin_db_check_manifests.pl create mode 100644 scripts/_FromProd/v1.0/db/admin/admin_db_clients_table_1.pl create mode 100644 scripts/_FromProd/v1.0/db/admin/admin_db_shipper_details.pl create mode 100644 scripts/_FromProd/v1.0/db/admin/amend_db_clients_with_id.pl create mode 100644 scripts/_FromProd/v1.0/db/admin/amend_db_clients_with_missing.pl create mode 100644 scripts/_FromProd/v1.0/db/admin/amend_db_towns_airportcode.pl create mode 100644 scripts/_FromProd/v1.0/db/admin/amend_db_waybills_add_address.pl create mode 100644 scripts/_FromProd/v1.0/db/admin/amend_db_waybills_fix_address.pl create mode 100644 scripts/_FromProd/v1.0/db/admin/amend_db_waybills_remove_f.pl create mode 100644 scripts/_FromProd/v1.0/db/admin/amend_db_waybills_update_invno.pl create mode 100644 scripts/_FromProd/v1.0/db/admin/create_db_loc_table.pl create mode 100644 scripts/_FromProd/v1.0/db/admin/create_db_other_service_table.pl create mode 100644 scripts/_FromProd/v1.0/delivered_report.pl create mode 100644 scripts/_FromProd/v1.0/demos.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_analytics_client.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_city.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_city_test.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_club.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_customer.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_event_poc.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_event_poc_or_recipient.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_existing_team.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_ht_colour.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_logistics_item.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_operator.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_poc.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_quote_type.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_region.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_school.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_sport_type.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_team.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_tenant.pl create mode 100644 scripts/_FromProd/v1.0/dialog/add_venue_address.pl create mode 100644 scripts/_FromProd/v1.0/dialog/calibration_status_report_uploads.pl create mode 100644 scripts/_FromProd/v1.0/dialog/dcb_trackntrace.pl create mode 100644 scripts/_FromProd/v1.0/dialog/email.pl create mode 100644 scripts/_FromProd/v1.0/dialog/event_email.pl create mode 100644 scripts/_FromProd/v1.0/dialog/events.pl create mode 100644 scripts/_FromProd/v1.0/dialog/get_bank_transactions.pl create mode 100644 scripts/_FromProd/v1.0/dialog/getmail.pl create mode 100644 scripts/_FromProd/v1.0/dialog/import.pl create mode 100644 scripts/_FromProd/v1.0/dialog/import_analytics_fixtures.pl create mode 100644 scripts/_FromProd/v1.0/dialog/import_bank_trans.pl create mode 100644 scripts/_FromProd/v1.0/dialog/import_bank_trans_cat.pl create mode 100644 scripts/_FromProd/v1.0/dialog/import_logistics_costs.pl create mode 100644 scripts/_FromProd/v1.0/dialog/import_unmatched.pl create mode 100644 scripts/_FromProd/v1.0/dialog/manually_match_csv_row.pl create mode 100644 scripts/_FromProd/v1.0/dialog/read_ticket.pl create mode 100644 scripts/_FromProd/v1.0/documents.pl create mode 100644 scripts/_FromProd/v1.0/event_cost_items.pl create mode 100644 scripts/_FromProd/v1.0/event_invoicing_report.pl create mode 100644 scripts/_FromProd/v1.0/event_quotes.pl create mode 100644 scripts/_FromProd/v1.0/event_quotes_report.pl create mode 100644 scripts/_FromProd/v1.0/event_summary_report.pl create mode 100644 scripts/_FromProd/v1.0/event_systems.pl create mode 100644 scripts/_FromProd/v1.0/event_types.pl create mode 100644 scripts/_FromProd/v1.0/events_detailed_report.pl create mode 100644 scripts/_FromProd/v1.0/events_pixellot_report.pl create mode 100644 scripts/_FromProd/v1.0/events_summary_report.pl create mode 100644 scripts/_FromProd/v1.0/fixed_systems_report.pl create mode 100644 scripts/_FromProd/v1.0/fixtures_report.pl create mode 100644 scripts/_FromProd/v1.0/get/add_event_system_hours.pl create mode 100644 scripts/_FromProd/v1.0/get/get_cities_from_country.pl create mode 100644 scripts/_FromProd/v1.0/get/get_cities_from_region.pl create mode 100644 scripts/_FromProd/v1.0/get/get_correct_camera_nr.pl create mode 100644 scripts/_FromProd/v1.0/get/get_country_and_region_from_city.pl create mode 100644 scripts/_FromProd/v1.0/get/get_country_from_region.pl create mode 100644 scripts/_FromProd/v1.0/get/get_dates_from_event_quote.pl create mode 100644 scripts/_FromProd/v1.0/get/get_db_cal_events.pl create mode 100644 scripts/_FromProd/v1.0/get/get_db_cal_events_test.pl create mode 100644 scripts/_FromProd/v1.0/get/get_db_cal_events_test2.pl create mode 100644 scripts/_FromProd/v1.0/get/get_db_cameras.pl create mode 100644 scripts/_FromProd/v1.0/get/get_db_client_details.pl create mode 100644 scripts/_FromProd/v1.0/get/get_db_delete_client.pl create mode 100644 scripts/_FromProd/v1.0/get/get_db_delete_temp_support.pl create mode 100644 scripts/_FromProd/v1.0/get/get_db_delete_town.pl create mode 100644 scripts/_FromProd/v1.0/get/get_db_latest_cam_nr.pl create mode 100644 scripts/_FromProd/v1.0/get/get_db_latest_cam_nr_test.pl create mode 100644 scripts/_FromProd/v1.0/get/get_db_linked_vpu.pl create mode 100644 scripts/_FromProd/v1.0/get/get_delete_attach.pl create mode 100644 scripts/_FromProd/v1.0/get/get_delete_event_quote.pl create mode 100644 scripts/_FromProd/v1.0/get/get_event_cost_item_rates.pl create mode 100644 scripts/_FromProd/v1.0/get/get_event_quote_conflicts.pl create mode 100644 scripts/_FromProd/v1.0/get/get_event_quote_conflicts_test.pl create mode 100644 scripts/_FromProd/v1.0/get/get_poc_contact_nr.pl create mode 100644 scripts/_FromProd/v1.0/get/get_poc_or_recipient_contact_nr.pl create mode 100644 scripts/_FromProd/v1.0/get/get_recipient_from_event_quote.pl create mode 100644 scripts/_FromProd/v1.0/get/get_region_country_from_client.pl create mode 100644 scripts/_FromProd/v1.0/get/get_region_from_city.pl create mode 100644 scripts/_FromProd/v1.0/get/get_regions_from_country.pl create mode 100644 scripts/_FromProd/v1.0/get/get_roe.pl create mode 100644 scripts/_FromProd/v1.0/get/get_roe_test.pl create mode 100644 scripts/_FromProd/v1.0/get/get_sss_teams_from_client.pl create mode 100644 scripts/_FromProd/v1.0/get/get_sss_teams_from_region.pl create mode 100644 scripts/_FromProd/v1.0/get/get_typeahead_json.pl create mode 100644 scripts/_FromProd/v1.0/get/get_venues_from_region.pl create mode 100644 scripts/_FromProd/v1.0/index.pl create mode 100644 scripts/_FromProd/v1.0/installation_partners.pl create mode 100644 scripts/_FromProd/v1.0/integration_partners.pl create mode 100644 scripts/_FromProd/v1.0/leave.pl create mode 100644 scripts/_FromProd/v1.0/leave_report.pl create mode 100644 scripts/_FromProd/v1.0/leave_settings.pl create mode 100644 scripts/_FromProd/v1.0/live_reacon.pl create mode 100644 scripts/_FromProd/v1.0/login.pl create mode 100644 scripts/_FromProd/v1.0/logistics_costs_report.pl create mode 100644 scripts/_FromProd/v1.0/logistics_items.pl create mode 100644 scripts/_FromProd/v1.0/logistics_locations.pl create mode 100644 scripts/_FromProd/v1.0/logistics_payments.pl create mode 100644 scripts/_FromProd/v1.0/logistics_report.pl create mode 100644 scripts/_FromProd/v1.0/logistics_shipment_costs.pl create mode 100644 scripts/_FromProd/v1.0/logistics_suppliers.pl create mode 100644 scripts/_FromProd/v1.0/logout.pl create mode 100644 scripts/_FromProd/v1.0/management_report.pl create mode 100644 scripts/_FromProd/v1.0/match_credits_report.pl create mode 100644 scripts/_FromProd/v1.0/match_credits_report_test.pl create mode 100644 scripts/_FromProd/v1.0/mobile_site_surveys_report.pl create mode 100644 scripts/_FromProd/v1.0/mobile_system_tracking_report.pl rename scripts/{ => _FromProd/v1.0}/mobilesystemtracking_report_test.pl (100%) create mode 100644 scripts/_FromProd/v1.0/monitor_payments_report.pl rename scripts/{ => _FromProd/v1.0}/monitoring_report.pl (100%) rename scripts/{ => _FromProd/v1.0}/monitoring_report_test.pl (78%) create mode 100644 scripts/_FromProd/v1.0/operator_payments.pl create mode 100644 scripts/_FromProd/v1.0/operator_payments_test.pl create mode 100644 scripts/_FromProd/v1.0/operators.pl create mode 100644 scripts/_FromProd/v1.0/operators_booking_summary_report.pl create mode 100644 scripts/_FromProd/v1.0/operators_report.pl create mode 100644 scripts/_FromProd/v1.0/operators_summary_report.pl create mode 100644 scripts/_FromProd/v1.0/pdf/delivery_note_pdf.pl create mode 100644 scripts/_FromProd/v1.0/pdf/event_details_pdf.pl create mode 100644 scripts/_FromProd/v1.0/pdf/event_details_pdf_orig.pl create mode 100644 scripts/_FromProd/v1.0/pdf/event_quote_pdf.pl create mode 100644 scripts/_FromProd/v1.0/pdf/event_quote_pdf_test.pl create mode 100644 scripts/_FromProd/v1.0/pdf/inv_pdf.pl create mode 100644 scripts/_FromProd/v1.0/pdf/label_pdf.pl create mode 100644 scripts/_FromProd/v1.0/pdf/mail_attach.pl create mode 100644 scripts/_FromProd/v1.0/pdf/operators_invoice_pdf.pl create mode 100644 scripts/_FromProd/v1.0/pdf/quote_pdf.pl create mode 100644 scripts/_FromProd/v1.0/pdf/vat_recon_pdf.pl create mode 100644 scripts/_FromProd/v1.0/pdf/warranty_pdf.pl create mode 100644 scripts/_FromProd/v1.0/pdf/warranty_report.pl create mode 100644 scripts/_FromProd/v1.0/pocs.pl create mode 100644 scripts/_FromProd/v1.0/price_list.pl create mode 100644 scripts/_FromProd/v1.0/quote_defaults.pl create mode 100644 scripts/_FromProd/v1.0/quote_notes.pl create mode 100644 scripts/_FromProd/v1.0/quotes.pl create mode 100644 scripts/_FromProd/v1.0/quotes_test.pl create mode 100644 scripts/_FromProd/v1.0/recipients.pl create mode 100644 scripts/_FromProd/v1.0/regions.pl create mode 100644 scripts/_FromProd/v1.0/rma.pl create mode 100644 scripts/_FromProd/v1.0/rma_test.pl create mode 100644 scripts/_FromProd/v1.0/school_managers.pl create mode 100644 scripts/_FromProd/v1.0/set_up_groups_report.pl create mode 100644 scripts/_FromProd/v1.0/sport_types.pl create mode 100644 scripts/_FromProd/v1.0/stock_report.pl create mode 100644 scripts/_FromProd/v1.0/storage.pl create mode 100644 scripts/_FromProd/v1.0/supplier_contacts.pl create mode 100644 scripts/_FromProd/v1.0/teams.pl create mode 100644 scripts/_FromProd/v1.0/teams_test.pl create mode 100644 scripts/_FromProd/v1.0/temp_calibrator_payments_report.pl create mode 100644 scripts/_FromProd/v1.0/temp_calibrator_report.pl create mode 100644 scripts/_FromProd/v1.0/tickets.pl create mode 100644 scripts/_FromProd/v1.0/towns.pl create mode 100644 scripts/_FromProd/v1.0/troubleshoot_monitor_payments_report.pl create mode 100644 scripts/_FromProd/v1.0/troubleshoot_monitoring_report.pl create mode 100644 scripts/_FromProd/v1.0/users.pl create mode 100644 scripts/_FromProd/v1.0/venue.pl create mode 100644 scripts/_FromProd/v1.0/warranty_report.pl create mode 100644 scripts/_FromProd/v1.0/weekend.pl create mode 100644 scripts/_FromProd/v1.0/weekend_report.pl create mode 100644 scripts/admin/oneoff/find_saved_fixtures.pl create mode 100644 scripts/admin/oneoff/sendmailv5.pl create mode 100644 scripts/aisa_event_feedback.pl create mode 100644 scripts/all_fixtures_report.pl create mode 100644 scripts/audit_trail.pl create mode 100644 scripts/dialog/add_fixtures_analyst.pl create mode 100644 scripts/dialog/add_fixtures_charge_free_reason.pl create mode 100644 scripts/dialog/add_fixtures_charge_free_table_reason.pl create mode 100644 scripts/dialog/add_team_test.pl create mode 100644 scripts/event_quotes_test.pl create mode 100644 scripts/eventinvoicing_report_test.pl create mode 100644 scripts/fixedsystems_report_test.pl create mode 100644 scripts/get/get_analyst_from_coding_provider.pl create mode 100644 scripts/get/get_analytics_charge_client.pl create mode 100644 scripts/get/get_sss_teams_from_typeahead.pl create mode 100644 scripts/get/get_venues_from_region_test.pl create mode 100644 scripts/live_recon.pl create mode 100644 scripts/pod_report.pl create mode 100644 scripts/sss_event_feedback.pl create mode 100644 shared/libs/modules/_FromProd/common_shared.pm create mode 100644 shared/libs/modules/_FromProd/fixed_systems.pm create mode 100644 shared/libs/modules/_FromProd/fixed_systems_test.pm diff --git a/libs/html/_FromProd/401.pm b/libs/html/_FromProd/401.pm new file mode 100644 index 0000000..668dca7 --- /dev/null +++ b/libs/html/_FromProd/401.pm @@ -0,0 +1,99 @@ +print < + + + + + + + Error + + + +

+ 401 +

+ +

Unauthorised

+ +
+
+ You are not authorised to view this page +
+
+ Click here to go back to your Dashboard +
+ + +
+ + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/_blank.pm b/libs/html/_FromProd/_blank.pm new file mode 100644 index 0000000..7184485 --- /dev/null +++ b/libs/html/_FromProd/_blank.pm @@ -0,0 +1,42 @@ +require header ; + +print < + + $useropts{'breadcrumbs'} + + $alert + +
+
+
+
+

$page_title

+ $box_icon +
+
+ $print_box_content_rows +
+
+
+
+ $print_more_boxes + + + +ENDOFTEXT + +require footer ; + +print < + +$print_footer_forms + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/_blank_3.pm b/libs/html/_FromProd/_blank_3.pm new file mode 100644 index 0000000..e85e9ed --- /dev/null +++ b/libs/html/_FromProd/_blank_3.pm @@ -0,0 +1,32 @@ +require header ; + +print < + + $useropts{'breadcrumbs'} + + $alert + + $print_box_content_rows + + + + $print_more_boxes + + +ENDOFTEXT + +require footer ; + +print < + +$print_footer_forms + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/_blank_4.pm b/libs/html/_FromProd/_blank_4.pm new file mode 100644 index 0000000..f1d94f3 --- /dev/null +++ b/libs/html/_FromProd/_blank_4.pm @@ -0,0 +1,88 @@ +# require header ; +print < + + + + $useropts{title} + + + + + + $extra_css + + + + + + + + + + + + + + + + + + $typeahead_css + + + + + + + + + + + + + + + + + + + +ENDOFTEXT +# + +print < + + + $alert + + $print_box_content_rows + + + + $print_more_boxes + + +ENDOFTEXT + +require footer ; + +print < + +$print_footer_forms + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/_return.pm b/libs/html/_FromProd/_return.pm new file mode 100644 index 0000000..ec74b2b --- /dev/null +++ b/libs/html/_FromProd/_return.pm @@ -0,0 +1,26 @@ +unless ($goaction) { $goaction = 'list' ; } + +print < + + + + $useropts{title} + + + + + + +
+ + +
+ + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/archive.pm b/libs/html/_FromProd/archive.pm new file mode 100644 index 0000000..645736c --- /dev/null +++ b/libs/html/_FromProd/archive.pm @@ -0,0 +1,95 @@ +require header ; + +print < + + $useropts{'breadcrumbs'} + + $alert + + $print_usage + + $print_download + + $print_delete_uploads_form + + $print_buttons + + + + + +
+ +ENDOFTEXT + +require footer ; + +print < + + + + +
+ + +
+ +
+ + +
+ +
+ +
+ + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/calendar.pm b/libs/html/_FromProd/calendar.pm new file mode 100644 index 0000000..7ed135f --- /dev/null +++ b/libs/html/_FromProd/calendar.pm @@ -0,0 +1,37 @@ +require header ; + +print < + + $useropts{'breadcrumbs'} + +
+
+
+
+

Calendar

+ $box_icon +
+
+
+
+
+
+
+
+ + + + +
+ +ENDOFTEXT + +require footer ; + +print < + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/fixedsystems.pm b/libs/html/_FromProd/fixedsystems.pm new file mode 100644 index 0000000..78beb63 --- /dev/null +++ b/libs/html/_FromProd/fixedsystems.pm @@ -0,0 +1,23 @@ +print < + + + + $useropts{title} + + + + + + +
+ +
+ + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/footer.pm b/libs/html/_FromProd/footer.pm new file mode 100644 index 0000000..8f6a809 --- /dev/null +++ b/libs/html/_FromProd/footer.pm @@ -0,0 +1,103 @@ +print < + + +

Kre8IT Programming (Pty) Ltd
062 133 6754
info\@kre8it.co.za

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +$extra_js + + + +
+ + +
+ +
+ + +
+ +$extra_form_footer + +ENDOFTEXT +# + +# +# \ No newline at end of file diff --git a/libs/html/_FromProd/header.pm b/libs/html/_FromProd/header.pm new file mode 100644 index 0000000..0195b35 --- /dev/null +++ b/libs/html/_FromProd/header.pm @@ -0,0 +1,618 @@ + + my $manage_quote_defaults_menu = '' ; + my $manage_price_list_menu = '' ; + + my $rma_list_menu = ($usertype eq 'it' || $usertype eq 'senior_manager' || $usertype eq 'manager' || $usertype eq 'support' || $usertype eq 'casual_c') ? qq~
  • RMA List
  • ~ : '' ; + + my $manage_price_list_menu_top = '' ; + + my $manage_logistics_report_menu_top = qq~
  • Logistics
  • ~ ; + my $manage_leave_menu = '' ; + my $reports_menu_top = '' ; + my $accounts_menu_top = '' ; + + my $analytics_reports = ($glod_user_level >= 5) ? qq~ + +
  • + ~ : qq~~ ; + + # my $calibration_menu_top = qq~
  • Calibration
  • ~ ; + my $calibration_menu_top = qq~
  • Calibration
  • ~ ; + + + + my $fixedsystem_menu_top = qq~
  • Fixed System
  • ~ ; + my $home_menu_top = '' ; + my $search_menu_top = '' ; + my $quotes_menu_top = '' ; + my $events_menu_top = qq~
  • Events
  • ~; + # my $analytics_menu_top = ($glod_user_level >= 5) ? qq~
  • Analytics
  • ~ : qq~~ ; + + + my $analytics_menu_top = ($glod_user_level >= 5) ? qq~ + + ~ : qq~~ ; + + + + # my $events_filter = qq~
  • Search Events
  • ~; + # my $events_systems = '' ; + my $cameras_menu_top = qq~
  • Cameras
  • ~; + my $documents_menu_top = '' ; + my $calendar_menu_top = qq~
  • Calendar
  • ~; + my $manage_camera_systems_menu = '' ; + my $manage_users_menu = '' ; + my $manage_operators_menu = '' ; + my $manage_installation_partners_menu = '' ; + my $manage_analytics_client_menu = '' ; + my $manage_coding_providers_menu = '' ; + my $manage_customers_menu = '' ; + my $manage_archive_menu = '' ; + my $manage_event_systems = '' ; + my $manage_logistics_suppliers = '' ; + my $manage_logistics_locations = '' ; + my $manage_logistics_items = '' ; + my $manage_sport_types = '' ; + my $manage_cities = '' ; + my $manage_organisations = '' ; + my $manage_regions = '' ; + my $manage_teams = '' ; + my $manage_operator_payments = '' ; + my $manage_monitor_payments = '' ; + my $manage_troubleshoot_monitor_payments = '' ; + my $manage_temp_calibrator_payments = '' ; + my $manage_event_invoicing = '' ; + my $manage_logistics_report = '' ; + + my $manage_logistics_payments_report = '' ; + my $manage_logistics_shipment_costs_report = '' ; + + my $quote_search_menu_top = '' ; + my $reports_event_quotes = qq~
  • Event Quotes Report
  • ~; + my $reports_management_report = '' ; + my $logistics_costs_report = '' ; + my $events_reports = '' ; + my $reports_active_camera = '' ; + my $reports_active_camera = qq~
  • Active Cameras Report
  • ~; + # my $reports_stock_report = '' ; + my $reports_delivered_report = qq~
  • Delivered Report
  • ~; + # my $reports_delivered_report = '' ; + my $reports_warranty_report = '' ; + my $reports_match_credits = '' ; + my $manage_fixedsystem = '' ; + # my $monitor_report_menu_top = qq~
  • Monitor Report
  • ~ ; + + my $schedule_menu_top = '' ; + my $reports_monitor_report = ($glod_user_level >= 3) ? qq~
  • Monitor Allocations
  • ~ : '' ; + my $reports_temp_calibration = ($glod_user_level >= 3) ? qq~
  • Temp Calibrator Allocations
  • ~ : '' ; + my $reports_troubleshoot_monitor_report = ($glod_user_level >= 3) ? qq~
  • Troubleshoot Monitor Allocations
  • ~ : '' ; + my $reports_site_surveys = ($glod_user_level >= 3) ? qq~
  • Mobile Site Surveys
  • ~ : '' ; + my $reports_set_up_groups = ($glod_user_level >= 2) ? qq~
  • Set Up Groups
  • ~ : '' ; + my $mobile_tracking_system = ($glod_user_level >= 3) ? qq~
  • Mobile System Tracking
  • ~ : qq~~ ; + + my $report_audit_trial = ($glod_user_level > 3) ? qq~
  • Audit Trial
  • ~ : '' ; + + if ($useropts{super}{$username} and $pixellot_limit{$username}!=1 and $events_limit{$username}!=1) { + # $manage_quote_defaults_menu = qq~
  • Quote Defaults
  • ~ ; + $manage_quote_defaults_menu = qq~
  • Quote Defaults
  • ~ ; + $manage_price_list_menu = qq~
  • Price List
  • ~ ; + $manage_price_list_menu_top = qq~
  • Price List
  • ~ ; + # $manage_leave_menu = qq~
  • + #
  • List Leave
  • + #
  • Leave Settings
  • + #
  • Leave Report
  • ~ ; + + # $events_systems = qq~
  • Event Systems
  • ~; + } + + # unless ($pixellot_limit{$username} || $events_limit{$username} || $is_operator || $usertype eq 'external' || $usertype eq 'schools_manager') { + if ($glod_user_level >= 4) { + $reports_stock_report = qq~
  • Stock Report
  • ~; + } + + if ($glod_user_level >= 5) { + # $reports_delivered_report = qq~
  • Delivered Report
  • ~; + $reports_warranty_report = qq~
  • Extended Warranty Report
  • ~; + $reports_match_credits = qq~
  • Match Credits Report
  • ~; + $reports_management_report = qq~
  • Management Report
  • ~; + $logistics_costs_report = qq~
  • Logistics Costs Report
  • ~; + # $reports_operators_report = qq~
  • Operators Report
  • ~; + $events_reports = qq~
  • + +
  • + ~; + + + + $events_menu_top = qq~
  • Events
  • ~; + $home_menu_top = qq~
  • ~; + # $search_menu_top = qq~
  • Search
  • ~; + $quotes_menu_top = qq~
  • Quotes
  • ~ unless $usertype eq 'manager' ; + # $documents_menu_top = qq~
  • Documents
  • ~; + # $calendar_menu_top = qq~
  • Calendar
  • ~; + + $manage_camera_systems_menu = qq~
  • Camera Systems
  • ~; + $manage_users_menu = qq~
  • All Users
  • ~; + $manage_operators_menu = qq~
  • Operators
  • ~; + $manage_school_managers_menu = qq~
  • School Managers
  • ~; + + $manage_installation_partners_menu = qq~
  • Installation Partners
  • ~; + $manage_analytics_client_menu = ($glod_user_level >= 5) ? qq~
  • Analytics Clients
  • ~ : qq~~ ; + $manage_coding_providers_menu = ($glod_user_level >= 5) ? qq~
  • Coding Providers
  • ~ : qq~~ ; + + # $manage_logistics_shipment_costs_report = qq~
  • Logistics Shipment Costs
  • ~ ; + + $manage_customers_menu = qq~
  • Customers
  • ~; + $manage_archive_menu = qq~
  • Archive
  • ~; + $manage_event_systems = qq~
  • Event Systems
  • +
  • Event Types
  • +
  • Event Cost Items
  • + $manage_logistics_shipment_costs_report +
  • ~; + + # $manage_logistics_report = qq~
  • Logistics Report
  • ~ ; + $manage_event_invoicing = qq~
  • Event Invoicing
  • ~ ; + $manage_operator_payments = qq~
  • Operator Payments
  • ~ ; + $manage_monitor_payments = qq~
  • Monitor Payments
  • ~ ; + $manage_troubleshoot_monitor_payments = qq~
  • Troubleshoot Monitor Payments
  • ~ ; + $manage_temp_calibrator_payments = qq~
  • Temp Calibrator Payments
  • ~ ; + + $manage_logistics_payments_report = qq~
  • Logistics Payments
  • ~ ; + + + $manage_regions = qq~
  • Regions
  • ~ ; + $manage_teams = qq~
  • Teams
  • ~ if $glod_user_level >= 5 ; + $manage_cities = qq~
  • Cities
  • ~ ; + $manage_organisations = qq~
  • Venue
  • ~ ; + $manage_sport_types = qq~
  • Sport Types
  • ~; + $manage_logistics_suppliers = qq~
  • Logistics Suppliers
  • ~ ; + $manage_logistics_items = qq~
  • Logistics Items
  • ~; + $manage_logistics_locations = qq~
  • Logistics Locations
  • ~ ; + + + # $manage_fixedsystem = qq~
  • Fixed System
  • ~ ; + + $quote_search_menu_top = qq~
  • + +
  • ~; + + # $reports_monitor_report = qq~
  • Monitor Report
  • ~ ; + # $reports_temp_calibration = qq~
  • Temp Calibration Report
  • ~ ; + + # $accounts_menu_top = qq~~; + $accounts_menu_top = qq~ + +
  • + ~; + + } + + if ($events_limit{$username}) { + $events_reports = qq~
  • + +
  • + ~; + } + + + if ($pixellot_limit{$username} || $usertype eq 'external') { + $events_filter = '' ; + $reports_event_quotes = '' ; + $calendar_menu_top = '' ; + $reports_management_report = '' ; + $logistics_costs_report = '' ; + $events_menu_top = '' if $glod_user_level < 2 ; + } + + if ($events_limit{$username}) { + $cameras_menu_top = '' ; + $manage_operators_menu = qq~
  • Operators
  • ~; + } + + if ($glod_user_level < 5) { + $quotes_menu_top = '' ; + } + + $reports_menu_top = qq~~; + + $schedule_menu_top = qq~~; + # + + # $calibration_menu_top = qq~
  • Calibration
  • ~ ; + + + my $pre_sales_and_sales_menu_top = ($glod_user_level >= 5 || $usertype eq 'support') ? qq~ + + ~ : qq~~ ; + + # $calibration_menu_top = qq~
  • Calibration
  • ~ ; + + # # if ($useropts{super}{$username} || $useropts{boss}{$username} || $useropts{it}{$username} || $useropts{tickets}{$username}) { + # my $msgtxt = ($activetickets > 1) ? 'messages' : 'message' ; + # my $notif = ($activetickets > 0) ? qq~$activetickets~ : '' ; + # my $tooltip = ($activetickets > 0) ? qq~data-toggle="tooltip" data-title="$activetickets new $msgtxt" data-placement="left"~ : '' ; + # my $top = ($activetickets > 0) ? '10px' : '6px' ; + # $tickets_menu_top = qq~~ ; + # # } + + if ($useropts{tickets}{$username} || $usertype eq 'nonquotes') { + $search_menu_top = '' ; + $quotes_menu_top = '' ; + $manage_price_list_menu = '' ; + $manage_price_list_menu_top = '' ; + } + + # if ($usertype eq 'schools_manager') { + if ($glod_user_level < 3) { + $home_menu_top = '' ; + $search_menu_top = '' ; + $quotes_menu_top = '' ; + $cameras_menu_top = '' ; + $documents_menu_top = '' ; + # $calendar_menu_top = '' ; + $reports_menu_top = '' ; + $schedule_menu_top = '' if $glod_user_level < 2 ; + $manage_price_list_menu_top = '' ; + # $manage_logistics_report_menu_top = '' ; + $quote_search_menu_top = '' ; + # unless ($usertype eq 'support') { + if (($usertype eq 'schools_manager' || $glod_user_level < 2) && !$is_temp_calibrator) { + $calibration_menu_top = '' ; + # $fixedsystem_menu_top = '' ; + } + $events_menu_top = qq~
  • Events
  • ~; + } + + if ($is_operator) { + $events_menu_top = '' if $glod_user_level < 2 ; + $reports_event_quotes = '' ; + $cameras_menu_top = '' ; + $reports_menu_top = '' ; + # $schedule_menu_top = '' ; + $reports_management_report = '' ; + $logistics_costs_report = '' ; + # $calibration_menu_top = '' ; + + if ($glod_user_level == 3) { + $manage_operators_menu = qq~
  • Operators
  • ~; + $events_menu_top = qq~
  • Events
  • ~; + } + } + + if ($is_installation_partner) { + $calendar_menu_top = '' ; + $events_menu_top = '' ; + } + + if ($is_temp_calibrator) { + $fixedsystem_menu_top = '' ; + } + + if ($is_dcb_partner) { + $events_menu_top = '' ; + $calendar_menu_top = '' ; + $fixedsystem_menu_top = '' ; + } + + my $section_1 = ($manage_camera_systems_menu || $manage_customers_menu || $manage_quote_defaults_menu || $manage_price_list_menu || $rma_list_menu || $manage_leave_menu) ? qq~ + $manage_camera_systems_menu + $manage_customers_menu + $manage_quote_defaults_menu + $manage_price_list_menu + $rma_list_menu + $manage_leave_menu +
  • + ~ : qq~~ ; + + my $users_section = ($manage_users_menu || $manage_analytics_client_menu || $manage_coding_providers_menu || $manage_installation_partners_menu || $manage_operators_menu || $manage_school_managers_menu) ? qq~ + + +
  • + + ~ : qq~~ ; + + my $credits_section = ($glod_user_level >= 5) ? qq~ + + +
  • + + ~ : qq~~ ; + + my $section4 = ($manage_regions || $manage_cities || $manage_organisations || $manage_teams || $manage_sport_types) ? qq~ + $manage_regions + $manage_cities + $manage_organisations + $manage_teams + $manage_sport_types +
  • + ~ : qq~~ ; + + my $event_specifics = ($username eq 'handre' || $username eq 'rory' || $username eq 'vivian' || $usertype eq 'schools_manager' || $usertype eq 'manager' || $usertype eq 'senior_manager') ? qq~ + +
  • ~ : qq~~ ; + + my $logistics_sub_menu = ($manage_logistics_suppliers || $manage_logistics_items || $manage_logistics_locations) ? qq~ + + +
  • + + ~ : qq~~ ; + + my $calibration_status_report = ($calibration_menu_top || $usertype eq 'support') ? qq~
  • Calibration Status Report
  • ~ : qq~~ ; + + $calibration_menu_top = qq~ + ~ if $calibration_menu_top ; + + $calibration_menu_top = qq~ + ~ if $calibration_status_report && !$calibration_menu_top ; + +print < + + + + $useropts{title} + + + + + + $extra_css + + + + + + + + + + + + + + + + + + $typeahead_css + + + + + + + + + + + + + + + + + + + + +
    + +
    +
    + + + + + + + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/index.pm b/libs/html/_FromProd/index.pm new file mode 100644 index 0000000..7bf2620 --- /dev/null +++ b/libs/html/_FromProd/index.pm @@ -0,0 +1,65 @@ +require header ; + +local $index_menu = qq~
    +
    + +
    +
    +
    +
    ~ ; + +if (substr($usertype,0,6) eq 'casual') { + $index_menu = qq~
    +
    + +
    +
    +
    +
    ~ ; + } + +print < + + $useropts{'breadcrumbs'} + +
    +
    +
    +
    +

    Dashboard

    +
    +
    +
     
    +
    +
     
    + $index_menu +
     
    +
    +
     
    +
    +
    +
    + +
    + + +
    +
    + + +
    + +ENDOFTEXT + +require footer ; + +print < + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/login.pm b/libs/html/_FromProd/login.pm index d32cf33..6d7ccb5 100644 --- a/libs/html/_FromProd/login.pm +++ b/libs/html/_FromProd/login.pm @@ -62,17 +62,19 @@ print < - - + + diff --git a/libs/html/_FromProd/redirect.pm b/libs/html/_FromProd/redirect.pm new file mode 100644 index 0000000..d7acc5b --- /dev/null +++ b/libs/html/_FromProd/redirect.pm @@ -0,0 +1,23 @@ +print < + + + + $useropts{title} + + + + + + +
    + +
    + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/redirectcalibrator.pm b/libs/html/_FromProd/redirectcalibrator.pm new file mode 100644 index 0000000..78b5681 --- /dev/null +++ b/libs/html/_FromProd/redirectcalibrator.pm @@ -0,0 +1,23 @@ +print < + + + + $useropts{title} + + + + + + +
    + +
    + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/redirectfixed.pm b/libs/html/_FromProd/redirectfixed.pm new file mode 100644 index 0000000..78beb63 --- /dev/null +++ b/libs/html/_FromProd/redirectfixed.pm @@ -0,0 +1,23 @@ +print < + + + + $useropts{title} + + + + + + +
    + +
    + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/redirectlogistics.pm b/libs/html/_FromProd/redirectlogistics.pm new file mode 100644 index 0000000..ab349dd --- /dev/null +++ b/libs/html/_FromProd/redirectlogistics.pm @@ -0,0 +1,23 @@ +print < + + + + $useropts{title} + + + + + + +
    + +
    + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/tickets.pm b/libs/html/_FromProd/tickets.pm new file mode 100644 index 0000000..e0419a3 --- /dev/null +++ b/libs/html/_FromProd/tickets.pm @@ -0,0 +1,23 @@ +print < + + + + $useropts{title} + + + + + + +
    + +
    + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/401.pm b/libs/html/_FromProd/v1.0/401.pm new file mode 100644 index 0000000..668dca7 --- /dev/null +++ b/libs/html/_FromProd/v1.0/401.pm @@ -0,0 +1,99 @@ +print < + + + + + + + Error + + + +

    + 401 +

    + +

    Unauthorised

    + +
    +
    + You are not authorised to view this page +
    +
    + Click here to go back to your Dashboard +
    + + +
    + + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/_blank.pm b/libs/html/_FromProd/v1.0/_blank.pm new file mode 100644 index 0000000..7184485 --- /dev/null +++ b/libs/html/_FromProd/v1.0/_blank.pm @@ -0,0 +1,42 @@ +require header ; + +print < + + $useropts{'breadcrumbs'} + + $alert + +
    +
    +
    +
    +

    $page_title

    + $box_icon +
    +
    + $print_box_content_rows +
    +
    +
    +
    + $print_more_boxes + + + +ENDOFTEXT + +require footer ; + +print < + +$print_footer_forms + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/_blank_3.pm b/libs/html/_FromProd/v1.0/_blank_3.pm new file mode 100644 index 0000000..e85e9ed --- /dev/null +++ b/libs/html/_FromProd/v1.0/_blank_3.pm @@ -0,0 +1,32 @@ +require header ; + +print < + + $useropts{'breadcrumbs'} + + $alert + + $print_box_content_rows + + + + $print_more_boxes + + +ENDOFTEXT + +require footer ; + +print < + +$print_footer_forms + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/_blank_4.pm b/libs/html/_FromProd/v1.0/_blank_4.pm new file mode 100644 index 0000000..f1d94f3 --- /dev/null +++ b/libs/html/_FromProd/v1.0/_blank_4.pm @@ -0,0 +1,88 @@ +# require header ; +print < + + + + $useropts{title} + + + + + + $extra_css + + + + + + + + + + + + + + + + + + $typeahead_css + + + + + + + + + + + + + + + + + + + +ENDOFTEXT +# + +print < + + + $alert + + $print_box_content_rows + + + + $print_more_boxes + + +ENDOFTEXT + +require footer ; + +print < + +$print_footer_forms + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/_return.pm b/libs/html/_FromProd/v1.0/_return.pm new file mode 100644 index 0000000..ec74b2b --- /dev/null +++ b/libs/html/_FromProd/v1.0/_return.pm @@ -0,0 +1,26 @@ +unless ($goaction) { $goaction = 'list' ; } + +print < + + + + $useropts{title} + + + + + + +
    + + +
    + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/archive.pm b/libs/html/_FromProd/v1.0/archive.pm new file mode 100644 index 0000000..645736c --- /dev/null +++ b/libs/html/_FromProd/v1.0/archive.pm @@ -0,0 +1,95 @@ +require header ; + +print < + + $useropts{'breadcrumbs'} + + $alert + + $print_usage + + $print_download + + $print_delete_uploads_form + + $print_buttons + + + + + +
    + +ENDOFTEXT + +require footer ; + +print < + + + + +
    + + +
    + +
    + + +
    + +
    + +
    + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/calendar.pm b/libs/html/_FromProd/v1.0/calendar.pm new file mode 100644 index 0000000..7ed135f --- /dev/null +++ b/libs/html/_FromProd/v1.0/calendar.pm @@ -0,0 +1,37 @@ +require header ; + +print < + + $useropts{'breadcrumbs'} + +
    +
    +
    +
    +

    Calendar

    + $box_icon +
    +
    +
    +
    +
    +
    +
    +
    + + + + +
    + +ENDOFTEXT + +require footer ; + +print < + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/fixedsystems.pm b/libs/html/_FromProd/v1.0/fixedsystems.pm new file mode 100644 index 0000000..78beb63 --- /dev/null +++ b/libs/html/_FromProd/v1.0/fixedsystems.pm @@ -0,0 +1,23 @@ +print < + + + + $useropts{title} + + + + + + +
    + +
    + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/footer.pm b/libs/html/_FromProd/v1.0/footer.pm new file mode 100644 index 0000000..8f6a809 --- /dev/null +++ b/libs/html/_FromProd/v1.0/footer.pm @@ -0,0 +1,103 @@ +print < + + +

    Kre8IT Programming (Pty) Ltd
    062 133 6754
    info\@kre8it.co.za

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +$extra_js + + + +
    + + +
    + +
    + + +
    + +$extra_form_footer + +ENDOFTEXT +# + +# +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/header.pm b/libs/html/_FromProd/v1.0/header.pm new file mode 100644 index 0000000..0195b35 --- /dev/null +++ b/libs/html/_FromProd/v1.0/header.pm @@ -0,0 +1,618 @@ + + my $manage_quote_defaults_menu = '' ; + my $manage_price_list_menu = '' ; + + my $rma_list_menu = ($usertype eq 'it' || $usertype eq 'senior_manager' || $usertype eq 'manager' || $usertype eq 'support' || $usertype eq 'casual_c') ? qq~
  • RMA List
  • ~ : '' ; + + my $manage_price_list_menu_top = '' ; + + my $manage_logistics_report_menu_top = qq~
  • Logistics
  • ~ ; + my $manage_leave_menu = '' ; + my $reports_menu_top = '' ; + my $accounts_menu_top = '' ; + + my $analytics_reports = ($glod_user_level >= 5) ? qq~ + +
  • + ~ : qq~~ ; + + # my $calibration_menu_top = qq~
  • Calibration
  • ~ ; + my $calibration_menu_top = qq~
  • Calibration
  • ~ ; + + + + my $fixedsystem_menu_top = qq~
  • Fixed System
  • ~ ; + my $home_menu_top = '' ; + my $search_menu_top = '' ; + my $quotes_menu_top = '' ; + my $events_menu_top = qq~
  • Events
  • ~; + # my $analytics_menu_top = ($glod_user_level >= 5) ? qq~
  • Analytics
  • ~ : qq~~ ; + + + my $analytics_menu_top = ($glod_user_level >= 5) ? qq~ + + ~ : qq~~ ; + + + + # my $events_filter = qq~
  • Search Events
  • ~; + # my $events_systems = '' ; + my $cameras_menu_top = qq~
  • Cameras
  • ~; + my $documents_menu_top = '' ; + my $calendar_menu_top = qq~
  • Calendar
  • ~; + my $manage_camera_systems_menu = '' ; + my $manage_users_menu = '' ; + my $manage_operators_menu = '' ; + my $manage_installation_partners_menu = '' ; + my $manage_analytics_client_menu = '' ; + my $manage_coding_providers_menu = '' ; + my $manage_customers_menu = '' ; + my $manage_archive_menu = '' ; + my $manage_event_systems = '' ; + my $manage_logistics_suppliers = '' ; + my $manage_logistics_locations = '' ; + my $manage_logistics_items = '' ; + my $manage_sport_types = '' ; + my $manage_cities = '' ; + my $manage_organisations = '' ; + my $manage_regions = '' ; + my $manage_teams = '' ; + my $manage_operator_payments = '' ; + my $manage_monitor_payments = '' ; + my $manage_troubleshoot_monitor_payments = '' ; + my $manage_temp_calibrator_payments = '' ; + my $manage_event_invoicing = '' ; + my $manage_logistics_report = '' ; + + my $manage_logistics_payments_report = '' ; + my $manage_logistics_shipment_costs_report = '' ; + + my $quote_search_menu_top = '' ; + my $reports_event_quotes = qq~
  • Event Quotes Report
  • ~; + my $reports_management_report = '' ; + my $logistics_costs_report = '' ; + my $events_reports = '' ; + my $reports_active_camera = '' ; + my $reports_active_camera = qq~
  • Active Cameras Report
  • ~; + # my $reports_stock_report = '' ; + my $reports_delivered_report = qq~
  • Delivered Report
  • ~; + # my $reports_delivered_report = '' ; + my $reports_warranty_report = '' ; + my $reports_match_credits = '' ; + my $manage_fixedsystem = '' ; + # my $monitor_report_menu_top = qq~
  • Monitor Report
  • ~ ; + + my $schedule_menu_top = '' ; + my $reports_monitor_report = ($glod_user_level >= 3) ? qq~
  • Monitor Allocations
  • ~ : '' ; + my $reports_temp_calibration = ($glod_user_level >= 3) ? qq~
  • Temp Calibrator Allocations
  • ~ : '' ; + my $reports_troubleshoot_monitor_report = ($glod_user_level >= 3) ? qq~
  • Troubleshoot Monitor Allocations
  • ~ : '' ; + my $reports_site_surveys = ($glod_user_level >= 3) ? qq~
  • Mobile Site Surveys
  • ~ : '' ; + my $reports_set_up_groups = ($glod_user_level >= 2) ? qq~
  • Set Up Groups
  • ~ : '' ; + my $mobile_tracking_system = ($glod_user_level >= 3) ? qq~
  • Mobile System Tracking
  • ~ : qq~~ ; + + my $report_audit_trial = ($glod_user_level > 3) ? qq~
  • Audit Trial
  • ~ : '' ; + + if ($useropts{super}{$username} and $pixellot_limit{$username}!=1 and $events_limit{$username}!=1) { + # $manage_quote_defaults_menu = qq~
  • Quote Defaults
  • ~ ; + $manage_quote_defaults_menu = qq~
  • Quote Defaults
  • ~ ; + $manage_price_list_menu = qq~
  • Price List
  • ~ ; + $manage_price_list_menu_top = qq~
  • Price List
  • ~ ; + # $manage_leave_menu = qq~
  • + #
  • List Leave
  • + #
  • Leave Settings
  • + #
  • Leave Report
  • ~ ; + + # $events_systems = qq~
  • Event Systems
  • ~; + } + + # unless ($pixellot_limit{$username} || $events_limit{$username} || $is_operator || $usertype eq 'external' || $usertype eq 'schools_manager') { + if ($glod_user_level >= 4) { + $reports_stock_report = qq~
  • Stock Report
  • ~; + } + + if ($glod_user_level >= 5) { + # $reports_delivered_report = qq~
  • Delivered Report
  • ~; + $reports_warranty_report = qq~
  • Extended Warranty Report
  • ~; + $reports_match_credits = qq~
  • Match Credits Report
  • ~; + $reports_management_report = qq~
  • Management Report
  • ~; + $logistics_costs_report = qq~
  • Logistics Costs Report
  • ~; + # $reports_operators_report = qq~
  • Operators Report
  • ~; + $events_reports = qq~
  • + +
  • + ~; + + + + $events_menu_top = qq~
  • Events
  • ~; + $home_menu_top = qq~
  • ~; + # $search_menu_top = qq~
  • Search
  • ~; + $quotes_menu_top = qq~
  • Quotes
  • ~ unless $usertype eq 'manager' ; + # $documents_menu_top = qq~
  • Documents
  • ~; + # $calendar_menu_top = qq~
  • Calendar
  • ~; + + $manage_camera_systems_menu = qq~
  • Camera Systems
  • ~; + $manage_users_menu = qq~
  • All Users
  • ~; + $manage_operators_menu = qq~
  • Operators
  • ~; + $manage_school_managers_menu = qq~
  • School Managers
  • ~; + + $manage_installation_partners_menu = qq~
  • Installation Partners
  • ~; + $manage_analytics_client_menu = ($glod_user_level >= 5) ? qq~
  • Analytics Clients
  • ~ : qq~~ ; + $manage_coding_providers_menu = ($glod_user_level >= 5) ? qq~
  • Coding Providers
  • ~ : qq~~ ; + + # $manage_logistics_shipment_costs_report = qq~
  • Logistics Shipment Costs
  • ~ ; + + $manage_customers_menu = qq~
  • Customers
  • ~; + $manage_archive_menu = qq~
  • Archive
  • ~; + $manage_event_systems = qq~
  • Event Systems
  • +
  • Event Types
  • +
  • Event Cost Items
  • + $manage_logistics_shipment_costs_report +
  • ~; + + # $manage_logistics_report = qq~
  • Logistics Report
  • ~ ; + $manage_event_invoicing = qq~
  • Event Invoicing
  • ~ ; + $manage_operator_payments = qq~
  • Operator Payments
  • ~ ; + $manage_monitor_payments = qq~
  • Monitor Payments
  • ~ ; + $manage_troubleshoot_monitor_payments = qq~
  • Troubleshoot Monitor Payments
  • ~ ; + $manage_temp_calibrator_payments = qq~
  • Temp Calibrator Payments
  • ~ ; + + $manage_logistics_payments_report = qq~
  • Logistics Payments
  • ~ ; + + + $manage_regions = qq~
  • Regions
  • ~ ; + $manage_teams = qq~
  • Teams
  • ~ if $glod_user_level >= 5 ; + $manage_cities = qq~
  • Cities
  • ~ ; + $manage_organisations = qq~
  • Venue
  • ~ ; + $manage_sport_types = qq~
  • Sport Types
  • ~; + $manage_logistics_suppliers = qq~
  • Logistics Suppliers
  • ~ ; + $manage_logistics_items = qq~
  • Logistics Items
  • ~; + $manage_logistics_locations = qq~
  • Logistics Locations
  • ~ ; + + + # $manage_fixedsystem = qq~
  • Fixed System
  • ~ ; + + $quote_search_menu_top = qq~
  • + +
  • ~; + + # $reports_monitor_report = qq~
  • Monitor Report
  • ~ ; + # $reports_temp_calibration = qq~
  • Temp Calibration Report
  • ~ ; + + # $accounts_menu_top = qq~~; + $accounts_menu_top = qq~ + +
  • + ~; + + } + + if ($events_limit{$username}) { + $events_reports = qq~
  • + +
  • + ~; + } + + + if ($pixellot_limit{$username} || $usertype eq 'external') { + $events_filter = '' ; + $reports_event_quotes = '' ; + $calendar_menu_top = '' ; + $reports_management_report = '' ; + $logistics_costs_report = '' ; + $events_menu_top = '' if $glod_user_level < 2 ; + } + + if ($events_limit{$username}) { + $cameras_menu_top = '' ; + $manage_operators_menu = qq~
  • Operators
  • ~; + } + + if ($glod_user_level < 5) { + $quotes_menu_top = '' ; + } + + $reports_menu_top = qq~~; + + $schedule_menu_top = qq~~; + # + + # $calibration_menu_top = qq~
  • Calibration
  • ~ ; + + + my $pre_sales_and_sales_menu_top = ($glod_user_level >= 5 || $usertype eq 'support') ? qq~ + + ~ : qq~~ ; + + # $calibration_menu_top = qq~
  • Calibration
  • ~ ; + + # # if ($useropts{super}{$username} || $useropts{boss}{$username} || $useropts{it}{$username} || $useropts{tickets}{$username}) { + # my $msgtxt = ($activetickets > 1) ? 'messages' : 'message' ; + # my $notif = ($activetickets > 0) ? qq~$activetickets~ : '' ; + # my $tooltip = ($activetickets > 0) ? qq~data-toggle="tooltip" data-title="$activetickets new $msgtxt" data-placement="left"~ : '' ; + # my $top = ($activetickets > 0) ? '10px' : '6px' ; + # $tickets_menu_top = qq~~ ; + # # } + + if ($useropts{tickets}{$username} || $usertype eq 'nonquotes') { + $search_menu_top = '' ; + $quotes_menu_top = '' ; + $manage_price_list_menu = '' ; + $manage_price_list_menu_top = '' ; + } + + # if ($usertype eq 'schools_manager') { + if ($glod_user_level < 3) { + $home_menu_top = '' ; + $search_menu_top = '' ; + $quotes_menu_top = '' ; + $cameras_menu_top = '' ; + $documents_menu_top = '' ; + # $calendar_menu_top = '' ; + $reports_menu_top = '' ; + $schedule_menu_top = '' if $glod_user_level < 2 ; + $manage_price_list_menu_top = '' ; + # $manage_logistics_report_menu_top = '' ; + $quote_search_menu_top = '' ; + # unless ($usertype eq 'support') { + if (($usertype eq 'schools_manager' || $glod_user_level < 2) && !$is_temp_calibrator) { + $calibration_menu_top = '' ; + # $fixedsystem_menu_top = '' ; + } + $events_menu_top = qq~
  • Events
  • ~; + } + + if ($is_operator) { + $events_menu_top = '' if $glod_user_level < 2 ; + $reports_event_quotes = '' ; + $cameras_menu_top = '' ; + $reports_menu_top = '' ; + # $schedule_menu_top = '' ; + $reports_management_report = '' ; + $logistics_costs_report = '' ; + # $calibration_menu_top = '' ; + + if ($glod_user_level == 3) { + $manage_operators_menu = qq~
  • Operators
  • ~; + $events_menu_top = qq~
  • Events
  • ~; + } + } + + if ($is_installation_partner) { + $calendar_menu_top = '' ; + $events_menu_top = '' ; + } + + if ($is_temp_calibrator) { + $fixedsystem_menu_top = '' ; + } + + if ($is_dcb_partner) { + $events_menu_top = '' ; + $calendar_menu_top = '' ; + $fixedsystem_menu_top = '' ; + } + + my $section_1 = ($manage_camera_systems_menu || $manage_customers_menu || $manage_quote_defaults_menu || $manage_price_list_menu || $rma_list_menu || $manage_leave_menu) ? qq~ + $manage_camera_systems_menu + $manage_customers_menu + $manage_quote_defaults_menu + $manage_price_list_menu + $rma_list_menu + $manage_leave_menu +
  • + ~ : qq~~ ; + + my $users_section = ($manage_users_menu || $manage_analytics_client_menu || $manage_coding_providers_menu || $manage_installation_partners_menu || $manage_operators_menu || $manage_school_managers_menu) ? qq~ + + +
  • + + ~ : qq~~ ; + + my $credits_section = ($glod_user_level >= 5) ? qq~ + + +
  • + + ~ : qq~~ ; + + my $section4 = ($manage_regions || $manage_cities || $manage_organisations || $manage_teams || $manage_sport_types) ? qq~ + $manage_regions + $manage_cities + $manage_organisations + $manage_teams + $manage_sport_types +
  • + ~ : qq~~ ; + + my $event_specifics = ($username eq 'handre' || $username eq 'rory' || $username eq 'vivian' || $usertype eq 'schools_manager' || $usertype eq 'manager' || $usertype eq 'senior_manager') ? qq~ + +
  • ~ : qq~~ ; + + my $logistics_sub_menu = ($manage_logistics_suppliers || $manage_logistics_items || $manage_logistics_locations) ? qq~ + + +
  • + + ~ : qq~~ ; + + my $calibration_status_report = ($calibration_menu_top || $usertype eq 'support') ? qq~
  • Calibration Status Report
  • ~ : qq~~ ; + + $calibration_menu_top = qq~ + ~ if $calibration_menu_top ; + + $calibration_menu_top = qq~ + ~ if $calibration_status_report && !$calibration_menu_top ; + +print < + + + + $useropts{title} + + + + + + $extra_css + + + + + + + + + + + + + + + + + + $typeahead_css + + + + + + + + + + + + + + + + + + + + +
    + +
    +
    + + + + + + + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/index.pm b/libs/html/_FromProd/v1.0/index.pm new file mode 100644 index 0000000..7bf2620 --- /dev/null +++ b/libs/html/_FromProd/v1.0/index.pm @@ -0,0 +1,65 @@ +require header ; + +local $index_menu = qq~
    +
    + +
    +
    +
    +
    ~ ; + +if (substr($usertype,0,6) eq 'casual') { + $index_menu = qq~
    +
    + +
    +
    +
    +
    ~ ; + } + +print < + + $useropts{'breadcrumbs'} + +
    +
    +
    +
    +

    Dashboard

    +
    +
    +
     
    +
    +
     
    + $index_menu +
     
    +
    +
     
    +
    +
    +
    + +
    + + +
    +
    + + +
    + +ENDOFTEXT + +require footer ; + +print < + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/login.pm b/libs/html/_FromProd/v1.0/login.pm new file mode 100644 index 0000000..90569fd --- /dev/null +++ b/libs/html/_FromProd/v1.0/login.pm @@ -0,0 +1,84 @@ +print < + + + + $useropts{title} + + + + + + + + + +
    +
    + +
    + + +
    + +
    + + +
    +
    + +
    + + + + + + + + + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/redirect.pm b/libs/html/_FromProd/v1.0/redirect.pm new file mode 100644 index 0000000..d7acc5b --- /dev/null +++ b/libs/html/_FromProd/v1.0/redirect.pm @@ -0,0 +1,23 @@ +print < + + + + $useropts{title} + + + + + + +
    + +
    + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/redirectcalibrator.pm b/libs/html/_FromProd/v1.0/redirectcalibrator.pm new file mode 100644 index 0000000..78b5681 --- /dev/null +++ b/libs/html/_FromProd/v1.0/redirectcalibrator.pm @@ -0,0 +1,23 @@ +print < + + + + $useropts{title} + + + + + + +
    + +
    + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/redirectfixed.pm b/libs/html/_FromProd/v1.0/redirectfixed.pm new file mode 100644 index 0000000..78beb63 --- /dev/null +++ b/libs/html/_FromProd/v1.0/redirectfixed.pm @@ -0,0 +1,23 @@ +print < + + + + $useropts{title} + + + + + + +
    + +
    + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/redirectlogistics.pm b/libs/html/_FromProd/v1.0/redirectlogistics.pm new file mode 100644 index 0000000..ab349dd --- /dev/null +++ b/libs/html/_FromProd/v1.0/redirectlogistics.pm @@ -0,0 +1,23 @@ +print < + + + + $useropts{title} + + + + + + +
    + +
    + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/_FromProd/v1.0/tickets.pm b/libs/html/_FromProd/v1.0/tickets.pm new file mode 100644 index 0000000..e0419a3 --- /dev/null +++ b/libs/html/_FromProd/v1.0/tickets.pm @@ -0,0 +1,23 @@ +print < + + + + $useropts{title} + + + + + + +
    + +
    + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/header.pm b/libs/html/header.pm index 0195b35..c3ae338 100644 --- a/libs/html/header.pm +++ b/libs/html/header.pm @@ -40,6 +40,21 @@ + + ~ : ($usertype eq 'coding_provider') ? qq~ + + ~ : ($usertype eq 'analytics_client') ? qq~ + ~ : qq~~ ; @@ -94,14 +109,16 @@ # my $monitor_report_menu_top = qq~
  • Monitor Report
  • ~ ; my $schedule_menu_top = '' ; - my $reports_monitor_report = ($glod_user_level >= 3) ? qq~
  • Monitor Allocations
  • ~ : '' ; + # my $reports_monitor_report = ($glod_user_level >= 3) ? qq~
  • Monitor Allocations
  • ~ : '' ; + my $reports_monitor_report = ($glod_user_level >= 3) ? qq~
  • SSS Event Feedback
  • ~ : '' ; my $reports_temp_calibration = ($glod_user_level >= 3) ? qq~
  • Temp Calibrator Allocations
  • ~ : '' ; - my $reports_troubleshoot_monitor_report = ($glod_user_level >= 3) ? qq~
  • Troubleshoot Monitor Allocations
  • ~ : '' ; + # my $reports_troubleshoot_monitor_report = ($glod_user_level >= 3) ? qq~
  • Troubleshoot Allocations
  • ~ : '' ; + my $reports_troubleshoot_monitor_report = ($glod_user_level >= 3) ? qq~
  • AISA Event Feedback
  • ~ : '' ; my $reports_site_surveys = ($glod_user_level >= 3) ? qq~
  • Mobile Site Surveys
  • ~ : '' ; my $reports_set_up_groups = ($glod_user_level >= 2) ? qq~
  • Set Up Groups
  • ~ : '' ; my $mobile_tracking_system = ($glod_user_level >= 3) ? qq~
  • Mobile System Tracking
  • ~ : qq~~ ; - my $report_audit_trial = ($glod_user_level > 3) ? qq~
  • Audit Trial
  • ~ : '' ; + my $report_audit_trial = ($glod_user_level > 3) ? qq~
  • Audit Trail
  • ~ : '' ; if ($useropts{super}{$username} and $pixellot_limit{$username}!=1 and $events_limit{$username}!=1) { # $manage_quote_defaults_menu = qq~
  • Quote Defaults
  • ~ ; @@ -419,7 +436,7 @@
  • @@ -477,6 +494,13 @@ $calibration_status_report ~ if $calibration_status_report && !$calibration_menu_top ; + + if ($usertype eq 'coding_provider' || $usertype eq 'analytics_client') { + $events_menu_top = qq~~ ; + $calendar_menu_top = qq~~ ; + $fixedsystem_menu_top = qq~~ ; + $manage_logistics_report_menu_top = qq~~ ; + } print < diff --git a/libs/html/redirectallfixtures.pm b/libs/html/redirectallfixtures.pm new file mode 100644 index 0000000..3f19dfc --- /dev/null +++ b/libs/html/redirectallfixtures.pm @@ -0,0 +1,23 @@ +print < + + + + $useropts{title} + + + + + + +
    + +
    + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/html/redirectanalytics.pm b/libs/html/redirectanalytics.pm new file mode 100644 index 0000000..b6cb2f6 --- /dev/null +++ b/libs/html/redirectanalytics.pm @@ -0,0 +1,23 @@ +print < + + + + $useropts{title} + + + + + + +
    + +
    + + +ENDOFTEXT +# \ No newline at end of file diff --git a/libs/modules/_FromProd/analytics_event_booking_tabs.pm b/libs/modules/_FromProd/analytics_event_booking_tabs.pm new file mode 100644 index 0000000..05ca4b2 --- /dev/null +++ b/libs/modules/_FromProd/analytics_event_booking_tabs.pm @@ -0,0 +1,2029 @@ +sub analytics_event_bookings_tabs_build_qt_left { + + my ($id,$tab,$ret) = @_ ; + + if ($tab == 1) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_customer_details' ; + + my ($sec_name,$sec_cnt,$sec_col) = &analytics_event_bookings_tabs_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + $lcol = 2 ; $fcol = 1 ; $add_form_fields = '' ; + + # $add_form_fields .= qq~
    ~ if $is_schools_manager ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + + my $checked = ($db{$table}{$id}{event_completed}) ? 'CHECKED' : '' ; + $preferred_title{event_completed} = "Event Completed" ; + $add_form_fields .= &common_min_form_checkbox('event_completed',$db{$table}{$id}{event_completed},$checked) ; + + # my $checked = 'CHECKED' if $db{$table}{$id}{event_accepted} ; + my $checked = ($db{$table}{$id}{event_accepted}) ? 'CHECKED' : '' ; + $preferred_title{event_accepted} = "Event Accepted" ; + $add_form_fields .= &common_min_form_checkbox('event_accepted',$db{$table}{$id}{event_accepted},$checked) ; + + my $checked = ($db{$table}{$id}{event_rejected}) ? 'CHECKED' : '' ; + $preferred_title{event_rejected} = "Event Rejected" ; + $add_form_fields .= &common_min_form_checkbox('event_rejected',$db{$table}{$id}{event_rejected},$checked) ; + + # my $checked = 'CHECKED' if $db{$table}{$id}{event_pending} or $iaction eq 'add' ; + my $checked = ($db{$table}{$id}{event_pending} || $iaction eq 'add') ? 'CHECKED' : '' ; + $preferred_title{event_pending} = "Event Pending" ; + $add_form_fields .= &common_min_form_checkbox('event_pending',$db{$table}{$id}{event_pending},$checked) ; + + # my $checked = 'CHECKED' if $db{$table}{$id}{event_cancelled} ; + my $checked = ($db{$table}{$id}{event_cancelled}) ? 'CHECKED' : '' ; + $preferred_title{event_cancelled} = "Event Cancelled" ; + $add_form_fields .= &common_min_form_checkbox('event_cancelled',$db{$table}{$id}{event_cancelled},$checked) ; + + # $add_form_fields .= qq~
    ~ if $is_schools_manager ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + + # $add_form_fields .= qq~~ if $is_schools_manager ; + $add_form_fields .= qq~~ if $glod_user_level < 3 ; + + $fcol = 4 ; + $add_form_fields .= &common_min_form_input('contact_name',$db{$table}{$id}{contact_name},'') ; + $add_form_fields .= &common_min_form_input('address',$db{$table}{$id}{address},'') ; + $add_form_fields .= &common_min_form_input('email',$db{$table}{$id}{email},'') ; + $add_form_fields .= &common_min_form_input('tel',$db{$table}{$id}{tel},'') ; + # $fcol = 5 ; + + $add_form_fields .= qq~
     
    ~ ; + + &analytics_event_bookings_tabs_content_box($sec_name,$sec_col); + + $trigger_jquery_raw .= qq~ + + if (!\$("#checkboxEvent_accepted").is(":checked") && !\$("#checkboxEvent_rejected").is(":checked") && !\$("#checkboxEvent_pending").is(":checked") && !\$("#checkboxEvent_cancelled").is(":checked") && !\$("#checkboxEvent_completed").is(":checked")) { + \$("#checkboxEvent_pending").prop("checked","true") ; + } + + \$("#checkboxEvent_completed,#checkboxEvent_accepted,#checkboxEvent_rejected,#checkboxEvent_pending,#checkboxEvent_cancelled").click( function () { + + if (this.id != 'checkboxEvent_completed' && \$("#checkboxEvent_completed").is(":checked")) { + \$("#checkboxEvent_completed").prop("checked",false) ; + } + + if (this.id != 'checkboxEvent_accepted' && \$("#checkboxEvent_accepted").is(":checked")) { + \$("#checkboxEvent_accepted").prop("checked",false) ; + } + + if (this.id != 'checkboxEvent_rejected' && \$("#checkboxEvent_rejected").is(":checked")) { + \$("#checkboxEvent_rejected").prop("checked",false) ; + } + + if (this.id != 'checkboxEvent_pending' && \$("#checkboxEvent_pending").is(":checked")) { + \$("#checkboxEvent_pending").prop("checked",false) ; + } + + if (this.id != 'checkboxEvent_cancelled' && \$("#checkboxEvent_cancelled").is(":checked")) { + \$("#checkboxEvent_cancelled").prop("checked",false) ; + } + + if (this.id == 'checkboxEvent_completed' && !\$("#checkboxEvent_accepted").is(":checked")) { + \$("#checkboxEvent_accepted").prop("checked",true) ; + } + + if (!\$("#checkboxEvent_accepted").is(":checked") && !\$("#checkboxEvent_rejected").is(":checked") && !\$("#checkboxEvent_pending").is(":checked") && !\$("#checkboxEvent_cancelled").is(":checked") && !\$("#checkboxEvent_completed").is(":checked")) { + \$("#checkboxEvent_pending").prop("checked","true") ; + } + + }); + + ~ ; + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + + if ($tab == 2) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + return if $ret ; + + my $sec = '_event_details' ; + + my ($sec_name,$sec_cnt,$sec_col) = &analytics_event_bookings_tabs_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + $preferred_title{sport_type_ids} = "Sport Type(s)" ; + $preferred_title{start_date_time} = "Event Date/Time From" ; + $preferred_title{end_date_time} = "Event Date/Time To" ; + $add_form_fields = "" ; + + + foreach (keys %service_types) { + $opts{service_type_id} .= qq~~ ; + } + + foreach (split(/\,/,$db{$table}{$id}{sport_type_ids})) { + $opts{sport_type_ids} =~ s/value="$_"/value="$_" SELECTED/g ; + } + + $db{$table}{$id}{service_type_id} = 3 unless $db{$table}{$id}{service_type_id}; + + $opts{service_type_id} =~ s/value="$db{$table}{$id}{service_type_id}"/value="$db{$table}{$id}{service_type_id}" SELECTED/g ; + + for (1 .. 100) { + $opts{total_fixtures} .= qq~~ ; + } + + $db{$table}{$id}{total_fixtures} = 1 unless $db{$table}{$id}{total_fixtures} ; + + $opts{total_fixtures} =~ s/value="$db{$table}{$id}{total_fixtures}"/value="$db{$table}{$id}{total_fixtures}" SELECTED/g ; + + $db{$table}{$id}{start_date_time} = "$now_year-$now_mm-$now_dd 08:00:00" unless $db{$table}{$id}{start_date_time} ; + $db{$table}{$id}{end_date_time} = "$now_year-$now_mm-$now_dd 17:00:00" unless $db{$table}{$id}{end_date_time} ; + + $allow_deselect{client_id} = 1 ; + # $allow_deselect{total_fixtures} = 1 ; + # $allow_deselect{service_type_id} = 1 ; + + $lcol = 2 ; $fcol = 4 ; + + # if ($usertype eq 'analytics_client') { + # &db_min_ro('users','id,name',"id='$userid'") ; + # $opts{client_id} = qq~~ ; + # } else { + # &common_min_select_opts('client_id','customers','name','','','',"analytics='1'") ; + # # $db{$table}{$id}{client_id} = $userid if !$db{$table}{$id}{client_id} && $usertype eq 'analytics_client' ; + # $opts{client_id} =~ s/value="$db{$table}{$id}{client_id}"/value="$db{$table}{$id}{client_id}" SELECTED/g if $db{$table}{$id}{client_id} ; + # } + + $dlg{client_id} .= qq~
    ~ ; + + $dlg{sport_type_ids} .= qq~
    ~ ; + + # $onload = qq~onload=dispCustomer();~ if $iaction eq 'add' ; # SuperSport Schools (Pty) Ltd + + if ($sql_limit_user_regions) { + $sql_limit_user_regions =~ s/id/region_id/g ; + $sql_limit_user_regions .= "region_id='0' OR ($sql_limit_user_regions)" ; + } + + &analytics_event_bookings_tabs_customer_select_opts('customers','name',$sql_limit_user_regions,'client_id'); + + # $allow_deselect{client_id} = 1 ; + + # $required{client_id} = 1 ; + + $add_form_fields .= &common_min_form_select('client_id',$db{$table}{$id}{client_id}) ; + $add_form_fields .= &common_min_form_input('event_name',$db{$table}{$id}{event_name}) ; + $add_form_fields .= &common_min_form_datetimepicker('start_date_time',$db{$table}{$id}{start_date_time}) ; + $add_form_fields .= &common_min_form_datetimepicker('end_date_time',$db{$table}{$id}{end_date_time}) ; + $add_form_fields .= &common_min_form_select('sport_type_ids',$db{$table}{$id}{sport_type_ids}) ; + $add_form_fields .= &common_min_form_select('total_fixtures',$db{$table}{$id}{total_fixtures}) ; + $add_form_fields .= &common_min_form_select('service_type_id',$db{$table}{$id}{service_type_id}) ; + + $db{$table}{$id}{tournament_festival_id} = 1 if !$db{$table}{$id}{derby_day_weekly_fixture_id} && !$db{$table}{$id}{tournament_festival_id} ; + + $add_form_fields .= &common_min_form_checkbox('derby_day_weekly_fixture_id',$db{$table}{$id}{derby_day_weekly_fixture_id}) ; + $add_form_fields .= &common_min_form_checkbox('tournament_festival_id',$db{$table}{$id}{tournament_festival_id}) ; + + $trigger_jquery .= qq~ + // \$('.iPhoneCheckContainer').css("width","76px") ; + // \$('.iPhoneCheckHandle').css("width","32px") ; + // \$('.iPhoneCheckHandle').css("left","0px") ; + // \$('.iPhoneCheckLabelOff').css("width","71px") ; + // \$('.iPhoneCheckLabelOff').css("top","-5px") ; + // \$('.iPhoneCheckLabelOn').css("top","-5px") ; + // \$('.iPhoneCheckLabelOn').css("width","45px") ; + // \$('.iPhoneCheckLabelOff span').css("font-size","14px"); + // \$('.iPhoneCheckLabelOn span').css("font-size","14px"); + ~ ; + + $trigger_jquery_raw .= qq~\$("#checkboxTournament_festival_id").prop("checked",true) ;~ if $db{$table}{$id}{tournament_festival_id} ; + $trigger_jquery_raw .= qq~\$("#checkboxDerby_day_weekly_fixture_id").prop("checked",true) ;~ if $db{$table}{$id}{derby_day_weekly_fixture_id} ; + + &common_shared_build_select_primary_jquery ; + + $trigger_jquery_raw .= qq~ + + const getClientId = () => { + const val = \$clientSelect.val(); + return val ? val.toString().split(":")[0] : null; + }; + + const fillTeamSelect = (\$el, teams) => { + clearSelect(\$el); + teams.forEach(({ id, name }) => { + \$el.append(``); + }); + updateChosen(\$el); + }; + + \$("#checkboxDerby_day_weekly_fixture_id").on("change",function () { + if (\$(this).is(":checked")) { + \$("#checkboxTournament_festival_id").prop("checked",false) ; + \$("#add_existing_home_team").css("display","none") ; + build_teams_from_client() ; + } else { + \$("#checkboxTournament_festival_id").prop("checked",true) ; + \$("#add_existing_home_team").css("display","") ; + } + }) ; + \$("#checkboxTournament_festival_id").change( function () { + if (\$(this).is(":checked")) { + \$("#add_existing_home_team").css("display","") ; + \$("#checkboxDerby_day_weekly_fixture_id").prop("checked",false) ; + } else { + \$("#add_existing_home_team").css("display","none") ; + \$("#checkboxDerby_day_weekly_fixture_id").prop("checked",true) ; + build_teams_from_client() ; + } + }) ; + + + async function build_teams_from_client () { + + const clientId = getClientId() ; + + let teams_ = "[]" ; + + if (clientId) { + let url_teams2 = `$useropts{scripts}/get/get_sss_teams_from_client.pl?client_id=\${clientId}` ; + teams_ = await fetchJSON(url_teams2); + } + + \$("#fixtures_table select[id^='selectHome_team_']").each( function () { + let selected_val = (\$(this).val()) ? \$(this).val() : "" ; + clearSelect(\$(this)); + fillTeamSelect(\$(this),teams_) ; + if (teams_.length === 1) { + \$(this).val(teams_[0].id).trigger("chosen:updated") ; + } else { + \$(this).val(selected_val).trigger("chosen:updated") ; + } + + }) ; + + } + + ~ ; + + $add_form_fields .= &common_min_form_textarea('additional_notes',$db{$table}{$id}{additional_notes}) ; + + $trigger_jquery_raw .= qq~ + // let end_time = new Date("$db{$table}{$id}{end_date_time}") ; + // let start_time = new Date("$db{$table}{$id}{start_date_time}") ; + // \$("#datetimepickerStart_date_time").datetimepicker("setEndDate",end_time) ; + // \$("#datetimepickerEnd_date_time").datetimepicker("setStartDate",start_time) ; + + // let picker = \$("#datetimepickerStart_date_time").data("datetimepicker").endDate.toISOString().slice(0,19).replace('T',' ') ; + // console.log("endDate : "+picker); + + ~ ; + + &analytics_event_bookings_tabs_content_box($sec_name,$sec_col); + + # custom_selected_region" + # custom_selected_country + + $trigger_jquery_raw .= qq~ + + let map_client_to_country = {} ; + let map_region_to_country = {} ; + let map_client_to_region = {} ; + + const \$clientSelect = \$("#selectClient_id") ; + const \$countrySelect = \$("#selectCountry_id") ; + const \$regionSelect = \$("#selectRegion_id") ; + const \$fixturesTable = \$("#fixtures_table"); + + let regionId = \$regionSelect.val() ; + let countryId = \$("#selectCountry_id").val() ; + + // const populateSelect = (\$el, dataList, labelFn) => { + // let lastId = null ; + // for (const data of dataList) { + // \$el.append(``); + // lastId = data.id; + // } + // updateChosen(\$el) ; + // return { count: dataList.length, lastId } ; + // } ; + // const populateSelect = (\$el, list, getLabel) => { + // list.forEach(data => { \$el.append(``); }) ; + // updateChosen(\$el); + // return list.length; + // }; + + // const fillTeamSelect = (\$el, teams) => { + // \$el.empty().append(""); + // teams.forEach(team => { + // \$el.append(``); + // }); + // \$el.val("").trigger("chosen:updated"); + // }; + + + + const getInputValue = name => \$(`input[name='\${name}']`).val(); + const setInputValue = (name, val = "") => \$(`input[name='\${name}']`).val(val); + + + let prev_country_id = \$countrySelect.val() ; + let prev_region_id = \$regionSelect.val() ; + + \$clientSelect.on("change", async function () { + + dispCustomer() ; + + const hasCustomRegion = !!getInputValue('custom_selected_region') ; + const clientId = getClientId() ; + const hasCustomCountry = !!getInputValue('custom_selected_country') ; + + if (clientId && !hasCustomRegion) { + let url1 = `$useropts{scripts}/get/get_region_country_from_client.pl?client_id=\${clientId}` ; + if (!hasCustomRegion || !hasCustomCountry) { + const data = await fetchJSON(url1) ; + data.forEach(({region_id,country_id}) => { + if (region_id == '0') region_id = '' ; + if (country_id == '0') country_id = '' ; + if (\$regionSelect.val() == '13' && (!region_id || hasCustomCountry)) region_id = '13' ; + if (!hasCustomRegion && region_id != \$regionSelect.val()) \$regionSelect.val(region_id).trigger("chosen:updated") ; + if (!hasCustomCountry && country_id != \$countrySelect.val()) \$countrySelect.val(country_id).trigger("chosen:updated") ; + }) ; + } + + } else if (!clientId) { + + if (!hasCustomCountry) \$countrySelect.val("").trigger("chosen:updated") ; + if (!hasCustomRegion && \$regionSelect.val() != '13') \$regionSelect.val("").trigger("chosen:updated") ; + } + + let cnt = 0 ; let teams = "[]" ; + + if (clientId) { + let url_teams2 = `$useropts{scripts}/get/get_sss_teams_from_client.pl?client_id=\${clientId}` ; + teams = await fetchJSON(url_teams2); + } + + if (teams.length > 0 && teams != "[]") { + \$("input[name='home_teams_built_on_regions']").val("") ; + \$("#fixtures_table select[id^='selectHome_team_']").each( function () { + let selected_val = (\$(this).val()) ? \$(this).val() : "" ; + const \$teamSelect = \$(this) ; + clearSelect(\$teamSelect); + fillTeamSelect(\$teamSelect,teams) ; + if (teams.length === 1) { + \$teamSelect.val(teams[0].id).trigger("chosen:updated") ; + } else { + \$teamSelect.val(selected_val).trigger("chosen:updated") ; + } + + }) ; + } else if (\$regionSelect.val() && \$regionSelect.val() != prev_region_id) { + \$("input[name='home_teams_built_on_regions']").val("1") ; + await build_teams_from_region(\$regionSelect.val()) ; + } else if (\$countrySelect.val() && \$countrySelect.val() != prev_country_id) { + \$("input[name='home_teams_built_on_regions']").val("1") ; + await build_teams_from_region("",\$countrySelect.val()) ; + } else if (!\$regionSelect.val() && !\$countrySelect.val() && (\$("input[name='home_teams_built_on_regions']").val() || (!\$("input[name='home_teams_built_on_regions']").val() && !clientId))) { + \$("#fixtures_table select[id^='selectHome_team_']").each(function () { + clearSelect(\$(this)) ; + }) ; + } else if (!\$("input[name='home_teams_built_on_regions']").val() && \$regionSelect.val()) { + \$("input[name='home_teams_built_on_regions']").val("1") ; + await build_teams_from_region(\$regionSelect.val()) ; + } else if (!\$("input[name='home_teams_built_on_regions']").val() && \$countrySelect.val()) { + \$("input[name='home_teams_built_on_regions']").val("1") ; + await build_teams_from_region("",\$countrySelect.val()) ; + } + + prev_country_id = \$countrySelect.val() ; + prev_region_id = \$regionSelect.val() ; + + // else { + // \$("input[name='home_teams_built_on_regions']").val("1") ; + // const away_team_options = \$("#selectAway_team_fixtures_1").children().clone(); + // \$("#fixtures_table select[id^='selectHome_team_']").each( function () { + // let \$teamSelect = \$(this) ; + // clearSelect(\$teamSelect); + // \$teamSelect.append(away_team_options).trigger("chosen:updated") ; + // }) ; + // } + + hide_or_display_buttom_to_add_hometeam_from_existing() ; + + }) ; + + \$countrySelect.on("change", async function () { + + \$("input[name='custom_selected_country']").val("1") ; + await update_region_drop_down(\$countrySelect.val()) ; + if (\$regionSelect.val() && prev_region_id != \$regionSelect.val()) { + await build_teams_from_region(\$regionSelect.val()) ; + } else if (!\$regionSelect.val() && \$countrySelect.val() && prev_country_id != \$countrySelect.val()) { + await build_teams_from_region("",\$countrySelect.val()) ; + } + prev_country_id = \$countrySelect.val() ; + prev_region_id = \$regionSelect.val() ; + + }) ; + + \$regionSelect.on("change", async function () { + + \$("input[name='custom_selected_country']").val("") ; + \$("input[name='custom_selected_region']").val(\$(this).val()) ; + // await build_teams_from_region(\$regionSelect.val()) ; + await select_country_from_region(\$regionSelect.val(),1) ; + \$("input[name='custom_selected_country']").val("1") ; + prev_country_id = \$countrySelect.val() ; + prev_region_id = \$regionSelect.val() ; + // hide_or_display_buttom_to_add_hometeam_from_existing() ; + + }) ; + + function hide_or_display_buttom_to_add_hometeam_from_existing () { + + // // // if ((\$clientSelect.val()) && \$("#selectHome_team_fixtures_1 option").length > 0) { + // // // \$("#add_existing_home_team").css("display","none") ; + // // // } else { + // // // \$("#add_existing_home_team").css("display","") ; + // // // } + } + + async function update_region_drop_down (countryId) { + + if (typeof countryId === 'undefined') { + countryId = "" ; + } + + let region_id = \$regionSelect.val() ; + + clearSelect(\$regionSelect) ; + + const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}`; + + console.log("regionUrl : "+regionUrl) ; + + const regions = await fetchJSON(regionUrl); + + for (const data of regions) { + map_region_to_country[data.id] = countryId; + } + + const regionCount = populateSelect(\$regionSelect, regions, r => r.code ? `\${r.name} [\${r.code}]` : r.name ) ; + + let selectedRegionId = 0 ; + + if (regionCount["count"] === 1) { + selectedRegionId = regions[0].id ; + \$regionSelect.val(regions[0].id) ; + } else if (regionCount["count"] === 0 && \$countrySelect.val()) { + selectedRegionId = 13 ; + \$regionSelect.append(``) ; + } + if (selectedRegionId == 0) \$regionSelect.val(region_id) ; + updateChosen(\$regionSelect) ; + } + + async function select_country_from_region (regionId,update_country=0) { + + if (map_region_to_country[regionId]) { + \$countrySelect.val(map_region_to_country[regionId]).trigger("chosen:updated") ; + } else if (!\$("input[name='custom_selected_country']").val() || update_country) { + // let url_teams1 = "$useropts{scripts}/get/get_country_from_region.pl?region_id="+regionId ; + const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=®ion_id=\${regionId}`; + const regionMeta = await fetchJSON(lookupUrl); + const { country_id } = regionMeta[0] ?? {}; + + if (country_id) { + map_region_to_country[regionId] = country_id; + \$countrySelect.val(country_id).trigger("chosen:updated"); + } + } + } + + async function build_teams_from_region (regionId="",countryId="") { + + let url_teams1 = `$useropts{scripts}/get/get_sss_teams_from_region.pl?region_id=\${regionId}&country_id=\${countryId}` ; + // let tabs = (\$("input[name='home_teams_built_on_regions']").val() == "1") ? "#fixtures_table select[id^='selectHome_team_'],#fixtures_table select[id^='selectAway_team_']" : "#fixtures_table select[id^='selectAway_team_']" ; + + console.log("build_teams_from_region URL : "+url_teams1) ; + + let tabs = (\$("input[name='home_teams_built_on_regions']").val() == "1") ? "#fixtures_table select[id^='selectHome_team_']" : "" ; + const teams = await fetchJSON(url_teams1); + if (tabs != "") { + \$(tabs).each(function () { + const \$teamSelect = \$(this); + clearSelect(\$teamSelect); + fillTeamSelect(\$teamSelect, teams); + }); + } + + } + + ~ ; + + } + + if ($tab == 3) { + + return if $ret; + + my $sec = '_fixtures' ; + + my ($sec_name,$sec_cnt,$sec_col) = &analytics_event_bookings_tabs_sec_det($sec) ; + + $sec = 'fixtures' ; + + $add_form_fields = '' ; + + $lcol = 1; + $fcol = 2; + + our @headers = @fixture_headers ; + our %custom_header = () ; + + push @headers, "Stream Forwarding" ; + push @headers, "Stream Key" ; + push @headers, "Stream URL" ; + + &report_xlsx_export_header("Analytics-Fixtures-$i{id}",'analytics_fixtures') ; + + our $csvpath = "$htmlpath/csv/analytics_fixtures" ; + our $csvname = "Analytics-Fixtures-$i{id}-" . $now_ccyymmdd . $now_hour . $now_min . $now_sec . '.csv' ; ; + + &csv_clear_folder($csvpath,"Analytics-Fixtures-$i{id}") ; + &csv_create_new_file($csvpath,$csvname) ; + + &analytics_event_bookings_tabs_build_fixtures_table_headers(3) ; + &analytics_event_bookings_tabs_build_fixtures_table($id,"$sec") ; + + my $add_box_icon = $box_icon ; + $box_icon = "" ; + + $worksheet{$ws}->set_column(0,0,20) ; + $worksheet{$ws}->set_column(1,3,10) ; + $worksheet{$ws}->set_column(4,4,30) ; + $worksheet{$ws}->set_column(5,5,10) ; + $worksheet{$ws}->set_column(6,6,30) ; + $worksheet{$ws}->set_column(7,8,10) ; + + $box_icon .= qq~ +
    + + + +
    + ~ ; + + &csv_close_file("$csvpath/$csvname") ; + + &report_xlsx_export_footer('L',15,'analytics_fixtures') ; + + if (-f "$csvpath/$csvname") { + # $box_icon .= qq(
    ) ; + } + + $add_form_fields .= qq~
     
    ~ ; + + &analytics_event_bookings_tabs_content_box($sec_name,$sec_col,$box_icon); + + $box_icon = $add_box_icon ; + + $trigger_jquery_raw .= qq~ + function importDoc(t,b) { + dlgMdl("$useropts{'scripts'}/dialog/import_analytics_fixtures.pl?"+t+"&"+b,"Import EXCEL",'height:210px','min-dialog') ; + } + ~; + + $trigger_jquery_raw .= qq~ + \$('[data-toggle="tooltip"]').tooltip({ container: 'body' }); + // \$(' + + + + +
    + + $useropts{short} +

    + $email_msg + $br + + $thead + + $table_msg + +
    +
    +

    $display_notif_msg + Best regards, +
    +
    + The $useropts{short} Team. +

    +
    + + +END_OF_BODY + + return ($mail_body) ; + +} #---------------------------------------------------------------------------------------- + +sub common_email_with_attachments { + + my ($from,$to,$cc,$bcc,$subj,$text_msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication) = @_ ; + + use MIME::Lite; + use Net::SMTP_auth; + + return if $env eq 'DEV' ; + + # # SMTP configuration + # my $smtp_host = $afrihost_smtp ; + # my $smtp_port = $afrihost_port ; + # my $smtp_user = $afrihost_from ; + # my $smtp_pass = $afrihost_psw ; + $from = $afrihost_from ; + + # HTML body part + my $mail_body = &common_get_mail_body($text_msg,$table_msg) ; + + my $fullattachpath = "$attachpath/$attachname"; + die "Attachment file not found: $fullattachpath" unless -e $fullattachpath; + + # === build the MulitPart MIME Message === + + # Create the Message + my $msg = MIME::Lite::->new( + 'From' => "$useropts{short} Events <$from>", + 'Reply-To' => $email_reply_to, + 'To' => $to, + 'Cc' => $cc, + 'Bcc' => $bcc, + 'Subject' => $subj, + 'Type' => 'multipart/mixed', + ); + + # Create the HTML part + my $html_part = MIME::Lite::->new( + 'Type' => 'multipart/related', + ); + + $html_part->attach( + 'Type' => 'text/html', + 'Data' => $mail_body, + ) ; + + # === Attachments === + + my $attachtype = ($attachapplication) ? "application/$attachapplication" : 'AUTO' ; # application/pdf or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet + my $attach_part = MIME::Lite::->new( + 'Type' => 'multipart/mixed', + ); + $attach_part->attach ( + Type => "$attachtype", + Encoding => 'base64', + Path => "$fullattachpath", + Filename => $attachname, + Disposition => 'attachement' + ) ; + + $msg->attach($attach_part); + $msg->attach($html_part); + + my $email = $msg->as_string(); + + my $smtp_msg = Net::SMTP_auth->new('localhost') or die "Can't connect"; + + # my $smtp_msg = Net::SMTP_auth->new($smtp_host, Port=>587) or die "Can't connect"; + # $smtp_msg->auth('PLAIN', $smtp_user, $smtp_pass) or die "Can't authenticate:" . $smtp_msg->message(); + + $smtp_msg->mail($from) or die "Error:" . $smtp_msg->message(); + + $smtp_msg->to($_) for split(/\s*,\s*/, join(',', $to, $cc, $bcc)); + + # $smtp_msg->recipient($to) or die "Error:".$smtp_msg->message(); + $smtp_msg->data() or die "Error:".$smtp_msg->message(); + $smtp_msg->datasend($email) or die "Error:".$smtp_msg->message(); + $smtp_msg->dataend() or die "Error:".$smtp_msg->message(); + $smtp_msg->quit or die "Error:".$smtp_msg->message(); + +} #---------------------------------------------------------------------------------------- + +# sub common_send_mail { + + # my ($to,$cc,$bcc,$html,$thead,$msg,$subj) = @_ ; + + # return unless $msg ; + # return unless $subj ; + + # # my $res = &common_mailsend_sendgrid('html',$to,$subject,$emailmsg,'','','Film Freight','pod@ffwaybill.co.za'); + + # # return if $res eq 'success' ; # carry on if mailsend_sendgrid failed + + # use Mail::Sendmail; + + # my $main_email = 'tickets@interactivetvafrica.com' ; + + # $to = $main_email unless $to ; + + # my %mail = () ; + + # %mail = ( + # smtp => 'localhost', + # From => $main_email, + # To => $to, + # Cc => $cc, + # Bcc => $bcc, + # Subject => $subj + # ); + + # $mail{smtp} = "smtp.interactivetvafrica.com"; + # # $mail{Debug} = 6; + # $mail{port} = 587; + # # $mail{port} = 465; + # $mail{Auth} = {user => $main_email, pass => $send_mail_psw, method => "LOGIN", required => 1}; + + # $mail{body} = < + # + # + # + # $useropts{short} + # + # + # + #
    + # $useropts{short} + #

    + # + # $thead + # + # $msg + # + #
    + #
    + #

    + # Best regards, + #
    + #
    + # The $useropts{short} Team. + #

    + #
    + # + # + + # $boundary-- + +# END_OF_BODY + + # } + + # sendmail(%mail) ; + +# } #------------------------------------------------------------------------------------------ + +# sub common_send_smtp_mail { + + # my ($from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication,$uploaded_doc,$operator_email) = @_ ; + + # &common_debug("common_send_smtp_mail [$from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication,$uploaded_doc,$operator_email]") ; + + # return unless $msg ; + # return unless $subj ; + + # # my $htype = (-f "$attachpath/$attachname" || $uploaded_doc || $operator_email) ? 'htmlattach' : ($html eq 'html') ? $html : 'text' ; + + # # my $res = &common_mailsend_sendgrid($htype,$to,$subj,$msg,$attachpath,$attachname,"$useropts{short} Events",'events@itvadmin.co.za',$cc,$bcc,$uploaded_doc,$operator_email); + + # # return if $res eq 'success' ; # carry on if mailsend_sendgrid failed + + # my $main_email = $email_add{'events'} ; + + # $to = $main_email unless $to ; + # $from = $main_email unless $from ; + + # my $mail_body = ($html) ? &common_get_mail_body($msg,$table_msg,$thead) : $msg ; + + # if ($html) { + + # if (($attachname && -f "$attachpath/$attachname") or $uploaded_doc) { + + # use MIME::Lite; + # use Net::SMTP_auth; + + + # # ################################################################# + # # Lets build the MulitPart MIME Message + # # ################################################################# + # # Create the Message + # my $msg = MIME::Lite::->new( + # 'From' => "$useropts{short} Events <$from>", + # 'Reply-To' => $email_reply_to, + # 'To' => $to, + # 'Cc' => $cc, + # 'Bcc' => $bcc, + # 'Subject' => $subj, + # 'Type' => 'multipart/mixed', + # ); + + # # Create the text part + # # my $text_part = MIME::Lite::->new( + # # 'Type' => 'text/plain', + # # 'Data' => 'Hi\nThis is a test message', + # # ); + + # # Create the HTML part + # my $html_part = MIME::Lite::->new( + # 'Type' => 'multipart/related', + # ); + + # $html_part->attach( + # 'Type' => 'text/html', + # 'Data' => $mail_body, + # ) ; + + # if ($attachname && -f "$attachpath/$attachname") { + # my $attachtype = ($attachapplication) ? "application/$attachapplication" : 'AUTO' ; + # my $attach_part = MIME::Lite::->new( + # 'Type' => 'multipart/mixed', + # ); + # $attach_part->attach ( + # Type => "$attachtype", + # Encoding => 'base64', + # Path => "$attachpath/$attachname", + # Filename => $attachname, + # Disposition => 'attachement' + # ) or &common_send_mail('rory@kre8it.co.za','','','',"$useropts{short} ERROR : common.pm","common_send_smtp_mail cant attach $attachpath/$attachname : $!") ; + # $msg->attach($attach_part); + # } + + # if ($uploaded_doc) { + # my $upload_part = MIME::Lite::->new( + # 'Type' => 'multipart/mixed', + # ); + # $upload_part->attach ( + # Type => 'AUTO', + # FH => $uploaded_doc, + # Filename => $uploaded_doc, + # Disposition => 'attachment' + # ) or die "Error adding : $uploaded_doc $!\n"; + # $msg->attach($upload_part); + # } + + # if ($operator_email) { + # my $attach_flyer = MIME::Lite::->new( + # 'Type' => 'multipart/mixed', + # ); + # $attach_flyer->attach ( + # Type => "application/$attachapplication", + # Encoding => 'base64', + # Path => "$htmlpath/pdf/operator_flyer", + # Filename => "operator_email_attach.pdf", + # Disposition => 'attachement' + # ) or &common_send_mail('handre@kre8it.co.za','','','',"$useropts{short} ERROR : common.pm","common_send_smtp_mail cant attach $attachpath/$attachname : $!") ; + # $msg->attach($attach_flyer); + # } + + # # Now lets attach the text and html parts to the message + # # $msg->attach($text_part); + # $msg->attach($html_part); + + # my $email = $msg->as_string(); + + # # ################################################################# + # # Lets sent the Message + # # ################################################################# + + # my $smtp_msg = Net::SMTP_auth->new($smtp_server, Port=>587) or die "Can't connect"; + # # my $smtp_msg = Net::SMTP_auth->new($smtp_server, Port=>465) or die "Can't connect"; + # $smtp_msg->auth('PLAIN', $main_email, $send_mail_psw_events) or die "Can't authenticate:".$smtp_msg->message(); + + # $smtp_msg->mail($from) or die "Error:".$smtp_msg->message(); + # $smtp_msg->recipient($to) or die "Error:".$smtp_msg->message(); + + # $smtp_msg->data() or die "Error:".$smtp_msg->message(); + # $smtp_msg->datasend($email) or die "Error:".$smtp_msg->message(); + # $smtp_msg->dataend() or die "Error:".$smtp_msg->message(); + # $smtp_msg->quit or die "Error:".$smtp_msg->message(); + + # } else { + # &common_send_mail($to,$cc,$bcc,$html,$thead,$msg,$subj,$table_msg) ; + # } + + # } else { + # &common_send_mail($to,$cc,$bcc,$html,$thead,$msg,$subj,$table_msg) ; + # } + +# } #------------------------------------------------------------------------------------------ + +# sub common_mailsend_sendgrid { + + # local ($qtype,$qemail,$qsubject,$qbody,$qattachfilepath,$qattachfilename,$qfromname,$qfromemail,$qccemail,$qbccemail,$uploaded_doc,$operator_email) = @_; + + # $qccemail =~ s/\;/\,/g ; + # $qbccemail =~ s/\;/\,/g ; + + # use Email::SendGrid::V3; + + # &common_debug("common_mailsend_sendgrid [$qtype,$qemail,$qsubject,$qbody,$qattachfilepath,$qattachfilename,$qfromname,$qfromemail,$qccemail,$qbccemail,$uploaded_doc,$operator_email]") ; + + # #======================= + # #REF1: https://docs.sendgrid.com/for-developers/sending-email/curl-examples + # #REF2: https://github.com/GrantStreetGroup/Email-SendGrid-V3 + # #To Install: + # #cpan -i Email::SendGrid::V3 + # #cd /root/perl5/lib/perl5 + # #cp -R Email /usr/local/lib64/perl5 + # #======================= + + # my $sg = Email::SendGrid::V3->new(api_key => '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'); + + # $qbody =~ s/'/`/gi; + # $qbody =~ s/\r//gi; + # $qbody =~ s/\n//gi; + + # #------------------------------------------------ + # #SEND TEXT ONLY MAIL + # if ($qtype eq "text") { + + # # , cc => [ $qccemail ], bcc => [ $qbccemail ] + + # my %cc_args = ($qccemail) ? (cc => [ "$qccemail" ]) : () ; + # my %bcc_args = ($qbccemail) ? (bcc => [ "$qbccemail" ]) : () ; + + # my $result = $sg->from($qfromemail,$qfromname) + # ->reply_to($email_reply_to, "$useropts{short} Events") + # ->subject($qsubject) + # ->add_content('text/plain', $qbody) + # ->add_envelope( to => [ "$qemail" ], %cc_args, %bcc_args) + # ->send; + + # $qres = $result->{success} ? "success" : "error: " . $result->{reason}; + + # } + + # #------------------------------------------------ + # #SEND HTML ONLY MAIL + # if ($qtype eq "html") { + + # my $logo_domain = ($useropts{web}) ? $useropts{web} : $ENV{SERVER_NAME} ; + + # $qbody = qq~ +# +# +# +# $useropts{short} +# +# +# +#

    +# +#

    +#

    +# $qbody +#

    +#
    +#
    +# +# +# ~; + # my %cc_args = ($qccemail) ? (cc => [ "$qccemail" ]) : () ; + # my %bcc_args = ($qbccemail) ? (bcc => [ "$qbccemail" ]) : () ; + + # my $result = $sg->from($qfromemail,$qfromname) + # ->reply_to($email_reply_to, "$useropts{short} Events") + # ->subject($qsubject) + # ->add_content('text/html', $qbody) + # ->add_envelope( to => [ "$qemail" ], %cc_args, %bcc_args) + # ->send; + + # $qres = $result->{success} ? "success" : "error: " . $result->{reason}; + + # } + + # #------------------------------------------------ + # #SEND HTML WITH ATTACHMENT MAIL + # if ($qtype eq "htmlattach") { + + # my $encodedcontent = &encode_attachment("$qattachfilepath/$qattachfilename"); + + # my %args = ( + # type => 'AUTO', + # disposition => 'attachment' + # ); + + # my $logo_domain = ($useropts{web}) ? $useropts{web} : $ENV{SERVER_NAME} ; + + # $qbody = qq~ +# +# +# +# $useropts{short} +# +# +# +#

    +# +#

    +#

    +# $qbody +#

    +#
    +#
    +# +# +# ~; + + # my @attachments = ($qattachfilename, $encodedcontent, %args) ; + + # if ($uploaded_doc) { + # my $encodedcontent = &encode_attachment("$uploaded_doc") ; + # push @attachments, ($uploaded_doc, $encodedcontent, %args) ; + # } + + # if ($operator_email) { + # my $encodedcontent = &encode_attachment("$htmlpath/pdf/operator_flyer") ; + # push @attachments, ("operator_email_attach.pdf", $encodedcontent, %args) ; + # } + + + # my %cc_args = ($qccemail) ? (cc => [ "$qccemail" ]) : () ; + # my %bcc_args = ($qbccemail) ? (bcc => [ "$qbccemail" ]) : () ; + + # my $result = $sg->from($qfromemail,$qfromname) + # ->reply_to($email_reply_to, "$useropts{short} Events") + # ->subject($qsubject) + # ->add_content('text/html', $qbody) + # ->add_attachment(@attachments) + # ->add_envelope( to => [ "$qemail" ], %cc_args, %bcc_args) + # ->send; + + # $qres = $result->{success} ? "success" : "error: " . $result->{reason}; + + # #NOTE: Cannot use command line cURL here as the body (base64 pdf) is too large - below works for smaller content + # #$qres = `/usr/bin/curl --request POST --url https://api.sendgrid.com/v3/mail/send --header 'authorization: Bearer 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' --header 'Content-Type: application/json' --data '{"personalizations": [{"to": [{"email": "$qemail"}]}],"from": {"email": "no-reply\@myappointment.co.za"},"subject":"$qsubject","content": [{"type": "text/html","value": "$qbody"}], "attachments": [{"content": "$encodedcontent", "type": "text/plain", "filename": "$qattachfilename"}]}'`; + # } + # #------------------------------------------------ + + # &common_debug("common_mailsend_sendgrid [$qres]") ; + + # return "$qres"; + +# } #------------------------------------------------------------------------------------------ + +sub encode_attachment { + + my ($fh) = @_ ; + + use MIME::Base64 qw(encode_base64); + + my $myfilecontents = '' ; + + open (infile, "$fh"); + binmode infile; + while () { + $myfilecontents .= "$_"; + } + close(infile); + + my $encodedcontent = encode_base64($myfilecontents); + + $encodedcontent =~ s/'/`/gi; + $encodedcontent =~ s/\r//gi; + $encodedcontent =~ s/\n//gi; + + return($encodedcontent) ; + +} #------------------------------------------------------------------------------------------ + +sub common_fix_str { + + my ($txt) = @_ ; + + $txt = lc $txt ; + $txt =~ s/\'//iog ; + $txt =~ s/^\s+|\s+$//g; # remove whitespace before and after + local $txt_new = '' ; + foreach (split(/ /,$txt)) { + if ($_ ne 'and' and $_ ne 'or' and $_ ne 'of' and $_ ne 'in') { + $txt_new .= ucfirst $_ ; + } else { + $txt_new .= "$_" ; + } + $txt_new .= ' ' ; + } + chop $txt_new if $txt_new ; + + return ($txt_new) ; + +} #------------------------------------------------------------------------------- + +sub common_date_array { + + my ($from_date, $to_date) = @_ ; + + my $date_array_date = $from_date ; + + @common_date_array = () ; + + # &common_debug ("common_date_array : $from_date, $to_date") ; + + while ($date_array_date <= $to_date) { + + # &common_debug ("common_date_array : push \@common_date_array, $date_array_date") ; + push @common_date_array, $date_array_date ; + + my $array_date_dd = substr($date_array_date,6,2) ; + my $array_date_mm = substr($date_array_date,4,2) ; + my $array_date_ccyy = substr($date_array_date,0,4) ; + + $day_of_week{$date_array_date} = Day_of_Week($array_date_ccyy,$array_date_mm,$array_date_dd) unless $day_of_week{$date_array_date} ; # 1 is Monday + # $day_of_week{"$array_date_ccyy-$array_date_mm-$array_date_dd"} = Day_of_Week($array_date_ccyy,$array_date_mm,$array_date_dd) unless $day_of_week{"$array_date_ccyy-$array_date_mm-$array_date_dd"} ; # 1 is Monday + # $date_hash{$date_array_date} = 1 ; + + my ($ccyy,$month,$day) = Add_Delta_Days($array_date_ccyy,$array_date_mm,$array_date_dd,1) ; + $month = sprintf("%02s", $month) ; + $day = sprintf("%02s", $day) ; + + $date_array_date = "$ccyy$month$day" ; + } + + &common_debug ("common_date_array : @common_date_array") ; + +} #------------------------------------------------------------------------------- + +sub common_clean_json_one { + + my ($txt) = @_ ; + + # $txt =~ s/ //g; + $txt =~ s/\s+//g; # remove all spaces + $txt =~ s/\r\n|\n//g; + $txt =~ s/\t//g; + + $txt = &common_clean_json_two($txt) ; + + return ($txt) ; + +} #---------------------------------------------------------------------------------------- + +sub common_clean_json_two { + + my ($txt) = @_ ; + + $txt =~ s/\r\n|\n/ /g; + $txt =~ s/\t/ /g; + $txt =~ s/\"//g; + $txt =~ s/\'//g; + $txt =~ s/\’//g; + $txt =~ s/\/>/g; + $txt =~ s/\&/&/g; + $txt =~ s/\Ë/E/g; + $txt =~ s/ +/ /g; # remove excess spaces + + return ($txt) ; + +} #---------------------------------------------------------------------------------------- + +sub common_reverse_geocode_osm_address { + + my ($lat,$lng,$typ) = @_ ; + + my $address = '' ; my $decoded_json = '' ; + + my $url = "http://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=$lat&lon=$lng" ; # http://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=-32.851705&lon=24.727521&zoom=18&addressdetails=1&extratags=1 # https://wiki.openstreetmap.org/wiki/Key:highway # Google Roads API : https://roads.googleapis.com/v1/speedLimits?path=-32.851705,24.727521|-32.856349,24.730925|-32.89585,24.693126|-32.923483,24.675421&key=AIzaSyBVeP-dp1VpeceSo-80pukUBFaPsN_mcRw (https://developers.google.com/maps/documentation/roads/speed-limits) + my $json = get ($url) ; # or die "Couldn't get $url : $!"; + + if ($json) { + $decoded_json = decode_json $json ; + } + + if ($typ eq 'min') { + my @add = () ; %gotpart = () ; + push @add, $decoded_json->{'address'}->{'road'} if $decoded_json->{'address'}->{'road'} ; + + my ($suburb,$junk) = split / Ward /, $decoded_json->{'address'}->{'suburb'} ; + my ($suburb,$junk) = split / Industria /, $suburb ; $suburb =~ s/ Industrial//g ; + push @add, $suburb if $suburb ; + + $gotpart{$suburb} = 1 ; + + my $city = $decoded_json->{'address'}->{'city'} ; $city =~ s/ Local Municipality//g ; + + if ($gotpart{$city}) { + push @add, $decoded_json->{'address'}->{'state'} if $decoded_json->{'address'}->{'state'} ; + } else { + push @add, $city if $city ; + } + + my $country = $decoded_json->{'address'}->{'country'} ; + push @add, $country if $country and $country ne 'South Africa' ; + + $address = join ", ", @add ; + } elsif ($json) { + $address = $decoded_json->{'display_name'} ; + &common_debug("[API] common_get_osm_address : [$url] [$address] ") ; + } + + return ($address) ; + +} #---------------------------------------------------------------------------------------- + +sub common_location_osm_address { + + my ($loc) = @_ ; + + my $address = '' ; my $postcode = '' ; my $suburb = '' ; my $city = '' ; my $decoded_json = '' ; + + my $url = "https://nominatim.openstreetmap.org/search?q=$loc&format=json&addressdetails=1" ; + my $json = get ($url) ; # or die "Couldn't get $url : $!"; + + if ($json) { + $decoded_json = decode_json $json ; + } + + &common_debug("[API] common_location_osm_address : [$url] [$decoded_json] ") ; + + if (ref $decoded_json eq 'ARRAY' && @$decoded_json) { + + my $amenity = $decoded_json->[0]->{'address'}->{'amenity'} ; # "Rondebosch Boys' High School" + my $road = $decoded_json->[0]->{'address'}->{'road'} ; # "Canigou Avenue" + $postcode = $decoded_json->[0]->{'address'}->{'postcode'} ; # "7700" + + my @add = () ; %gotpart = () ; + push @add, $amenity if $amenity ; + push @add, $road if $road ; + + ($suburb,$junk) = split / Ward /, $decoded_json->[0]->{'address'}->{'suburb'} ; + ($suburb,$junk) = split / Industria /, $suburb ; $suburb =~ s/ Industrial//g ; + push @add, $suburb if $suburb ; + + $gotpart{$suburb} = 1 ; + + $city = $decoded_json->[0]->{'address'}->{'city'} ; $city =~ s/ Local Municipality//g ; # "Cape Town" + + if ($gotpart{$city}) { + push @add, $decoded_json->[0]->{'address'}->{'state'} if $decoded_json->[0]->{'address'}->{'state'} ; + } else { + push @add, $city if $city ; + } + + my $country = $decoded_json->[0]->{'address'}->{'country'} ; + push @add, $country if $country and $country ne 'South Africa' ; + + $address = join ", ", @add ; + } else { + return ('', '', ''); + } + + &common_debug("[API] common_location_osm_address : [suburb=$suburb] [postcode=$postcode] [address=$address]") ; + + # 0 + # place_id 60085165 + # licence "Data © OpenStreetMap contributors, ODbL 1.0. http://osm.org/copyright" + # osm_type "relation" + # osm_id 3068903 + # lat "-33.9696668" + # lon "18.477931506136713" + # class "amenity" + # type "school" + # place_rank 30 + # importance 0.3041234681398241 + # addresstype "amenity" + # name "Rondebosch Boys' High School" + # display_name "Rondebosch Boys' High School, Canigou Avenue, Cape Town Ward 59, Cape Town, City of Cape Town, Western Cape, 7700, South Africa" + # address + # amenity "Rondebosch Boys' High School" + # road "Canigou Avenue" + # suburb "Cape Town Ward 59" + # city "Cape Town" + # county "City of Cape Town" + # state "Western Cape" + # ISO3166-2-lvl4 "ZA-WC" + # postcode "7700" + # country "South Africa" + # country_code "za" + # boundingbox + # 0 "-33.9728789" + # 1 "-33.9664854" + # 2 "18.4755388" + # 3 "18.4820403" + + return ($suburb,$city,$postcode,$address) ; + +} #---------------------------------------------------------------------------------------- + +sub common_log_changes { + +my ($log,$nline) = @_ ; + +unless ($log) { return ; } + +$nline =~ s/[ ]+/ /g ; # Replaces all occurances of two spaces with one space +$nline =~ s/\n/ /g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc +$nline =~ s/\t/ /g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc +$nline =~ s/\r/ /g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc + +my $logfile = "/home/libs/data/logs/$log"; + +open (LFILE, "+>>$logfile") or die "can't open $logfile : $!" ; +flock (LFILE, LOCK_EX) or die "can't lock $logfile : $!" ; +seek (LFILE, 0, 0) or die "can't rewind $logfile : $!" ; +@lines = ; +seek (LFILE, 0, 0) or die "can't rewind $logfile : $!" ; +truncate (LFILE, 0) or die "can't truncate $logfile : $!" ; + +my @sort_lines = reverse sort @lines ; # put newest ones first + +my $log_cnt = 0 ; + +print LFILE $nline . "\n" ; + +foreach my $line (@sort_lines) { # 20181109104451|||| + + next unless $line ; + + chomp $line; + + @linex = split(/\|/,$line); + + my $data_col = ($linex[4] eq 'changed_from' || $linex[4] =~/action='Add'/ || $linex[4] =~/action='Edit'/) ? 5 : 4 ; + + my $num_of_data_splits = scalar @linex ; + + for ($data_col+1 .. $num_of_data_splits) { + $linex[$data_col] .= qq~|$linex[$_]~ ; + } + + my @changes = split(",","$linex[$data_col]") ; + + my $num_of_changes = scalar @changes ; + + next if $num_of_changes == 1 && ($changes[0] =~ /last_update/) ; + + my $hashkey = $linex[2] . $linex[3] . $linex[$data_col] ; + # my $hashkey = $linex[2] . $linex[3] . $linex[5] . substr($linex[0],0,8) ; + + if ($done_log_line{$hashkey}) { next ; } + + if ($log_cnt > 10000) { last ; } # only retain 10000 lines + + print LFILE "$line\n"; + + $done_log_line{$hashkey} = 1 ; + + $log_cnt++; +} + +close (LFILE) ; + +} #---------------------------------------------------------------------------------------- + +sub common_fix_cell { + +my ($cell) = @_ ; + + $cell =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; + $cell =~ s/amp;//g; + $cell =~ s/\(//g; + $cell =~ s/\)//g; + $cell =~ s/ //g; + + if ($cell == 0) { + return ; + } elsif ((substr($cell,0,1) == 0) and (length($cell) == 10)) { # e.g. 0825564120 + $cell = 27 . substr($cell,1) ; # 27825564120 + } elsif (substr($cell,0,1) eq '+') { + $cell = substr($cell,1) ; # 27825564120 + } + + return ($cell) ; + +} #------------------------------------------------------------------------------------------ + +sub add_extra_region_filter { + + my ($regions_sql) = @_ ; + + my $sql_limit_user_regions = ($is_schools_manager || $is_operator) ? join(' OR ', map { "id = '$_'" } keys %{$glob_regids{$userid}}) : '' ; + + if ($regions_sql && $sql_limit_user_regions) { + $regions_sql = "$regions_sql AND ($sql_limit_user_regions)" ; + } elsif (!$regions_sql && $sql_limit_user_regions) { + $regions_sql = $sql_limit_user_regions ; + } + + return $regions_sql ; + +}#------------------------------------------------------------------------------- + +1; diff --git a/libs/modules/_FromProd/common_min.pm b/libs/modules/_FromProd/common_min.pm new file mode 100644 index 0000000..6be46bc --- /dev/null +++ b/libs/modules/_FromProd/common_min.pm @@ -0,0 +1,3123 @@ +sub common_min_load_params { + +for my $p ($q->param) { + my $val = $q->param($p) ; + $val =~ s/\"//g ; + $i{$p} = $val ; + # &common_min_debug("$p - $val") ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_alert_type { + +if ($error) { + $alert = &common_min_alert('danger',"$error",'remove-sign') ; + } +elsif ($warning) { + $alert = &common_min_alert('warning',"$warning") ; + } +elsif ($success) { + $alert = &common_min_alert('success',"$success",'ok') ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_alert { + +my ($type,$msg,$glyphicon,$id) = @_ ; + +unless ($id) { $id = 'alertmsg'; } +unless ($glyphicon) { $glyphicon = 'exclamation-sign'; } + +my $alert = qq() ; + +return ($alert) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_add_form { + +my ($table,$action,$label_col,$field_col,$ignore_colpart,$skip) = @_ ; + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +my $form = '' ; + +$form .= &common_min_forms_start($table,$skip) ; + +if (%sort_field) { + foreach my $cnt (sort {$a <=> $b} keys %sort_field) { + $col = $sort_field{$cnt} ; + &common_debug("common_min_add_form [sort_field] = $col [$cnt]") ; + $form .= &common_min_forms_loop('',$table,$ignore_colpart) ; + } + } +else + { + foreach (sort { $col_name{$a} cmp $col_name{$b} } keys %col_name) { + $col = $col_name{$_} ; + &common_debug("common_min_add_form = $col [$_]") ; + $form .= &common_min_forms_loop('',$table,$ignore_colpart) ; + } + } + + +$form .= &common_min_forms_end('',$table,$action,$skip) ; + +return ($form) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_edit_form { + +my ($iid,$table,$action,$label_col,$field_col,$ignore_colpart,$skip) = @_ ; + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +my $form = '' ; + +$form .= &common_min_forms_start($table,$skip) ; + +if (%sort_field) { + foreach my $cnt (sort {$a <=> $b} keys %sort_field) { + $col = $sort_field{$cnt} ; + $form .= &common_min_forms_loop($iid,$table,$ignore_colpart) ; + } + } +else + { + foreach $col (sort keys %{$db{$table}{$iid}}) { + $form .= &common_min_forms_loop($iid,$table,$ignore_colpart) ; + } + } + +$form .= &common_min_forms_end($iid,$table,$action,$skip) ; + +return ($form) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_forms_start { + +my ($table,$skip) = @_ ; + +if ($skip) { return ; } + +my $form = qq(
    ) ; + +$form .= $extra_form_fields_start ; + +return ($form) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_forms_loop { + + my ($iid,$table,$ignore_colpart) = @_ ; + + unless ($col) { return('') ; } + + if ($hidden{$col}) { return('') ; } + if ($ignore{$col}) { return('') ; } + + my ($colpart) = split(/\_/,$col) ; + if (($ignore_colpart) and ($ignore{$colpart})) { return('') ; } + + $ucfirst_col = ucfirst $col ; + + my $val = $db{$table}{$iid}{$col} ; + + # $tindex++ ; + + my $form = '' ; + + if ($checkbox{$col}) { + if ($val) { $checked = 'CHECKED'; } else { $checked = ''; } + $form .= &common_min_form_checkbox($col,$val,$checked) ; + return ($form) ; + } + + if ($radio{$col}) { + $form .= &common_min_form_radio($col,$val) ; + return ($form) ; + } + + &common_min_forms_required ; + + # $req_glyph = '' ; + + # if ($required{$col}) { + # if ($required{$col} == 1){ $required{$col} = 'data-validation="required"' ; } + # elsif ($required{$col} == 2){ $required{$col} = 'data-validation="length alphanumeric" data-validation-length="6-6"' ; } + # elsif ($required{$col} == 3){ $required{$col} = 'data-validation="alphanumeric"' ; } + # elsif ($required{$col} == 4){ $required{$col} = 'data-validation="number"' ; } + # elsif ($required{$col} == 5){ $required{$col} = 'data-validation="number" data-validation-allowing="range[0;1]"' ; } + # elsif ($required{$col} == 6){ $required{$col} = 'data-validation="email"' ; } + # elsif ($required{$col} == 7){ $required{$col} = 'data-validation="url"' ; } + + # $req_glyph = qq() ; + # } + + if ($datetimepicker{$col}) { + unless ($val) { $val = $now_ccyy_mm_dd . " $now_hour:$now_min:$now_sec" ; } + $form .= &common_min_form_datetimepicker($col,$val) ; + return ($form) ; + } + + if ($datepicker{$col}) { + unless ($val) { $val = $now_ccyy_mm_dd ; } + $form .= &common_min_form_datepicker($col,$val) ; + return ($form) ; + } + + if ($select{$col}) { + $form .= &common_min_form_select($col,$val) ; + return ($form) ; + } + + if ($textarea{$col}) { + $form .= &common_min_form_textarea($col,$val) ; + return ($form) ; + } + + if ($label{$col}) { + $form .= &common_min_form_label($col,$val) ; + return ($form) ; + } + + if ($add_col{$col}) { + $form .= &common_min_form_input_col($col,$val) ; + } else { + $form .= &common_min_form_input($col,$val) ; + } + + return ($form) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_forms_required { + +$req_glyph{$col} = '' ; + +if ($required{$col}) { + if ($required{$col} == 1){ $required{$col} = 'data-validation="required"' ; } + elsif ($required{$col} == 2){ $required{$col} = 'data-validation="length alphanumeric" data-validation-length="6-6"' ; } + elsif ($required{$col} == 3){ $required{$col} = 'data-validation="alphanumeric"' ; } + elsif ($required{$col} == 4){ $required{$col} = 'data-validation="number"' ; } + elsif ($required{$col} == 5){ $required{$col} = 'data-validation="number" data-validation-allowing="range[0;1]"' ; } + elsif ($required{$col} == 6){ $required{$col} = 'data-validation="email"' ; } + elsif ($required{$col} == 7){ $required{$col} = 'data-validation="url"' ; } + elsif ($required{$col} == 8){ $required{$col} = 'data-validation="" data-validation-allowing="" data-validation-decimal-separator=""' ; } + elsif ($required{$col} == 9){ $required{$col} = 'data-validation="custom" data-validation-regexp="^\d+(\.\d{1,2})?$"' ; } # New condition + elsif ($required{$col} == 10) { $required{$col} = 'data-validation="length number" data-validation-length="10-20"' ; } # 0846758345 or 27846758345 + + $req_glyph{$col} = qq() ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_forms_end { + +my ($iid,$table,$action,$skip) = @_ ; + +if ($skip) { return ; } + +my $form = '' ; + +$form .= $extra_form_fields ; + +foreach (keys %hidden) { + $form .= qq~~ ; +} + +if ($dialog) { + $varbtn = qq~ ~ ; +} else { + $varbtn = qq~ ~ ; +} +# if ($savjqy) { $savbtn = qq() ;} else { $savbtn = qq() ; } + +if ($savjqy) { + my $custom_class = ($invoice_exists && !$useropts{super}{$username} && !$useropts{it}{$username}) ? "custom" : "primary" ; + my $custom_tooltip = ($invoice_exists) ? qq~title data-toggle="tooltip" data-placement="top" data-original-title="Invoice Nr Exists!!!"~ : qq~~ ; + $savbtn = qq~  ~ ; +} elsif ($srchjqy) { + $savbtn = qq~ ~ ; +} elsif ($srchscr) { + $savbtn = qq~ ~ ; +} else { + $savbtn = qq~ ~ ; +} + +if ($addbkb) { + $bakbtn = qq~ ~; +} else { + $bakbtn = qq~~ ; +} + +if ($addcpb) { + $cpybtn = qq~ ~; + &common_min_footer('id',"$lcpage\s"); +} else { + $cpybtn = qq~~ ; +} + +my $custom_class = ($cancel_butt & $invoice_exists && !$useropts{super}{$username} && !$useropts{it}{$username}) ? "custom" : "danger" ; +my $custom_tooltip = ($invoice_exists) ? qq~title data-toggle="tooltip" data-placement="top" data-original-title="Invoice Nr Exists!!!"~ : qq~~ ; +$canxbtn = ($cancel_butt) ? qq~  ~ : '' ; + +$varbtn = $custom_back_button if $custom_back_button ; + +$savbtn = qq~~ if $skip_save_btn ; + +$form .= qq~ +
     
    +
    $savbtn$canxbtn$cpybtn$varbtn$bakbtn
     
    +
    ~ ; + +return ($form) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_columns { + +my ($label_col,$field_col) = @_ ; + +unless ($label_col) { $lcol = 2 ; } else { $lcol = $label_col ; } +unless ($field_col) { $fcol = 4 ; } else { $fcol = $field_col ; } + +return ($lcol,$fcol) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_status { + +my ($closed,$deleted) = @_ ; + +my ($class,$txt) ; + +if ($deleted == 1) { $class = 'danger' ; $txt = 'DELETED' ; $del{$iaction} = 1 ; } +elsif ($closed == 1) { $class = 'success' ; $txt = 'CLOSED' ; $clo{$iaction} = 1 ; } +elsif ($closed == 0) { $class = 'warning' ; $txt = 'ACTIVE' ; $act{$iaction} = 1 ; } + +return ($class,$txt) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_view { + +my ($field,$val,$type,$addclass,$dont_end_row) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +# $vrowcnt++; if ($vrowcnt % 2 == 0) { $bgcolor = '#cecbcb' ; } else { $bgcolor = '#eeeeee' ; } + +$bgcolor = '#eeeeee' ; + +unless ($val) { $val = ' ' ; } + +my $row = qq(
    +
    + +
    +
    +
    +
    + + $val +
    +
    +
    ) ; + +unless ($dont_end_row) { $row .= qq(
    ) ; } + +$row = qq~$row

    ~ if $val =~ /
    / ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_view_col { + +my ($val) = @_ ; + +# my $ucfirst_field = ucfirst $field ; +# my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +# $vrowcnt++; if ($vrowcnt % 2 == 0) { $bgcolor = '#cecbcb' ; } else { $bgcolor = '#eeeeee' ; }
    + +unless ($val) { $val = ' ' ; } + +my $row = qq~ +
    +
    +
    + $val +
    +
    +
    ~ ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_input { + +my ($field,$val,$type,$addclass,$dont_end_row) = @_ ; + +if ($field eq 'password') { $type = 'password' ; } unless ($type) { $type = 'text' ; } if ($cust_class{$field}) { $addclass = $cust_class{$field} ; } + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +if ($type eq 'hidden') { return ("") ; } + +my $labelid = '' ; if ($label_id{$field}) { $labelid = $label_id{$field} ; } + +$tindex++ ; + +$fcol = $fcol{$field} if $fcol{$field} ; + +my $row = '' ; + +if ($add_finish_div{$field}) { $row .= qq~
    ~ ; } + +$row .= qq~
    +
    + +
    +
    +
    +
    + +
    +
    +
    $dlg{$field}~ ; + +if (not $dont_end_row and not $dont_end_row{$field}) { $row .= qq~
    ~ ; } + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_input_col { + +my ($field,$val) = @_ ; + +unless ($type) { $type = 'text' ; } + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } +my $placeholder = $print_field ; if ($preferred_placeholder{$field}) { $placeholder = $preferred_placeholder{$field} ; } +my $field_id = "input$ucfirst_field" ; + +# unless ($excl_on_change{$field}) { push @jquery_workings_trigger_fields, $field_id ; } +unless ($excl_on_change{$field}) { push @jquery_trigger_fields, $field_id ; } + +if ($type eq 'hidden') { return ("") ; } + +$tindex++ ; + +$fcol = $fcol{$field} if $fcol{$field} ; + +my $row = qq~ +
    +
    +
    + +
    +
    +
    + $dlg{$field}~ ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_label { + +my ($field,$val) = @_ ; + +$hidden{$field} = 1 ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } +my $field_id = "label$ucfirst_field" ; + +my $row .= qq~
    +
    + +
    +
    +
    $val
    +
    $dlg{$field}~ ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_label_col { + +my ($field) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } +my $field_id = "label$ucfirst_field" ; + +my $row = qq~
    + +
    ~; + +unless ($excl_on_change{$field}) { push @jquery_trigger_fields, $field_id ; } +# unless ($excl_on_change{$field}) { push @jquery_workings_trigger_fields, $field_id ; } + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_textarea { + +my ($field,$val,$height) = @_ ; + +if ($textarea_height{$field}) { $height = $textarea_height{$field}; } + +unless ($height) { $height = 100; } + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +$tindex++ ; + +my $row = qq~
    +
    + +
    +
    +
    + +
    +
    +
    ~ ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_textarea_col { + +my ($field,$val,$height,$hide) = @_ ; + +if ($textarea_height{$field}) { $height = $textarea_height{$field}; } + +unless ($height) { $height = 100; } + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +$tindex++ ; + +my $hide = ($hide) ? "none" : "" ; + +my $row = qq~ +
    +
    + +
    +
    ~ ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_checkbox { + +my ($field,$val,$checked,$classic) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } +my $check_class = ($classic) ? 'class="iphone-toggle"' : '' ; +# + +$tindex++ ; + +my $row = qq(
    +
    +
    + +
    +
    ) ; + +# + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_checkbox_col { + +my ($field,$val,$checked,$classic) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } +my $field_id = "checkbox$ucfirst_field" ; +my $check_class = ($classic) ? 'class="iphone-toggle"' : '' ; + +my $label = '' ; if ($label{$field}) { $label = "" ; } + +$tindex++ ; + +my $row = qq(
    + + $label +
    ) ; + +unless ($excl_on_change{$field}) { push @jquery_trigger_fields, $field_id ; } +# unless ($excl_on_change{$field}) { push @jquery_workings_trigger_fields, $field_id ; } + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_radio { + +my ($field,$val,$opts) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +my @opts = split(/\+/,$radio_opts{$field}); + +foreach (@opts) { + if ($_ eq $val) { $checked = 'CHECKED'; } else { $checked = ''; } + $print_radios .= qq( $_) ; + } + +my $row = qq(
    +
    +
    + +
    +
    ) ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_select { + +my ($field,$val,$dont_end_row) = @_ ; + +if ($multiple{$field}) { $setmultiple = 'multiple' ; } else { $setmultiple = '' ; } + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +$tindex++ ; + +my $row = qq~
    +
    +
    +
    +
    + +
    +
    +
    + $dlg{$field}~ ; + +unless ($dont_end_row) { $row .= qq~
    ~ ; } + +if ($allow_deselect{$field}) { + if ($minify_jquery) { + push @all_select_ids,"#select$ucfirst_field" if $ucfirst_field ; + } else { + $trigger_jquery_raw .= qq~\$("#select$ucfirst_field").chosen({ allow_single_deselect:true,search_contains:true });~ ; + } +} + +# if ($val) { + # $trigger_jquery_raw .= qq~\$("#select$ucfirst_field").val($val) ; \$("#select$ucfirst_field").trigger("chosen:updated"); ~ ; +# } + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_select_col { + +my ($field,$val) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +if ($multiple{$field}) { $setmultiple = 'multiple' ; } else { $setmultiple = '' ; } + +$tindex++ ; + +my $row = qq~
    +
    +
    + + $dlg_operator{$field} +
    +
    +
    + $dlg{$field}~ ; + +if ($allow_deselect{$field}) { + if ($minify_jquery) { + push @all_select_ids,"#select$ucfirst_field" if $ucfirst_field ; + } else { + $trigger_jquery_raw .= qq~\$("#select$ucfirst_field").chosen({ allow_single_deselect:true });~ ; + } +} + +# if ($val) { + # $trigger_jquery_raw .= qq~\$("#select$ucfirst_field").val($val) ; \$("#select$ucfirst_field").trigger("chosen:updated"); ~ ; +# } + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_datetimepicker { + +my ($field,$val,$diff) = @_ ; + + $diff = 10 unless $diff ; +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +$tindex++ ; + +# if ($field eq 'date_from') { $val = "$now_ccyy_mm_dd $now_hour:00:00" unless $val ; } +if ($field eq 'date_from') { $val = "$now_ccyy_mm_dd 08:00:00" unless $val ; } +if ($field eq 'date_to') { my $hr = sprintf("%02s", $now_hour + 2) ; $val = "$now_ccyy_mm_dd $hr:00:00" unless $val ; } + +my $row = qq(
    +
    +
    +
    +
    + + + + + +
    +
    +
    +
    ) ; + +$trigger_jquery_raw .= qq(\$('#datetimepicker$ucfirst_field').datetimepicker({language: 'pt-BR'}); ) ; + +my @field_name_parts = split(/\_/,$field) ; + +if ($field_name_parts[-1] eq 'from' && !($ENV{'SCRIPT_NAME'} =~ /event_quotes/ && ($ENV{'QUERY_STRING'} =~ /edit/ || $ENV{'QUERY_STRING'} =~ /add/))) { + pop @field_name_parts ; my $field_prefix = join("_",@field_name_parts) ; my $ucfirst_field_prefix = ucfirst $field_prefix ; + if ($ENV{'QUERY_STRING'} =~ /filter/ || $ENV{'QUERY_STRING'} =~ /search/ || $ENV{'SCRIPT_NAME'} =~ /report/) { + $trigger_jquery_raw .= qq~ + \$('#datetimepicker$ucfirst_field_prefix\_from').on('changeDate', function(e) { + var datetimepickerDate_from = \$("input[name='$field_prefix\_from']").val(); + var datetimepickerDate_to = \$("input[name='$field_prefix\_to']").val(); + var newDatetimepickerDate_from = new Date(datetimepickerDate_from); + var newDatetimepickerDate_to = new Date(datetimepickerDate_to); + + if (newDatetimepickerDate_from > newDatetimepickerDate_to) { + newDatetimepickerDate_to = new Date(datetimepickerDate_from); + } + + console.log("datetimepickerDate_from="+datetimepickerDate_from) ; + newDatetimepickerDate_from.setHours(+2); + newDatetimepickerDate_from.setMinutes(0); + newDatetimepickerDate_from.setSeconds(0); + newDatetimepickerDate_from.setMilliseconds(0); + console.log("newDatetimepickerDate_from="+newDatetimepickerDate_from) ; + \$("#datetimepicker$ucfirst_field_prefix\_from").datetimepicker("setDate", newDatetimepickerDate_from); + + + console.log("datetimepickerDate_to="+newDatetimepickerDate_to) ; + newDatetimepickerDate_to.setHours(23+2); + newDatetimepickerDate_to.setMinutes(59); + newDatetimepickerDate_to.setSeconds(59); + newDatetimepickerDate_to.setMilliseconds(59); + console.log("newDatetimepickerDate_to="+newDatetimepickerDate_to) ; + \$("#datetimepicker$ucfirst_field_prefix\_to").datetimepicker("setDate", newDatetimepickerDate_to); + }) ; + \$('#datetimepicker$ucfirst_field_prefix\_to').on('changeDate', function(e) { + var datetimepickerDate_to = \$("input[name='$field_prefix\_to']").val(); + var newDatetimepickerDate_to = new Date(datetimepickerDate_to); + console.log("datetimepickerDate_to="+datetimepickerDate_to) ; + newDatetimepickerDate_to.setHours(23+2); + newDatetimepickerDate_to.setMinutes(59); + newDatetimepickerDate_to.setSeconds(59); + newDatetimepickerDate_to.setMilliseconds(59); + console.log("newDatetimepickerDate_to="+newDatetimepickerDate_to) ; + \$("#datetimepicker$ucfirst_field_prefix\_to").datetimepicker("setDate", newDatetimepickerDate_to); + }) ; + ~; + } else { + $trigger_jquery_raw .= qq~ + if (\$("#datetimepicker$ucfirst_field_prefix\_to").length) { + \$('#datetimepicker$ucfirst_field_prefix\_from').on('changeDate', function(e) { + var datetimepickerDate_from = \$("input[name='$field_prefix\_from']").val(); + console.log("datetimepickerDate_from="+datetimepickerDate_from) ; + + if (datetimepickerDate_from) { + // Parse datetimepickerDate_from value to a Date object + var datetimepickerDate_to = new Date(datetimepickerDate_from); + console.log("datetimepickerDate_to="+datetimepickerDate_to) ; + + // Add 2 hours to datetimepickerDate_from value + // datetimepickerDate_to.setHours(datetimepickerDate_to.getHours() + $diff); + datetimepickerDate_to.setHours(datetimepickerDate_to.getHours() + $diff); + console.log("datetimepickerDate_to="+datetimepickerDate_to) ; + \$("#datetimepicker$ucfirst_field_prefix\_to").datetimepicker("setDate", datetimepickerDate_to); + } + }) ; + } + ~; + } +} + +return ($row) ; + +# + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_datepicker { + +my ($field,$val,$label,$dont_end_row) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($label) { $print_field = $label ; } if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +if ($val eq '0000-00-00') { $val = '' ; } + +$tindex++ ; + +my $row = qq~
    +
    +
    +
    +
    + + + + +
    +
    +
    + ~ ; + +unless ($dont_end_row) { + $row .= qq~ +
    + ~ ; +} + +&common_min_form_datepicker_jquery($ucfirst_field); + +return ($row) ; + +# + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_datepicker_col { + +my ($field,$val,$end_row) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +$tindex++ ; + +if ($val eq '0000-00-00') { $val = '' ; } + +my $row = qq(
    +
    +
    + + + + +
    +
    +
    ) ; + +$row .= qq~
    ~ if $end_row ; + +&common_min_form_datepicker_jquery($ucfirst_field); + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_datepicker_jquery { + + my ($ucfirst_field) = @_ ; + + $trigger_jquery_raw .= qq~ + \$('#datepicker$ucfirst_field').datepicker({ + format: "yyyy-mm-dd"}).on('changeDate', function (ev) { + \$('.datepicker').hide(); + }) ; + ~ ; + + my $lc_field = lc $ucfirst_field ; + my @field_name_parts = split(/\_/,$lc_field) ; + + # if ($field_name_parts[-1] eq 'from') { + # pop @field_name_parts ; my $field_prefix = join("_",@field_name_parts) ; my $ucfirst_field_prefix = ucfirst $field_prefix ; + # $trigger_jquery_raw .= qq~ + # if (\$("#datepicker$ucfirst_field_prefix\_to").length) { + # // \$('#datepicker$ucfirst_field_prefix\_from').on('changeDate', function(e) { + # // var datepickerDate_from = \$("input[name='$field_prefix\_from']").val(); + # // console.log("datepickerDate_from [$field_prefix\_from]="+datepickerDate_from) ; + + # // if (datepickerDate_from) { + # // // Parse datepickerDate_from value to a Date object + # // var datepickerDate_to = new Date(datepickerDate_from); + # // console.log("datepickerDate_to="+datepickerDate_to) ; + # // // Add 1 month to datepickerDate_from value + # // datepickerDate_to.setMonth(datepickerDate_to.getMonth() + 1); + # // // var formattedDate = \$("#datepicker$ucfirst_field_prefix\_to").formatDate("yyyy-mm-dd", new Date(datepickerDate_to)); + # // // console.log("datepickerDate_to [datepicker$ucfirst_field_prefix\_to]="+datepickerDate_to+" ["+formattedDate+"]") ; + # // console.log("datepickerDate_to [datepicker$ucfirst_field_prefix\_to]="+datepickerDate_to) ; + # // // \$("#datepicker$ucfirst_field_prefix\_to").datepicker("setDate", new Date(datepickerDate_to)); + # // // \$("#datepicker$ucfirst_field_prefix\_to").setDate(datepickerDate_to); + # // } + # // }) ; + # var nowTemp = new Date(); + # var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0); + + # var from = \$('#datepicker$ucfirst_field_prefix\_from').datepicker({ + # format: "yyyy-mm-dd", + # onRender: function (date) { + # return date.valueOf() < now.valueOf() ? 'disabled' : ''; + # } + # }).on('changeDate', function (ev) { + # if (ev.date.valueOf() > to.date.valueOf()) { + # var newDate = new Date(ev.date) + # newDate.setDate(newDate.getDate() + 30); + # to.setValue(newDate); + # } + # // from.hide(); + # \$('#datepicker$ucfirst_field_prefix\_to')[0].focus(); + # }).data('datepicker'); + # var to = \$('#datepicker$ucfirst_field_prefix\_to').datepicker({ + # format: "yyyy-mm-dd", + # onRender: function (date) { + # return (date.valueOf() < now.valueOf()) && (date.valueOf() >= from.date.valueOf()) ? 'disabled' : ''; + # } + # }).on('changeDate', function (ev) { + # // to.hide(); + # }).data('datepicker'); + # } + # ~; + # } + +} #------------------------------------------------------------------------------------------ + +# sub common_min_form_datepicker { + +# my ($field,$val) = @_ ; + +# my $ucfirst_field = ucfirst $field ; +# my $print_field = &common_min_print_field($field) ; + +# my $row = qq(
    + #
    + #
    + #
    + #
    + # + # + # + # + # + #
    + #
    + #
    + #
    ) ; + +# $trigger_jquery_raw .= qq(\$('#datetimepicker$ucfirst_field').datetimepicker({language: 'pt-BR'}); ) ; + +# # $trigger_jquery_raw .= qq( +# # \$('#datepicker$ucfirst_field').datepicker({ + # # format: "yyyy-mm-dd"}).on('changeDate', function (ev) { + # # \$('.datepicker').hide(); + # # }) ; +# # ) ; + +# return ($row) ; + +# } #------------------------------------------------------------------------------------------ + +sub common_min_form_timepicker_col { + + my ($field,$val,$diff) = @_; + + $diff = 10 unless $diff; + my $ucfirst_field = ucfirst $field; + my $print_field = ($preferred_title{$field}) ? $preferred_title{$field} : &common_min_print_field($field) ; + + $tindex++; + + my $row = qq~ +
    +
    +
    + + + + +
    +
    +
    + ~ ; + + $trigger_jquery_raw .= qq(\$('#timepicker$ucfirst_field').datetimepicker({language:'pt-BR',pickDate:false});) ; + + return $row ; + +} #------------------------------------------------------------------------------------------ + +# # sub common_min_form_radio_col { + + # # my ($field,$val,$opts) = @_ ; + + # # my $ucfirst_field = ucfirst $field ; + # # my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + + # # my @opts = split(/\+/,$radio_opts{$field}); my $cnt = 0 ; + + # # foreach (@opts) { + # # my $value = $_ ; $value = lc $value ; $value =~ s/ /\_/g ; $cnt++ ; + # # if ($value eq $val) { $checked = 'CHECKED'; } else { $checked = ''; } + # # $print_radios .= qq~
     $_
    ~ ; #### WHY NOT class="radio col-md-$fcol" ????????????? + # # } + + # # my $row = qq~
    + # # + # # + # #
    + # # $print_radios~ ; + + # # for (1 .. $cnt) { + # # $trigger_jquery_raw .= qq~ + # # \$("#radio_$_").change(function () { + # # if(\$(this).is(":checked")) { + # # let sel_val = \$("#radio_$_").val() ; + # # console.log("sel_val : "+sel_val) ; + # # \$("#selected_$field").val(sel_val) ; + # # } + # # }) ; + # # ~ ; + # # } + + # # return ($row) ; + +# # } #------------------------------------------------------------------------------------------ + +sub common_min_form_radio_col { + + my ($field,$val,$opts,$columns,$nr_of_columns_to_display,$radio_row_id,$row_cnt,$display_horizontally) = @_ ; + + + # my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + + $nr_of_columns_to_display = $columns unless $nr_of_columns_to_display ; + + $row_cnt = 1 unless $row_cnt ; + + my %display = () ; + for ($nr_of_columns_to_display+1 .. 10) { + $display{$_} = qq~style="display:none;"~ ; + } + $display{row} = qq~style="display:none;"~ if $nr_of_columns_to_display < 0 ; ## HIDE SECOND ROW BY DEFAULT + + my @default_checked = split(/\;/,$val) ; my $print_radios = qq~~ ; my @opts = split(/\+/,$radio_opts{$field}); my $cnt = 0 ; my $ucfirst_field = ucfirst $field ; + + $print_radios .= qq~
    ~ if $display_horizontally ; + + foreach my $option (@opts) { + + $cnt++ ; + + my $row_id = ($radio_row_id) ? "$radio_row_id\_$cnt" : "" ; + + # my $print_field = ucfirst $option; + + $print_radios .= qq~
    ~ unless $display_horizontally ; + + my $align = qq~align='right'~ if $display_horizontally ; + + $print_radios .= qq~ +
    + +
    ~ ; + for (1 .. $columns) { + my $value = $option; $value = lc $value ; $value =~ s/ /\_/g ; + + my $radio_nr = ($display_horizontally) ? $display_horizontally : ($row_cnt*$columns - $columns) + $_ ; + + if ($value eq $default_checked[$radio_nr - 1]) { $checked = 'CHECKED'; } else { $checked = ''; } + + $print_radios .= qq~~ if $cnt == 1 ; + $print_radios .= qq~ +
    + +
    + ~ ; + } + + $print_radios .= qq~ +
    + ~ unless $display_horizontally ; #### WHY NOT class="radio col-md-$fcol" ????????????? + } + + $print_radios .= qq~ +
    + ~ if $display_horizontally ; + + my $row = qq~$print_radios~ ; + + my @radio_ids = () ; my $radio_to_selected = qq~~ ; + + for my $option_cnt (1 .. $cnt) { + for (1 .. $columns) { + push @radio_ids,"#radio_$_\_$option_cnt" ; + $radio_to_selected .= qq~"radio_$_\_$option_cnt":"selected_$_\_$option_cnt",~ ; + } + } + + chop $radio_to_selected if $radio_to_selected ; + my $radio_ids_string = join(",",@radio_ids) ; + $trigger_jquery_raw .= qq~ + \$("$radio_ids_string").change(function () { + if (\$(this).is(":checked")) { + const id = this.id ; + const radio_to_selected = {$radio_to_selected} ; + let sel_val = \$(this).val() ; + // console.log("sel_val : "+sel_val) ; + \$("#"+radio_to_selected[id]).val(sel_val) ; + } + }) ; + ~ ; + + return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_print_field { + +my ($txt) = @_ ; + +if (($testing == 1) and ($username eq 'rory')) { return($txt) ; } + +if ($addid{$txt}) { $addtxt = ' ID' ; } else { $addtxt = '' ; } + +$txt =~ s/\_id/ /gi ; + +@strings = split(/\_/,$txt) ; +@strings_ucf = map(ucfirst, map(lc,@strings)); +$txt = join(' ', @strings_ucf); +$txt .= $addtxt ; + +return ($txt) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table { + +my ($id,$page,$list,$sort_col,$do_not_auto_sort_table) = @_ ; + +unless ($sort_col) { $sort_col = 0 ; } if ($fnsortcol) { $sort_col = $fnsortcol ; } + +my $sort_order = ($do_not_auto_sort_table) ? '' : 'desc' ; if ($fnsortorder) { $sort_order = $fnsortorder; } + +$print_box_content_rows .= qq~ + + $print_thead + + $print_tbody + +
    ~ ; + +if ($list) { $trigger_jquery .= qq~var oTable = \$('#itv-table').dataTable(); oTable.fnSort( [ [$sort_col,'$sort_order'] ] );~ ; } + +&common_min_footer($id,$page); + +} #------------------------------------------------------------------------------------------ + +sub common_min_footer { + +my ($id,$page) = @_ ; + +if ($uniq_id) { $id = $uniq_id ; } + +$print_footer_jscript = qq( +) ; + +if ($page && $ENV{SCRIPT_NAME} =~ /\_test/) { $page .= '-test' ; } + +if ($page) { $action_delete = qq(delete-$page) ; $action_edit = qq(edit-$page) ; $action_view = qq(view-$page) ; $action_copy = qq(copy-$page) ; } else { $action_delete = '' ; $action_edit = '' ; $action_view = '' ; $action_copy = '' ; } + +if ($blank_action) { $action_delete = '' ; $action_edit = '' ; $action_view = '' ; $action_copy = '' ; } + +$print_footer_forms .= qq~ +
    + + +
    + +
    + + +$extra_edit_hidden_inputs +
    + +
    + + +
    + +
    + + +$extra_edit_hidden_inputs +
    +~ ; + +} #------------------------------------------------------------------------------------------ + +# sub common_min_select_opts { + +# my ($field,$table,$valfield,$fid,$required,$addfield,$where) = @_ ; + +# $select{$field} = 1 ; + +# if ($required) { $required{$field} = 1 ; } + +# &db_min_ro($table,'*',$where,'','') ; + +# foreach my $id (keys %{$db{$table}}) { + # if ($fid == $id) { $selected = 'selected="selected"'; } else { $selected = ''; } + + # # &common_min_debug("common_min_select_opts - $fid == $id [$valfield] [$table] [$db{$table}{$id}{$valfield}] [[$table][$id][$valfield]]") ; + + # if ($db{$table}{$id}{$addfield}) { $disp_addfield = " ($db{$table}{$id}{$addfield})" ; } else { $disp_addfield = '' ; } + # if ($extra{$table}{$id}{$addfield}) { $disp_addfield = " $extra{$table}{$id}{$addfield}" ; } else { $disp_addfield = '' ; } + # $opts{$field} .= qq() ; + # } + +# } #------------------------------------------------------------------------------------------ + +sub common_min_select_opts { + + my ($field,$table,$dispfield,$fid,$required,$addfield,$where,$valfield,$addmore,$select,$order_dropdown) = @_ ; + + $select{$field} = 1 ; + + my $val = '' ; + + # $select = '*' unless $select; + + unless ($select) { $select = '*' ; } + + # &common_min_debug("common_min_select_opts:$field,$table,$dispfield,$fid,$required,$addfield,$where,$valfield,$addmore,$select") ; + + if ($required) { $required{$field} = 1 ; } + + # if ($dispfield){ + # my $orderby = "' $dispfield '" ; + # } else { + # my $orderby = ' id DESC ' ; + # } + + my $orderby = ($dispfield) ? "' $dispfield '" : ' id DESC' ; + + &db_min_ro($table,$select,$where,$orderby,'') ; + + $order_dropdown = $dispfield if $dispfield and not $order_dropdown ; + + unless ($order_dropdown) { + foreach my $id (keys %{$db{$table}}) { + foreach (keys %{$db{$table}{$id}}) { + $order_dropdown = $_ ; + last ; + } + last ; + } + } + + foreach my $id (sort {$db{$table}{$a}{$order_dropdown} cmp $db{$table}{$b}{$order_dropdown}}keys %{$db{$table}}) { + + $selected = ($fid && ($fid eq $db{$table}{$id}{$valfield} || $fid == $id)) ? 'SELECTED' : '' ; + + # if ($table eq 'regions') { &common_debug("$selected = ($fid and ($fid eq $db{$table}{$id}{$valfield} || $fid == $id)) ? 'SELECTED' : '' ;") ; } + + if ($db{$table}{$id}{$addfield} && $db{$table}{$id}{$dispfield} ne $db{$table}{$id}{$addfield}) { $disp_addfield = " [$db{$table}{$id}{$addfield}]" ; } else { $disp_addfield = '' ; } + + my $disp_addmore = '' ; + + if ($display_addmore{$table}{$addmore}) { + my $glyph = '' ; + if ($db{$table}{$id}{$addmore} == 1) { + # $glyph = qq(); + $disp_addmore = " - $addmore" ; + } + } + + if ($valfield) { $val = $db{$table}{$id}{$valfield} ; } else { $val = $id ; } + + # if ($table eq 'regions') { &common_debug("filter_select_opts = $filter_select_opts{$table}, filter_val = $filter_val{$table}{$val} [$val] valfield=$valfield") ; } + + if ($filter_select_opts{$table} == 1) { + next unless $filter_val{$table}{$val} == 1 ; + } + + # if ($table eq 'countries') { &common_debug("$field : [$val] $db{$table}{$id}{$dispfield}$disp_addfield$disp_addmore") ; } + + # &common_debug("table=$table, id=$id, val=$val, dispfield=$dispfield [$db{$table}{$id}{$dispfield}]") ; + + $opts{$field} .= qq~~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_box_top { + +my ($glyphicon,$title,$bgcolor,$boxicon,$chevronid) = @_ ; + +# f5af19 +if ($bgcolor) { $box_header_style = qq~style="background:#$bgcolor;color:#ffffff;"~ ; } else { $box_header_style = '' ; } +if ($chevronid) { $box_chevron_id = qq~id="$chevronid"~ ; } else { $box_chevron_id = '' ; } + +my $box = qq~

    $title

    $boxicon
    ~ ; + +return($box) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_box_foot { + +my $box = qq(
    ) ; + +return ($box) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_extra_crumb { + +my ($crumb_url,$crumb_txt) = @_ ; + +$crumb_txt =~ s/\-/ /g; my @crumbs = split(/ /,$crumb_txt); my @crumbs_ucf = map ucfirst, @crumbs; $crumb_txt = join(' ',@crumbs_ucf) ; + +$insert_crumbs .= qq(
  • $crumb_txt
  • ) ; + +&config_set_breadcrumbs ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_dialog { + +$dialog{'common'}{'head'} = qq( + + + + $useropts{title} + + + + + + + + + + + + + $extra_dialog_js + + + + +) ; + +# table>thead>tr>th, .table>thead>tr>th, table>tbody>tr>th, .table>tbody>tr>th, table>tfoot>tr>th, .table>tfoot>tr>th, table>thead>tr>td, .table>thead>tr>td, table>tbody>tr>td, .table>tbody>tr>td, table>tfoot>tr>td, .table>tfoot>tr>td { border: 1px solid black; } +# .table>caption+thead>tr:first-child>th, .table>colgroup+thead>tr:first-child>th, .table>thead:first-child>tr:first-child>th, .table>caption+thead>tr:first-child>td, .table>colgroup+thead>tr:first-child>td, .table>thead:first-child>tr:first-child>td { border-top: 1px solid black; } + +$dialog{'common'}{'js'} = qq( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +) ; + +} #------------------------------------------------------------------------------------ + +sub common_min_commify { + +local($_) = shift; +1 while s/^(-?\d+)(\d{3})/$1,$2/; +return $_; + +} #------------------------------------------------------------------------------- + +sub common_min_debug { + +my ($msg) = @_ ; + +unless ($username eq 'rory') { return ; } +unless (($testing == 1) or ($debug == 1)) { return ; } + +print "\n" . $msg ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_action { + +if ($iaction eq 'add'){ + &common_min_add_screen; + &common_min_screen1; + } + +if ($iaction eq 'list' or $iaction eq 'detailed' or $iaction eq 'summary' or $iaction eq 'accepted' or $iaction eq 'pending' or $iaction eq 'closed' or $iaction eq 'all' or $iaction eq 'open' or $iaction eq 'active') { + &list_screen ; + &common_min_screen3; + } + +if ($iaction eq 'display'){ + &list_screen ; + &common_min_screen3; + } + +if ($iaction eq 'view'){ + &common_min_load_params ; + &common_min_view_screen ; + &common_min_screen1; + } + +if ($iaction eq 'edit'){ + &common_min_load_params ; + &common_min_edit_screen ; + &common_min_screen1; + } + +if ($iaction eq 'save'){ + &common_min_load_params ; + &validate ; + &insert ; + &common_min_screen2; + } + +if ($iaction eq 'update'){ + &common_min_load_params ; + &update ; + &common_min_screen2; + } + +if ($iaction eq 'delete'){ + &common_min_load_params ; + &common_min_delete ; + &common_min_screen2; + } + +if ($iaction eq 'copy'){ + &common_min_load_params ; + &duplicate ; ### Will cause error if using use File::Copy;, do not use sub copy { .. } ... + &common_min_edit_screen; + &common_min_screen1; + } + +if ($iaction eq 'search'){ + $srchscr = 1 ; + &report_screen ; + } + +if ($iaction eq 'filter'){ + $srchscr = 1 ; + &filter_screen ; + } + +if ($iaction eq 'report'){ + &common_min_load_params ; + &report_ifields; + &list_screen ; + &common_min_screen3; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_add_screen { + +&add_screen; + +%col_name = () ; + +my $dbid = 'id' ; if ($uniq_id) { $dbid = $uniq_id ; } + +&db_min_ro($table,'*',"$dbid > 0 AND $dbid < 10",'','') ; + +$page_title = 'Add' ; + +&add_db_fields ; + +unless ($double_box_layout) { $print_box_content_rows = &common_min_add_form($table,'save') ; } + +} #------------------------------------------------------------------------------------------ + +sub common_min_error_screen { + + $page_title = ($iaction eq 'save') ? 'Add' : "Edit $i{id}" ; + + foreach (keys %i) { $db{$table}{''}{$_} = $i{$_} ; } # reset other fields after &db_common_ro($table,'*','','id DESC',1) ; ## ALSO CHECK THAT THIS INCLUDES ALL THE FIELD IN ON SCREEN!!! + + &add_screen; # must occur before %col_name set to blank otherwise will include all previous columns + + %col_name = () ; + + &add_db_fields ; + + unless ($double_box_layout) { $print_box_content_rows = &common_min_add_form($table,'save') ; } + +} #------------------------------------------------------------------------------------------ + +sub common_min_edit_screen { + +my $dbid = 'id' ; if ($uniq_id) { $dbid = $uniq_id ; } + +unless ($i{$dbid}) { $warning = uc "NO $dbid" ; return ; } + +&db_min_ro($table,'*',"`$dbid`='$i{$dbid}'",'','') ; + +$page_title = 'Edit' ; +$page_title .= " : $i{$dbid}" ; + +&edit_db_fields ; + +&edit_screen; + +unless ($double_box_layout) { $print_box_content_rows = &common_min_edit_form($i{$dbid},$table,'update') ; } + +} #------------------------------------------------------------------------------------------ + +sub common_min_view_screen { + +my $dbid = 'id' ; if ($uniq_id) { $dbid = $uniq_id ; } + +unless ($i{$dbid}) { $warning = uc "NO $dbid" ; return ; } + +&db_min_ro($table,'*',"`$dbid`='$i{$dbid}'",'','') ; + +$page_title = 'View' ; +$page_title .= " : $i{$dbid}" ; + +&view_db_fields ; + +&view_screen($i{$dbid}); + +} #------------------------------------------------------------------------------------------ + +sub common_min_delete { + +my $dbid = 'id' ; if ($uniq_id) { $dbid = $uniq_id ; } + +unless ($i{$dbid}) { $error = uc "NO $dbid" ; return ; } + +&db_min_delete($table,"$dbid='$i{$dbid}'") ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_search_screen { + +&thead; + +&common_min_alert_type ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_thead { + +$print_thead = qq() ; + +foreach (@sql_col_display) { + my $coltitle = $_ ; $coltitle =~ s/\_id//g ; $coltitle =~ s/\_/ /g ; $coltitle = uc $coltitle ; $coltitle = $replace_blank_table_top_right if $coltitle eq '' and $replace_blank_table_top_right ; + # $custom_column_styles{$_} = qq~style="min-width:120px;"~ unless $custom_column_styles{$_} ; + $print_thead .= qq($coltitle); +} + +if ($add_th_row) { $print_thead .= $add_th_row ; } # used in agent_commission_report.pl and cruiseline_commission_report.pl + +$print_thead .= qq() ; + +} #------------------------------------------------------------------------------- + +sub common_min_split_sql_date_time { + +my ($datetime) = @_ ; + +my ($date,$time) = split(/ /,$datetime) ; + +my $dy = substr($date,0,4) ; +my $dm = substr($date,5,2) ; +my $dd = substr($date,8,2) ; + +my ($th,$tm,$ts) = split(/:/,$time) ; + +return($dy,$dm,$dd,$th,$tm,$ts) ; + +} #------------------------------------------------------------------------------- + +sub common_min_convert_sql_date_time { + +my ($datetime) = @_ ; + +my ($date,$time) = split(/ /,$datetime) ; + +my $dy = substr($date,0,4) ; +my $dm = substr($date,5,2) ; +my $dd = substr($date,8,2) ; + +my ($th,$tm,$ts) = split(/:/,$time) ; + +my $return = "$dy$dm$dd" ; if ($time) { $return .= "$th$tm$ts" ; } + +return($return) ; + +} #------------------------------------------------------------------------------- + +sub common_min_restriction_super { + +unless ($useropts{super}{lc $username}){ print "This page is restricted!" ; exit ; } + +} #------------------------------------------------------------------------------- + +sub common_min_add_extras { + +my $page = "$lcpage\s" ; if ($s{no}) { $page = $lcpage ; } + +$box_icon = qq(
    ) ; + +$useropts{'common'}{'css'} .= qq(.box-icon a i { top:1px; } .iPhoneCheckContainer { margin:2px 0 2px 0; } .iPhoneCheckContainer label { font-size: 14px; line-height: 14px; padding-top:7px; } .iPhoneCheckLabelOff { padding-right:5px; } ) ; + +# $extra_css .= qq~~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_add_box_icon { + +my $page = "$lcpage\s" ; if ($s{no}) { $page = $lcpage ; } + +$box_icon = qq(
    ) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_screen1 { + +&thead; + +&common_min_alert_type ; + +my $page = "$lcpage\s" ; if ($s{no}) { $page = $lcpage ; } +my $ucfpage = "$ucfirstpage\s" ; if ($s{no}) { $ucfpage = $ucfirstpage ; } + +unless ($redirtype) { $redirtype = 'list' ; } my $pname = ucfirst $redirtype ; + +&common_min_extra_crumb("$redirtype-$page","$pname $ucfpage") ; + +# &common_min_extra_crumb("list-$page","List $ucfpage") ; + +if ($cust_cols or $double_box_layout) { + require _blank_3 ; + } +else + { + require _blank ; + } + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_screen2 { + +my $page = "$lcpage\s" ; if ($s{no}) { $page = $lcpage ; } + +unless ($redirsave) { $redirsave = 'list' ; } +# unless ($redirsave) { $redirsave = 'edit' ; } + +if ($i{id} and $iaction ne 'delete') { + &common_min_edit_screen ; + &common_min_screen1; + # $input_hidden_id = qq~~ ; +} + +# # if ($i{id} && $redirsave eq 'edit') { +# if ($redirsave eq 'edit') { + # $input_hidden_id = qq~~ ; +# } + +# my $doc_ready_jquery = qq~\$(document).ready(function(){ \$('#$redirsave-form').submit(); })~ unless $username eq 'rory' ; + +my $form_name = $redirsave . 'form' ; + +&common_min_alert_type ; + +print < + + + + $useropts{title} + + + + + + +
    + + +$input_hidden_id +
    + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +my $page = "$lcpage\s" ; if ($s{no}) { $page = $lcpage ; } + +&common_min_table('id',$page,'list') ; + +# &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_opts { + +my ($whichone,$field,$deselect) = @_ ; + +if ($whichone eq 'leave_type') { + $required{$field} = 1 ; + $select{$field} = 1 ; + $opts{$field} = qq( + + + + ) ; + } + +my $ucfirst_field = ucfirst $field ; + +if ($deselect){ + $trigger_jquery_raw .= qq(\$("#select$ucfirst_field").chosen({ allow_single_deselect:true });) ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_dialog_load_screen { + +&dialog_common ; + +print < + + + $alert + +
    +
    +
    +
    + $print_box_content_rows +
    +
    +
    +
    + + + + + + + + + + + + + + + +ENDOFTEXT +# + +exit; + +} #------------------------------------------------------------------------------------------ + +sub common_min_dialog_save_screen { + +print < + + + + ITV Admin + + + + + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_validate_date_inputs_jquery { + + my $date_value_ids_str = join(",",@date_value_ids) ; + + return unless $date_value_ids_str ; + + $trigger_jquery_raw .= qq~ + + function isLeapYear(year) { + return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0); + } + + function isValidDate(dateString) { + + let count_comp = 0 ; let found_non_int = 0 ; + + for (let key in dateString.split('-').map(Number)) { + count_comp++ ; + if (dateString.split('-').map(Number)[key] != parseInt(dateString.split('-').map(Number)[key])) { + found_non_int = 1 ; + } + } + + if (count_comp != 3 || found_non_int) { + return false + } else { + return true ; + } + + } + + \$("$date_value_ids_str").change( function () { + + // console.log("date_value_ids_str : $date_value_ids_str") ; + + const dateInput = \$(this).val() ; + + if (!dateInput) { + return ; + } + + let result = "" ; + + if (!isValidDate(dateInput)) { + result = "Invalid Date Format!!!"; + } + + let [inputYear,inputMonth,inputDay] = dateInput.split("-").map(Number); + + if (inputYear > 2100 || inputYear < 2000) { + if (result) { + result = result + "
    "; + } + result = result + "Invalid Year!!!"; + } + + if (inputMonth < 1 || inputMonth > 12) { + if (result) { + result = result + "
    "; + } + result = result + "Invalid Month!!!"; + } + + const daysInMonth = [31, (isLeapYear(inputYear) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + + if (inputDay < 1 || inputDay > daysInMonth[inputMonth - 1]) { + if (result) { + result = result + "
    "; + } + result = result + "Invalid Day!!!"; + } + + if (result) { + + noty({text:result,layout:"center",type:"error",timeout:3000}) ; + + } else { + + let correct_day_or_month_format = 0 ; + + if (inputMonth > 0 && inputMonth < 10) { + inputMonth = inputMonth.toString() ; + inputMonth = inputMonth.padStart(2,'0'); + correct_day_or_month_format = 1 ; + } + if (inputDay > 0 && inputDay < 10) { + inputDay = inputDay.toString() ; + inputDay = inputDay.padStart(2,'0'); + correct_day_or_month_format = 1 ; + } + if (correct_day_or_month_format) { + \$("#"+this.id).val(inputYear+"-"+inputMonth+"-"+inputDay) ; + } + } + + }) ; + + ~ ; +} #------------------------------------------------------------------------------------------ + +sub common_min_table_update_checkbox_col_default { + + my $default_javascript_by_id_str = join ",", @default_javascript_by_id ; + + if ($default_javascript_by_id_str) { + $trigger_jquery_raw .= qq~ + let all_def_vals = {$default_javascript_by_id_str} ; + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_update_checkbox_col_jquery { + + my ($nr_of_characters_in_id_to_determine_row,$content_id,$update_fields_short_1,$update_fields_short_2) = @_ ; + + $content_id = "content" unless $content_id ; + + $nr_of_characters_in_id_to_determine_row = 1 unless $nr_of_characters_in_id_to_determine_row ; + + my $jquery_on_change_1 = "" ; + my $jquery_on_change_2 = "" ; + + if ($update_fields_short_1 || $update_fields_short_2) { + + ## NEW WAY + + $jquery_on_change_1 = qq~\$("#$content_id").on("change","$update_fields_short_1", function (event) {~ if $update_fields_short_1 ; # EXAMPLE: [id^='selectFixture_check_'],[id^='selectStatus_'] + $jquery_on_change_2 = qq~\$("#$content_id").on("changeDate","$update_fields_short_2", function (event) {~ if $update_fields_short_2 ; + + } else { + + ## OLD WAY + + my @all_update_field_ids_1 = () ; my @all_update_field_ids_2 = () ; + + foreach my $fields (@all_update_field_ids) { + foreach (split(/\,/,$fields)) { + if ($_ =~ /#datepicker/ || $_ =~ /#datetimepicker/ || $_ =~ /#timepicker/) { + push @all_update_field_ids_2,$_ ; + } else { + push @all_update_field_ids_1,$_ ; + } + } + } + + # my $all_update_field_ids_str = join "," , @all_update_field_ids ; + my $all_update_field_ids_str_1 = join "," , @all_update_field_ids_1 ; + my $all_update_field_ids_str_2 = join "," , @all_update_field_ids_2 ; + + $jquery_on_change_1 = qq~\$("$all_update_field_ids_str_1").change( function (event) {~ if $all_update_field_ids_str_1 ; + $jquery_on_change_2 = qq~\$("$all_update_field_ids_str_2").on('changeDate',function() {~ if $all_update_field_ids_str_2 ; + + } + + chop $multi_select_ids if $multi_select_ids ; + + if ($jquery_on_change_1 || $jquery_on_change_2) { + + $trigger_jquery_raw .= qq~ + + function get_row_nr (id,nr_of_characters_in_id_to_determine_row) { + + // console.log("get_row_nr : "+id) ; + // console.log("nr_of_characters_in_id_to_determine_row : "+nr_of_characters_in_id_to_determine_row) ; + + let lastIndex = id.lastIndexOf('_'); + lastIndex = parseInt(lastIndex) ; + let row_nr_1 = id.substring(1+lastIndex); + + if (!nr_of_characters_in_id_to_determine_row || nr_of_characters_in_id_to_determine_row == 1) { + return row_nr_1 ; + } + + let id_2 = id.substring(0,lastIndex); + lastIndex = id_2.lastIndexOf('_'); + lastIndex = parseInt(lastIndex) ; + let row_nr_2 = id_2.substring(1+lastIndex); + + if (nr_of_characters_in_id_to_determine_row == 2) { + return row_nr_2+"_"+row_nr_1 ; + } + + let id_3 = id_2.substring(0,lastIndex); + lastIndex = id_3.lastIndexOf('_'); + lastIndex = parseInt(lastIndex) ; + let row_nr_3 = id_3.substring(1+lastIndex); + + if (nr_of_characters_in_id_to_determine_row == 3) { + // console.log("return : "+row_nr_3+"_"+row_nr_2+"_"+row_nr_1) ; + return row_nr_3+"_"+row_nr_2+"_"+row_nr_1 ; + } + + } + + function check_whether_to_update (changed_id) { + + let row_nr = get_row_nr(changed_id) ; + + $trigger_jquery_raw_default_alt + + let nr_of_characters_in_id_to_determine_row = "$nr_of_characters_in_id_to_determine_row" ; + + if (row_nr == "row") { + row_nr = "add_row" ; + } else if (nr_of_characters_in_id_to_determine_row == "2") { + // Nothing Yet + row_nr = get_row_nr(changed_id,2) ; + } else if (nr_of_characters_in_id_to_determine_row == "3") { + row_nr = get_row_nr(changed_id,3) ; + } + + let def_vals = all_def_vals[row_nr] ; + + + console.log("changed_id val : "+\$("#"+changed_id).val()) ; + + let tick_update = 0 ; + + let multi_select_ids = {$multi_select_ids} ; + + for (const id in def_vals) { + + console.log("def_vals : "+\$("#"+id).val()) ; + + if ((\$("#"+id).attr('type') == 'radio' && (\$("#"+id).is(":checked") !== (def_vals[id] === "true"))) || (id.includes('input[name') && def_vals[id] != \$(id).val())) { + tick_update = 1 ; + } else if (id.includes('datepicker') || id.includes('timepicker')) { + console.log("1 tick_update : "+tick_update) ; + console.log("11 def_vals : "+def_vals[id]) ; + console.log("22 def_vals : "+\$("#"+id).data("date")) ; + if (def_vals[id] != \$("#"+id).data("date")) { + tick_update = 1 ; + } + console.log("2 tick_update : "+tick_update) ; + } else if (\$("#"+id).attr('type') == 'checkbox') { + if ((\$("#"+id).is(":checked") !== (def_vals[id] === "true")) || (!\$("#"+id).is(":checked") !== (def_vals[id] === "false"))) { + tick_update = 1 ; + } + } else if (!multi_select_ids[id] && !id.includes('input[name') && \$("#"+id).attr('type') != 'radio') { + + let sel_val = \$("#"+id).val() ; + if (sel_val == null) { + sel_val = '' ; + } + if (sel_val != def_vals[id]) { + tick_update = 1 ; + } + + } else if (multi_select_ids[id]) { + + let select_multi = \$("#"+id).chosen().val() ; + if (select_multi == null) { select_multi = "" ; } + if (select_multi != def_vals[id]) { + tick_update = 1 ; + } + } + + + + } + + if (tick_update && !\$("#checkboxUpdate_"+row_nr).is(":checked")) { + \$("#checkboxUpdate_"+row_nr).prop("checked",true) ; + } else if (!tick_update && \$("#checkboxUpdate_"+row_nr).is(":checked")) { + \$("#checkboxUpdate_"+row_nr).prop("checked",false) ; + } + } + ~ ; + + # $trigger_jquery_raw .= ($ids_short) ? qq~ + # \$("#$content_id").on("change","$update_fields_short_1", function (event) { // EXAMPLE: [id^='selectFixture_check_'],[id^='selectStatus_'] + # event.preventDefault(); + # check_whether_to_update(this.id); + # }); + # ~ : qq~ + # // \$("$all_update_field_ids_str_1").change( function (event) { + # $jquery_on_change_1 + # event.preventDefault(); + # $trigger_jquery_raw_on_change_1 + # check_whether_to_update(this.id) ; + # }) ; + + # ~ ; + + $trigger_jquery_raw .= qq~ + $jquery_on_change_1 + event.preventDefault(); + check_whether_to_update(this.id); + }); + ~ if $jquery_on_change_1 ; + + $trigger_jquery_raw .= qq~ + $jquery_on_change_2 + $trigger_jquery_raw_on_change_2 + check_whether_to_update(this.id) ; + }) ; + + ~ if $jquery_on_change_2 && !$no_dates_in_table ; + # unless $no_dates_in_table ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_update_checkbox_col { + + my ($nr_of_characters_in_id_to_determine_row,$content_id,$ids_short_1,$ids_short_2) = @_ ; + + &common_min_table_update_checkbox_col_default ; + + &common_min_table_update_checkbox_col_jquery($nr_of_characters_in_id_to_determine_row,$content_id,$ids_short_1,$ids_short_2) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_checkbox { + + my ($field_id,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved) = @_ ; + + if (!$only_display_val) { + my $ucfirstfield = ($ucfirstfield{$field_id}) ? $ucfirstfield{$field_id} : "checkbox" . ucfirst $field_id ; + $val = qq~~ ; + } else { + $val = qq~~ ; + } + $val_min = '' ; + return $val ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_textarea { + + my ($field_id,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved,$col_name,$table_id,$hide_textarea) = @_ ; + + $val = '' ; $val_min = 'MUSTBEBLANK' ; + + $table_id = "itv-table" unless $table_id ; + + if (!$only_display_val && $table_col) { + $found_editable = 1 ; + # my $print_field = ($preferred_placeholder{$field_id}) ? $preferred_placeholder{$field_id} : &common_min_print_field($field_id) ; + my $print_field = ($preferred_placeholder{$field_id}) ? $preferred_placeholder{$field_id} : ($preferred_title{$field_id}) ? $preferred_title{$field_id} : &common_min_print_field($field_id) ; + + $tindex++ ; + + $val_min = $default_val if $default_val ; + + my $ucfirstfield = ($ucfirstfield{$field_id}) ? $ucfirstfield{$field_id} : "textarea" . ucfirst $field_id ; + + # my $style = ($default_val && $default_val =~ /\n/) ? qq~style="height:100%;"~ : qq~~ ; + + # $default_val =~ s/\\n/\n/g ; + + $hide_textarea = ($hide_textarea) ? qq~display:none;~ : qq~~ ; + + $val = qq~ +
    +
    + +
    +
    + ~ ; + + # $default_val =~ s/\n/\\n/g ; + $default_val =~ s/[\n\r]+/\\n/g ; + + if ($default_val && $default_val_is_saved) { + $background_color = "#424949" unless $background_color ; + $table_with_default_ids{$background_color} .= "#$table_id tr:eq($table_row) td:nth-last-child($table_col)," ; + # $trigger_jquery .= qq~ \$("#$ucfirstfield").css("width","100%") ;~ ; + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ ; + } elsif ($default_val && !$default_val_is_saved) { + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ ; + } else { + $default_javascript .= qq~"$ucfirstfield":"",~ ; + } + + # box-sizing:border-box;overflow:hidden; + # box-sizing:border-box;overflow: hidden; + # oninput="adjustHeight(this)" row="1" + + # $trigger_jquery .= qq~ + # window.onload = function() { + # var textarea = document.getElementById('$ucfirstfield'); + # adjustHeight(textarea,'$ucfirstfield'); + # }; + # ~ ; + + # $trigger_jquery .= qq~ + # \$("#$ucfirstfield").css("width","100%") ; + # ~ ; + + #$trigger_jquery_raw .= qq~ + # \$('#$ucfirstfield').on('input', function() { + # // this.style.height = 'auto' ; + # // this.style.height = (this.clientHeight) + 'px'; + # }) ; + # \$('#$ucfirstfield').trigger('input'); + # ~ ; + + } elsif ($default_val) { + $val = $default_val ; + $val_min = $val ; + $val =~ s/\n/\
    /g ; + } + + $val_min =~ s/\\n/ /g ; + + return $val ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_input { + + my ($field_id,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved,$col_name,$table_id,$hide_input_field) = @_ ; + + $val = '' ; $val_min = 'MUSTBEBLANK' ; + + if (!$only_display_val) { + $found_editable = 1 ; + # my $print_field = ($preferred_placeholder{$field_id}) ? $preferred_placeholder{$field_id} : &common_min_print_field($field_id) ; + my $print_field = ($preferred_placeholder{$field_id}) ? $preferred_placeholder{$field_id} : ($preferred_title{$field_id}) ? $preferred_title{$field_id} : &common_min_print_field($field_id) ; + $tindex++ ; + + my $ucfirstfield = ($ucfirstfield{$field_id}) ? $ucfirstfield{$field_id} : "input" . ucfirst $field_id ; + + $hide_input_field = qq~display:none;~ if $hide_input_field ; + + $val = qq~
    +
    ~ ; + + # $trigger_jquery .= qq~ \$("#$ucfirstfield").css("width","100%") ;~ ; + if ($default_val && $default_val_is_saved) { + $background_color = "#424949" unless $background_color ; + $table_with_default_ids{$background_color} .= "#itv-table tr:eq($table_row) td:nth-last-child($table_col)," ; + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ ; + $val_min = $default_val ; + } else { + $val_min = '' ; + $default_javascript .= qq~"$ucfirstfield":"",~ ; + } + } else { + $val = $default_val ; + $val_min = $val ; + } + + return $val ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_select { + + my ($field_id,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved,$col_name,$table_id,$tooltip_1_text) = @_ ; + + if ($multiple{$field_id}) { $setmultiple = 'multiple' ; } else { $setmultiple = '' ; } + + $table_id = "itv-table" unless $table_id ; + + $val = '' ; + # $val_min = 'MUSTBEBLANK' ; + + # if (!$only_display_val && $table_col) { + if (!$only_display_val) { + + $found_editable = 1 ; + + my $ucfirstfield = ($ucfirstfield{$field_id}) ? $ucfirstfield{$field_id} : "select" . ucfirst $field_id ; + + my $print_field = ($preferred_placeholder{$field_id}) ? $preferred_placeholder{$field_id} : ($preferred_title{$field_id}) ? "Select $preferred_title{$field_id}" : "Select " . &common_min_print_field($field_id) ; + + push @all_select_ids,"#$ucfirstfield" if $ucfirstfield ; + if ($multiple{$field_id}) { + push @all_multi_select_ids,"#$ucfirstfield" if $ucfirstfield ; + $multi_select_ids .= qq~"$ucfirstfield":"1",~ if $ucfirstfield ; + push @dropdown_multi_chosen_ids,"#$ucfirstfield\_chosen" if $ucfirstfield ; + + } + + # $table_select_rows{$table_row} .= qq~#itv-table tr:eq($table_row) td:nth-last-child($table_col),~ ; + + # $trigger_jquery_raw .= qq~ + # \$("#$ucfirstfield").chosen({ allow_single_deselect:true }) ; \$("#itv-table tr:eq($table_row) td:nth-last-child($table_col)").css("z-index","$table_row") ; + # ~ ; + + # my $tooltip_1 = qq~~ ; + # if ($tooltip_1_text) { + # $tooltip_1 = qq~title data-toggle='tooltip' data-placement='top' data-original-title='$tooltip_1_text'~ ; + # } + + if ($tooltip_1_text) { + $add_tooltip{$tooltip_1_text} .= "#$ucfirstfield\_chosen," ; + } + + if (!$col_name) { + + $val = qq~ + + ~ ; + + } else { + $val = qq~ + + ~ ; + $opts{$col_name} = $opts{$field_id} unless $opts{$col_name} ; + $col_name_select_ids{$col_name} .= "#$ucfirstfield," ; + + } + + if ($default_val) { + unless ($val_min) { + $val_min = $default_val ; + $val_min =~ s/\_/ \[/g ; + $val_min .= qq~]~ if $val_min =~ /\[/; + } + + push @selects_with_default_ids,"#$ucfirstfield" if $ucfirstfield ; + + # foreach (split(/\,/,$default_val)) { + $selects_by_def_val{$default_val} .= "#$ucfirstfield," if $ucfirstfield ; + # } + + + # $trigger_jquery_raw .= qq~ + # \$("#$ucfirstfield").val("$default_val") ; + # ~ ; + + # if ($default_val_is_saved) { + if ($default_val_is_saved && $table_col) { + $background_color = "#424949" unless $background_color ; + $table_with_default_ids{$background_color} .= "#$table_id tr:eq($table_row) td:nth-last-child($table_col)," ; + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ ; + } elsif ($default_val_is_saved && !$table_col) { + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ ; + } else { + $default_javascript .= qq~"$ucfirstfield":"",~ ; + } + + } else { + $default_javascript .= qq~"$ucfirstfield":"",~ ; + } + if ($ucfirstfield) { push @dropdown_chosen_ids,"#$ucfirstfield\_chosen" unless $multiple{$field_id} ; } + + } elsif ($default_val) { + $val = $default_val ; + $val_min = $default_val ; + $val_min =~ s/\_/ \[/g ; + $val_min .= qq~]~ if $val_min =~ /\[/; + + # $val =~ s/\_/\[/g ; + $val =~ s/\_//g ; + # $val .= qq~]~ ; + # $val_min = $val unless $val_min ; + $table_with_default_ids{$background_color} .= "#$table_id tr:eq($table_row) td:nth-last-child($table_col)," if $background_color && $background_color ne "#424949" ; + } + + return $val ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_textarea_jquery { + + # $trigger_jquery .= qq~ + # function adjustHeight(textarea,id) { + + # textarea.style.height = 'auto'; // Reset height to auto to get the scroll height + # // textarea.style.height = textarea.scrollHeight + 'px'; // Set the height to the scroll height + + # \$("#"+id).css("height",textarea.scrollHeight+"px") ; + + # console.log("scrollHeight : "+textarea.scrollHeight) ; + # console.log("textarea : "+textarea) ; + # console.log("id : "+id) ; + + # } + # ~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_select_jquery { + + my ($columns_with_selects,$table_id) = @_ ; + + &common_min_table_select_fixed_width_jquery($columns_with_selects) ; + + &common_min_table_select_prevent_dropdown_overlap_jquery($table_id) ; + + &common_min_table_select_default_values_jquery ; + + &common_min_table_multi_select_jquery ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_select_fixed_width_jquery { + + my ($columns_with_selects) = @_ ; + + return unless $columns_with_selects ; + + $trigger_jquery_raw .= qq~ + \$("$columns_with_selects").css("position","relative") ; + \$("$columns_with_selects").css("text-align","center") ; + ~ ; + + my $dropdown_chosen_ids_str = join(',',@dropdown_chosen_ids) ; + my $dropdown_multi_chosen_ids_str = join(',',@dropdown_multi_chosen_ids) ; + + $trigger_jquery .= qq~ + \$("$dropdown_multi_chosen_ids_str").css("width","100%") ;~ if $dropdown_multi_chosen_ids_str ; + + return unless $dropdown_chosen_ids_str ; + + $trigger_jquery .= qq~ + \$("$dropdown_chosen_ids_str").css("position","absolute") ;~ ; + $trigger_jquery .= qq~ + \$("$dropdown_chosen_ids_str").css("width","90%") ;~ ; + $trigger_jquery .= qq~ + \$("$dropdown_chosen_ids_str").css("left","5%") ;~ ; + $trigger_jquery .= qq~ + \$("$dropdown_chosen_ids_str").css("top","50%") ;~ ; + $trigger_jquery .= qq~ + \$("$dropdown_chosen_ids_str").css("transform","translateY(-50%)") ;~ ; + + foreach (keys %add_tooltip) { + chop $add_tooltip{$_} ; + + $trigger_jquery .= qq~ + \$("$add_tooltip{$_}").attr({ + title : '', + 'data-original-title': '$_', + 'data-toggle': 'tooltip', + 'data-placement': 'top' + }); + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_select_prevent_dropdown_overlap_jquery_1 { + + my ($table_id) = @_ ; + + $table_id = "$useropts{table_id}" unless $table_id ; + + $trigger_jquery .= qq~ + + function prevent_drop_down_overlap (loading_page) { + + const table_ = \$('#$table_id').DataTable()._('tr') ; + // var table_ =\$("#$table_id").find('tr') ; + let row_nr = 1 ; + let z_index = 1 ; + + for (let i = table_.length; i >= 1 ; i--) { + + if (loading_page) { + $hide_other_column_for_logistics_report + $hide_columns_by_default + } + + if (!\$("#$table_id tr:eq("+i+") td:nth-last-child(1)").find('input').length && !\$("#$table_id tr:eq("+i+") td:nth-last-child(2)").find('input').length) { + continue ; + } + + let columns = table_[row_nr - 1]; + + for (let col_nr = 1; col_nr <= columns.length ; col_nr++) { + + if (!\$("#$table_id tr:eq("+i+") td:nth-last-child("+col_nr+")").find('select').length) { + continue ; + } + \$("#$table_id tr:eq("+i+") td:nth-last-child("+col_nr+")").css("z-index",z_index) ; + z_index++ ; + } + row_nr++ ; + } + // table_ = "" ; + } + + \$('#$table_id th').on('click', function() { + prevent_drop_down_overlap(0) ; + }); + + // \$("#select_temp_calibrators_2_length").css("display","none"); + // \$("#select_temp_calibrators_2_filter").css("display","none"); + // \$("#select_temp_calibrators_2_info").css("display","none"); + // \$("#select_temp_calibrators_2_paginate").css("display","none"); + + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_select_prevent_dropdown_overlap_jquery_2 { + + $trigger_jquery .= qq~ + prevent_drop_down_overlap(1) ; + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_select_prevent_dropdown_overlap_jquery { + + my ($table_id) = @_ ; + + &common_min_table_select_prevent_dropdown_overlap_jquery_1($table_id) ; + &common_min_table_select_prevent_dropdown_overlap_jquery_2 ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_select_default_values_jquery { + + foreach my $col_name (keys %col_name_select_ids) { + chop $col_name_select_ids{$col_name} if $col_name_select_ids{$col_name} ; + $opts{$col_name} =~ s/\"/\'/g ; + $opts{$col_name} =~ s/\' >/\'>/g ; + $opts{$col_name} =~ s/\' >/\'>/g ; + $trigger_jquery_raw .= qq~ + \$("$col_name_select_ids{$col_name}").html("$opts{$col_name}").trigger("chosen:updated") ; + ~ ; + } + + my $all_select_ids_str = join(",",@all_select_ids) ; + + $trigger_jquery_raw .= qq~\$("$all_select_ids_str").chosen({ allow_single_deselect:true }) ;~ ; + + # $trigger_jquery_raw .= qq~ + # \$("$all_select_ids_str").on("change", function () { + # console.log("FOCUS!!!!") ; + # event.preventDefault() ; + # }) ; + # ~ ; + + # $trigger_jquery_raw .= qq~ + # // \$("$all_select_ids_str").change( function () { + # // console.log("preventDefault") ; + # // event.preventDefault() ; + # // let scrollContainer = \$('#itv-table_wrapper') ; + # // let scrollPosition = scrollContainer.scrollLeft() ; + # // console.log("scrollPosition : "+scrollPosition) ; + # // scrollContainer.scrollLeft(scrollPosition) ; + + # // }) ; + # ~ ; + + foreach (keys %table_with_default_ids) { + chop $table_with_default_ids{$_} if $table_with_default_ids{$_} ; + $trigger_jquery_raw .= qq~ + \$("$table_with_default_ids{$_}").css("background-color","$_") ; + ~ ; + } + + foreach my $def_val (keys %selects_by_def_val) { + chop $selects_by_def_val{$def_val} if $selects_by_def_val{$def_val} ; + my $def_val2 = $def_val ; + if ($def_val2 =~ /,/) { + $def_val2 =~ s/\,/\','/g ; + $def_val2 = qq~['$def_val2']~ ; + $trigger_jquery_raw .= qq~ + \$("$selects_by_def_val{$def_val}").val($def_val2).trigger("chosen:updated") ; + ~ ; + } else { + + # foreach (split(/\,/,$selects_by_def_val{$def_val})) { + # $trigger_jquery_raw .= qq~ + # \$("$_").val("$def_val2").trigger("chosen:updated") ; + # ~ ; + # } + $trigger_jquery_raw .= qq~ + \$("$selects_by_def_val{$def_val}").val("$def_val2").trigger("chosen:updated") ; + ~ ; + } + + } + + # my $selects_with_default_ids_str = join(',',@selects_with_default_ids) ; + # $trigger_jquery_raw .= qq~ + # \$("$selects_with_default_ids_str").trigger("chosen:updated") ; + # ~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_multi_select_jquery { + + # my $all_multi_select_ids_str = join(",",@all_multi_select_ids) ; + + # foreach (@all_multi_select_ids) { + # $trigger_jquery_raw .= qq~set_row_height("$_") ; ~ ; + # } + + # $trigger_jquery_raw .= qq~ + + # function set_row_height (multi_id) { + + # let row_nr = get_row_nr(multi_id) ; + # let numOptions = \$(multi_id).find('option:selected').length; + # var optionHeight = 25; + # var padding = 40 ; + # let numOptions2 = Math.floor(numOptions/3) ; + + # var newHeight = numOptions * optionHeight + padding; + # console.log("set_row_height : "+multi_id) ; + + # if (numOptions == '3' || numOptions2 == '0') { + # newHeight = 0 ; + # } + # \$("#"+row_nr).height(newHeight); + # } + + # \$("$all_multi_select_ids_str").change( function() { + # set_row_height("#"+this.id) ; + # }); + + # ~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_datepicker { + + my ($field_id,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved,$col_name,$table_id,$icon_color,$tooltip_text,$tooltip_1_text,$tooltip_2_text) = @_ ; + + if ($default_val eq '0000-00-00') { $default_val = '' ; } + + if (!$only_display_val) { + + my $ucfirstfield = ($ucfirstfield{$field_id}) ? $ucfirstfield{$field_id} : "datepicker" . ucfirst $field_id ; + + $tindex++ ; + + my $tooltip_1 = qq~~ ; my $tooltip_2 = qq~~ ; + + if ($tooltip_1_text) { + $tooltip_1 = qq~title data-toggle='tooltip' data-placement='top' data-original-title='$tooltip_1_text'~ ; + } + + if ($default_val && $add_datepicker_tooltip{$field_id}) { + $tooltip_2 = qq~title data-toggle='tooltip' data-placement='top' data-original-title='$default_val'~ ; + } elsif ($tooltip_2_text) { + $tooltip_2 = qq~title data-toggle='tooltip' data-placement='top' data-original-title='$tooltip_2_text'~ ; + } + + if (!$default_val) { $default_val = "$now_year-$now_mm-$now_dd" ; } ; + + $icon_color = (!$icon_color) ? 'black' : $icon_color ; + + $val = qq~ +
    + + + + +
    + ~ ; + + if ($default_val_is_saved) { + $background_color = "#424949" unless $background_color ; + $table_with_default_ids{$background_color} .= "#itv-table tr:eq($table_row) td:nth-last-child($table_col)," if $table_row && $table_col ; + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ if $ucfirstfield ; + $val_min = $default_val ; + } else { + $default_javascript .= qq~"$ucfirstfield":"",~ if $ucfirstfield ; + $val_min = '' ; + } + push @all_datepicker_ids,"#$ucfirstfield" if $ucfirstfield ; + push @all_datepicker_names,"input[name='$field_id']" if $field_id ; + + } else { + $val = $default_val ; + $val_min = $val ; + } + +# &common_min_form_datepicker_jquery($ucfirst_field); + + return ($val) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_datepicker_jquery { + + our $all_datepicker_ids_str = join(",",@all_datepicker_ids) ; + + $trigger_jquery_raw .= qq~ + \$('$all_datepicker_ids_str').datepicker({format: "yyyy-mm-dd"}).on('changeDate', function (ev) { + \$('.datepicker').hide(); + \$("input[name='"+this.id.substring(10).toLowerCase()+"']").val(\$("#"+this.id).data("date")) ; + }) ; + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_timepicker { + + my ($field_id,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved,$col_name,$table_id,$icon_color,$tooltip_1_text,$tooltip_2_text) = @_ ; + + $tindex++; + $val = '' ; $val_min = '' ; + + if (!$only_display_val) { + + my $ucfirstfield = ($ucfirstfield{$field_id}) ? $ucfirstfield{$field_id} : "timepicker" . ucfirst $field_id ; + + if (!$default_val) { $default_val = "$now_hour:$now_min:$now_sec" ; } ; + + my $tooltip_1 = qq~~ ; my $tooltip_2 = qq~~ ; + + if ($tooltip_1_text) { + $tooltip_1 = qq~title data-toggle='tooltip' data-placement='top' data-original-title='$tooltip_1_text'~ ; + } + + if ($default_val && $add_timepicker_tooltip{$field_id}) { + $tooltip_2 = qq~title data-toggle='tooltip' data-placement='top' data-original-title='$default_val'~ ; + } elsif ($tooltip_2_text) { + $tooltip_2 = qq~title data-toggle='tooltip' data-placement='top' data-original-title='$tooltip_2_text'~ ; + } + + $icon_color = (!$icon_color) ? 'black' : $icon_color ; + + # + # + # + + # + + $val = qq~ +
    + + + + +
    + ~ ; + + if ($default_val && $default_val_is_saved) { + $background_color = "#424949" unless $background_color ; + $table_with_default_ids{$background_color} .= "#itv-table tr:eq($table_row) td:nth-last-child($table_col)," if $table_row && $table_col ; + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ if $ucfirstfield && $default_val ; + $val_min = $default_val ; + } else { + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ if $ucfirstfield ; + $val_min = '' ; + } + push @all_timepicker_ids,"#$ucfirstfield" if $ucfirstfield ; + push @all_timepicker_names,"input[name='$field_id']" if $field_id ; + # $trigger_jquery_raw .= qq(\$('#timepicker$ucfirst_field').datetimepicker({language:'pt-BR',pickDate:false});) ; + } else { + $val = $default_val ; + $val_min = $val ; + } + return $val ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_timepicker_jquery { + + my ($ids_short) = @_ ; + + if ($ids_short) { + $trigger_jquery_raw .= qq~\$("$ids_short").datetimepicker({language:'pt-BR',pickDate:false});~ ; + return ; + } + + our $all_timepicker_ids = join(",",@all_timepicker_ids) ; + + $trigger_jquery_raw .= qq~\$('$all_timepicker_ids').datetimepicker({language:'pt-BR',pickDate:false});~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_get_event_quote_button { + + my ($event_id,$table,$page_url_part) = @_ ; + + $table = "event_quotes" unless $table ; + + return unless $event_id ; + + my $class = 'info' ; my $style = '' ; my $does_not_exist = 0 ; + if ($db{$table}{$event_id}{demo_id}) { + $style = 'style="background-color:rgb(255,64,255);border-color:rgb(255,64,255);"'; # pink + $tt_txt = 'Demo' ; + if ($db{$table}{$event_id}{quote_completed}) { + $tt_txt = 'Completed ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_accepted}) { + $tt_txt = 'Accepted ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_rejected}) { + $tt_txt = 'Rejected ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_cancelled}) { + $tt_txt = 'Cancelled ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_created}) { + $tt_txt = 'Pending, Created by School Manager ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_pending}) { + $tt_txt = 'Pending ' . $tt_txt ; + } + } elsif ($analytics_events{$event_id}) { + $style = 'style="background-color:rgb(255,129,0);border-color:rgb(255,129,0);"'; # pink + $tt_txt = 'Analytics Event' ; + if ($db{$table}{$event_id}{quote_completed}) { + $tt_txt = 'Completed ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_accepted}) { + $tt_txt = 'Accepted ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_rejected}) { + $tt_txt = 'Rejected ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_cancelled}) { + $tt_txt = 'Cancelled ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_created}) { + $tt_txt = 'Pending, Created by School Manager ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_pending}) { + $tt_txt = 'Pending ' . $tt_txt ; + } + } elsif ($db{$table}{$event_id}{quote_completed} || $db{$table}{$event_id}{event_completed} || $quote_completed) { + $class = 'success' ; # green + $tt_txt = 'Completed' ; + } elsif ($db{$table}{$event_id}{quote_accepted} || $db{$table}{$event_id}{event_completed} || $quote_accepted) { + $class = 'info' ; # blue + $tt_txt = 'Accepted' ; + my @fixed_system_overall_statuses = split(/\;/,$db{$table}{$event_id}{fixed_system_overall_status}) ; + my @event_system_ids = split(/\;/,$db{$table}{$event_id}{event_system_id_multiple}) ; + my $event_sys_cnt = 0 ; my $event_sys_test_status = 0 ; my $got_some_fixed = 0 ; my $fixed_status_color = '164473' ; # Dark Blue + foreach my $event_id (@event_system_ids) { + if ($db{event_systems}{$event_id}{system_type} eq 'fixed') { + $tt_txt = 'Accepted and tests show All Clear for the Fixed Systems' if $tt_txt eq 'Accepted' ; + $got_some_fixed = 1 ; + if ($fixed_system_overall_statuses[$event_sys_cnt] == 3) { # Not Clear + $fixed_status_color = '5d09d3' ; # Dark Purple + $tt_txt = 'Accepted but Not Clear on some Fixed Systems' ; + } elsif ($fixed_system_overall_statuses[$event_sys_cnt] == 2) { # Sound Issue + $fixed_status_color = '5d092c' ; + $tt_txt = 'Accepted but Sound Issue found on some Fixed Systems' ; + } + } + $event_sys_cnt++ ; + } + if ($got_some_fixed) { $style = "style='background-color:#$fixed_status_color;border-color:#$fixed_status_color'"; } + } elsif ($db{$table}{$event_id}{quote_rejected} || $db{$table}{$event_id}{event_rejected} || $quote_rejected) { + $style = 'style="background-color:#ca0ad3;border-color:#ca0ad3"'; # purple + $tt_txt = 'Rejected' ; + } elsif ($db{$table}{$event_id}{quote_cancelled} || $db{$table}{$event_id}{event_cancelled} || $quote_cancelled) { + $class = 'danger' ; # red + $tt_txt = 'Cancelled' ; + } elsif ($db{$table}{$event_id}{quote_created} || $db{$table}{$event_id}{event_created} || $quote_created) { # create by schools_manager + $style = 'style="background-color:#f6e305;border-color:#f6e305"'; # yellow + $tt_txt = 'Pending, Created by School Manager' ; + } elsif ($db{$table}{$event_id}{quote_pending} || $db{$table}{$event_id}{event_pending} || $quote_pending) { + $class = 'warning' ; # orange + $tt_txt = ($db{$table}{$event_id}{sssadmin_quote_nr}) ? 'Pending [Created by SSS platform]' : 'Pending' ; + } elsif (!$db{$table}{$event_id}{id}) { + $style = 'style="background-color:black;border-color:black"'; + $tt_txt = 'Does not Exist!!!' ; + $does_not_exist = 1 ; + } + + my $tt = qq~data-toggle="tooltip" data-placement="right" data-title="$tt_txt"~; + # ($glod_user_level < 3 && !$is_operator) + + my $glod_user_level_eff = ($glod_user_level == 2 && $is_operator) ? 3 : $glod_user_level ; + + my $href = ($page_url_part) ? qq~javascript:editMinItem('$event_id','$page_url_part');~ : qq~javascript:editMinItem('$event_id');~ ; + + my $event_quote_btn = ($glod_user_level_eff < 3 || $db{$table}{$event_id}{quote_cancelled} || $does_not_exist) ? qq~$event_id~ : qq~$event_id~ ; + + # || ($db{$table}{$event_id}{quote_completed} && $glod_user_level <= 3) + + return ($event_quote_btn) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_get_quote_button { + + my ($quote_id,$table) = @_ ; + + $table = "quotes" unless $table ; + + return unless $quote_id ; + + my $class = 'info' ; my $style = '' ; my $tt_txt = '' ; + + if ($db{$table}{$quote_id}{quote_cancelled}) { + $class = 'danger' ; + $tt_txt = 'Cancelled' ; + } elsif ($db{$table}{$quote_id}{quote_accepted}) { + $class = 'success' ; + $tt_txt = 'Accepted' ; + } elsif ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd") { ### $quote_expiry must be defined + $class = 'danger' ; + $tt_txt = 'Expired' ; + } elsif ($db{$table}{$quote_id}{quote_pending}) { + $class = 'warning' ; + $tt_txt = 'Pending' ; + } + + my $tt = qq~data-toggle="tooltip" data-placement="right" data-title="$tt_txt"~; + + my $quote_btn = qq~$db{$table}{$quote_id}{quote_nr}~ ; + + return ($quote_btn) ; + +} #------------------------------------------------------------------------------------------ + +# sub common_min_date_as_string { + + # my ($date) = @_ ; + + # my ($yr,$mon,$day) = split("-",$date) ; ## our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + # return ("$day-$months[$mon]-$yr") ; + +# } #------------------------------------------------------------------------------------------ + +sub common_min_date_as_string { + + my ($date) = @_ ; + + return if $date !~ /(\d+)/g ; + + my ($yr,$mon,$day) = split("-",substr($date,0,10)) ; ## our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + if (substr($date,11,5)) { + return ("$day-$months[$mon]-$yr \@ " . substr($date,11,5)) ; + } else { + return ("$day-$months[$mon]-$yr") ; + } + +} #------------------------------------------------------------------------------------------ + +sub greater_date_time { + + local ($date_time_1,$date_time_2) = @_ ; + + return Time::Piece->strptime($date_time_1,'%Y-%m-%d %H:%M:%S') <= Time::Piece->strptime($date_time_2,'%Y-%m-%d %H:%M:%S') ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_greater_date_time { + + local ($date_time_1,$date_time_2) = @_ ; + + return Time::Piece->strptime($date_time_1,'%Y-%m-%d %H:%M:%S') <= Time::Piece->strptime($date_time_2,'%Y-%m-%d %H:%M:%S') ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_greater_date { + + local ($date_1,$date_2) = @_ ; + + return Time::Piece->strptime($date_1,'%Y-%m-%d') <= Time::Piece->strptime($date_2,'%Y-%m-%d') ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_calc_time_diff { + + local ($date_time_1,$date_time_2) = @_ ; + + return "blank_date" if !$date_time_1 || !$date_time_2 ; + + return (Time::Piece->strptime($date_time_2,'%Y-%m-%d %H:%M:%S') - Time::Piece->strptime($date_time_1,'%Y-%m-%d %H:%M:%S')) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_calc_day_diff { + + local ($date_1,$date_2) = @_ ; + + return 1 + abs(Time::Piece->strptime(substr($date_2,0,10),'%Y-%m-%d') - Time::Piece->strptime(substr($date_1,0,10),'%Y-%m-%d'))->days ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_delete_files { + + my ($dir,$file_name) = @_ ; + + return if !$dir || ($dir && not -d $dir) || ($file_name && not -f "$dir/$file_name") ; + + my @files = () ; my $dh ; + if ($file_name) { + push @files,$file_name ; + } else { + opendir($dh, $dir) or die "Cannot open directory: $!"; + @files = grep { !/^\.\.?$/ } readdir($dh); + } + foreach my $file (@files) { + my $file_path = "$dir/$file" ; + if (-f $file_path) { + unlink ("$file_path") or print "\n unable to unlink - $file_path : $!"; + } + } + if (!$file_name) { + closedir($dh); + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_copy_files { + + # # # # use File::Copy; Make Sure THis is called ; + + my ($dir_from,$dir_to,$file_name) = @_ ; + + return if !$dir_from || !$dir_to || not -d $dir_from || ($file_name && not -f "$dir_from/$file_name"); + + mkdir $dir_to if not -d $dir_to; + + my @files = () ; my $dh ; + + if ($file_name) { + push @files,$file_name ; + } else { + opendir($dh,$dir_from) or die "Can't open $dir_from: $!"; + my $file_counter = 0 ; + @files = readdir($dh); + } + + foreach my $file (@files) { + next if $file =~ /^\.\.?$/ ; + my $src_file = "$dir_from/$file"; + my $dst_file = "$dir_to/$file"; + if (-f $src_file) { + copy("$src_file","$dst_file") or die "File cannot be copied." ; + } + } + + if (!$file_name) { + closedir($dh); + } + +} #------------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/common_test.pm b/libs/modules/_FromProd/common_test.pm similarity index 100% rename from libs/modules/common_test.pm rename to libs/modules/_FromProd/common_test.pm diff --git a/libs/modules/_FromProd/csv.pm b/libs/modules/_FromProd/csv.pm new file mode 100644 index 0000000..c10e12f --- /dev/null +++ b/libs/modules/_FromProd/csv.pm @@ -0,0 +1,54 @@ +sub csv_create_new_file { + + my ($filepath,$filename,$seperator) = @_ ; + + use Text::CSV; + + return if !$filepath || !$filename ; + + unlink "$filepath/$filename" or die "Cannot remove $filepath/$filename: $!" if -e "$filepath/$filename" ; + + $seperator = ';' unless $seperator ; + + our $csv = Text::CSV->new({ binary => 1, sep_char => $seperator, eol => "\n" }) or die "Cannot use CSV: " . Text::CSV->error_diag(); + + open(our $fh, ">", "$filepath/$filename") or die "Cannot open $filepath/$filename: $!"; + +} #------------------------------------------------------------------------------------------ + +sub csv_write_in_file { + + my ($row) = @_ ; + $csv->print($fh, $row); + +} #------------------------------------------------------------------------------------------ + +sub csv_close_file { + + my ($filepath) = @_ ; + close $fh or die "Cannot close $filepath: $!"; + +} #------------------------------------------------------------------------------------------ + +sub csv_clear_folder { + + my ($path,$name_to_look_for) = @_ ; + + return unless -d $path ; + + opendir(DIR, "$path") or die "cant open Directory $path: $!\n"; + + while(defined($folder = readdir(DIR))) { + if (length $folder > 2) { + my ($file,$type) = split(/\./,$folder) ; + if ((-e "$path/$file.csv" && !$name_to_look_for) || ($name_to_look_for && -e "$path/$file.csv" && $file =~ /$name_to_look_for/)) { + unlink ("$path/$file.csv") or print "unable to unlink - $path/$file.csv : $!"; + } + } + } + + closedir(DIR) ; + +} #------------------------------------------------------------------------------------ + +1; \ No newline at end of file diff --git a/libs/modules/_FromProd/db.pm b/libs/modules/_FromProd/db.pm index f33861b..8360829 100644 --- a/libs/modules/_FromProd/db.pm +++ b/libs/modules/_FromProd/db.pm @@ -63,11 +63,25 @@ sub ops_db_credentials { my $dbuser = "itv_admin_user"; my $dbpass = '!Ja16Q7P0X3SVTWr'; + if ($env eq 'DEV') { + $db = 'dev_aisa' ; + $dbhost = 'localhost' ; + $dbuser = 'dev_aisa_user' ; + $dbpass = 'L0rdJ35u5R31gN51vQow*!' ; + } + if ($sys eq 'sss') { $db = "sss_admin_db"; $dbhost = "localhost"; $dbuser = "sss_admin_user"; $dbpass = 'bVrC2kyGJ8ZO0oVe!'; + + if ($env eq 'DEV') { + $db = 'dev_sss' ; + $dbhost = 'localhost' ; + $dbuser = 'dev_sss_user' ; + $dbpass = 'L0rdJ35u5R31gN51vQow*!' ; + } } return ($db,$dbhost,$dbuser,$dbpass) ; diff --git a/libs/modules/_FromProd/db_min.pm b/libs/modules/_FromProd/db_min.pm new file mode 100644 index 0000000..497de06 --- /dev/null +++ b/libs/modules/_FromProd/db_min.pm @@ -0,0 +1,269 @@ +sub db_min_upd { + + my ($table,$where) = @_ ; + + our $set = '' ; + + foreach (keys %i) { + if (substr($_,0,3) eq 'new') { next ; } + if ($ignore{$_}) { next ; } + if ($hidden{$_} == 1) { next ; } + if ($i{$_} =~ /\"/) { $set .= qq(`$_`='$i{$_}',) ; } elsif ($i{$_} eq 'NULL') { $set .= qq(`$_`=$i{$_},) ; } else { $set .= qq(`$_`="$i{$_}",) ; } + } + + $set = substr($set,0,-1) ; + + unless ($set) { return ; } + + &db_open_upd ; + + my $sql = qq(UPDATE $table SET $set WHERE $where) ; + + &common_debug($sql) ; + + if ($testing == 1 && $useropts{it}{$username}) { &common_debug(">>>>>> *** TESTING, DB NOT UPDATED *** <<<<<<") ; return ; } + + $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + + &db_close_conn ; + + $success = qq($i{id} SUCCESSFULLY SAVED) ; + +} #------------------------------------------------------------------------------------------ + +sub db_min_insert { + + my ($table) = @_ ; + + my $columns = '' ; + my $values = '' ; + + foreach (keys %i) { + if ($ignore{$_}) { next ; } + if ($hidden{$_} == 1) { next ; } + $columns .= qq(`$_`,) ; + if ($i{$_} =~ /\"/) { $values .= qq('$i{$_}',) ; } elsif ($i{$_} eq 'NULL') { $values .= qq(`$_`=$i{$_},) ; } else { $values .= qq("$i{$_}",) ; } + } + + $columns = substr($columns,0,-1) ; + $values = substr($values,0,-1) ; + + &db_open_upd ; + + my $sql = qq(INSERT INTO $table ($columns) VALUES ($values) ;) ; + + &common_debug($sql) ; + + if ($testing == 1 && $useropts{it}{$username}) { &common_debug(">>>>>> *** TESTING, DB NOT UPDATED *** <<<<<<") ; return ; } + + $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + our $new_row_id = $dbh->last_insert_id(undef, undef, $table, 'id') ; # or die "no insert id?"; + + &db_close_conn ; + + $success = qq($i{id} SUCCESSFULLY SAVED) ; + +} #------------------------------------------------------------------------------------------ + +sub db_min_delete { + +my ($table,$where) = @_ ; + +&db_open_upd ; + +my $sql = qq(DELETE FROM $table WHERE $where) ; + +&common_debug($sql) ; + +if ($testing == 1 && $useropts{it}{$username}) { &common_debug(">>>>>> *** TESTING, DB NOT UPDATED *** <<<<<<") ; return ; } + +$sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +&db_close_conn ; + +$success = qq($i{id} SUCCESSFULLY DELETED) ; + +} #------------------------------------------------------------------------------------------ + +sub db_min_ro { + +my ($table,$select,$where,$orderby,$limit) = @_ ; + +if ($where) { $where = 'WHERE ' . $where ; } +if ($limit) { $limit = 'LIMIT ' . $limit ; } +if ($orderby) { $orderby = 'ORDER BY ' . $orderby ; } + +&db_open_ro ; + +my $sql = qq(SELECT $select FROM $table $where $orderby $limit) ; + +&common_debug($sql) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; + +$col_cnt=0; + +foreach $col (@{$sth->{NAME}}) { $col_name{$col_cnt}=$col; $col_cnt++; } # &common_debug($col); NB *** must be before fetchall_arrayref + +my $rows_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +$db{$table} = () ; $done_col_val{$table} = () ; + +foreach $row (@$rows_array_ref) { + for (0 .. $col_cnt){ + if ($done_col_val{$table}{@$row[0]}{$col_name{$_}}) { next; } + # &common_debug("db_common_ro - [$_] [$table] [@$row[0]] [$col_name{$_}] [@$row[$_]]") ; + $db{$table}{@$row[0]}{$col_name{$_}} = @$row[$_] ; + $done_col_val{$table}{@$row[0]}{$col_name{$_}} = 1 ; + } + } + +} #------------------------------------------------------------------------------------------ + +sub db_min_raw { + +my ($sql) = @_ ; + +&common_debug($sql) ; + +if ($testing == 1 && $useropts{it}{$username}) { &common_debug(">>>>>> *** TESTING, DB NOT UPDATED *** <<<<<<") ; return ; } + +my $sth = $dbh->prepare($sql) ; + +$sth->execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; + +our $col_cnt=0; + +foreach $col (@{$sth->{NAME}}) { $col_name{$col_cnt}=$col; $col_cnt++; } # &common_debug($col); NB *** must be before fetchall_arrayref + +our $rows_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +} #------------------------------------------------------------------------------------------ + +sub db_min_copy { + +my ($table,$id) = @_ ; + +&db_open_upd ; + + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + $i{id} = &db_min_get_max($table,'id') ; + + my $add_upd_sql = '' ; + if ($table eq 'quotes' or $table eq 'event_quotes'){ + $i{quote_nr} = &db_min_get_max($table,'quote_nr') ; + $add_upd_sql = qq~, `quote_nr`='$i{quote_nr}'~; + } + + if ($table eq 'cameras'){ + $i{camera_nr} = &db_min_get_max_camera_nr($table,'camera_nr',$id) ; + $add_upd_sql = qq~, `camera_nr`='$i{camera_nr}'~; + } + + my $sql = qq~CREATE TEMPORARY TABLE `#temp` SELECT * FROM $table WHERE `id`='$id';~ ; + + &common_debug($sql) ; + + $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + + $sql = qq~UPDATE `#temp` SET `id`='$i{id}'$add_upd_sql WHERE `id`='$id';~ ; + + &common_debug($sql) ; + + $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + + $sql = qq~INSERT INTO $table SELECT * FROM `#temp` WHERE `id`='$i{id}';~ ; + + &common_debug($sql) ; + + $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + + $sql = qq~DROP TEMPORARY TABLE IF EXISTS `#temp`;~ ; + + &common_debug($sql) ; + + $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + +&db_close_conn ; + +$success = qq($id SUCCESSFULLY COPIED TO $i{id}) ; + +} #------------------------------------------------------------------------------------------ + +sub db_min_get_max_camera_nr { + +my ($table,$orderby,$camera_id) = @_ ; + +&db_min_ro($table,'id,camera_system_id',"`id`='$camera_id'",'','') ; +# &db_min_ro($table,'id,camera_nr',"`camera_system_id`='$db{$table}{$camera_id}{camera_nr}'",'`id` DESC',1) ; +&db_min_ro($table,'id,camera_nr',"`camera_system_id`='$db{$table}{$camera_id}{camera_system_id}'",'`id` DESC',1) ; + +my $max_cam_cnt = 0 ; + +foreach my $id (keys %{$db{$table}}) { + ($cam_type,$cam_cnt) = split(/\-/,$db{$table}{$id}{camera_nr}); + $max_cam_cnt = $cam_cnt unless $max_cam_cnt > $cam_cnt; +} + +$max_cam_cnt++; + +my $camera_nr = $cam_type . '-' . sprintf("%04s", $max_cam_cnt) ; # e.g. S1-0001 + +return ($camera_nr) ; + +} #------------------------------------------------------------------------------------------ + +sub db_min_get_max { + +my ($table,$orderby,$where) = @_ ; + +&db_open_ro ; + +if ($where) { $where = 'WHERE ' . $where ; } + +my $sql = qq~SELECT * FROM $table $where ORDER BY $orderby DESC LIMIT 1~ ; + +&common_debug($sql) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; + +$col_cnt=0; + +foreach $col (@{$sth->{NAME}}) { $col_name{$col_cnt}=$col; $col_cnt++; } # &common_debug($col); NB *** must be before fetchall_arrayref + +my $rows_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +my $new_id = 1 ; + +$db{$table} = () ; + +foreach $row (@$rows_array_ref) { + for (0 .. $col_cnt){ + $db{$table}{@$row[0]}{$col_name{$_}} = @$row[$_] ; + } + $new_id = $db{$table}{@$row[0]}{$orderby} ; + $new_id++ ; + } + +return ($new_id) ; + +} #------------------------------------------------------------------------------------------ + +1; \ No newline at end of file diff --git a/libs/modules/_FromProd/dcb.pm b/libs/modules/_FromProd/dcb.pm new file mode 100644 index 0000000..6a7fda1 --- /dev/null +++ b/libs/modules/_FromProd/dcb.pm @@ -0,0 +1,525 @@ + +sub dcb_trackntrace { + + my ($waybillNumber) = @_ ; + + our $soapenvelope = qq~ + + + + + + + + $waybillNumber + + + + ~ ; + + &common_debug("[API] dcb_trackntrace : [soapenvelope=$soapenvelope]") ; + + &dcb_send_it('TracknTrace') ; + &dcb_parse_it ; + &dcb_read_it('TracknTrace') ; + + # $returnxml = qq~ + # + # + # + # + # Completed + # + # + # + # DEV + # DARREN + # Proof of delivery + # 08052023 + # 0.00 + # 1 + # 15 SIM ROAD + # . + # KEMPTON PARK + # DARREN + # 0834752596 + # ReceiverName TESTING + # 1619 + # POMONA + # + # . + # KEMPTON PARK + # DEV + # 0112302085 + # 1619 + # POMONA + # EC + # YES + # + # DCBDEVLP + # + # + # overrideDefaultSubcontractor + # no + # Dn230505 + # + # + # + # + # + # PODCRE + # 09052023 + # Waybill has been PODed + # JNB + # 0719 + # + # + # WBLCRE + # 05052023 + # Waybill Dn230505 created in import + # JNB + # 0718 + # + # + # 05052023 + # Dn230505 + # + # + # + # +# ~ ; + +} #------------------------------------------------------------------------------- + +sub dcb_postalcode { + + our $soapenvelope = qq~ + + + + + $postal_code + $suburb + + + + ~ ; + + &common_debug("[API] dcb_postalcode : [soapenvelope=$soapenvelope]") ; + + &dcb_send_it('PostalCode') ; + &dcb_parse_it ; + &dcb_read_it('PostalCode') ; + +} #------------------------------------------------------------------------------- + +sub dcb_savewabill { + + my ($venue,$ft,$ev_id) = @_ ; + + my $system_loc = $i{"system_location_$ft\_$ev_id"} ; + my $supplier = $i{"logistics_supplier_id_$ft\_$ev_id"} ; + my $status = $i{"status_$ft\_$ev_id"} ; + my $waybill_nr = $i{"waybill_nr_$ft\_$ev_id"} ; + my $items = $i{"item_$ft\_$ev_id"} ; + my $poc = $i{"poc_$ft\_$ev_id"} ; + my $special_instructions = $i{"special_instructions_$ft\_$ev_id"} ; + + # my $dest = ($ft eq 'to') ? $db{organisations}{$venue}{name} : $db{logistics_locations}{$system_loc}{location} ; + # my $orig = ($ft eq 'from') ? $db{organisations}{$venue}{name} : $db{logistics_locations}{$system_loc}{location} ; + + my $dest = ($ft eq 'from') ? $db{logistics_locations}{$system_loc}{location} : ($routeCode) ? substr($routeCode,0,3) : $db{organisations}{$venue}{region_code} ; + my $orig = ($ft eq 'to') ? $db{logistics_locations}{$system_loc}{location} : ($routeCode) ? substr($routeCode,0,3) : $db{organisations}{$venue}{region_code} ; + + my ($poc_name,$poc_nr) = split(/\_/,$poc) ; + + if ($dest =~ /ITV/) { $dest =~ s/\ITV//g ; $dest =~ s/ //g ; } + elsif ($orig =~ /ITV/) { $orig =~ s/\ITV//g ; $orig =~ s/ //g ; } + + # my $accountnumber = ($testdcd) ? 'DCBMAILBAG' : 'DI31F' ; + my $accountnumber = ($testdcd) ? 'DCBMAILBAG' : 'DI31' ; + + our $soapenvelope = qq~ + + + + + + $accountnumber + $address1 + $address2 + $address3 + $address4 + $poc_nr + $poc_name + + $dcbdate + $dest + $waybill_nr + $orig + $postal_code + $suburb + $db{organisations}{$venue}{name} + $routeCode + $special_instructions + 1 + + + + ~ ; + + &common_debug("[API] dcb_savewabill : [soapenvelope=$soapenvelope]") ; + + &dcb_send_it('savewabill') ; + &dcb_parse_it ; + &dcb_read_it('savewabill') ; + +} #------------------------------------------------------------------------------- + +sub dcb_upload_oms_waybill { + + my ($venue,$ft,$ev_id) = @_ ; + + my $tbl_log_loc = 'logistics_locations' ; + my $tbl_org = 'organisations' ; + my $system_loc = $i{"system_location_$ft\_$ev_id"} ; + my $supplier = $i{"logistics_supplier_id_$ft\_$ev_id"} ; + my $status = $i{"status_$ft\_$ev_id"} ; + my $waybill_nr = $i{"waybill_nr_$ft\_$ev_id"} ; + my $items = $i{"item_$ft\_$ev_id"} ; + my $poc = $i{"poc_$ft\_$ev_id"} ; my ($poc_name,$poc_nr) = split(/\_/,$poc) ; + # my $special_instructions = $i{"special_instructions_$ft\_$ev_id"} ; + + my $start_end = ($ft eq 'from') ? 'end' : 'start' ; + my $special_instructions = "Event $start_end : $dcbdate. " . $i{"special_instructions_$ft\_$ev_id"} ; + + $rec{address1} = $address1 ; + $rec{address1} .= ', ' if $address1 && $address2 ; + $rec{address1} .= $address2 if $address2 ; + $rec{address2} = $address3 ; + $rec{address2} .= ', ' if $address3 && $address4 ; + $rec{address2} .= $address4 if $address4 ; + $rec{city} = $city ; + $rec{suburb} = $suburb ; + $rec{postal_code} = $postal_code ; + $rec{poc_name} = $poc_name ; + $rec{poc_nr} = $poc_nr ; + $rec{name} = $db{$tbl_org}{$venue}{name} ; + $rec{routecode} = $routeCode ; + + $send{address1} = $db{$tbl_log_loc}{$system_loc}{address_line_1} ; + $send{address1} .= ', ' if $db{$tbl_log_loc}{$system_loc}{address_line_1} && $db{$tbl_log_loc}{$system_loc}{address_line_2} ; + $send{address1} .= $db{$tbl_log_loc}{$system_loc}{address_line_2} if $db{$tbl_log_loc}{$system_loc}{address_line_2} ; + $send{address2} = $db{$tbl_log_loc}{$system_loc}{address_line_3} ; + $send{address2} .= ', ' if $db{$tbl_log_loc}{$system_loc}{address_line_3} && $db{$tbl_log_loc}{$system_loc}{address_line_4} ; + $send{address2} .= $db{$tbl_log_loc}{$system_loc}{address_line_4} if $db{$tbl_log_loc}{$system_loc}{address_line_4} ; + $send{city} = $db{$tbl_log_loc}{$system_loc}{city} ; + $send{suburb} = $db{$tbl_log_loc}{$system_loc}{suburb} ; + $send{postal_code} = $db{$tbl_log_loc}{$system_loc}{postal_code} ; + $send{poc_name} = $db{$tbl_log_loc}{$system_loc}{poc_name} ; + $send{poc_nr} = $db{$tbl_log_loc}{$system_loc}{poc_nr} ; + $send{name} = $db{$tbl_log_loc}{$system_loc}{location} ; + $send{routecode} = $db{$tbl_log_loc}{$system_loc}{dcb_route_code} ; + + # my $dest = ($ft eq 'from') ? $db{$tbl_log_loc}{$system_loc}{location} : ($routeCode) ? substr($routeCode,0,3) : $db{$tbl_log_loc}{$venue}{region_code} ; + # my $orig = ($ft eq 'to') ? $db{$tbl_log_loc}{$system_loc}{location} : ($routeCode) ? substr($routeCode,0,3) : $db{$tbl_log_loc}{$venue}{region_code} ; + + if ($ft eq 'from') { + foreach (keys %rec) { + my $rec = $rec{$_} ; + $rec{$_} = $send{$_} ; + $send{$_} = $rec ; + } + } + + # if ($dest =~ /ITV/) { $dest =~ s/\ITV//g ; $dest =~ s/ //g ; } + # elsif ($orig =~ /ITV/) { $orig =~ s/\ITV//g ; $orig =~ s/ //g ; } + + # our $soapenvelope = qq~ + # + # + # + # + # DCBMAILBAG + # $items_cnt~; + + # my $accountnumber = ($testdcd) ? 'DCBMAILBAG' : 'DI31F' ; + my $accountnumber = ($testdcd) ? 'DCBMAILBAG' : 'DI31' ; + + our $soapenvelope = qq~ + + + + + $accountnumber + + + + + + + 0 + + + $items_cnt~; + + for my $parcel_cnt (1 .. $items_cnt) { + my $parcel_qty = ($db{logistics_items}{$items[$parcel_cnt-1]}{qty}) ? $db{logistics_items}{$items[$parcel_cnt-1]}{qty} : 1 ; + my $parcel_desc = ($db{logistics_items}{$items[$parcel_cnt-1]}{name}) ? $db{logistics_items}{$items[$parcel_cnt-1]}{name} : 1 ; + $soapenvelope .= qq~ + + + STD + G + 0 + 1 + $parcel_desc + 1 + 1 + 1 + $parcel_cnt + $parcel_qty + + ~; + } + + $soapenvelope .= qq~ + $rec{address1} + $rec{address2} + $rec{city} + $rec{poc_name} + $rec{poc_nr} + $rec{name} + $rec{postal_code} + $rec{routecode} + $rec{suburb} + $send{address1} + $send{address2} + $send{city} + $send{poc_name} + $send{poc_nr} + $send{name} + $send{postal_code} + $send{routecode} + $send{suburb} + OE + $special_instructions + $waybill_nr + + + +~ ; + + &common_debug("[API] dcb_upload_oms_waybill : [soapenvelope=$soapenvelope]") ; + + &dcb_send_it('UploadOMSWaybill') ; + &dcb_parse_it ; + &dcb_read_it('UploadOMSWaybill') ; + +} #------------------------------------------------------------------------------- + +sub dcb_send_it { + + my ($soapaction) = @_ ; + + my $environment = ($testdcd) ? 'APIUAT' : 'API' ; + + my $header_soapaction = "http://tempuri.org/IOMSIntegrate/$soapaction" ; + my $host = "https://dcboms.co.za/$environment/OMSIntegrate.svc" ; + + &common_write_log("dcb/xml_send_$now_year\_$now_mm.log","$now_ccyymmddhrmnsc|$now_ccyy_mm_ddT$now_hh_min_sec|$soapaction|$host|$header_soapaction|$soapenvelope|"); + + &common_debug("[API] dcb_send_it : [host=$host]") ; + &common_debug("[API] dcb_send_it : [soapaction=$header_soapaction]") ; + + if ($testing == 1 && $useropts{it}{$username} && $soapaction ne 'PostalCode') { &common_debug(">>>>>> *** TESTING, $soapaction API call NOT SENT *** <<<<<<") ; return ; } + + my $userAgent = LWP::UserAgent->new(); + my $request = HTTP::Request->new(POST => $host); + $request->header(SOAPAction => "$header_soapaction"); + $request->content($soapenvelope); + $request->content_type("text/xml; charset=utf-8"); + my $response = $userAgent->request($request); + + # Check response + my $response_code = $response -> code ; + my $response_content = $response -> content ; + + &common_debug("[API] dcb_send_it : [response_code=$response_code]") ; + &common_debug("[API] response_content : [response_content=$response_content]") ; + + $returnxml = $response_content ; + + &common_write_log("dcb/xml_response_$now_year\_$now_mm.log","$now_ccyymmddhrmnsc|$now_ccyy_mm_ddT$now_hh_min_sec|$soapaction|$response_code|$returnxml|"); + +} #------------------------------------------------------------------------------- + +sub dcb_parse_it { + + # use Data::Dumper; + # print Dumper(\$returnxml); + # exit; + + $returnxml =~ s/[\x80-\xFF]/?/g ; + my $xml = new XML::Simple or die "Cant instantiate object XML::Simple $!" ; + # my $xmldata = $xml->XMLin($returnxml) or die "Cant open xmldata $!" ; + $xmldata = $xml->XMLin($returnxml, forcearray => 1) or die "Cant open xmldata $!"; + + if ($debug) { + use Data::Dumper; + print Dumper(\$xmldata); + # exit ; + } + +} #------------------------------------------------------------------------------- + +sub dcb_read_it { + + my ($soapaction) = @_ ; + + # my $result = '' ; + + if ($soapaction eq 'UploadOMSWaybill') { + our $uploadwaybillresult = $xmldata->{'s:Body'}->[0]->{'UploadOMSWaybillResponse'}->[0]->{'UploadOMSWaybillResult'}->[0] ; + } elsif ($soapaction eq 'savewabill') { + our $savewabillResult = $xmldata->{'s:Body'}->[0]->{'savewabillResponse'}->[0]->{'savewabillResult'}->[0] ; + } elsif ($soapaction eq 'PostalCode') { + our $routeCode = '' ; # our $routeCode = '' ; + foreach my $hashref (@{$xmldata->{'s:Body'}->[0]->{'PostalCodeResponse'}->[0]->{'PostalCodeResult'}->[0]->{'a:ArrayOfpostalCode'} } ) { + foreach $address (@{$hashref}{'a:postalCode'}) { + $routeCode = ${$hashref}{'a:postalCode'}->[0]->{'a:routeCode'}->[0] ; + } + } + # $routeCode = substr($routeCode,0,3) ; + } elsif ($soapaction eq 'TracknTrace') { + + + foreach my $hashref (@{$xmldata->{'s:Body'}->[0]->{'TracknTraceResponse'}->[0]->{'TracknTraceResult'}->[0]->{'a:Waybill'} } ) { + + $trackntrace{booking_date} = (ref(${$hashref}{'a:BookingDate'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:BookingDate'}->[0] ; + $trackntrace{comments} = ${$hashref}{'a:Comments'}->[0]->{'content'} ; + $trackntrace{consignee_name} = (ref(${$hashref}{'a:ConsigneeName'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ConsigneeName'}->[0] ; + $trackntrace{consignor_name} = (ref(${$hashref}{'a:ConsignorName'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ConsignorName'}->[0] ; + $trackntrace{current_status} = (ref(${$hashref}{'a:CurrentStatus'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:CurrentStatus'}->[0] ; + $trackntrace{delivery_date} = (ref(${$hashref}{'a:DeliveryDate'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:DeliveryDate'}->[0] ; + $trackntrace{insured_value} = (ref(${$hashref}{'a:InsuredValue'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:InsuredValue'}->[0] ; + $trackntrace{number_of_parcels} = (ref(${$hashref}{'a:NumberOfParcels'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:NumberOfParcels'}->[0] ; + $trackntrace{receiver_address_line_1} = (ref(${$hashref}{'a:ReceiverAddressLine1'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ReceiverAddressLine1'}->[0] ; + $trackntrace{receiver_address_line_2} = (ref(${$hashref}{'a:ReceiverAddressLine2'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ReceiverAddressLine2'}->[0] ; + $trackntrace{receiver_city} = (ref(${$hashref}{'a:ReceiverCity'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ReceiverCity'}->[0] ; + $trackntrace{receiver_contact_name} = (ref(${$hashref}{'a:ReceiverContactName'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ReceiverContactName'}->[0] ; + $trackntrace{receiver_contact_tel_1} = (ref(${$hashref}{'a:ReceiverContactTel1'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ReceiverContactTel1'}->[0] ; + $trackntrace{receiver_name} = ${$hashref}{'a:ReceiverName'}->[0]->{'content'} ; + $trackntrace{receiver_postal_code} = (ref(${$hashref}{'a:ReceiverPostalCode'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ReceiverPostalCode'}->[0] ; + $trackntrace{receiver_suburb} = (ref(${$hashref}{'a:ReceiverSuburb'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ReceiverSuburb'}->[0] ; + $trackntrace{sender_address_line_1} = (ref(${$hashref}{'a:SenderAddressLine1'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:SenderAddressLine1'}->[0] ; + $trackntrace{sender_address_line_2} = (ref(${$hashref}{'a:SenderAddressLine2'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:SenderAddressLine2'}->[0] ; + $trackntrace{sender_city} = (ref(${$hashref}{'a:SenderCity'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:SenderCity'}->[0] ; + $trackntrace{sender_contact_name} = (ref(${$hashref}{'a:SenderContactName'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:SenderContactName'}->[0] ; + $trackntrace{sender_contact_tel} = (ref(${$hashref}{'a:SenderContactTel'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:SenderContactTel'}->[0] ; + $trackntrace{sender_postal_code} = (ref(${$hashref}{'a:SenderPostalCode'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:SenderPostalCode'}->[0] ; + $trackntrace{sender_suburb} = (ref(${$hashref}{'a:SenderSuburb'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:SenderSuburb'}->[0] ; + $trackntrace{service_type_code} = (ref(${$hashref}{'a:ServiceTypeCode'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ServiceTypeCode'}->[0] ; + $trackntrace{shipment_is_insured} = (ref(${$hashref}{'a:ShipmentIsInsured'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ShipmentIsInsured'}->[0] ; + $trackntrace{shipper_reference} = (ref(${$hashref}{'a:ShipperReference'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ShipperReference'}->[0]->{''} ; + $trackntrace{account_nr} = (ref(${$hashref}{'a:accNr'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:accNr'}->[0] ; + $trackntrace{pod} = ${$hashref}{'a:pod'}->[0]->{'xmlns:b'} ; + $trackntrace{waybill_date} = (ref(${$hashref}{'a:waybillDate'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:waybillDate'}->[0] ; + $trackntrace{waybill_number} = (ref(${$hashref}{'a:waybillNumber'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:waybillNumber'}->[0] ; + + my $additional_info = $hashref->{'a:additionalInformation'}->[0]->{'b:AdditionalInformation'}->[0]; + $trackntrace{additional_information}{additional_info_code} = (ref($additional_info->{'b:additionalInfoCode'}->[0]) eq 'HASH') ? '' : $additional_info->{'b:additionalInfoCode'}->[0]; + $trackntrace{additional_information}{additional_info_value} = (ref($additional_info->{'b:additionalInfoValue'}->[0]) eq 'HASH') ? '' : $additional_info->{'b:additionalInfoValue'}->[0]; + $trackntrace{additional_information}{waybill_number} = (ref($additional_info->{'b:waybillNumber'}->[0]) eq 'HASH') ? '' : $additional_info->{'b:waybillNumber'}->[0]; + + my $tracking_details = $hashref->{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}; + for my $i (0..$#$tracking_details) { + my $event_index = $i + 1; + $trackntrace{tracking_detail}{event_code}{$event_index} = (ref($tracking_details->[$i]->{'b:eventCode'}->[0]) eq 'HASH') ? '' : $tracking_details->[$i]->{'b:eventCode'}->[0]; + $trackntrace{tracking_detail}{event_date}{$event_index} = (ref($tracking_details->[$i]->{'b:eventDate'}->[0]) eq 'HASH') ? '' : $tracking_details->[$i]->{'b:eventDate'}->[0]; + $trackntrace{tracking_detail}{event_description}{$event_index} = (ref($tracking_details->[$i]->{'b:eventDescription'}->[0]) eq 'HASH') ? '' : $tracking_details->[$i]->{'b:eventDescription'}->[0]; + $trackntrace{tracking_detail}{event_hub_code}{$event_index} = (ref($tracking_details->[$i]->{'b:eventHubCode'}->[0]) eq 'HASH') ? '' : $tracking_details->[$i]->{'b:eventHubCode'}->[0]; + $trackntrace{tracking_detail}{event_time}{$event_index} = (ref($tracking_details->[$i]->{'b:eventTime'}->[0]) eq 'HASH') ? '' : $tracking_details->[$i]->{'b:eventTime'}->[0]; + } + + # $trackntrace{additional_information}{additional_info_code} = ${$hashref}{'a:additionalInformation'}->[0]->{'b:AdditionalInformation'}->[0]->{'b:additionalInfoCode'}->[0] ; + # $trackntrace{additional_information}{additional_info_value} = ${$hashref}{'a:additionalInformation'}->[0]->{'b:AdditionalInformation'}->[0]->{'b:additionalInfoValue'}->[0] ; + # $trackntrace{additional_information}{waybill_number} = ${$hashref}{'a:additionalInformation'}->[0]->{'b:AdditionalInformation'}->[0]->{'b:waybillNumber'}->[0] ; + + # $trackntrace{tracking_detail}{event_code}{1} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[0]->{'b:eventCode'}->[0] ; + # $trackntrace{tracking_detail}{event_date}{1} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[0]->{'b:eventDate'}->[0] ; + # $trackntrace{tracking_detail}{event_description}{1} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[0]->{'b:eventDescription'}->[0] ; + # $trackntrace{tracking_detail}{event_hub_code}{1} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[0]->{'b:eventHubCode'}->[0] ; + # $trackntrace{tracking_detail}{event_time}{1} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[0]->{'b:eventTime'}->[0] ; + + # $trackntrace{tracking_detail}{event_code}{2} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[1]->{'b:eventCode'}->[0] ; + # $trackntrace{tracking_detail}{event_date}{2} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[1]->{'b:eventDate'}->[0] ; + # $trackntrace{tracking_detail}{event_description}{2} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[1]->{'b:eventDescription'}->[0] ; + # $trackntrace{tracking_detail}{event_hub_code}{2} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[1]->{'b:eventHubCode'}->[0] ; + # $trackntrace{tracking_detail}{event_time}{2} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[1]->{'b:eventTime'}->[0] ; + + } + + } + + # return ($result) ; + + # print "\n" . $xmldata->{'s:Body'}->[0]->{'savewabillResponse'}->[0]->{'savewabillResult'}->[0] ; + + # return unless $event_id ; + # return unless $from_to ; + + # &db_min_ro("event_quotes","1,logistics_dcb_waybill","`id`='$event_id'","","") ; + + # my @waybill_nrs = split(/\-/,$db{event_quotes}{1}{logistics_waybill_nrs}) ; + # my @dcb_waybill = split(/\-/,$logistics_dcb_waybill) ; + + # my $dcb_waybill = ($from_to eq 'to') ? "$dcb_waybill[0]-1" : "1-$dcb_waybill[1]" ; + + # $ii{$event_id}{logistics_dcb_waybill} = $dcb_waybill ; + + # our $testing = 1 ; + + # &db_min_upd('event_quotes',"`id`='$event_id'") ; + # &db_min_upd('event_quotes',"`id`='5136'") ; + +} #------------------------------------------------------------------------------- + +# sub dcb_send_it_get_route_code { + + # my ($postal_code,$suburb) = @_ ; + + # my $message = qq~ + # + # + # + # + # $postal_code + # $suburb + # + # + # + # + # ~ ; + + # if ($debug) { + # print $message; + # } + + # my $userAgent = LWP::UserAgent->new(); + # my $request = HTTP::Request->new(POST => 'https://dcboms.co.za/APIUAT/OMSIntegrate.svc'); + # $request->header(SOAPAction => '"http://tempuri.org/IOMSIntegrate/savewabill"'); + # $request->content($message); + # $request->content_type("text/xml; charset=utf-8"); + # my $response = $userAgent->request($request); + + # # Check response + # my $response_code = $response -> code ; + # my $response_content = $response -> content ; + + # $returnxml = $response_content ; + +# } #------------------------------------------------------------------------------- + + +1 ; \ No newline at end of file diff --git a/libs/modules/_FromProd/dialog.pm b/libs/modules/_FromProd/dialog.pm new file mode 100644 index 0000000..1d8643b --- /dev/null +++ b/libs/modules/_FromProd/dialog.pm @@ -0,0 +1,34 @@ +#--------------------------------------------------------------------------------- + +sub dialog_common { + +$dialog{'common'}{'head'} = qq( + + + + $useropts{short} Admin + + + + + + + + + + + + + + + + +) ; + +} #------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/_FromProd/event_email.pm b/libs/modules/_FromProd/event_email.pm new file mode 100644 index 0000000..6c175cc --- /dev/null +++ b/libs/modules/_FromProd/event_email.pm @@ -0,0 +1,146 @@ + +sub create_event_email_table { + + my ($event_id) = @_ ; + + &db_min_ro('event_quotes','1,country_id,event_system_id_multiple,type_details_id,qty,club_name,operator_ids,ref,organisation_ids,date_from,date_to,poc_name,poc_contact_nr,type,sport_type_ids,region_id,city_id,quote_to,category_id_1,category_id_2,additional_notes,user_id,format_of_title',"`id`='$event_id'",'','') ; + + # &db_min_ro('user_type','id,name,email,user_type',"",'','') ; + &db_min_ro('users','id,name,email,user_type',"",'','') ; + + our %operator_email = () ; + foreach (keys %{$db{user_type}}) { + $operator_email{$db{user_type}{$_}{email}} = 1 if substr($db{user_type}{$_}{user_type},0,6) eq 'casual' and $db{user_type}{$_}{email} ; + } + + my $system_details = "" ; + + &db_min_ro('event_type_details','id,name','','','') ; + + foreach (split(",",$db{event_quotes}{1}{type_details_id})) { + $system_details .= qq~$db{event_type_details}{$_}{name},~ ; + } + chop $system_details if $system_details ; + + &db_min_ro('sport_types','id,name','','','') ; + + &db_min_ro('event_systems','id,name','','','') ; + + my $SystemName = qq~~ ; + + foreach (split(";",$db{$table}{$qt_id}{event_system_id_multiple})) { + $SystemName .= qq~$db{event_systems}{$_}{name},~ ; + } + chop $SystemName if $SystemName ; + + &db_min_ro('event_quotes_categories','id,category','','','') ; + + &db_min_ro('regions','id,name','','','') ; + + &db_min_ro('countries','1,name,country',"`id`='$db{event_quotes}{1}{country_id}'",'','') ; + + &db_min_ro('cities','id,city','','','') ; + + &db_min_ro('organisations','id,name','','','') ; + + &db_min_ro('customers','id,name','','','') ; + + &db_min_ro('event_types','1,name',"`id`='$db{event_quotes}{1}{type}'",'','') if $db{event_quotes}{1}{type} ; + + &db_min_ro('event_quotes_min','1,category_details',"`id`='$event_id'",'','') ; + + my @cat_details = split('\|;\|',$db{event_quotes_min}{1}{category_details}) ; + + our $sports = qq~~ ; + + foreach (split(",",$db{event_quotes}{1}{sport_type_ids})) { + + $sports .= qq~$db{sport_types}{$_}{name},~ ; + + } + + chop $sports if $sports ; + + my $venues = qq~~ ; + + foreach (split(",",$db{event_quotes}{1}{organisation_ids})) { + + $venues .= qq~$db{organisations}{$_}{name},~ ; + + } + + chop $venues if $venues ; + + my $op_cnt = qq~~ ; my $op_names = qq~~ ; + + foreach (split(",",$db{event_quotes}{1}{operator_ids})) { + $op_cnt++ ; + $op_names .= qq~$db{users}{$_}{name},~ ; + } + chop $op_names if $op_names ; + $op_names = qq~$op_cnt [$op_names]~ if $op_names; + + my %event_details = () ; + + my $city_name = qq~~ ; + $city_name .= qq~$db{cities}{$db{event_quotes}{1}{city_id}}{city},~ if $db{cities}{$db{event_quotes}{1}{city_id}}{city} ; + $city_name .= qq~$db{regions}{$db{event_quotes}{1}{region_id}}{name},~ if $db{regions}{$db{event_quotes}{1}{region_id}}{name} ; + $city_name .= qq~$db{countries}{1}{name} [$db{countries}{1}{country}]~ ; + + $event_details{Client} = qq~Client$db{customers}{$db{event_quotes}{1}{quote_to}}{name}~ ; + $event_details{EventName} = qq~Event Name$db{event_quotes}{1}{ref} [$event_id]~ ; + $event_details{DateFrom} = qq~Event Date/Time From $db{event_quotes}{1}{date_from}~ if $db{event_quotes}{1}{date_from} ; + $event_details{DateTo} = qq~Event Date/Time To $db{event_quotes}{1}{date_to}~ if $db{event_quotes}{1}{date_to} ; + $event_details{Type} = qq~Type of System $db{event_types}{1}{name}~ if $db{event_types}{1}{name} ; + $event_details{SystemDetails} = qq~System Details $system_details~ if $system_details ; + $event_details{SystemName} = qq~System Name $SystemName~ if $SystemName ; + $event_details{ClubName} = qq~Club Name $db{event_quotes}{1}{club_name}~ if $db{event_quotes}{1}{club_name} ; + $event_details{Days} = qq~Days $db{event_quotes}{1}{qty}~ if $db{event_quotes}{1}{qty} ; + $event_details{NrofOperators} = qq~Nr of Operators $op_names~ if $op_names ; + $event_details{SportTypes} = qq~Sport Types(s) $sports~ if $sports ; + $event_details{City} = qq~City $city_name~ ; + $event_details{Venue} = qq~Venue(s) $venues~ if $venues ; + $event_details{PocName} = qq~Poc Name $db{event_quotes}{1}{poc_name}~ if $db{event_quotes}{1}{poc_name} ; + $event_details{PocContactNr} = qq~Poc Contact Nr $db{event_quotes}{1}{poc_contact_nr}~ if $db{event_quotes}{1}{poc_contact_nr} ; + + $cat_details[0] =~ s/\n/,/g; $cat_details[1] =~ s/\n/,/g; $db{event_quotes}{1}{additional_notes} =~ s/\n/,/g; $db{event_quotes}{1}{format_of_title} =~ s/\n/,/g; + + $event_details{Category1} = qq~Category 1 $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_1}}{category}~ if $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_1}}{category} ; + $event_details{Category1Details} = qq~Category 1 Details $cat_details[0]~ if $cat_details[0] ; + $event_details{Category2} = qq~Category 2 $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_2}}{category}~ if $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_2}}{category} ; + $event_details{Category2Details} = qq~Category 2 Details $cat_details[1]~ if $cat_details[1] ; + $event_details{AdditionalNotes} = qq~Additional Notes $db{event_quotes}{1}{additional_notes}~ if $db{event_quotes}{1}{additional_notes} ; + $event_details{format_of_title} = qq~Format of TITLE to be followed 
    when scheduling events $db{event_quotes}{1}{format_of_title}~ if $db{event_quotes}{1}{format_of_title} ; + + our $table_message = qq~ + $event_details{Client} + $event_details{EventName} + $event_details{DateFrom} + $event_details{DateTo} + $event_details{Type} + $event_details{SystemDetails} + $event_details{SystemName} + $event_details{ClubName} + $event_details{Days} + $event_details{NrofOperators} + $event_details{SportTypes} + $event_details{City} + $event_details{Venue} + $event_details{PocName} + $event_details{PocContactNr} + $event_details{Category1} + $event_details{Category1Details} + $event_details{Category2} + $event_details{Category2Details} + $event_details{AdditionalNotes} + $event_details{format_of_title} + ~ ; + + $message = qq~Good day + +Please find attached event details.~ ; + + +} #------------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/_FromProd/event_tabs.pm b/libs/modules/_FromProd/event_tabs.pm new file mode 100644 index 0000000..779c63b --- /dev/null +++ b/libs/modules/_FromProd/event_tabs.pm @@ -0,0 +1,5118 @@ +sub build_workings_costings_forms_jquery { + + my $description_options_costing = $opts{"description_costing_event_1"} ; + $description_options_costing =~ s/\SELECTED//g ; + $description_options_costing =~ s/\"/\'/g ; + + my $description_options_workings = $opts{"description_workings_event_1"} ; + $description_options_workings =~ s/\SELECTED//g ; + $description_options_workings =~ s/\"/\'/g ; + + our $operator_options = $opts{"operator_workings_event_1"} ; + $operator_options =~ s/\SELECTED//g ; + $operator_options =~ s/\"/\'/g ; + + my $btn_ids_string = join(",",@btn_ids) ; + + my $excl_field_ids_string = join(",",@excl_field_ids) ; + my $description_field_ids_string = join(",",@description_field_ids) ; + my $operator_field_ids_string = join(",",@operator_field_ids) ; + my $vat_field_ids_string = join(",",@vat_field_ids) ; + my $qty_field_ids_string = join(",",@qty_field_ids) ; + my $amount_usd_field_ids_string = join(",",@amount_usd_field_ids) ; + + $trigger_jquery_raw .= qq~ + // function update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days + function get_tab (id) { + let tab = "" ; + if (id.includes("workings_event")) { + tab = "workings_event" ; + } else if (id.includes("costing_event")) { + tab = "costing_event" ; + } + return tab ; + } + + function changed_vat (id) { + let tab = get_tab (id) ; + let row_nr = get_row_nr(id) ; + calc_totals(row_nr,tab) ; + } + + function changed_others (id) { + + let row_nr = get_row_nr(id) ; + let firstIndex = id.indexOf('_'); + let col = id.substring(0,firstIndex); + let tab = get_tab (id) ; + if (col == "inputAmount") { + let inp = parseFloat(\$("#"+id).val()) ; + inp = parseFloat(inp) ; + \$("#"+id).val(inp.toFixed(2)) ; + } else if (\$("#selectDescription_"+tab+"_"+row_nr).val() && \$("#selectDescription_"+tab+"_"+row_nr).val() != 14 && \$("#selectOperator_"+tab+"_"+row_nr).val()) { + // \$("#selectOperator_"+tab+"_"+row_nr).val("") ; + // \$("#selectOperator_"+tab+"_"+row_nr).trigger("chosen:updated") ; + } + // else if (col == "selectOperator" && \$("#selectDescription"+tab+"_"+row_nr).val() != 14) { + + // } + + if (col == "selectOperator") { // || (col == "selectDescription" && \$("#selectDescription_"+tab+"_"+row_nr).val( + return ; + } + + calc_totals(row_nr,tab) ; + } + + // \$("$vat_field_ids_string").change(function() { + \$("#content").on("change","[id^='checkboxVat_']", function () { + const id = this.id ; + changed_vat(id) ; + }); + + // \$("$excl_field_ids_string,$description_field_ids_string,$qty_field_ids_string,$amount_usd_field_ids_string,$operator_field_ids_string").change(function() { + \$("#content").on("change","[id^='checkboxExcl_'],[id^='selectDescription_'],[id^='inputQty_'],[id^='inputAmount_usd_'],[id^='selectOperator_workings_event_']", function () { + const id = this.id ; + + if ((id.includes("inputQty_") || id.includes("inputAmount_usd_")) && id.includes("costing_event")) { + + let row_nr = get_row_nr(id) ; + + let f_t = (\$("input[name='added_full_day_cost_item_"+row_nr+"']").val()) ? "full" : (\$("input[name='added_half_day_cost_item_"+row_nr+"']").val()) ? "half" : "" ; + + if (f_t) { + + let col = (id.includes("inputQty_")) ? "-2" : "-1" ; + + let full_half_add = \$("input[name='added_"+f_t+"_day_cost_item_"+row_nr+"']").val() ; + + let get_e_cost_id = (id.includes("inputAmount_usd_")) ? get_row_nr(\$("input[name='added_"+f_t+"_day_cost_item_"+row_nr+"']").val()) : "" ; + + if (((id.includes("inputQty_") && \$(this).val() == nr_days[f_t]) || (id.includes("inputAmount_usd_") && \$(this).val() == default_cost_item_rates[f_t+","+get_e_cost_id])) && full_half_add && full_half_add.includes(col)) { + full_half_add = full_half_add.replace(col+"_","") ; + \$("input[name='added_"+f_t+"_day_cost_item_"+row_nr+"']").val(full_half_add) ; + } else if (full_half_add && !full_half_add.includes(col)) { + \$("input[name='added_"+f_t+"_day_cost_item_"+row_nr+"']").val(col+"_"+full_half_add) ; + } + } + + } else if (id.includes("selectDescription_")) { + + let this_id = id ; + + let row_nr = get_row_nr(id) ; + + let tab = (this_id.includes("_costing_event_")) ? "costing_event" : (this_id.includes("_workings_event_")) ? "workings_event" : "" ; + + let full_day_exists = nr_days["full"] ; let half_day_exists = nr_days["half"] ; + + let already_loaded_full_day = (\$("#"+this_id).val()) ? \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val() : "" ; + let already_loaded_half_day = (\$("#"+this_id).val()) ? \$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val() : "" ; + + already_loaded_full_day = (typeof already_loaded_full_day == 'undefined') ? "" : 1 ; + already_loaded_half_day = (typeof already_loaded_half_day == 'undefined') ? "" : 1 ; + + if (already_loaded_full_day && already_loaded_half_day) { + return ; + } + + if (already_loaded_full_day == 1) { + full_day_exists = 0 ; + } + + if (already_loaded_half_day == 1) { + half_day_exists = 0 ; + } + + let date_from = \$("input[name='date_from']").val() ; + + date_from = date_from.substring(0,10) ; + + let full_half_day = 0 ; + + if (full_day_exists != 0) { + if ((typeof \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val() == 'undefined' || \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val()) && \$("#"+this_id).val()) { + \$("#content").append("") ; + } + full_half_day = 1 ; + // } else if (half_day_exists || (already_loaded_full_day && !half_day_exists && !already_loaded_half_day)) { + } else if (half_day_exists != 0) { + if ((typeof \$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val() == 'undefined' || !\$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val()) && \$("#"+this_id).val()) { + \$("#content").append("") ; + } + full_half_day = 2 ; + } + + let rate_ = "" ; + + if (default_cost_item_rates["full,"+\$("#"+this_id).val()] && full_half_day == 1) { + rate_ = default_cost_item_rates["full,"+\$("#"+this_id).val()] ; + } else if (default_cost_item_rates["half,"+\$("#"+this_id).val()] && full_half_day == 2) { + rate_ = default_cost_item_rates["half,"+\$("#"+this_id).val()] ; + } + if (rate_ == "") { + \$("input[name='added_full_day_cost_item_"+row_nr+"']").remove() ; + \$("input[name='added_half_day_cost_item_"+row_nr+"']").remove() ; + return ; + } + full_half_day = (full_half_day == 1) ? "full" : (full_half_day == 2) ? "half" : "" ; + + \$("input[name='qty_"+tab+"_"+row_nr+"']").val(nr_days[full_half_day]) ; + \$("input[name='amount_usd_"+tab+"_"+row_nr+"']").val(rate_) ; + \$("input[name='amount_ttl_"+tab+"_"+row_nr+"']").val((rate_*nr_days[full_half_day]).toFixed(2)) ; + if (!\$("input[name='added_"+full_half_day+"_day_cost_item_"+row_nr+"']").val()) { + \$("#"+tab+"_"+row_nr).append("") ; + } else { + \$("input[name='added_"+full_half_day+"_day_cost_item_"+row_nr+"']").val("-3_"+\$(this).val()) ; + } + + calc_totals(row_nr,tab) ; + + + } + + changed_others(id) ; + }); + ~ ; + + $trigger_jquery_raw .= qq~ + + \$("#content").on("click","[id^='btn_workings_event_'],[id^='btn_costing_event_']", function () { + // \$("$btn_ids_string").click(function () { + const id = this.id ; + let tab = get_tab (id) ; + + console.log("id : "+id) ; + console.log("tab : "+tab) ; + + add_quote_expenses_row_all(id,tab) ; + }); + + function add_quote_expenses_row_all (id,tab) { + + let row_nr = get_row_nr(id) ; + \$("#"+tab+"_"+row_nr).show(); + let row_html = "" ; + if (tab == "workings_event") { + row_html = add_quote_expenses_row(row_nr,tab,"$description_options_workings","$operator_options") ; + } else if (tab == "costing_event") { + row_html = add_quote_expenses_row(row_nr,tab,"$description_options_costing","") ; + } + \$("#"+tab+"_"+row_nr).html(row_html); + // \$("#$suffix\_"+row_nr).trigger("chosen:updated") ; + + \$("#selectDescription_"+tab+"_"+row_nr).chosen({ allow_single_deselect:true }) ; + + if (tab == "workings_event") { + \$("#selectOperator_workings_event_"+row_nr).chosen({ allow_single_deselect:true }); + \$("#inputRemarks_workings_event_"+row_nr).css("text-align","") ; + \$("#inputSupplier_workings_event_"+row_nr).css("text-align","") ; + \$("#inputRef_nr_workings_event_"+row_nr).css("text-align","") ; + } + + \$("#btn_"+tab+"_"+row_nr).hide(); + \$("#btn_row_"+tab+"_"+row_nr).hide(); + var v = row_nr + 1 ; + + // \$("#btn_$suffix\_"+v).css("padding-left","16px") ; + \$("#btn_"+tab+"_"+v).html("") ; + \$("#btn_"+tab+"_"+v).show(); + \$("#btn_row_"+tab+"_"+v).show() ; + \$("#2_"+tab+"_"+row_nr).show() ; + + \$("#checkboxExcl_"+tab+"_"+row_nr).prop('checked',false) ; + + // \$("#"+tab+"_"+row_nr).on("change","#checkboxVat_"+tab+"_"+row_nr+"", function() { + // const id = this.id ; + // changed_vat(id) ; + // }); + + // \$("#"+tab+"_"+row_nr).on("change","#checkboxExcl_"+tab+"_"+row_nr+",#selectDescription_"+tab+"_"+row_nr+",#selectOperator_"+tab+"_"+row_nr+",#inputQty_"+tab+"_"+row_nr+",#inputAmount_usd_"+tab+"_"+row_nr+"", function() { + // const id = this.id ; + // changed_others(id) ; + // }); + + } + + ~ if $btn_ids_string ; + + $trigger_jquery_raw .= qq~ + + \$("#selectCurrency").change(function () { + + }) ; + + \$("input[name='roe']").change(function () { + + let roe = \$(this).val() ; + if (roe < 0 || !roe) { + roe = 1 ; + } + \$(this).val(parseFloat(roe).toFixed(2)) ; + + var sub_total = 0 ; var vat_total = 0 ; var sub_total_quote = 0 ; var vat_total_quote = 0 ; + + [sub_total,vat_total] = add_up_totals("workings_event",50,roe,1) ; + [sub_total_quote,vat_total_quote] = add_up_totals("costing_event",30,roe,1) ; + + // // // \$("input[name='income']").val((sub_total_quote+vat_total_quote).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("input[name='income']").val((sub_total_quote+vat_total_quote).toFixed(2)) ; + \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + update_overall_totals(sub_total,vat_total,"workings_event") ; + update_overall_totals(sub_total_quote,vat_total_quote,"costing_event") ; + + }) ; + + function add_up_totals (tab,nr_of_rows,roe,recalc_totals) { + + let sub_total = 0 ; let vat_total = 0 ; + for (let i=1; i<=nr_of_rows; i++) { + if (!\$("#"+tab+"_"+i).html()) { break ; } + if (\$("#selectDescription_"+tab+"_"+i).val()) { + if (\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { continue ; } + let ttl = 0 ; + if (recalc_totals) { + ttl = parseFloat(\$("#inputAmount_usd_"+tab+"_"+i).val()) * parseFloat(\$("#inputQty_"+tab+"_"+i).val()) * parseFloat(roe) ; + } else { + ttl = parseFloat(\$("#inputAmount_ttl_"+tab+"_"+i).val().replace(/,/g, '')) + } + // // // // \$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toFixed(2)) ; + if (!\$("#inputAmount_ttl_"+tab+"_"+i).val() || \$("#inputAmount_ttl_"+tab+"_"+i).val() == "NaN") { + \$("#inputAmount_ttl_"+tab+"_"+i).val("0.00") ; + ttl = 0 ; + } + sub_total += ttl ; + if (\$("#checkboxVat_"+tab+"_"+i).is(":checked")) { + vat_total += ttl*0.15 ; + } + } else if (!\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { + \$("#checkboxExcl_"+tab+"_"+i).prop('checked',true) ; + } + } + return [sub_total,vat_total] ; + } + + // function getNum(val) { + + // if (isNaN(val)) { + // return 0; + // } + // return val; + // } + + function calc_totals (row_cnt,tab) { + + var qty = \$("#inputQty_"+tab+"_"+row_cnt) ; + var usd = \$("#inputAmount_usd_"+tab+"_"+row_cnt) ; + var conv = \$("#inputAmount_ttl_"+tab+"_"+row_cnt) ; + var excl = \$("#checkboxExcl_"+tab+"_"+row_cnt) ; + var item = \$("#selectDescription_"+tab+"_"+row_cnt) ; + + if (!usd.val() && !conv.val() && !usd.val()) { + // console.log("skip calc_totals_workings") ; + if (!item.val()) { + excl.prop("checked",true) ; + } + return ; + } + + var vat = \$("#checkboxVat_"+tab+"_"+row_cnt) ; + + if (!item.val()) { + + excl.prop("checked",true) ; + vat.prop("checked",true) ; + qty.val("") ; + usd.val("") ; + conv.val(""); + if (tab == "workings_event") { + var rem = \$("#inputRemarks_"+tab+"_"+row_cnt) ; + var sup = \$("#inputSupplier_"+tab+"_"+row_cnt) ; + var ref = \$("#inputRef_nr_"+tab+"_"+row_cnt) ; + var op = \$("#selectOperator_"+tab+"_"+row_cnt) ; + rem.val("") ; + sup.val("") ; + ref.val("") ; + op.val("") ; + op.trigger("chosen:updated") ; + } + // } else if (excl.is(":checked") && item.val() && conv.val() == "0.00") { + } else if (excl.is(":checked")) { + excl.prop("checked",false) ; + } + + if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) ; } + + let roe = parseFloat(\$("#inputRoe").val()) ; + + let ttl = usd.val() * qty.val() * roe ; + + // // // conv.val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + conv.val(ttl.toFixed(2)) ; + + let sub_total = 0 ; let vat_total = 0 ; + + let nr_of_rows = 50 ; + if (tab == "costing_event") { + nr_of_rows = 30 ; + } + + [sub_total,vat_total] = add_up_totals (tab,nr_of_rows,roe,0) ; + + if (tab == "workings_event") { + // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + update_overall_totals(sub_total,vat_total,tab) ; + } else { + // // // \$("input[name='income']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; + update_overall_totals(sub_total,vat_total,tab) ; + // update_overall_totals_costings(sub_total,vat_total) ; + } + } + + function update_overall_totals (sub_total,vat_total,tab) { + + let profit_loss = parseFloat(\$("input[name='income']").val().replace(/,/g, '')) - parseFloat(\$("input[name='expenses']").val().replace(/,/g, '')) ; + + // // // \$("input[name='profit_loss']").val(profit_loss.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='sub_total_"+tab+"']").val(sub_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='vat_total_"+tab+"']").val(vat_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + + \$("input[name='profit_loss']").val(profit_loss.toFixed(2)) ; + \$("input[name='sub_total_"+tab+"']").val(sub_total.toFixed(2)) ; + \$("input[name='vat_total_"+tab+"']").val(vat_total.toFixed(2)) ; + \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toFixed(2)) ; + } + + function add_quote_expenses_row (row_nr,tab,options1,options2) { + + let tindex = $tindex ; + tindex = parseInt(tindex) ; + row_nr = parseInt(row_nr) ; + tindex = tindex - 10*(1+50-row_nr) ; + + let row = add_checkbox(row_nr,"excl_"+tab+"_"+row_nr,"checkboxExcl_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + + // row = row+""+add_select(row_nr,"description_"+tab+"_"+row_nr,"selectDescription_"+tab+"_"+row_nr,"Select Description "+row_nr,options1,tindex,2,90,'','') ; tindex++ ; + row = row+add_select(row_nr,"description_"+tab+"_"+row_nr,"selectDescription_"+tab+"_"+row_nr,"Select Description "+row_nr,options1,tindex,2,90,'','') ; tindex++ ; + if (tab == "workings_event") { + row = row+add_select(row_nr,"operator_workings_event_"+row_nr,"selectOperator_workings_event_"+row_nr,"Select Operator "+row_nr,options2,tindex,2,90,'','') ; tindex++ ; + row = row+add_input(row_nr,"remarks_workings_event_"+row_nr,"inputRemarks_workings_event_"+row_nr,"Remarks "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"supplier_workings_event_"+row_nr,"inputSupplier_workings_event_"+row_nr,"Supplier "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"ref_nr_workings_event_"+row_nr,"inputRef_nr_workings_event_"+row_nr,"Ref Nr "+row_nr,tindex,'',1) ; tindex++ ; + } + row = row+add_input(row_nr,"qty_"+tab+"_"+row_nr,"inputQty_"+tab+"_"+row_nr,"Qty "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"amount_usd_"+tab+"_"+row_nr,"inputAmount_usd_"+tab+"_"+row_nr,"Amount "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"amount_ttl_"+tab+"_"+row_nr,"inputAmount_ttl_"+tab+"_"+row_nr,"Total Amount "+row_nr,tindex,"readonly",1) ; tindex++ ; + row = row+add_checkbox(row_nr,"vat_"+tab+"_"+row_nr,"checkboxVat_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + return row ; + } + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub event_tabs_build_qt_left { + + my ($id,$tab,$ret,$demo_page) = @_ ; + + if ($tab == 1) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $title_ = ($demo_page) ? "Demo" : "Event" ; + + my $sec = '_customer_details' ; + + my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + $lcol = 3 ; $fcol = 1 ; $add_form_fields = '' ; + + # $add_form_fields .= qq~
    ~ if $is_schools_manager ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + + my $checked = ($db{$table}{$id}{quote_completed}) ? 'CHECKED' : '' ; + $preferred_title{quote_completed} = "$title_ Completed" ; + $add_form_fields .= &common_min_form_checkbox('quote_completed',$db{$table}{$id}{quote_completed},$checked) ; + + # my $checked = 'CHECKED' if $db{$table}{$id}{quote_accepted} ; + my $checked = ($db{$table}{$id}{quote_accepted}) ? 'CHECKED' : '' ; + $preferred_title{quote_accepted} = "$title_ Accepted" ; + $add_form_fields .= &common_min_form_checkbox('quote_accepted',$db{$table}{$id}{quote_accepted},$checked) ; + + my $checked = ($db{$table}{$id}{quote_rejected}) ? 'CHECKED' : '' ; + $preferred_title{quote_rejected} = "$title_ Rejected" ; + $add_form_fields .= &common_min_form_checkbox('quote_rejected',$db{$table}{$id}{quote_rejected},$checked) ; + + # my $checked = 'CHECKED' if $db{$table}{$id}{quote_pending} or $iaction eq 'add' ; + my $checked = ($db{$table}{$id}{quote_pending} || $iaction eq 'add') ? 'CHECKED' : '' ; + $preferred_title{quote_pending} = "$title_ Pending" ; + $add_form_fields .= &common_min_form_checkbox('quote_pending',$db{$table}{$id}{quote_pending},$checked) ; + + # my $checked = 'CHECKED' if $db{$table}{$id}{quote_cancelled} ; + my $checked = ($db{$table}{$id}{quote_cancelled}) ? 'CHECKED' : '' ; + $preferred_title{quote_cancelled} = "$title_ Cancelled" ; + $add_form_fields .= &common_min_form_checkbox('quote_cancelled',$db{$table}{$id}{quote_cancelled},$checked) ; + + # $add_form_fields .= qq~
    ~ if $is_schools_manager ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + + $fcol = 8 ; + $add_form_fields .= &common_min_form_input('contact_name',$db{$table}{$id}{contact_name},'') ; + $add_form_fields .= &common_min_form_input('address',$db{$table}{$id}{address},'') ; + $add_form_fields .= &common_min_form_input('email',$db{$table}{$id}{email},'') ; + $add_form_fields .= &common_min_form_input('tel',$db{$table}{$id}{tel},'') ; + $fcol = 5 ; + + $add_form_fields .= qq~
     
    ~ ; + + &event_tabs_content_box($sec_name,$sec_col); + + $trigger_jquery_raw .= qq~ + + if (!\$("#checkboxQuote_accepted").is(":checked") && !\$("#checkboxQuote_rejected").is(":checked") && !\$("#checkboxQuote_pending").is(":checked") && !\$("#checkboxQuote_cancelled").is(":checked") && !\$("#checkboxQuote_completed").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked","true") ; + } + + \$("#checkboxQuote_completed,#checkboxQuote_accepted,#checkboxQuote_rejected,#checkboxQuote_pending,#checkboxQuote_cancelled").click( function () { + + if (this.id != 'checkboxQuote_completed' && \$("#checkboxQuote_completed").is(":checked")) { + \$("#checkboxQuote_completed").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_accepted' && \$("#checkboxQuote_accepted").is(":checked")) { + \$("#checkboxQuote_accepted").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_rejected' && \$("#checkboxQuote_rejected").is(":checked")) { + \$("#checkboxQuote_rejected").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_pending' && \$("#checkboxQuote_pending").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_cancelled' && \$("#checkboxQuote_cancelled").is(":checked")) { + \$("#checkboxQuote_cancelled").prop("checked",false) ; + } + + if (this.id == 'checkboxQuote_completed' && !\$("#checkboxQuote_accepted").is(":checked")) { + \$("#checkboxQuote_accepted").prop("checked",true) ; + } + + if (!\$("#checkboxQuote_accepted").is(":checked") && !\$("#checkboxQuote_rejected").is(":checked") && !\$("#checkboxQuote_pending").is(":checked") && !\$("#checkboxQuote_cancelled").is(":checked") && !\$("#checkboxQuote_completed").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked","true") ; + } + + }) ; + + ~ ; + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + + if ($tab == 2) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_event_details' ; + + my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + # my $op_change = qq~~ ; + + # for (1 .. $nr_of_system_names_and_clubs) { + # $op_change .= qq~,#selectOperator_id_calibration_$_~ ; + # } + # $op_change = substr($op_change,1) ; + + $lcol = 2 ; $fcol = 3 ; + + $add_form_fields = '' ; + + $add_form_fields .= qq~ +
    +
    ~ ; + + # $fcol = 6 ; + $preferred_title{ref} = 'Event Name' ; + $preferred_title{date_from} = 'Event Date/Time From' ; + $preferred_title{date_to} = 'Event Date/Time To' ; + + my $current_day_of_week = Day_of_Week($now_year,$now_mm,$now_dd) ; + + my $delta_days = 6 - $current_day_of_week ; + $delta_days = 7 unless $delta_days ; + $delta_days = 6 if $delta_days < 0 ; + + my ($def_year,$def_mon,$def_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,$delta_days) ; + $def_mon = sprintf("%02d",$def_mon) ; + $def_day = sprintf("%02d",$def_day) ; + + $db{$table}{$id}{date_from} = "$def_year-$def_mon-$def_day 08:00:00" unless $db{$table}{$id}{date_from} ; + $db{$table}{$id}{date_to} = "$def_year-$def_mon-$def_day 17:00:00" unless $db{$table}{$id}{date_to} ; + + my $hide_select_1 = '' ; my $readonly_select = '' ; my $sport_type_ids_readonly = '' ; my $organisation_ids_readonly = '' ; my $linear_id_readonly = '' ; my $readonlyform = 0 ; # my $hide_select_2 = qq~~ ; + + my $quote_accepted = $db{$table}{$id}{quote_accepted} ; + my $quote_rejected = $db{$table}{$id}{quote_rejected} ; + my $quote_cancelled = $db{$table}{$id}{quote_cancelled} ; + my $quote_completed = $db{$table}{$id}{quote_completed} ; +# $db{$table}{$event_id}{quote_completed} + # if (($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 4) { + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { + + for (1 .. 20) { + $readonly{"time_from_$_"} = "READONLY"; + $readonly{"time_to_$_"} = "READONLY"; + } + + $readonlyform = 1 ; + + $readonly{ref} = "READONLY" ; $readonly{date_from} = "READONLY" ; $readonly{date_to} = "READONLY" ; $readonly{qty} = "READONLY" ; $readonly{city_id} = "READONLY" ; + $add_form_fields .= &common_min_form_input('ref',$db{$table}{$id}{ref},'') ; + $add_form_fields .= &common_min_form_input('date_from',$db{$table}{$id}{date_from}) ; + $add_form_fields .= &common_min_form_input('date_to',$db{$table}{$id}{date_to}) ; + $hide_select_1 = qq~~ ; + + $readonly{sport_type_ids_readonly} = "READONLY" ; $readonly{region_id_readonly} = "READONLY" ; $readonly{city_id_readonly} = "READONLY" ; $readonly{organisation_ids_readonly} = "READONLY" ; $readonly{linear_id_readonly} = "READONLY" ; + + $preferred_title{sport_type_ids_readonly} = "Sport Type(s)" ; $preferred_title{region_id_readonly} = "Regions" ; $preferred_title{city_id_readonly} = "City" ; $preferred_title{organisation_ids_readonly} = "Venue(s)" ; $preferred_title{linear_id_readonly} = "Linear" ; + + foreach (split(",",$db{$table}{$id}{sport_type_ids})) { + $sport_type_ids_readonly .= qq~$db{sport_types}{$_}{name},~ ; + } + chop $sport_type_ids_readonly if $sport_type_ids_readonly ; + + foreach (split(",",$db{$table}{$id}{organisation_ids})) { + $organisation_ids_readonly .= qq~$db{organisations}{$_}{name},~ ; + } + chop $organisation_ids_readonly if $organisation_ids_readonly ; + + local %linear_vals = () ; $linear_vals{1} = "Yes" ; $linear_vals{2} = "No" ; $linear_vals{3} = "Delayed" ; + + # my $cities_readoly = qq~~ ; + # foreach my $city_id (split(",",$db{$table}{$id}{city_id})) { + # $cities_readoly .= qq~$db{cities}{$city_id}{city}, ~ ; + # } + # chop $cities_readoly if $cities_readoly ; chop $cities_readoly if $cities_readoly ; + + my $cities_readoly = join (", ", map { "$db{cities}{$city_id}{name}" } split(/\,/,$db{$table}{$id}{city_id})) ; + + # $readonly_select .= &common_min_form_input('sport_type_ids_readonly',$db{sport_types}{$db{$table}{$id}{sport_type_ids}}{name},'') ; + $readonly_select .= &common_min_form_input('sport_type_ids_readonly',$sport_type_ids_readonly ,'') ; + $readonly_select .= &common_min_form_input('region_id_readonly',$db{regions}{$db{$table}{$id}{region_id}}{name},'') ; + $readonly_select .= &common_min_form_input('city_id_readonly',$cities_readoly,'') ; + # $readonly_select .= &common_min_form_input('organisation_ids_readonly',$db{organisations}{$db{$table}{$id}{organisation_ids}}{name},'') ; + $readonly_select .= &common_min_form_input('organisation_ids_readonly',$organisation_ids_readonly,'') ; + $readonly_select .= &common_min_form_input('linear_id_readonly',$linear_vals{$db{$table}{$id}{linear_id}},'') ; + } else { + $add_form_fields .= &common_min_form_input('ref',$db{$table}{$id}{ref},'') ; + $readonly{date_from} = "READONLY" ; $readonly{date_to} = "READONLY" ; + $add_form_fields .= &common_min_form_datetimepicker('date_from',$db{$table}{$id}{date_from}) ; + $add_form_fields .= &common_min_form_datetimepicker('date_to',$db{$table}{$id}{date_to}) ; + + $dlg{sport_type_ids} = qq~   $db{$table}{$id}{sports_type}~ ; + $dlg{sport_type_ids} .= qq~
    ~ ; + $dlg{city_id} .= qq~   $db{$table}{$id}{city}~ ; + $dlg{city_id} .= qq~
    ~ ; + $dlg{organisation_ids} .= qq~   $db{$table}{$id}{location}~ ; + $dlg{organisation_ids} .= qq~
    ~ ; + $dlg{region_id} .= qq~   $db{$table}{$id}{location}~ ; + $dlg{region_id} .= qq~
    ~ ; + } + + # $fcol = 1 ; + $preferred_title{qty} = 'Actual Days' ; $dont_end_row{qty} = 1 ; + + # if (($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 4) { $readonly{qty} = "READONLY" ; } + # if (($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) { $readonly{qty} = "READONLY" ; } + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { $readonly{qty} = "READONLY" ; } + + my @times_from = split(/\;/,";$db{$table}{$id}{times_from}") ; + my @times_to = split(/\;/,$db{$table}{$id}{times_to}) ; + + my @default = () ; my $saved_time_from = qq~~ ; my $saved_time_to = qq~~ ; + + my $year = ($db{$table}{$id}{date_from}) ? substr($db{$table}{$id}{date_from},0,4) : $now_year ; + my $month = ($db{$table}{$id}{date_from}) ? substr($db{$table}{$id}{date_from},5,2) : $now_mm ; + my $day = ($db{$table}{$id}{date_from}) ? substr($db{$table}{$id}{date_from},8,2) : $now_dd ; + + $fcol = 1 ; + + $radio_opts{event_length} = "Full Day+Half Day" ; + + # my $cnt_radio_opts = 0 ; + + # foreach (split(/\+/,$radio_opts{event_length})) { + # $cnt_radio_opts++ ; + # } + + my @timepicker_ids = () ; my @day_ids = () ; + + my %default_days_selected = () ; our %default_active_event_dates = () ; + + # our $final_day_active = 0 ; local $cnt_days = 0 ; + + # foreach (@defaut_days_active) { + # $cnt_days++ ; + # $final_day_active = $cnt_days if $_ ; + # } + + my ($year1,$month1,$day1) = split(/\-/,substr($db{$table}{$id}{date_from},0,10)); + my ($year2,$month2,$day2) = split(/\-/,substr($db{$table}{$id}{date_to},0,10)); + + our $final_day = Delta_Days($year1,$month1,$day1,$year2,$month2,$day2) + 1 ; + + our @defaut_days_active = split(/\;/,$db{$table}{$id}{days_active}) ; + + my $event_without_saved_defaults = 0 ; + + if (!$db{$table}{$id}{days_active}) { + $event_without_saved_defaults = 1 ; + # my $def_qty = ($db{$table}{$id}{qty}) ? $db{$table}{$id}{qty} : 1 ; + + for (1 .. $final_day) { + # for (1 .. $def_qty) { + $db{$table}{$id}{days_active} .= "1;" ; + } + # $trigger_jquery .= qq~\$("#selectDay_1_chosen").css("width","100%" );~ if $def_qty== 1 ; + } + my @default_event_length = split(/\;/,$db{$table}{$id}{event_length}) ; my %calc_default_event_length = () ; + + my @days_active = split(/\;/,$db{$table}{$id}{days_active}) ; + + my $cnt = 0 ; + # my $final_day = 0 ; + my $no_event_days_cnt = 0 ; + + my $hide_rows_1 = (substr($db{$table}{$id}{date_from},0,10) eq substr($db{$table}{$id}{date_to},0,10)) ? "style='display:none;'" : "" ; + my $hide_rows_2 = ($final_day <= 10) ? "style='display:none;'" : "" ; + + my %time_label_header_row = () ; + + $time_label_header_row{1} = qq~
    ~ ; + $time_label_header_row{2} = qq~
    ~ ; + + # foreach (@days_active) { + # $cnt++ ; + # $final_day = $cnt if $_ ; + # } + + # $final_day = 1 unless $final_day ; + # $final_day = $db{$table}{$id}{qty} if $db{$table}{$id}{qty} && !$days_active[$db{$table}{$id}{qty}-1] ; + + my $def_nr_of_full_days = 0 ; my $def_nr_of_half_days = 0 ; + + for (1 .. 20) { + + my $cnt_row = ($_ <= 10) ? 1 : 2 ; + + $default_days_selected{blank}{$_} = "SELECTED" unless $days_active[$_ - 1] ; + $default_days_selected{1}{$_} = "SELECTED" if $days_active[$_ - 1] ; + + push @timepicker_ids,"#timepickerTime_from_$_" ; + push @timepicker_ids,"#timepickerTime_to_$_" ; + push @day_ids,"#day_$_" ; + + my ($new_year,$new_month,$new_day) = ($_ > 1) ? Add_Delta_Days($year,$month,$day,$_-1) : ($year,$month,$day) ; + $new_day = sprintf("%02s",$new_day) ; + $new_month = sprintf("%02s",$new_month) ; + + # $default_active_event_dates{$_} = "$new_year-$new_month-$new_day" if $days_active[$_ - 1] ; + $default_active_event_dates{$_} = "$new_year-$new_month-$new_day" if $_ <= $final_day ; + + my $field = "time_from_$_" ; + $default[$_ - 1] = $times_from[$_ - 1] ; + $default[$_ - 1] = substr($db{$table}{$id}{date_from},11) if $db{$table}{$id}{date_from} && (!$times_from[$_ - 1] || $_ == 1) ; + my $default1 = $default[$_ - 1] ; + + $custom_style{$field} = ((!$event_without_saved_defaults && !$defaut_days_active[$_ - 1]) || $_ == 1 || ($_ > $final_day)) ? qq~display:none;~ : '' ; + # $days_time_row .= ($glod_user_level > 2) ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} ne "READONLY" || ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~ ; + $days_time_row{$cnt_row} .= ($readonly{qty} ne "READONLY") ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} eq "READONLY" && ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~ ; + + $trigger_jquery_raw .= qq~\$("#timepickerTime_from_1").css("display","none");~ ; + + # $default_time_from .= qq~"$_":"$default[$_ - 1]",~ ; + $saved_time_from .= qq~"$_":"$times_from[$_ - 1]",~ if $times_from[$_ - 1] ; + # $final_day = $_ if $times_from[$_ - 1] ; + $field = "time_to_$_" ; + + + $custom_style{$field} = ((!$event_without_saved_defaults && !$defaut_days_active[$_ - 1]) || $_ >= $final_day) ? qq~display:none;~ : '' ; + $default[$_ - 1] = $times_to[$_ - 1] ; + $default[$_ - 1] = substr($db{$table}{$id}{date_to},11) if $db{$table}{$id}{date_to} && (!$times_to[$_ - 1] || $_ == 6) ; + #___ + # $days_time_row_2 .= ($readonly{qty} ne "READONLY") ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($final_day >= $_ && !$custom_style{$field}) ? &common_min_form_input_col($field,$default[$_ - 1],'',0) : qq~
    ~ ; + + # $days_time_row_2 .= ($glod_user_level > 2) ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} ne "READONLY" || ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~ ; + $days_time_row_2{$cnt_row} .= ($readonly{qty} ne "READONLY") ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} eq "READONLY" && ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~ ; + + # $trigger_jquery_raw .= qq~\$("#timepickerTime_from_$_").css("display","none");~ if $db{$table}{$id}{qty} < $_ ; + + # if (!$db{$table}{$id}{days_active} && ($db{$table}{$id}{qty} != 1 || !$db{$table}{$id}{event_length}) && $db{$table}{$id}{qty} >= $_) { + # if (!$db{$table}{$id}{days_active} || ($days_active[$_ - 1] && !$default_event_length[$_ - 1])) { + + # $trigger_jquery .= qq~ + # \$("#radio_1_1").prop('checked',true) ; + # ~ if $_ == 1 ; + + if ($default_event_length[$_ - 1] eq '1' && $days_active[$_ - 1]) { + $def_nr_of_full_days++ ; + } elsif ($default_event_length[$_ - 1] eq '2' && $days_active[$_ - 1]) { + $def_nr_of_half_days++ ; + } + + if (!$db{$table}{$id}{event_length}) { + + my ($h1,$m1,$s1) = ($_ == 1 || !$times_from[$_ - 1]) ? split(/\:/,substr($db{$table}{$id}{date_from},11)) : split(/\:/,$times_from[$_ - 1]) ; + my ($h2,$m2,$s2) = split(/\:/,substr($db{$table}{$id}{date_to},11)) ; + my $time_diff = 3600*($h2-$h1) + 60*($m2-$m1) + ($s2-$s1) ; + + if ($time_diff >= 18000) { + $calc_default_event_length{$_} = 1 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_1").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_full_days++ if $default_event_length[$_ - 1] ; + } elsif ($time_diff >= 0 && $time_diff < 18000) { + $calc_default_event_length{$_} = 2 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_2").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_half_days++ if $default_event_length[$_ - 1] ; + } + + $trigger_jquery .= qq~ + \$("#day_$_").val("1") ; + \$("#day_$_").trigger("chosen:updated") ; + ~ if $_ <= $final_day && $readonly{qty} ne "READONLY" ; + + } elsif ($_ <= $final_day) { + + # $days_active[$_ - 1 + + # my ($h1,$m1,$s1) = split(/\:/,$times_from[$_ - 1]) ; + # my ($h2,$m2,$s2) = split(/\:/,$times_to[$_ - 1]) ; + # my $time_diff = 3600*($h2-$h1) + 3600*($m2-$m1) + ($s2-$s1) ; + if ($default_event_length[$_ - 1]) { + if ($default_event_length[$_-1] eq "1") { + $trigger_jquery .= qq~ + // \$("input[name='selected_$_\_event_length']").val("1") ; + \$("#radio_$_\_1").prop('checked',true) ; + ~ ; + # $def_nr_of_full_days++ ; + } elsif ($default_event_length[$_-1] eq "2") { + $trigger_jquery .= qq~ + // \$("input[name='selected_$_\_event_length']").val("2") ; + \$("#radio_$_\_2").prop('checked',true) ; + ~ ; + # $def_nr_of_half_days++ ; + } + } else { + my ($h1,$m1,$s1) = split(/\:/,substr($db{$table}{$id}{date_from},11)) ; + my ($h2,$m2,$s2) = split(/\:/,substr($db{$table}{$id}{date_to},11)) ; + my $time_diff = 3600*($h2-$h1) + 60*($m2-$m1) + ($s2-$s1) ; + + if ($time_diff >= 18000) { + $calc_default_event_length{$_} = 1 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_1").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_full_days++ ; + } elsif ($time_diff >= 0 && $time_diff < 18000) { + $calc_default_event_length{$_} = 2 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_2").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_half_days++ ; + } + } + } + + if ((!$days_active[$_ - 1] && $_ > $final_day) || ($db{$table}{$id}{days_active} == ";;;;;") || (!$days_active[$_ - 1] && $_ <= $final_day)) { + $trigger_jquery .= qq~\$("#radio_$_\_1").css("display","none") ; ~ ; + $trigger_jquery .= qq~\$("#radio_$_\_2").css("display","none") ; ~ ; + } + + # $default_time_to .= qq~"$_":"$default[$_ - 1]",~ ; + $saved_time_to .= qq~"$_":"$times_to[$_ - 1]",~ if $times_to[$_ - 1] ; + + $field = "day_$_" ; + $custom_style{$field} = ($final_day < $_ || $final_day == 1) ? qq~display:none;~ : '' ; + + if ($readonly{qty} ne "READONLY") { + # if ($glod_user_level > 2) { + + $trigger_jquery .= qq~\$("#day_$_\_chosen").css("display","none");~ if $_ > $final_day || $final_day == 1 ; + + # $time_label_header_row .= qq~
    ~ ; + + $time_label_header_row{$cnt_row} .= qq~ +
    + +
    + ~ ; + + # $trigger_jquery .= qq~ console.log("Day $_ : ;$default_days_selected{blank}{$_};$default_days_selected{1}{$_}; "+\$("#day_$_").val()) ; ~ ; + + } else { + $time_label_header_row{$cnt_row} .= (!$default_days_selected{1}{$_}) ? qq~ +
    + ~ : qq~ +
    +
    + ~ ; + } + } + + $def_nr_of_full_days = 1 if !$def_nr_of_full_days && !$def_nr_of_half_days ; + + $trigger_jquery_raw .= qq~\$("#timepickerTime_to_$final_day").css("display","none");~ if $final_day ; + + my $day_ids_string = join(",",@day_ids) ; + + # chop $default_time_from if $default_time_from ; chop $default_time_to if $default_time_to ; + + $trigger_jquery_raw .= qq~ + + // let [nr_days["full"],nr_days["half"]] = count_nr_of_full_day_and_half_days() ; + + let nr_days = {} ; let prev_nr_days = {} ; + + nr_days["full"] = "$def_nr_of_full_days" ; + nr_days["half"] = "$def_nr_of_half_days" ; + + nr_days["full"] = parseInt(nr_days["full"]) ; + nr_days["half"] = parseInt(nr_days["half"]) ; + + prev_nr_days["full"] = nr_days["full"] ; prev_nr_days["half"] = nr_days["half"] ; + const default_cost_item_rates = {$default_cost_item_rates_javascript} ; + // const default_full_day_cost_item_rates = {$default_full_day_cost_item_rates_javascript} ; + // const default_half_day_cost_item_rates = {$default_half_day_cost_item_rates_javascript} ; + + let ij = 0 ; let orig_selected_system_names = {} ; + // const get_event_cost_id = {"63":"24","286":"25","285":"10"} ; // TESTING + const get_event_cost_id = {$get_event_cost_id_from_system_id_javascript} ; // TESTING + let cnt_systems_per_cost_item = {} ; + + let changed_radio_cnt = 0 ; let system_with_cost_item_rates_selected = 0 ; + + let saved_time_from = {$saved_time_from} ; + let saved_time_to = {$saved_time_to} ; + + // while (true) { + // ij++ ; + // if (!\$("#system_name_row_"+ij).html()) { + // break ; + // } + // orig_selected_system_names[ij] = (\$("#selectSystem_name_"+ij).val()) ? \$("#selectSystem_name_"+ij).val() : "" ; + // if (default_cost_item_rates[get_event_cost_id[\$("#selectSystem_name_"+ij).val()]]) { + // system_with_cost_item_rates_selected = 1 ; + // } + + // } + ~ ; + + $trigger_jquery_raw .= qq~ + cnt_selected_systems_per_cost_item() ; + ~ if $cntxt{4} ; + + $trigger_jquery_raw .= qq~ + + \$("#days_drop_downs_1 [id^='day_'],#days_drop_downs_2 [id^='day_']").on("change", function (e) { + // \$("$day_ids_string").change(function (e) { + + console.log("changed day "+this.id) ; + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + + const id = this.id ; + let col_nr = get_row_nr(id) ; + // const secondLastIndex = beforeLastUnderscore.lastIndexOf('_'); + // const changedInput = beforeLastUnderscore.substring(secondLastIndex + 1); + + let nr_days = \$("input[name='qty']").val() ; + + let nr_of_active_days = calc_nr_of_active_days() ; + + let datesBetween ; + + let date_counter = 0 ; let dates_map = {} ; + + // if ((\$\(this).val() && (nr_of_active_days == 7 || nr_of_active_days == 11)) || (!\$\(this).val() && (nr_of_active_days == 6 || nr_of_active_days == 10))) { + datesBetween = getDatesBetween(\$("input[name='date_from']").val(),\$("input[name='date_to']").val(),0) ; + for (const date of datesBetween) { + date_counter++ ; + dates_map[date_counter] = date ; + // console.log("date_counter : "+date_counter+" , dates_map[date_counter] : "+dates_map[date_counter]) ; + } + // } + + let all_added_dropdowns = "#1" ; + let all_added_dropdowns_chosen = "#1" ; + + // let select_chosen_ids_1 = '#3' ; + // let select_chosen_ids_2 = '#4' ; + + // let def_val = 0 ; + + // if (\$("#day_"+b).val()) { + + // def_val = \$("#selectCustom_operator_"+a+"_"+b).val() ; + // add_operator_dropdown("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,0) ; + // select_chosen_ids_1 = select_chosen_ids_1+",#selectCustom_operator_"+a+"_"+b ; + // select_chosen_ids_2 = select_chosen_ids_2+",#selectCustom_operator_"+a+"_"+b+"_chosen" ; + // names_to_display = names_to_display + ",#day_"+b+"_name_"+a+"_extra_1" ; + // } + + // delete_operator_dropdown ("day_"+b+"_name","day_"+a+"_"+b) ; + // delete_operator_dropdown ("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_2") ; + + // if (!\$("#selectCustom_operator_"+a+"_"+b).val() && def_val) { + // \$("#selectCustom_operator_"+a+"_"+b).val(def_val) ; + // \$("#selectCustom_operator_"+a+"_"+b).trigger("chosen:updated") ; + // } + // } + + let def_val = 0 ; + + let hide_this_1 = '' ; + let hide_this_2 = '' ; + + if (!\$\(this).val()) { + + \$("#timepickerTime_from_"+col_nr+"").css("display","none") ; + \$("#timepickerTime_to_"+col_nr+"").css("display","none") ; + \$("#radio_"+col_nr+"_1").css("display","none") ; + \$("#radio_"+col_nr+"_2").css("display","none") ; + nr_days=nr_days-1; + if (nr_of_active_days < 6) { + \$("#day_"+col_nr+"_name").css("display","none") ; + \$("#day_"+col_nr+"_name").removeClass('col-md-1').addClass('col-md-0') ; + } + for (let q=1;q<=15;q++) { + if (\$("input[name='clicked_button_"+q+"']").val()) { + + if (nr_of_active_days <= 6 && q > 1 && !\$("#extra_heading_"+q).is(":hidden")) { + \$("#extra_heading_"+q).hide() ; + console.log("Hide Heading") ; + } else if (nr_of_active_days > 6 && q > 1 && \$("#extra_heading_"+q).length && \$("#extra_heading_"+q).is(":hidden") && \$("input[name='clicked_button_"+q+"']").val()) { + \$("#extra_heading_"+q).show() ; + console.log("Display Heading") ; + } else if (nr_of_active_days > 6 && q > 1 && !\$("#extra_heading_"+q).length && \$("input[name='clicked_button_"+q+"']").val()) { + console.log("Add Heading") ; + \$("#system_name_row_"+q).before("
    ") ; + + } + + if (nr_of_active_days < 6) { + \$("#day_"+q+"_"+col_nr).css("display","none") ; + \$("#day_"+q+"_"+col_nr).removeClass('col-md-1').addClass('col-md-0') ; + } else if (nr_of_active_days == 6) { + + if (q > 1 && !\$("#extra_heading_"+q).is(":hidden")) { + \$("#extra_heading_"+q).hide() ; + } + + for (let col=1;col<=20;col++) { + if (\$("#day_"+col).val() && !\$("#day_"+q+"_"+col).html()) { + add_operator_dropdown ("day_"+col+"_name","day_"+q+"_"+col,"custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,0) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (!\$("#day_"+col).val() && dates_map[col] && !\$("#day_"+q+"_"+col).html()) { + add_operator_dropdown ("day_"+col+"_name","day_"+q+"_"+col,"custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,1) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (\$("#day_"+col).val() && \$("#day_"+q+"_"+col).html() && \$("#day_"+q+"_"+col).is(":hidden")) { + display_non_empty_operator_dropdown("day_"+col+"_name","day_"+q+"_"+col) ; + } + delete_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1") ; + // console.log("hide_operator_dropdown : ) ; + } + \$("#system_name_row_"+q+"_extra_1").hide() ; + \$("#day_names_"+q+"_extra_1").hide() ; + } else if (nr_of_active_days > 6 && nr_of_active_days < 10) { + // hide_non_empty_operator_dropdown("day_"+col_nr+"_name","day_"+q+"_"+col_nr) ; + hide_non_empty_operator_dropdown("day_"+col_nr+"_name_"+q+"_extra_1","day_"+q+"_"+col_nr+"_extra_1") ; + } else if (nr_of_active_days == 10) { + for (let col=1;col<=20;col++) { + if (\$("#day_"+col).val() && dates_map[col]) { + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,0) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (!\$("#day_"+col).val() && dates_map[col]) { + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,1) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (\$("#day_"+col).val() && \$("#day_"+q+"_"+col+"_extra_1").html() && \$("#day_"+q+"_"+col+"_extra_1").is(":hidden")) { + display_non_empty_operator_dropdown("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1") ; + } + delete_operator_dropdown ("day_"+col+"_name_"+q+"_extra_2","day_"+q+"_"+col+"_extra_2") ; + } + hide_non_empty_operator_dropdown("day_"+col_nr+"_name_"+q+"_extra_1","day_"+q+"_"+col_nr+"_extra_1") ; + \$("#system_name_row_"+q+"_extra_1").show() ; + \$("#day_names_"+q+"_extra_1").show() ; + \$("#system_name_row_"+q+"_extra_2").hide() ; + \$("#day_names_"+q+"_extra_2").hide() ; + } else if (nr_of_active_days > 10) { + + let nr_dates_used = 0 ; + + console.log("de select : #nr_of_active_days : "+nr_of_active_days) ; + + for (let col=1;col<=20;col++) { + + if (nr_dates_used == 10 && !dates_map[col]) { + break ; + } + if (\$("#day_"+col).val() && dates_map[col] && nr_dates_used < 10) { + nr_dates_used++ ; + if (\$("#day_"+q+"_"+col+"_extra_1").is(":hidden")) { + def_val = \$("#selectCustom_operator_"+q+"_"+col).val() ; + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,0) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + delete_operator_dropdown("day_"+col+"_name_"+q+"_extra_2","day_"+q+"_"+col+"_extra_2",0) ; + if (!\$("#selectCustom_operator_"+q+"_"+col).val() && def_val) { + \$("#selectCustom_operator_"+q+"_"+col).val(def_val) ; + \$("#selectCustom_operator_"+q+"_"+col).trigger("chosen:updated") ; + } + } + } else if (!\$("#day_"+col).val() && dates_map[col]) { + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,1) ; + if (!\$("#day_"+q+"_"+col+"_extra_1").is(":hidden")) { + hide_this_1 = "day_"+col+"_name_"+q+"_extra_1" ; + hide_this_2 = "day_"+q+"_"+col+"_extra_1" ; + } + if (!\$("#day_"+q+"_"+col+"_extra_2").is(":hidden") && col > 10) { + hide_this_1 = "day_"+col+"_name_"+q+"_extra_2" ; + hide_this_2 = "day_"+q+"_"+col+"_extra_2" ; + } + } + } + } + } + if (hide_this_1) { + console.log("hide this : "+hide_this_1+" , "+hide_this_2) ; + hide_non_empty_operator_dropdown (hide_this_1,hide_this_2) ; + } + } + } else { + if (col_nr != "1") { + \$("#timepickerTime_from_"+col_nr).css("display","") ; + } + \$("#timepickerTime_to_"+col_nr).css("display","") ; + \$("#radio_"+col_nr+"_1").css("display","") ; + \$("#radio_"+col_nr+"_2").css("display","") ; + nr_days=parseInt(nr_days)+1; + + for (let q=1;q<=15;q++) { + if (\$("input[name='clicked_button_"+q+"']").val()) { + \$("#day_"+q+"_"+col_nr).css("display","") ; + if (\$("#selectCustom_operator_"+q+"_"+col_nr+"_chosen").css("width") !== "100%"){ + \$("#selectCustom_operator_"+q+"_"+col_nr+"_chosen").css("width","100%") ; + } + } + } + + if (nr_of_active_days <= 6 && \$("#clicked_any_button").text() && \$("#day_"+col_nr+"_name").css("display") === "none") { + \$("#day_"+col_nr+"_name").show() ; + \$("#day_"+col_nr+"_name").removeClass('col-md-0').addClass('col-md-1') ; + } + for (let q=1;q<=15;q++) { + + if (\$("input[name='clicked_button_"+q+"']").val()) { + + if (nr_of_active_days <= 6 && q > 1 && !\$("#extra_heading_"+q).is(":hidden")) { + \$("#extra_heading_"+q).hide() ; + console.log("Hide Heading") ; + } else if (nr_of_active_days > 6 && q > 1 && \$("#extra_heading_"+q).length && \$("#extra_heading_"+q).is(":hidden") && \$("input[name='clicked_button_"+q+"']").val()) { + \$("#extra_heading_"+q).show() ; + console.log("Display Heading") ; + } else if (nr_of_active_days > 6 && q > 1 && !\$("#extra_heading_"+q).length && \$("input[name='clicked_button_"+q+"']").val()) { + console.log("Add Heading") ; + \$("#system_name_row_"+q).before("
    ") ; + + } + + if (q > 1 && \$("#extra_heading_"+q).is(":hidden")) { + \$("#extra_heading_"+q).show() ; + } + + if (nr_of_active_days <= 6) { + \$("#day_"+q+"_"+col_nr).show() ; + \$("#day_"+q+"_"+col_nr).removeClass('col-md-0').addClass('col-md-1') ; + console.log("#day_"+q+"_"+col_nr) ; + } else if (nr_of_active_days == 7) { + for (let col=1;col<=20;col++) { + def_val = \$("#selectCustom_operator_"+q+"_"+col).val() ; + if (\$("#day_"+col).val()) { + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,0) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (!\$("#day_"+col).val() && dates_map[col]) { + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,1) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (\$("#day_"+col).val() && \$("#day_"+q+"_"+col).html() && \$("#day_"+q+"_"+col).is(":hidden")) { + display_non_empty_operator_dropdown("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1") ; + } + delete_operator_dropdown ("day_"+col+"_name","day_"+q+"_"+col) ; + if (!\$("#selectCustom_operator_"+q+"_"+col).val() && def_val) { + \$("#selectCustom_operator_"+q+"_"+col).val(def_val) ; + \$("#selectCustom_operator_"+q+"_"+col).trigger("chosen:updated") ; + } + } + \$("#day_"+col_nr+"_name").hide() ; + \$("#system_name_row_"+q+"_extra_1").show() ; + \$("#day_names_"+q+"_extra_1").show() ; + } else if (nr_of_active_days > 7 && nr_of_active_days <= 10) { + display_non_empty_operator_dropdown("day_"+col_nr+"_name_"+q+"_extra_1","day_"+q+"_"+col_nr+"_extra_1") ; + hide_non_empty_operator_dropdown("day_"+col_nr+"_name","day_"+q+"_"+col_nr) ; + } else if (nr_of_active_days >= 11) { + let date_used = {} ; let date_used_hidden = {} ; let nr_dates_used = 0 ; + for (let col=1;col<=20;col++) { + + if (nr_dates_used == 10 && !dates_map[col]) { + break ; + } + if (\$("#day_"+col).val() && dates_map[col] && nr_dates_used < 10) { + date_used[col] = 1 ; + nr_dates_used++ ; + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,0) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (!\$("#day_"+col).val() && dates_map[col]) { + date_used_hidden[col] = 1 ; + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,1) ; + } + } + + for (let col=11;col<=20;col++) { + // if (col > 10) { + if (\$("#day_"+col).val() && !date_used[col]) { + def_val = \$("#selectCustom_operator_"+q+"_"+col).val() ; + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_2","day_"+q+"_"+col+"_extra_2","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + delete_operator_dropdown("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1",0) ; + if (!\$("#selectCustom_operator_"+q+"_"+col).val() && def_val) { + \$("#selectCustom_operator_"+q+"_"+col).val(def_val) ; + \$("#selectCustom_operator_"+q+"_"+col).trigger("chosen:updated") ; + } + } else { + delete_operator_dropdown ("day_"+col+"_name_"+q+"_extra_2","day_"+q+"_"+col+"_extra_2",0) ; + } + } + \$("#system_name_row_"+q+"_extra_2").show() ; + \$("#day_names_"+q+"_extra_2").show() ; + \$("#system_name_row_"+q+"_extra_1").show() ; + \$("#day_names_"+q+"_extra_1").show() ; + } + } + } + } + + // hide_non_empty_operator_dropdown (hide_this_1,hide_this_2) ; + + \$(all_added_dropdowns).chosen({allow_single_deselect:true}) ; + \$(all_added_dropdowns_chosen).css("width","100%") ; + + // \$(select_chosen_ids_1).chosen({allow_single_deselect:true}) ; + // \$(select_chosen_ids_2).css("width","100%") ; + \$("input[name='qty']").val(nr_days) ; + }) ; + ~ if $readonly{qty} ne "READONLY" ; + + my $timepicker_ids_string = join(",",@timepicker_ids) ; + + # $trigger_jquery_raw .= qq~ \$("$timepicker_ids_string").datetimepicker({language:'pt-BR',pickDate:false});~ ; + + if ($readonly{qty} ne "READONLY") { + + $trigger_jquery_raw .= qq~ + + function set_full_half_day (beforeUnderscore,afterUnderscore) { + + let start_time = \$("input[name='time_from_"+afterUnderscore+"']").val() ; + let end_time = \$("input[name='time_to_"+afterUnderscore+"']").val() ; + + let seconds1 = timeStringToSeconds(start_time) ; + let seconds2 = timeStringToSeconds(end_time) ; + + let diffSeconds = seconds2 - seconds1 ; + + // let nr_days = \$("#inputQty").val() ; + + let changed_a_full_half_day_toggle = 0 ; + if (diffSeconds >= 18000) { + if (\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + nr_days["half"]-- ; + } + if (!\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + \$("#radio_"+afterUnderscore+"_1").prop('checked',true) ; + changed_a_full_half_day_toggle = 1 ; + nr_days["full"]++ ; + } + } else if (diffSeconds >= 0 && diffSeconds < 18000) { + if (\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + nr_days["full"]-- ; + } + if (!\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + \$("#radio_"+afterUnderscore+"_2").prop('checked',true) ; + changed_a_full_half_day_toggle = 1 ; + nr_days["half"]++ ; + } + } else { + // nr_days = parseInt(nr_days) ; + // nr_days-- ; + // \$("#inputQty").val(nr_days) ; + + if (\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + \$("#radio_"+afterUnderscore+"_1").prop('checked',false) ; + changed_a_full_half_day_toggle = 1 ; + nr_days["full"]-- ; + } + if (\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + \$("#radio_"+afterUnderscore+"_2").prop('checked',false) ; + changed_a_full_half_day_toggle = 1 ; + nr_days["half"]-- ; + } + if (beforeUnderscore == 'timepickerTime_from') { + \$("input[name='time_from_"+afterUnderscore+"']").val(end_time) ; + } else if (beforeUnderscore == 'timepickerTime_to') { + \$("input[name='time_to_"+afterUnderscore+"']").val(start_time) ; + } + } + if (changed_a_full_half_day_toggle == 1) { + changed_radio_cnt++ ; + } + + } + + \$("$timepicker_ids_string").datetimepicker({language:'pt-BR',pickDate:false}); + + // \$("#timepickerTime_from_1").on('changeDate', function() { + // let dateString1 = \$("input[name='time_from").val() ; + // }) ; + + \$("$timepicker_ids_string").on('changeDate', function() { + + const id = this.id ; + const lastIndex = id.lastIndexOf('_'); + const beforeUnderscore = id.substring(0,lastIndex); + let afterUnderscore = id.substring(lastIndex+1); + afterUnderscore = parseInt(afterUnderscore) ; + // const from_to_toggle = {"timepickerTime_from":"time_to","timepickerTime_to":"time_from"} ; + // console.log("timepicker change id : "+id+" , beforeUnderscore : "+beforeUnderscore+" , afterUnderscore : "+afterUnderscore) ; + // let date_to = \$("input[name='date_to']").val() ; + // let datetimeValue = \$("#datetimepickerDate_to").data("date"); + // // // if (beforeUnderscore == 'from' && afterUnderscore == 1) { + + // // // let dateString = \$("input[name='time_from").val() ; + // // // let timePart = dateString.split(' ')[1]; + // // // \$("input[name='time_from_1']").val(timePart) ; + // // // return ; + // // // } + // // // if (beforeUnderscore == 'to') { + // // // let dateString1 = \$("input[name='time_from").val() ; + // // // let dateString2 = \$("input[name='time_to").val() ; + // // // const count_dates = getDatesBetween(dateFromInput,dateToInput,1) ; + // // // if (afterUnderscore == count_dates) { + // // // let timePart = dateString.split(' ')[1]; + // // // \$("input[name='time_to_"+count_dates+"']").val(timePart) ; + // // // return ; + // // // } + // // // } + + if (id.includes("timepickerTime_from_")) { + saved_time_from[afterUnderscore] = \$("input[name='time_from_"+afterUnderscore+"']").val() ; + } else if (id.includes("timepickerTime_to_")) { + saved_time_to[afterUnderscore] = \$("input[name='time_to_"+afterUnderscore+"']").val() ; + } + + // console.log("input[name='time_from_"+afterUnderscore+"']") ; + // console.log("input[name='time_to_"+afterUnderscore+"']") ; + + changed_radio_cnt = 0 ; + + set_full_half_day(beforeUnderscore,afterUnderscore) ; + + if (changed_radio_cnt) { + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + } + + // let start_time = \$("input[name='time_from_"+afterUnderscore+"']").val() ; + // let end_time = \$("input[name='time_to_"+afterUnderscore+"']").val() ; + // let seconds1 = timeStringToSeconds(start_time) ; + // let seconds2 = timeStringToSeconds(end_time) ; + + // let diffSeconds = seconds2 - seconds1 ; + // if (diffSeconds >= 18000) { + // if (!\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + // \$("#radio_"+afterUnderscore+"_1").prop('checked',true) ; + // } + // } else if (diffSeconds >= 0 && diffSeconds < 18000) { + // if (!\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + // \$("#radio_"+afterUnderscore+"_2").prop('checked',true) ; + // } + // } else { + // if (\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + // \$("#radio_"+afterUnderscore+"_1").prop('checked',false) ; + // } + // if (\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + // \$("#radio_"+afterUnderscore+"_2").prop('checked',false) ; + // } + // if (beforeUnderscore == 'timepickerTime_from') { + // \$("input[name='time_from_"+afterUnderscore+"']").val(end_time) ; + // } else { + // \$("input[name='time_to_"+afterUnderscore+"']").val(start_time) ; + // } + + // } + // console.log("start_time : "+start_time+" , end_time : "+end_time+" , seconds1 : "+seconds1+" , seconds2 : "+seconds2+" , diffSeconds : "+diffSeconds) ; + }) ; + ~ ; + } + + chop $default_time_from if $default_time_from ; chop $default_time_to if $default_time_to ; + + $fcol = 3 ; $lcol = 2 ; my $expenses_html_for_javascript = qq~~ ; my $vat_default_for_hidden_expenses = qq~~ ; my $cnt_hidden_rows = 0 ; my $changed_opid_as_level_3 = 0 ; + + # my $default_event_length_1 = qq~~ ; my $default_event_length_2 = qq~~ ; my $e_cnt = 0 ; + # foreach (split(/\;/,$db{$table}{$id}{event_length})) { + # $e_cnt++ ; + # $default_event_length_1 .= qq~$_;~ if $e_cnt <= 10 ; + # $default_event_length_2 .= qq~$_;~ if $e_cnt > 10 ; + # } + # chop $default_event_length_1 if $default_event_length_1 ; + # chop $default_event_length_2 if $default_event_length_2 ; + + my %event_length_rows = () ; + + if ($readonly{qty} eq "READONLY") { + + $readonly{nr_of_systems} = "READONLY" ; + + $event_length_rows{1} .= qq~ +
    ~ ; + + $event_length_rows{1} .= qq~ +
    + +
    + ~ ; + + # $event_length_rows{2} = $event_length_rows{1} ; + + if ($db{$table}{$id}{event_length}) { + + # my + my @words = split /\;/, $db{$table}{$id}{event_length} ; + my $output = join ' ', map { ucfirst lc $_ } @words; + # style="top:4px;left:-4px;" + + # my $time_label_header_row = qq~
    ~ ; +# + my $cnt = 0 ; + foreach (@words) { + $cnt++ ; + + $event_length_rows{2} = qq~
    ~ if $cnt >= 11 && $_ && !$event_length_rows{2} ; + + my $el_row_cnt = ($cnt <= 10) ? 1 : 2 ; + + $event_length_rows{$el_row_cnt} .= ($_ eq '1') ? qq~ +
    + +
    + ~ : ($_ eq '2') ? qq~ +
    + +
    ~ : qq~ +
    +
    ~ ; + + } + } else { + for (1 .. $final_day) { # + + my $el_row_cnt = ($cnt <= 10) ? 1 : 2 ; + $event_length_rows{$el_row_cnt} .= ($calc_default_event_length{$_} eq '1') ? qq~ +
    + +
    + ~ : ($calc_default_event_length{$_} eq '2') ? qq~ +
    + +
    + ~ : qq~ +
    +
    + ~ ; + } + } + + # $add_form_fields .= &common_min_form_label('event_length',$output) ; + # $add_form_fields .= qq~
    ~ ; + $event_length_rows{1} .= qq~ +
    ~ if $event_length_rows{1} ; + + $event_length_rows{2} .= qq~ +
    ~ if $event_length_rows{2} ; + # $add_form_fields .= &common_min_form_input('qty',$db{$table}{$id}{qty},'',1) ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + + } else { + + $fcol = 1 ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'',10,$final_day) ; + + $event_length_rows{1} .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'',10,$final_day,"",1) ; + my $final_day_second = $final_day - 10 ; + $final_day_second = -1 if $final_day_second <= 0 ; + $event_length_rows{2} .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'',10,$final_day_second,"radio_row_id_2",2) ; + + # my $sec = &common_min_form_radio_col('event_length',$default_event_length_2,'',10,$final_day_second) ; + + # $add_form_fields .= qq~
    ~ ; + $fcol = 3 ; + # $add_form_fields .= &common_min_form_input('qty',$db{$table}{$id}{qty},'',1) ; + # $add_form_fields .= qq~
    ~ ; + if ($glod_user_level < 4) { + + $changed_opid_as_level_3 = 1 ; + + my @excl_def = split(/\;/,$db{event_quotes_min}{$id}{excl_workings_event}) ; + my @saved_des = split(/\;/,$db{event_quotes_min}{$id}{description_workings_event}) ; + my @saved_op = split(/\;/,$db{event_quotes_min}{$id}{operator_workings_event}) ; + my @remarks_def = split(/\;/,$db{event_quotes_min}{$id}{remarks_workings_event}) ; + my @supp_def = split(/\;/,$db{event_quotes_min}{$id}{supplier_workings_event}) ; + my @ref_nr_def = split(/\;/,$db{event_quotes_min}{$id}{ref_nr_workings_event}) ; + my @qty_old = split(/\;/,$db{event_quotes_min}{$id}{qty_workings_event}); + my @amount_usd_old = split(/\;/,$db{event_quotes_min}{$id}{amount_usd_workings_event}); + my @amount_old = split(/\;/,$db{event_quotes_min}{$id}{amount_workings_event}); + my @vat_default = split(/\;/,$db{event_quotes_min}{$id}{vat_workings_event}) ; + + my %expenses_html = () ; + + &db_min_ro('users','id',"user_type LIKE 'casual%' AND block <> 1 AND inactive <> 1",'','') ; + + foreach (keys %{$db{users}}) { + $opts{users} .= qq~~ ; + } + $opts{description} = qq~~ ; + + $add_form_fields .= qq~
    ~ ; + $db{$table}{$id}{roe} = 1 unless $db{$table}{$id}{roe} ; + + my $custom_set_checked = ($db{$table}{$id}{custom_set} || $db{$table}{$id}{demo_id}) ? "CHECKED" : "" ; + + $add_form_fields .= qq~ + + + + + + + ~ ; + + for (1 .. 50) { + if ($qty_old[50-$_] || $amount_usd_old[50-$_] || $amount_old[50-$_] || $saved_des[50-$_] || $saved_op[50-$_]) { + $cnt_hidden_rows = 51-$_ ; + last ; + } + } + + my @ttlarr = ("sub_total_workings_event","vat_total_workings_event","grand_total_workings_event") ; + + if ($cnt_hidden_rows) { + + # &db_min_ro('event_cost_items','id','','','') ; + &db_min_ro('event_cost_items','id',"excl_from_expenses < 1",'','') ; + + for my $row_cnt (1 .. $cnt_hidden_rows) { + + foreach (keys %{$db{event_cost_items}}) { + my $sel = ($saved_des[$row_cnt-1] and $saved_des[$row_cnt-1] eq $_) ? "SELECTED" : "" ; + $opts{"description_$row_cnt"} .= qq~~ ; + } + foreach (keys %{$db{users}}) { + my $sel = ($saved_op[$row_cnt-1] and $saved_op[$row_cnt-1] eq $_) ? "SELECTED" : "" ; + $opts{"users_$row_cnt"} .= qq~~ ; + } + + $vat_default_for_hidden_expenses .= qq~$row_cnt:"$vat_default[$row_cnt-1],"~ ; + + $add_form_fields .= qq~
    ~ ; + my $excl_checked = ($excl_def[$row_cnt-1]) ? "CHECKED" : "" ; + my $vat_checked = ($vat_default[$row_cnt-1]) ? "CHECKED" : "" ; + + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + + $add_form_fields .= qq~
    ~ ; + + last if $cnt_hidden_rows == $row_cnt ; + } + + $add_form_fields .= qq~
    ~ ; + foreach (@ttlarr) { + my $inp_name = "input" . ucfirst $_ ; + $add_form_fields .= qq~~ ; + } + $add_form_fields .= qq~
    ~ ; + # chop $vat_default_for_hidden_expenses if $vat_default_for_hidden_expenses ; + } + + for ($cnt_hidden_rows+1 .. 50) { + # next if $cnt_hidden_rows && $_ <= $cnt_hidden_rows ; + $add_form_fields .= qq~
    ~ ; + # $expenses_html{$_} = qq~$_:""~ ; + } + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + foreach (@ttlarr) { + my $inp_name = "input" . ucfirst $_ ; + $expenses_html{1000} .= qq~~ ; + } + $expenses_html{1000} = qq~1000:"$expenses_html{1000}"~ ; + + foreach (sort keys %expenses_html) { + $expenses_html_for_javascript .= qq~$expenses_html{$_},~ ; + } + chop $expenses_html_for_javascript if $expenses_html_for_javascript ; + + } + } + + $add_form_fields .= qq~$time_label_header_row{1}
    ~ ; + $add_form_fields .= qq~
    $days_time_row{1}
    ~ ; + $add_form_fields .= qq~
    $days_time_row_2{1}
    ~ ; + $add_form_fields .= qq~$event_length_rows{1}~ ; + + $add_form_fields .= qq~$time_label_header_row{2}~ ; + $add_form_fields .= qq~
    $days_time_row{2}
    ~ ; + $add_form_fields .= qq~
    $days_time_row_2{2}
    ~ ; + $add_form_fields .= qq~$event_length_rows{2}~ ; + + $add_form_fields .= &common_min_form_input('qty',$db{$table}{$id}{qty},'',1) ; + $add_form_fields .= qq~~ ; + + $db{$table}{$id}{nr_of_systems} = 0 unless $db{$table}{$id}{nr_of_systems} ; + + $preferred_title{nr_of_systems} = "Number of Systems" ; + + # if ($glod_user_level > 3) { + # if ($glod_user_level > 2) { + + if ($glod_user_level > 3 || (!$quote_completed && $glod_user_level == 3)) { + $preferred_title{type} = "Type of System" ; + $add_form_fields .= &common_min_form_select('type',$db{$table}{$id}{type},'') ; + $trigger_jquery .= qq~\$("#selectType\_chosen").css( "width", "100%" );~ ; + $add_form_fields .= &common_min_form_input('nr_of_systems',$db{$table}{$id}{nr_of_systems},'') ; + $preferred_title{type_details_id} = "Type Details" ; + $add_form_fields .= &common_min_form_select('type_details_id',$db{$table}{$id}{type_details_id},'') ; + $trigger_jquery .= qq~\$("#selectType_details_id\_chosen").css("width","100%") ;~ ; + # } elsif ($glod_user_level < 4 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + } + # elsif ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + elsif ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { + &db_min_ro('event_types','id,name',"`id`='$db{$table}{$id}{type}'",'','') if $db{$table}{$id}{type} ; + $readonly{type_of_system} = "READONLY" ; $readonly{system_details} = "READONLY" ; $readonly{system_name} = "READONLY" ; $readonly{club_name} = "READONLY" ; + $preferred_title{type_of_system} = "Type of System" ; + $add_form_fields .= &common_min_form_input('type_of_system',$db{event_types}{$db{$table}{$id}{type}}{name},'') ; + $add_form_fields .= &common_min_form_input('nr_of_systems',$db{$table}{$id}{nr_of_systems},'') ; + + &db_min_ro('event_type_details','id,name',"`id`='$db{$table}{$id}{type_details_id}'",'','') unless $db{$table}{$id}{type_details_id} =~ /;/ ; + &db_min_ro('event_type_details','id,name',"",'','') if $db{$table}{$id}{type_details_id} =~ /;/ ; + my $input_val = qq~~ ; + foreach my $type_id (split(",",$db{$table}{$id}{type_details_id})) { + next unless $db{event_type_details}{$type_id}{name} ; + $input_val .= qq~$db{event_type_details}{$type_id}{name}, ~ ; + } + chop $input_val if $input_val ; chop $input_val if $input_val ; + $add_form_fields .= &common_min_form_input('system_details',$input_val,'') ; + } else { + $preferred_title{type} = "Type of System" ; + $add_form_fields .= &common_min_form_select('type',$db{$table}{$id}{type},'') ; + $trigger_jquery .= qq~\$("#selectType\_chosen").css("width","100%" );~ ; + $add_form_fields .= &common_min_form_input('nr_of_systems',$db{$table}{$id}{nr_of_systems},'') ; + } + + our $remaining_op_ids = qq~~ ; + + &build_system_name_form($db{$table}{$id}{event_system_id_multiple},$db{$table}{$id}{club_ids},$quote_accepted,$quote_rejected,$quote_cancelled,$db{$table}{$id}{daily_operator_ids},$db{$table}{$id}{days_active},$db{$table}{$id}{quote_completed}) ; + + my $hide_club_name1 = qq~~ ; my $hide_club_name2 = qq~~ ; my $required_fields_full = 0 ; + + $required_fields_full = 1 if $db{$table}{$id}{ref} and $db{$table}{$id}{type} and $db{$table}{$id}{event_system_id} + and $db{$table}{$id}{qty} and $db{$table}{$id}{region_id} and $db{$table}{$id}{city_id} ; + + $add_form_fields .= qq~
    ~ ; + + $fcol = 3 ; + + # # if ($glod_user_level > 3) { + # if ($glod_user_level > 2) { + # $dlg{operator_ids} .= qq~
    ~ ; + # $preferred_title{operator_ids} = "Operator(s)" ; + # $add_form_fields .= &common_min_form_select('operator_ids',$remaining_op_ids,'') ; + # $trigger_jquery .= qq~\$("#selectOperator_ids\_chosen").css( "width", "100%" );~ ; + # # } elsif ($glod_user_level < 4 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + # } + + # if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { + my @op_names = map { $db{users}{$_}{name} } @multi_select_op_ids; + $op_names = join(", ",@op_names) ; + $preferred_title{operators} = "Operator(s)" ; $readonly{operators} = "READONLY" ; + $add_form_fields .= &common_min_form_input('operators',$op_names,'') ; + } else { + + if ($glod_user_level > 2) { + $dlg{operator_ids} .= qq~
    ~ ; + $preferred_title{operator_ids} = "Operator(s)" ; + $trigger_jquery .= qq~\$("#selectOperator_ids\_chosen").css( "width", "100%" );~ ; + } + + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + $add_form_fields .= &common_min_form_select('operator_ids',$remaining_op_ids,'') ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + # } elsif ($glod_user_level < 4 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + } + + my @casuals = () ; + + foreach (keys %{$db{events}}) { + $qnr = $db{events}{$_}{event_quote_nr} ; + $uid = $db{events}{$_}{user_id} ; + next unless $db{events}{$_}{category} eq 'available' ; + push @casuals, "$casual_name{$uid} [$casual_type{$uid}]" ; + } + + $add_form_fields .= &common_min_form_input('casual_worker','A','hidden') ; + $add_form_fields .= &common_min_form_input('casual_worker_2','B','hidden') ; + + my $nr_of_casuals = 0 + $db{$table}{$id}{nr_of_casuals} + $db{$table}{$id}{nr_of_casuals_2} ; + + $add_form_fields .= &common_min_form_input('nr_of_casuals',$nr_of_casuals,'hidden') ; + $add_form_fields .= &common_min_form_input('nr_of_casuals_2',0,'hidden') ; + + $fcol = 3 ; + # $add_form_fields .= &common_min_form_input('sports_type',$db{$table}{$id}{sports_type},'') ; + + if ($hide_select_1) { + $add_form_fields .= qq~$readonly_select~ ; + } + + $preferred_title{sport_type_ids} = "Sport Type(s)" ; $preferred_title{organisation_ids} = "Venue(s)" ; + $add_form_fields .= qq~$hide_select_1~ ; + $add_form_fields .= &common_min_form_select('sport_type_ids',$db{$table}{$id}{sport_type_ids},'') ; + # $add_form_fields .= &common_min_form_input('ligr',$db{$table}{$id}{ligr},'') ; + # if ($db{$table}{$id}{ligr} eq 'Yes') { $checked = 'CHECKED'; } else { $checked = ''; } + # $add_form_fields .= &common_min_form_checkbox('ligr',$db{$table}{$id}{ligr},$checked) ; + # $add_form_fields .= &common_min_form_input('Location',$db{$table}{$id}{location},'') ; + $add_form_fields .= &common_min_form_select('region_id',$db{$table}{$id}{region_id},'') ; + + $add_form_fields .= &common_min_form_select('city_id',$db{$table}{$id}{city_id},'') ; + $add_form_fields .= &common_min_form_select('organisation_ids',$db{$table}{$id}{organisation_ids},'') ; + + $allow_deselect{linear_id} = 1 ; + my %linear_def = () ; $linear_def{$db{$table}{$id}{linear_id}} = 'SELECTED' ; + $opts{linear_id} .= qq~~ ; + $add_form_fields .= &common_min_form_select('linear_id',$db{$table}{$id}{linear_id},'') ; + + # $supplier_type_ids + + $preferred_title{supplier_type_ids} = "Supplier Type(s)" ; + $add_form_fields .= qq~~ . &common_min_form_select('supplier_type_ids',$db{$table}{$id}{supplier_type_ids},'') if $db{$table}{$id}{sss_quote_nr} ; + + if ($hide_select_1) { + $add_form_fields .= qq~~ ; + } + + # $opts{event_length} = qq~~ ; + # $radio_opts{event_length} = "Full Day+Half Day" ; + # $fcol = 1 ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'') ; + # $add_form_fields .= qq~
    ~ ; + # $fcol = 6 ; + # $add_form_fields .= qq~$hide_select_2~ ; + + # $ignore{club} = 1 ; + # $add_form_fields .= &common_min_form_input('club','','') ; + # $add_form_fields .= &common_min_form_input('City',$db{$table}{$id}{city},'') ; + + $add_form_fields .= qq~~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + + # $operator_options = qq~~ ; + + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + + $trigger_jquery_raw .= qq~ + + // // // \$("input[name='event_length']").change( function () { + + // // // let radio_sel = \$(this).val() ; + + // // // for (let i = 1; i<=50; i++) { + + // // // let usd = \$("#inputAmount_usd_workings_event_"+i) ; + // // // let item = \$("#selectDescription_workings_event_"+i) ; + + // // // let amnt = 0 ; + // // // if (\$('input[name="event_length"][value="full_day"]').is(":checked") && usd.val() == '500.00' && item.val() == 14) { + // // // amnt = 750 ; + // // // } else if (\$('input[name="event_length"][value="half_day"]').is(":checked") && usd.val() == '750.00' && item.val() == 14) { + // // // amnt = 500 ; + // // // } else { + // // // continue ; + // // // } + + // // // let qty = \$("#inputQty_workings_event_"+i) ; + // // // let conv = \$("#inputAmount_ttl_workings_event_"+i) ; + + // // // usd.val(amnt.toFixed(2)) ; + // // // let total_amnt = qty.val()*amnt ; + // // // conv.val(total_amnt.toFixed(2)) ; + // // // } + // // // if ($changed_opid_as_level_3) { + // // // calc_hidden_totals() ; + // // // } else { + // // // calcAllWorkings() ; + // // // } + // // // }) ; + + + + let map_region_to_country = {} ; + + const \$clientSelect = \$("#selectQuote_to") ; + const \$countrySelect = \$("#selectCountry_id") ; + const \$regionSelect = \$("#selectRegion_id") ; + const \$citySelect = \$("#selectCity_id") ; + const \$venuesSelect = \$("#selectOrganisation_ids") ; + + let prev_region = \$regionSelect.val() ; + let prev_country = \$countrySelect.val() ; + + const updateChosen = \$el => \$el.trigger("chosen:updated"); + + const getClientId = () => { + const val = \$clientSelect.val(); + return val ? val.toString().split(":")[0] : null; + } ; + + const fetchJSON = async url => { + try { + const res = await fetch(url); + if (!res.ok) throw new Error(`Request failed: \${res.status}`); + return await res.json(); + } catch (err) { + console.error("Fetch error:", err); + return []; + } + }; + + const populateSelect = (\$field,json_list,getLabel,defaultSelected = () => "") => { + let isSelected ; + if (typeof defaultSelected === "function") { + isSelected = defaultSelected; + } else if (Array.isArray(defaultSelected)) { + isSelected = data => defaultSelected.includes(data.id) ? "selected" : ""; + } else { + isSelected = data => data.id == defaultSelected ? "selected" : ""; + } + + json_list.forEach(data => { + \$field.append(``); + }); + + updateChosen(\$field); + return json_list.length; + }; + + const getInputValue = name => \$(`input[name='\${name}']`).val(); + + const getMultiSelectSplitNumbers = (\$field) => { + + let field_ = \$field.chosen().val() ; + field_ = String(field_); + return field_.split(',') ; + + } ; + + const clearSelect = (\$el) => { + \$el.empty(); + \$el.append(``).trigger("chosen:updated"); + }; + + // async function update_country_region_from_client (clientId) { + + + // } + + async function update_region_drop_down_from_country (countryId) { + + clearSelect(\$regionSelect) ; + + const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}` ; + + const regions = await fetchJSON(regionUrl); + + for (const data of regions) { + map_region_to_country[data.id] = countryId ; + } + + const regionCount = populateSelect(\$regionSelect, regions, r => r.code ? `\${r.name} [\${r.code}]` : r.name , "") ; + + // let selectedRegionId = 0 ; + + if (regionCount === 1) { + \$regionSelect.val(regions[0].id) + } else if (regionCount === 0 && \$countrySelect.val()) { + // selectedRegionId = 13 ; + \$regionSelect.append(``) ; + } + updateChosen(\$regionSelect) ; + + const regionId = \$regionSelect.val() ; + + if (regionId != prev_region) { + await update_cities_from_region_and_country(regionId,countryId) ; + await update_venues_from_region_and_country(regionId,countryId) ; + } + prev_region = regionId ; + + } + + async function update_cities_from_region_and_country (regionId,countryId="") { + + let splittedNumbers = getMultiSelectSplitNumbers(\$citySelect) ; + clearSelect(\$citySelect) ; + + let url = `$useropts{scripts}/get/get_cities_from_region.pl?region_id=\${regionId}&country_id=\${countryId}` ; + const cities = await fetchJSON(url); + const citiesCount = populateSelect(\$citySelect, cities, r => r.city_name ? r.city_name : "",r => splittedNumbers.includes(r.id) ? "selected" : "" ) ; + if (citiesCount == 1) \$citySelect.val(cities[0].id).trigger("chosen:updated") ; + + } + + async function update_venues_from_region_and_country (regionId,countryId="") { + + let splittedNumbers2 = getMultiSelectSplitNumbers(\$venuesSelect) ; + clearSelect(\$venuesSelect) ; + url = `$useropts{scripts}/get/get_venues_from_region.pl?region_id=\${regionId}&country_id=\${countryId}` ; + const venues = await fetchJSON(url); + const venuesCount = populateSelect(\$venuesSelect, venues, r => r.venue_name , r => splittedNumbers2.includes(r.id) ? "selected" : "" ) ; + // if (venuesCount == 1) \$venuesSelect.val(venues[0].id).trigger("chosen:updated") ; + + } + + \$clientSelect.change( async function() { + + dispCustomer() ; + let clientId = getClientId() ; + + // __________________________________________________________________ update_country_region_from_client + + const hasCustomRegion = !!getInputValue('custom_selected_region'); + const hasCustomCountry = !!getInputValue('custom_selected_country'); + + if (clientId) { + let url1 = `$useropts{scripts}/get/get_region_country_from_client.pl?client_id=\${clientId}` ; + console.log("1 clientId : "+clientId) ; + + if (!hasCustomRegion || !hasCustomCountry) { + + const data = await fetchJSON(url1); + data.forEach(async ({region_id,country_id}) => { + + if (!hasCustomCountry && country_id && country_id != '0') { + + \$countrySelect.val(country_id).trigger("chosen:updated") ; + if (!hasCustomRegion) await update_region_drop_down_from_country(country_id) ; + if (!region_id || region_id == '0') { + await update_cities_from_region_and_country(0,country_id) ; + await update_venues_from_region_and_country(0,country_id) ; + } + } + + if (!hasCustomRegion && region_id && region_id != '0') { + \$regionSelect.val(region_id).trigger("chosen:updated") ; + await update_cities_from_region_and_country(region_id) ; + await update_venues_from_region_and_country(region_id) ; + } + + // if (!hasCustomCountry && country_id && country_id != '0') + // if (!hasCustomRegion && region_id && region_id != '0') \$regionSelect.val(region_id).trigger("chosen:updated") ; + + }); + } + } else { + if (!hasCustomCountry) \$countrySelect.val("").trigger("chosen:updated") ; + if (!hasCustomRegion) { + \$regionSelect.val("").trigger("chosen:updated") ; + let region_option_count = \$regionSelect.find("option").length ; + if (region_option_count <= 2) { + await update_region_drop_down_from_country(clientId) ; + } + } + } + + // await update_country_region_from_client(clientId) ; + + // __________________________________________________________________ update_country_region_from_client + + }) ; + + \$countrySelect.change( async function() { + + \$("input[name='custom_selected_country']").val("1") ; + await update_region_drop_down_from_country(\$countrySelect.val()) ; + + }) ; + + \$regionSelect.change( async function() { + + \$("input[name='custom_selected_region']").val("1") ; + \$("input[name='custom_selected_country']").val("1") ; + const regionId = \$regionSelect.val() ; + await update_country_from_region(regionId,1) ; + await update_cities_from_region_and_country(regionId) ; + await update_venues_from_region_and_country(regionId) ; + + }); + + let prev_date_part_from = \$("input[name='date_from']").val() ; + prev_date_part_from = prev_date_part_from.split(' ')[0] ; + let prev_date_part_to = \$("input[name='date_to']").val() ; + prev_date_part_to = prev_date_part_to.split(' ')[0] ; + + \$('#datetimepickerDate_from,#datetimepickerDate_to').on('changeDate', function(e) { + let from_to = get_row_nr(this.id) ; + // saved_time_from["1"] = $("input[name='date_from']").val() ; + if (this.id == "datetimepickerDate_from") { + let date_new = \$("input[name='date_from']").val() ; + let time_part = date_new.split(' ')[1]; + \$("input[name='time_from_1']").val(time_part) ; + } + calc_date_diff_in_days(this.id) ; + // \$("#day_4_name_1_extra_1").css("display","none") ; + }) ; + + async function update_country_from_region (regionId,update_country=0) { + + if (map_region_to_country[regionId] || regionId == '13') { + \$countrySelect.val(map_region_to_country[regionId]).trigger("chosen:updated") ; + } else if (!\$("input[name='custom_selected_country']").val() || update_country) { + const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=®ion_id=\${regionId}`; + console.log("update_country_from_region lookupUrl : "+lookupUrl) ; + const regionMeta = await fetchJSON(lookupUrl); + const { country_id } = regionMeta[0] ?? {} ; + if (country_id) { + map_region_to_country[regionId] = country_id; + \$countrySelect.val(country_id).trigger("chosen:updated"); + } + } + + } + + // function javascript_sprintf_sort_off (num) { + // if (num < 10) { + // num = "0"+num.toString() ; + // } + // return num ; + // } + + + + // // function move_system_operators_drop_downs_between_short_to_long () { + + // // let cnt_active_days = 0 ; let cnt_dates_between = 0 ; + // // for (let col=1; col<=20; col++) { + // // if (\$("#day_"+col).val()) { + // // cnt_active_days++ ; cnt_dates_between = col ; + // // } + // // } + // // if ((cnt_active_days <= 6 && \$("#day_1_1").html()) || (cnt_active_days <= 20 && cnt_active_days > 6 && \$("#day_1_1_1").html())) { + // // return ; + // // } + + // // if (cnt_active_days && &cnt_active_days <= 6 && !\$("#day_1_1").html() && \$("#day_1_1_extra_1").html()) { + // // for (let row=1; row<=15; col++) { + // // if (!\$("input[name='clicked_button_"+row+"']").val()) { continue ; } + + // // \$("#system_name_row_"+row+"_extra_1").css("display","none") ; + // // \$("#system_name_row_"+row+"_extra_2").css("display","none") ; + // // \$("day_names_extra_1").css("display","none") ; + // // \$("day_names_extra_2").css("display","none") ; + + // // for (let col=1; col<=20; col++) { + // // if (\$("#day_"+col).val()) { + // // \$("#day_"+row+"_"+col).append(\$("#day_"+row+"_"+col+"_extra").contents()); + // // \$("#day_"+row+"_"+col).css("display","") ; + // // } + // // } + // // } + + // // // \$("#2").append(\$("#1").contents()); + // // } else if (cnt_active_days > 6 && \$("#day_1_1").html() && !\$("#day_1_1_1").html()) { + // // for (let row=1; row<=15; col++) { + // // if (!\$("input[name='clicked_button_"+row+"']").val()) { continue ; } + + // // if (\$("#system_name_row_"+row+"_1").is(":hidden")) { + // // (\$("#system_name_row_"+row+"_1").css("display","") ; + // // } + // // if (\$("#system_name_row_"+row+"_2").is(":hidden") && cnt_active_days > 10) { + // // (\$("#system_name_row_"+row+"_2").css("display","") ; + // // } + // // let active_day_counter = 0 ; + // // for (let col=1; col<=20; col++) { + // // if (\$("#day_"+col).val()) { + // // active_day_counter++ ; + // // \$("#day_"+row+"_"+active_day_counter+"_extra").append(\$("#day_"+row+"_"+col+"").contents()); + // // } + // // } + // // } + // // } + + // // } + + function calc_date_diff_in_days(from_to) { + + // console.log("from_to : "+from_to) ; + + let dateFromInput = \$("input[name='date_from']").val(); + // const dateToInput = \$("#datetimepickerDate_to").data("date"); + let dateToInput = \$("input[name='date_to']").val() ; + + let date_part_from = dateFromInput.split(' ')[0]; + let date_part_to = dateToInput.split(' ')[0]; + + let time_part_from = dateFromInput.split(' ')[1]; + let time_part_to = dateToInput.split(' ')[1]; + + if (prev_date_part_from == date_part_from && date_part_to == prev_date_part_to) { + + changed_radio_cnt = 0 ; + + const datesBetween = getDatesBetween(dateFromInput,dateToInput,0) ; let date_counter = 0 ; + + for (const date of datesBetween) { + + date_counter++ ; + + if (date_counter > 20) { date_counter = 20 ; break ; } + + if (((!saved_time_to[date_counter] || datesBetween.length == date_counter) && from_to.includes("Date_to")) || (date_counter > 1 && !saved_time_from[date_counter] && from_to.includes("Date_from"))) { + + if (from_to.includes("Date_from")) { + \$("input[name='time_from_"+date_counter+"']").val(time_part_from) ; + } else { + \$("input[name='time_to_"+date_counter+"']").val(time_part_to) ; + } + + set_full_half_day('',date_counter) ; + if ((nr_days["full"] && !prev_nr_days["full"]) || (nr_days["half"] && !prev_nr_days["half"]) || (!nr_days["full"] && prev_nr_days["full"]) || (!nr_days["half"] && prev_nr_days["half"])) { + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + changed_radio_cnt = 0 ; + } + prev_nr_days["full"] = nr_days["full"] ; + prev_nr_days["half"] = nr_days["half"] ; + + } + } + + // if (saved_time_to[date_counter] && from_to.includes("Date_to")) { + // \$("input[name='time_to_"+date_counter+"']").val(time_part_to) ; + // } + + if (from_to.includes("Date_to")) { + saved_time_to[date_counter] = time_part_to ; + } else { + saved_time_from["1"] = time_part_from ; + } + + // if (from_to.includes("Date_from")) { + // \$("input[name='time_from_1']").val(time_part_from) ; + // set_full_half_day('',1) ; + // } else { + // let diffInDays = 1 + (new Date(date_part_to) - new Date(date_part_from)) / (1000 * 60 * 60 * 24) ; + // \$("input[name='time_to_"+diffInDays+"']").val(time_part_to) ; + // set_full_half_day('',diffInDays) ; + // } + + if (changed_radio_cnt) { + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + } + return ; + } + + prev_date_part_from = date_part_from ; + prev_date_part_to = date_part_to ; + + const date1 = new Date(dateFromInput) ; + const date2 = new Date(dateToInput) ; + + let hide_date_names = "#1" ; + + let glod_user_level = parseInt("$glod_user_level") ; + + let y1 = date1.getFullYear() ; let m1 = date1.getMonth() ; let d1 = date1.getDate() ; let y2 = date2.getFullYear() ; let m2 = date2.getMonth() ; let d2 = date2.getDate() ; + + m1 = m1 + 1 ; + if (m1 < 10) { + m1 = "0"+m1.toString() ; + } + m2 = m2 + 1 ; + if (m2 < 10) { + m2 = "0"+m2.toString() ; + } + + if ((y1 == y2 && m1 == m2 && d1 == d2) || date1 > date2) { + + if (date1 > date2 && from_to == "datetimepickerDate_from") { + \$("#datetimepickerDate_to").datetimepicker("setDate",date_part_from+" "+time_part_to) ; + \$("#day_1_name label.control-label").text(date_part_from) ; + } else if (date1 > date2 && from_to == "datetimepickerDate_to") { + \$("#datetimepickerDate_from").datetimepicker("setDate",date_part_to+" "+time_part_from) ; + \$("#day_1_name label.control-label").text(date_part_to) ; + } + + \$("input[name='time_from_1']").val(time_part_from) ; + \$("input[name='time_to_1']").val(time_part_to) ; + + changed_radio_cnt = 0 ; + + set_full_half_day('',1) ; + + \$("#radio_1_1").css("display",""); + \$("#radio_1_2").css("display",""); + + \$("#radio_row_id_2_1").hide() ; + \$("#radio_row_id_2_2").hide() ; + + if (!\$("#days_drop_downs_1").is(":hidden")) { + \$("#start_times_row_1").hide() ; + \$("#end_times_row_1").hide() ; + \$("#days_drop_downs_1").hide() ; + } + + if (!\$("#days_drop_downs_2").is(":hidden")) { + \$("#start_times_row_2").hide() ; + \$("#end_times_row_2").hide() ; + \$("#days_drop_downs_2").hide() ; + } + + let reduced_nr_of_days = 0 ; + + for (let i=2; i<=20; i++) { + \$("#day_"+i+"_chosen").css("display","none") ; + + if (\$("#day_"+i).val()) { + \$("#day_"+i).val("") ; + \$("#day_"+i).trigger("chosen:updated") ; + \$("#radio_"+i+"_1").css("display","none") ; + \$("#radio_"+i+"_2").css("display","none") ; + reduced_nr_of_days = 1 ; + } + } + + if (changed_radio_cnt || reduced_nr_of_days) { + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + } + + if (!\$("#day_1").val()) { + \$("#day_1").val("1") ; + \$("#day_1").trigger("chosen:updated") ; + } + \$("#inputQty").val("1") ; + + if (\$("#clicked_any_button").text()) { + + // if (!\$("#days_drop_downs_1").is(":hidden")) { + // \$("#days_drop_downs_1").css("display","none") ; + // \$("#start_times_row_1").css("display","none") ; + // \$("#end_times_row_1").css("display","none") ; + // } + + // if (!\$("#days_drop_downs_2").is(":hidden")) { + // \$("#days_drop_downs_2").css("display","none") ; + // \$("#start_times_row_2").css("display","none") ; + // \$("#end_times_row_2").css("display","none") ; + // } + // if (\$("#day_1_1").is(":hidden")) { + // \$("#day_1_1").removeClass('col-md-0').addClass('col-md-1') ; + // \$("#day_1_1").css("display","") ; + // } + + // if (!\$("#day_1_1").html()) { + // let select_1_1_raw = add_select_raw (1,"custom_operator_1_1","selectCustom_operator_1_1","Select an Option","$operator_options",-1,100) ; + // \$("#day_1_1").html(select_1_1_raw) ; + // } + + add_operator_dropdown("day_1_name","day_1_1","custom_operator_1_1","selectCustom_operator_1_1",y1+"-"+m1+"-"+d1,1,0) ; + + for (let a=1;a<=15;a++) { + if (!\$("input[name='clicked_button_"+a+"']").val()) { continue ; } + + if (a > 1 && !\$("#extra_heading_"+a).is(":hidden")) { + \$("#extra_heading_"+a).hide() ; + } + + if (!\$("#day_names_"+a+"_extra_1").is(":hidden")) { + \$("#day_names_"+a+"_extra_1").css("display","none") ; + \$("#system_name_row_"+a+"_extra_1").css("display","none") ; + } + if (!\$("#day_names_"+a+"_extra_2").is(":hidden")) { + \$("#day_names_"+a+"_extra_2").css("display","none") ; + \$("#system_name_row_"+a+"_extra_2").css("display","none") ; + } + + // \$("#day_"+row+"_"+active_day_counter+"_extra").append(\$("#day_"+row+"_"+col+"").contents()); + + \$("#day_1_name").css("display","") ; + \$("#day_"+a+"_1").css("display","") ; + + for (let b=2;b<=20;b++) { + if (!\$("#day_"+b+"_name").is(":hidden")) { + \$("#day_"+b+"_name").css("display","none") ; + } + if (!\$("#day_"+a+"_"+b).is(":hidden")) { + \$("#day_"+a+"_"+b).css("display","none") ; + } + } + } + } + + return ; + } + + // if (\$("#clicked_any_button").text()) { + + // for (let a=1;a<=15;a++) { + + // if (!\$("input[name='clicked_button_"+a+"']").val()) { continue ; } + + // for (let b=1;b<=date_counter;b++) { + // if (!\$("#day_"+b+"_name").is(":hidden")) { + // \$("#day_"+a+"_"+b).css("display","") ; + // \$("#selectCustom_operator_"+a+"_"+b+"_chosen").css("width","100%") ; + // } else { + // \$("#day_"+a+"_"+b).css("display","none") ; + // } + // } + // } + // } + + + if (\$("#days_drop_downs_1").is(":hidden")) { + // if (glod_user_level > 3) { + \$("#days_drop_downs_1").css("display","") ; + \$("#start_times_row_1").css("display","") ; + \$("#end_times_row_1").css("display","") ; + } + + // if (date1 > date2 ) { + + // \$("#inputQty").val("0") ; + // for (let k=1;k<=6;k++) { + // \$("#day_"+k).val('') ; + // \$("#day_"+k).trigger("chosen:updated") ; + // \$("input[name='time_from_"+k+"']").val('') ; + // \$("input[name='time_to_"+k+"']").val('') ; + // \$("#timepickerTime_from_"+k).css("display","none") ; + // \$("#timepickerTime_to_"+k).css("display","none") ; + // \$("#radio_"+k+"_1").css("display","none") ; + // \$("#radio_"+k+"_2").css("display","none") ; + // \$("#day_"+k+"_chosen").css("display","none") ; + // } + + // return ; + + + // let date_part_from = dateFromInput.split(' ')[0]; + // \$("#datetimepickerDate_to").datetimepicker("setDate",date_part_from+" "+time_part_to) ; + + // \$("input[name='time_from_1']").val(time_part_from) ; + // \$("input[name='time_to_1']").val(time_part_to) ; + + // let time_1 = timeStringToSeconds(time_part_from) ; + // let time_2 = timeStringToSeconds(time_part_to) ; + + // if (time_2 < time_1 || !\$("#day_1").val()) { + // \$("#inputQty").val("0") ; + // } else { + // \$("#inputQty").val("1") ; + // let time_diff_ = time_2 - time_1 ; + // if (time_diff_ >= 18000) { + // \$("#radio_1_1").prop('checked',true) ; + // } else { + // \$("#radio_1_2").prop('checked',true) ; + // } + // } + + // \$("#days_drop_downs").css("display","none") ; + // \$("#start_times_row").css("display","none") ; + // \$("#end_times_row").css("display","none") ; + + // for (let k=2;k<=6;k++) { + // if (\$("#day_"+k).val()) { + // \$("#day_"+k).val('') ; + // \$("#day_"+k).trigger("chosen:updated") ; + // \$("#radio_"+k+"_1").css("display","none") ; + // \$("#radio_"+k+"_2").css("display","none") ; + // } + // } + + // return ; + // } + + \$("input[name='time_from_1']").val(time_part_from) ; + + const datesBetween = getDatesBetween(dateFromInput,dateToInput,0) ; + let date_counter = 0 ; let dates_count = 0 ; let count_days = 0 ; + + let count_days_after = 0 ; let nr_of_active_days = 0 ; + + // for (const date of datesBetween) { + // date_counter++ ; dates_count++ ; + // if (\$("#day_"+date_counter+"_chosen").is(":hidden")) { + + // \$("#radio_"+date_counter+"_1").css("display",""); + // \$("#radio_"+date_counter+"_2").css("display",""); + // \$("#day_"+date_counter).val("1") ; + // \$("#day_"+date_counter).trigger("chosen:updated") ; + // \$("#day_"+date_counter+"_chosen").css("display",""); + // \$("#day_"+date_counter+"_chosen").css("width","100%"); + // \$("#day_"+date_counter).val('1') ; + // \$("#day_"+date_counter).trigger("chosen:updated") ; + // if (date_counter > 1) { + // console.log("1 . display timepickerTime_from_"+date_counter) ; + // \$("#timepickerTime_from_"+date_counter).css("display",""); + // } + // } + // if (\$("#day_"+date_counter).val()) { + // nr_of_active_days++ ; + // } + // } + + // date_counter = 0 ; + + let dates_map = {} ; + + changed_radio_cnt = 0 ; let changed_nr_of_days = 0 ; + + for (const date of datesBetween) { + + date_counter++ ; + + dates_map[date_counter] = date ; + + // console.log("1 . date_counter : "+dates_map[date_counter]) ; + + // if (date_counter > 6) { date_counter = 6 ; count_days_after++ ; continue ; } + if (date_counter > 20) { date_counter = 20 ; break ; } + if (date_counter > 1 && !saved_time_from[date_counter]) { + \$("input[name='time_from_"+date_counter+"']").val(time_part_from) ; + } + if (!saved_time_to[date_counter]) { + \$("input[name='time_to_"+date_counter+"']").val(time_part_to) ; + } + + set_full_half_day('',date_counter) ; + + if (\$("#day_"+date_counter+"_chosen").is(":hidden")) { + + \$("#radio_"+date_counter+"_1").css("display",""); + \$("#radio_"+date_counter+"_2").css("display",""); + \$("#day_"+date_counter).val("1") ; + \$("#day_"+date_counter).trigger("chosen:updated") ; + \$("#day_"+date_counter+"_chosen").css("display",""); + \$("#day_"+date_counter+"_chosen").css("width","100%"); + \$("#day_"+date_counter).val('1') ; + \$("#day_"+date_counter).trigger("chosen:updated") ; + if (date_counter > 1) { + // console.log("1 . display timepickerTime_from_"+date_counter) ; + \$("#timepickerTime_from_"+date_counter).css("display",""); + } + changed_nr_of_days = 1 ; + } + + if (\$("#day_"+date_counter).val()) { + \$("#timepickerTime_to_"+date_counter).css("display","") ; + nr_of_active_days++ ; + } + + \$("#day_"+date_counter+" option[value='1']").text(date); + \$("#day_"+date_counter+" option[value='1']").trigger("chosen:updated") ; + + if (\$("#day_"+date_counter).val()) { + count_days++ ; + } + } + + if (\$("#days_drop_downs_2").is(":hidden") && date_counter > 10) { + // if (glod_user_level > 3) { + \$("#days_drop_downs_2").css("display","") ; + \$("#start_times_row_2").css("display","") ; + \$("#end_times_row_2").css("display","") ; + \$("#radio_row_id_2_1").css("display","") ; + \$("#radio_row_id_2_2").css("display","") ; + } else if (!\$("#days_drop_downs_2").is(":hidden") && date_counter <= 10) { + \$("#days_drop_downs_2").css("display","none") ; + \$("#start_times_row_2").css("display","none") ; + \$("#end_times_row_2").css("display","none") ; + \$("#radio_row_id_2_1").css("display","none") ; + \$("#radio_row_id_2_2").css("display","none") ; + } + + if (count_days_after) { + + date2.setDate(date2.getDate() - count_days_after); + \$("#datetimepickerDate_to").datetimepicker("setDate",date2) ; + + } + + let select_raw ; + + // console.log("nr_of_active_days : "+nr_of_active_days) ; + + let select_chosen_ids_1 = '#1' ; + let select_chosen_ids_2 = '#2' ; + let names_to_display = '#3' ; + + let def_val = 0 ; + + if (\$("#clicked_any_button").text()) { + + if (nr_of_active_days <= 6) { + for (let b=1;b<=date_counter;b++) { + + if (from_to == "datetimepickerDate_from") { + \$("#day_"+b+"_name label.control-label").text('') ; + } + + // if (!\$("#day_"+date_counter+"_name label.control-label").text()) { + if (\$("#day_"+b+"_name").is(":hidden")) { + \$("#day_"+b+"_name label.control-label").text(dates_map[b]) ; + \$("#day_"+b+"_name").css("display","") ; + \$("#day_"+b+"_name").removeClass('col-md-0').addClass('col-md-1') ; + } + + if (!\$("#day_"+b).val() || !\$("#clicked_any_button").text()) { + \$("#day_"+b+"_name").css("display","none") ; + } + } + } + + for (let a=1;a<=15;a++) { + + if (!\$("input[name='clicked_button_"+a+"']").val()) { + let prev_row_nr = a - 1 ; + if (!\$("extra_heading_"+a).html() && \$("input[name='clicked_button_"+a+"']").val() && prev_row_nr && nr_of_active_days > 6) { + + console.log("hello world Add Heading") ; + + \$("#system_name_row_"+a).before("
    ") ; + } else if (\$("extra_heading_"+a).is(":hidden") && \$("input[name='clicked_button_"+a+"']").val() && prev_row_nr && nr_of_active_days > 6) { + \$("#system_name_row_"+a).show() ; + } else if (!\$("extra_heading_"+a).is(":hidden") && \$("input[name='clicked_button_"+a+"']").val() && prev_row_nr && nr_of_active_days <= 6) { + \$("#extra_heading_"+a).hide() ; + } + continue ; + } + + // let prev_row = a - 1 ; + + if (nr_of_active_days <= 6 && a > 1 && !\$("#extra_heading_"+a).is(":hidden")) { + \$("#extra_heading_"+a).hide() ; + console.log("Hide Heading") ; + } else if (nr_of_active_days > 6 && a > 1 && \$("#extra_heading_"+a).length && \$("#extra_heading_"+a).is(":hidden") && \$("input[name='clicked_button_"+a+"']").val()) { + \$("#extra_heading_"+a).show() ; + console.log("Display Heading") ; + } else if (nr_of_active_days > 6 && a > 1 && !\$("#extra_heading_"+a).length && \$("input[name='clicked_button_"+a+"']").val()) { + console.log("123 Add Heading") ; + \$("#system_name_row_"+a).before("
    ") ; + + } + + if (nr_of_active_days <= 6) { + + + if (!\$("#day_names_"+a+"_extra_1").is(":hidden")) { + \$("#day_names_"+a+"_extra_1").css("display","none") ; + \$("#system_name_row_"+a+"_extra_1").css("display","none") ; + } + if (!\$("#day_names_"+a+"_extra_2").is(":hidden")) { + \$("#day_names_"+a+"_extra_2").css("display","none") ; + \$("#system_name_row_"+a+"_extra_2").css("display","none") ; + } + for (let b=1;b<=date_counter;b++) { + // if (!\$("#day_"+b+"_name").is(":hidden")) { + + def_val = \$("#selectCustom_operator_"+a+"_"+b).val() ; + + if (!\$("#day_"+a+"_"+b).html() && \$("#day_"+b).val()) { + \$("#day_"+a+"_"+b).show() ; + \$("#day_"+a+"_"+b).removeClass('col-md-0').addClass('col-md-1') ; + if (!\$("#day_"+a+"_"+b).html()) { + let select_raw = add_select_raw (a,"custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,"Select an Option","$operator_options",-1,100) ; + \$("#day_"+a+"_"+b).html(select_raw) ; + \$("#day_"+a+"_"+b).trigger("chosen:updated") ; + \$("#selectCustom_operator_"+a+"_"+b).chosen({allow_single_deselect:true}) ; + \$("#selectCustom_operator_"+a+"_"+b+"_chosen").css("width","100%") ; + } + + // \$("#selectCustom_operator_"+a+"_"+b+"_chosen").css("width","100%") ; + } + + if (!\$("#selectCustom_operator_"+a+"_"+b).val() && def_val) { + \$("#selectCustom_operator_"+a+"_"+b).val(def_val) ; + \$("#selectCustom_operator_"+a+"_"+b).trigger("chosen:updated") ; + } + + // else { + // \$("#day_"+a+"_"+b).css("display","none") ; + // } + } + } else if (nr_of_active_days > 6 && nr_of_active_days <= 10) { + + // console.log("EXTRA TAB 1 nr_of_active_days : "+nr_of_active_days) ; + + if (\$("#day_names_"+a+"_extra_1").is(":hidden")) { + \$("#day_names_"+a+"_extra_1").show() ; + } + \$("#system_name_row_"+a+"_extra_1").show() ; + if (!\$("#day_names_"+a+"_extra_2").is(":hidden")) { + \$("#day_names_"+a+"_extra_2").hide() ; + } + \$("#system_name_row_"+a+"_extra_2").hide() ; + + for (let b=1;b<=date_counter;b++) { + // for (let b=1;b<=20;b++) { + + // if (\$("#day_"+b).val()) { + + def_val = \$("#selectCustom_operator_"+a+"_"+b).val() ; + add_operator_dropdown("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,0) ; + select_chosen_ids_1 = select_chosen_ids_1+",#selectCustom_operator_"+a+"_"+b ; + select_chosen_ids_2 = select_chosen_ids_2+",#selectCustom_operator_"+a+"_"+b+"_chosen" ; + names_to_display = names_to_display + ",#day_"+b+"_name_"+a+"_extra_1" ; + \$("#day_"+b+"_name_"+a+"_extra_1 label.control-label").text(dates_map[b]) ; + // } + console.log("#day_"+b+"_name_"+a+"_extra_1") ; + if (!\$("#day_"+b).val()) { + + hide_non_empty_operator_dropdown("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1") ; + // \$("#day_"+b+"_name_"+a+"_extra_1").css("display","none") ; + hide_date_names = hide_date_names + ",#day_"+b+"_name_"+a+"_extra_1" ; + // \$("#day_4_name_1_extra_1").css("display","none") ; + } + + delete_operator_dropdown ("day_"+b+"_name","day_"+a+"_"+b) ; + delete_operator_dropdown ("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_2") ; + + if (!\$("#selectCustom_operator_"+a+"_"+b).val() && def_val) { + \$("#selectCustom_operator_"+a+"_"+b).val(def_val) ; + \$("#selectCustom_operator_"+a+"_"+b).trigger("chosen:updated") ; + } + } + } else if (nr_of_active_days > 10) { + + if (\$("#day_names_"+a+"_extra_1").is(":hidden")) { + \$("#day_names_"+a+"_extra_1").show() ; + } + if (\$("#day_names_"+a+"_extra_2").is(":hidden")) { + \$("#day_names_"+a+"_extra_2").show() ; + } + \$("#system_name_row_"+a+"_extra_1").show() ; + \$("#system_name_row_"+a+"_extra_2").show() ; + + let used_dates = 0 ; + + for (let b=1;b<=date_counter;b++) { + + // if (used_dates <= 10) { + + let def_val = 0 ; + def_val = \$("#selectCustom_operator_"+a+"_"+b).val() ; + + if (used_dates < 10 && \$("#day_"+b).val()) { + + used_dates++ ; + add_operator_dropdown("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,0) ; + select_chosen_ids_1 = select_chosen_ids_1+",#selectCustom_operator_"+a+"_"+b ; + select_chosen_ids_2 = select_chosen_ids_2+",#selectCustom_operator_"+a+"_"+b+"_chosen" ; + delete_operator_dropdown ("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_2") ; + \$("#day_"+b+"_name_"+a+"_extra_2 label.control-label").text(dates_map[b]) ; + + } else if (!\$("#day_"+b).val() && dates_map[b]) { + add_operator_dropdown("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,1) ; + select_chosen_ids_1 = select_chosen_ids_1+",#selectCustom_operator_"+a+"_"+b ; + select_chosen_ids_2 = select_chosen_ids_2+",#selectCustom_operator_"+a+"_"+b+"_chosen" ; + hide_non_empty_operator_dropdown("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_2") ; + } else if (\$("#day_"+b).val() && used_dates == 10) { + add_operator_dropdown("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_2","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,0) ; + delete_operator_dropdown ("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1") ; + select_chosen_ids_1 = select_chosen_ids_1+",#selectCustom_operator_"+a+"_"+b ; + select_chosen_ids_2 = select_chosen_ids_2+",#selectCustom_operator_"+a+"_"+b+"_chosen" ; + } + + delete_operator_dropdown ("day_"+b+"_name","day_"+a+"_"+b) ; + + if (!\$("#selectCustom_operator_"+a+"_"+b).val() && def_val) { + \$("#selectCustom_operator_"+a+"_"+b).val(def_val) ; + \$("#selectCustom_operator_"+a+"_"+b).trigger("chosen:updated") ; + } + + // if (\$("#day_"+a+"_"+b+"_extra_2").html()) { + // \$("#day_"+a+"_"+b+"_extra_2").html('') ; + // \$("#day_"+a+"_"+b+"_extra_2").removeClass('col-md-1').addClass('col-md-0') ; + // \$("#day_"+a+"_"+b+"_extra_2").css("display","none") ; + // } + + // } + + // else { + + // if (\$("#day_"+b).val()) { + + // add_operator_dropdown("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_1","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,0) ; + + // } else if (!\$("#day_"+b).val() && dates_map[b]) { + // hide_non_empty_operator_dropdown("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_2") ; + // } + + // } + } + } + } + + } + + \$("#inputQty").val(count_days) ; + + \$("#timepickerTime_to_"+date_counter).css("display","none"); + + // console.log("date_counter : "+date_counter) ; + + if (date_counter <= 20) { + for (let j=date_counter+1;j<=20;j++) { + for (let k=1; k<=15; k++) { + if (\$("input[name='clicked_button_"+k+"']").val()) { + if ( \$("#day_"+k+"_"+j).html()) { + \$("#day_"+k+"_"+j).html('') ; + \$("#day_"+k+"_"+j).removeClass('col-md-1').addClass('col-md-0') ; + \$("#day_"+k+"_"+j).hide() ; + } + // delete_operator_dropdown("day_"+j+"_name_"+k,"day_"+k+"_"+j) ; + delete_operator_dropdown("day_"+j+"_name_"+k+"_extra_1","day_"+k+"_"+j+"_extra_1") ; + delete_operator_dropdown("day_"+j+"_name_"+k+"_extra_2","day_"+k+"_"+j+"_extra_2") ; + } + } + if (\$("#day_"+j).val()) { + \$("#day_"+j).val("").trigger("chosen:updated") ; changed_nr_of_days = 1 ; + } + if (!\$("#day_"+j+"_chosen").is(":hidden")) { + \$("#day_"+j+"_name label.control-label").text('') ; + \$("#day_"+j+"_name").css("display","none") ; + \$("#radio_"+j+"_1").css("display","none") ; + \$("#radio_"+j+"_2").css("display","none") ; + \$("#day_"+j+"_chosen").css("display","none") ; + // console.log("col : "+j) ; + } + if (!\$("#timepickerTime_from_"+j).is(":hidden")) { + \$("#timepickerTime_from_"+j).css("display","none") ; + } + if (!\$("#timepickerTime_to_"+j).is(":hidden")) { + \$("#timepickerTime_to_"+j).css("display","none") ; + } + + } + } + + + if (changed_radio_cnt || changed_nr_of_days) { + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + } + + + \$(names_to_display).removeClass('col-md-0').addClass('col-md-1'); + \$(names_to_display).show() ; + \$(select_chosen_ids_1).chosen({allow_single_deselect:true}) ; + \$(select_chosen_ids_2).css("width","100%") ; + + // // // for (let k=1;k<=50;k++) { + // // // if (\$("#selectDescription_workings_event_"+k).val() == 14) { + // // // \$("#inputQty_workings_event"+k).val(0) ; + // // // let ttl_amnt = 0 ; + // // // \$("#inputAmount_workings_event"+k).val(ttl_amnt.toFixed(2)) ; + // // // } + // // // } + // // // calcAllWorkings() ; + + // // // for (let k=1;k<=50;k++) { + // // // if (\$("#selectDescription_workings_event"+k).val() == 14) { + // // // let inp_qty = differenceDays ; + // // // \$("#inputQty_workings_event"+k).val(inp_qty) ; + // // // let amnt = \$("#inputAmount_usd_workings_event"+k).val() ; + // // // let ttl_amnt = amnt*inp_qty ; + // // // \$("#inputAmount_workings_event"+k).val(ttl_amnt.toFixed(2)) ; + // // // } + // // // } + // // // if ($changed_opid_as_level_3) { + // // // calc_hidden_totals() ; + // // // } else { + // // // calcAllWorkings() ; + // // // } + + // \$("#day_4_name_1_extra_1").css("display","none") ; + + if (hide_date_names != "#1") { + \$(hide_date_names).css("display","none") ; + } + + } + + + + + function timeStringToSeconds(timeString) { + + const [hours, minutes, seconds] = timeString.split(':').map(Number); + return hours * 3600 + minutes * 60 + seconds; + } + + function getDatesBetween(startDateStr,endDateStr,count_dates) { + if (!startDateStr || !endDateStr) { + return ; + } + const dates = []; + let currentDate = new Date(startDateStr); + let endDate = new Date(endDateStr) ; + // currentDate.setHours(currentDate.getHours() + 2); + // endDate.setHours(endDate.getHours() + 2); + currentDate.setHours(+2); + currentDate.setMinutes(0); + currentDate.setSeconds(0); + endDate.setHours(+2); + endDate.setMinutes(59); + endDate.setSeconds(59); + + // console.log("2 . currentDate : "+currentDate.toISOString().split('T')[0]) ; + while (currentDate < endDate) { + // console.log("3 . currentDate : "+currentDate.toISOString().split('T')[0]) ; + dates.push(currentDate.toISOString().split('T')[0]); + currentDate.setDate(currentDate.getDate() + 1); + if (count_dates) { count_dates++ ; } + } + if (count_dates) { + count_dates-- ; + return count_dates; + } else { + return dates; + } + } + ~ ; + + &event_tabs_content_box($sec_name,$sec_col); + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + + if ($tab == 3) { # Event Specifics + + # --------------- START DOCUMENT UPLOADS ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + my $sec = '_event_specifics' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $add_form_fields = '' ; + + my %selected_1 = () ; my %selected_2 = () ; + + &db_min_ro('event_quotes_categories','*','','','') ; + + $selected_1{$db{$table}{$id}{category_id_1}} = 'SELECTED' ; + $selected_2{$db{$table}{$id}{category_id_2}} = 'SELECTED' ; + my $none_id = 0 ; + + foreach (sort {$db{event_quotes_categories}{$a}{category} cmp $db{event_quotes_categories}{$b}{category}} keys %{$db{event_quotes_categories}}) { + + if ($db{event_quotes_categories}{$_}{category} eq 'None') { + $none_id = $_ ; + next ; + } + $opts{category_id_2} .= qq~~ ; + $opts{category_id_1} .= qq~~ ; + } + $opts{category_id_2} .= qq~~ ; + $opts{category_id_1} .= qq~~ ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + $fcol = 8 ; $lcol = 3 ; + + my @cat_details = split('\|;\|',$db{event_quotes_min}{$id}{category_details}) ; + + $preferred_title{category_1_details} = "Category 1 Sub Categories" ; + $preferred_title{category_2_details} = "Category 2 Sub Categories" ; + + &common_shared_poc_recipient_select_code("poc",'',$id) ; + + $add_form_fields .= qq~ +
    +
    + +
    +
    +

    SPORT:_AGE GROUP_TEAM 1_VS_AGE GROUP_TEAM 2
    SPORT:_AGE GROUP_TEAM 1_VS_AGE GROUP_TEAM 2-FESTIVAL/LEAGUE

    +
    +
    + ~ ; + + $add_form_fields .= &common_min_form_select('category_id_1',$db{$table}{$id}{category_id_1},'') ; + $add_form_fields .= &common_min_form_textarea('category_1_details',$cat_details[0],'') ; + $add_form_fields .= &common_min_form_select('category_id_2',$db{$table}{$id}{category_id_2},'') ; + $add_form_fields .= &common_min_form_textarea('category_2_details',$cat_details[1],'') ; + + $trigger_jquery .= qq~\$("#selectCategory_id_1\_chosen").css("width","100%");~ ; + $trigger_jquery .= qq~\$("#selectCategory_id_2\_chosen").css("width","100%");~ ; + + $preferred_title{format_of_title} = "Format of TITLE to be followed when scheduling events" ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= &common_min_form_input('recipient_name',$db{$table}{$id}{recipient_name},'') ; + # $add_form_fields .= &common_min_form_input('recipient_nr',$db{$table}{$id}{recipient_nr},'') ; + &common_shared_poc_recipient_select_code("recipient",'',$id) ; + $add_form_fields .= &common_min_form_textarea('additional_notes',$db{$table}{$id}{additional_notes},'') ; + $add_form_fields .= &common_min_form_textarea('format_of_title',$db{$table}{$id}{format_of_title},'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + my @docs = ('1','2','3') ; + + $add_form_fields .= qq~ +
     
    +
    + ~ ; + + &common_shared_poc_recipient_select_shared_jquery ; + + foreach (@docs) { + my $doc = lc $_ ; $doc =~ s/ /\_/ ; $doc =~ s/&/\_/ ; + $working_uploads = &common_get_field_uploads($id,"upload_$doc",'id') ; + if ($working_uploads) { + $add_form_fields .= qq~ +
    + $working_uploads +
    ~; + } else { + $add_form_fields .= qq~ +
    +
    + + +

    Upload file from PC.

    +
    +
    + ~; + } + } + + $add_form_fields .= qq~ +
    + ~ ; + + &event_tabs_content_box($sec_name,$sec_col); + + # --------------- END DOCUMENT UPLOADS ---------------------------------------------------------------------------------------------------------------- + } + + if ($tab == 4) { # Costing + + # --------------- START COSTING ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + $lcol = 1; + $fcol = 2; + $preferred_title{currency} = 'Currency' ; + $add_form_fields .= &common_min_form_select('currency',$db{$table}{$id}{currency},1) ; # don't end row + $trigger_jquery .= qq~\$("#selectCurrency_chosen").css( "width", "96%" );~ ; + $preferred_title{roe} = ' ROE ' ; $fcol=1; # $fcol=2 ; + $add_form_fields .= &common_min_form_label_col('roe') ; + $db{$table}{$id}{roe} = 1 if not $db{$table}{$id}{roe} ; + $add_form_fields .= &common_min_form_input_col('roe',$db{$table}{$id}{roe},1) ; + # $preferred_title{roe} = ' Discount ' ; + # $add_form_fields .= &common_min_form_label_col('discount') ; + # $add_form_fields .= &common_min_form_select_col('discount',$db{$table}{$id}{discount}) ; + $trigger_jquery .= qq~\$("#selectDiscount_chosen").css( "width", "96%" );~ ; + $add_form_fields .= qq~~ ; + + our %sec_cnt = ('a_event' => "30-List Event Costings"); + + our $display_hidden_input = ($username eq 'handre') ? "readonly" : "style='display:none;'" ; + + my $sec = 'costing' ; + my ($sec_name, $sec_cnt, $sec_col) = &tab_sec_det($sec) ; + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret; + + &event_tabs_build_sec($sec,$tab) ; + + foreach (sort keys %sec_cnt) { + $_k = substr($_, 1) ; + my @parts = split(/\-/, $sec_cnt{$_}) ; + $add_form_fields .= qq~ +
    +
    +

    + $parts[1] : +

    +
    +
    + ~ ; + &tab_build_qt_col_headers("$sec$_k"); + # # # &db_min_ro('event_quotes_min','id,excl_costing_event,item_costing_event,qty_costing_event,usd_amnt_costing_event,item_ttl_costing_event,vat_costing_event,curr_amnt_costing_event',"id=$id",'','') if $id ; + &event_tabs_build_costs_forms($id,$tab,$parts[0],"$sec$_k"); + } + + $add_form_fields .= qq~ +
    +
    +   +
    +
    ~ ; + $add_form_fields .= qq~ +
    +
    +   +
    + ~ ; + + my @ttlarr = ("sub_total","vat_total","grand_total") ; + $lcol = 1 ; + $fcol = 1 ; + foreach (@ttlarr) { + $lcol = 1 ; $add_form_fields .= &common_min_form_label_col($_) ; + } + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $lcol = 2 ; + $add_form_fields .= &common_min_form_label_col('Total') ; + $lcol = 1 ; $fcol = 1 ; + + foreach (@ttlarr) { + $readonly{"$_\_costing_event"} = "READONLY" ; + $input_style{"$_\_costing_event"} = qq~style="text-align:right;"~ ; + my $val = $db{$table}{$id}{$_} ? $db{$table}{$id}{$_} : '0.00' ; + $add_form_fields .= &common_min_form_input_col("$_\_costing_event",$val) ; + } + + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= qq~ +
    +
    +   +
    +
    + ~ ; + + &event_tabs_content_box($sec_name,$sec_col); + + $trigger_jquery_raw .= qq~ + + function count_nr_of_full_day_and_half_days () { + + let full_day_exists = 0 ; let half_day_exists = 0 ; + + console.log("count_nr_of_full_day_and_half_days") ; + + for (let i = 1; i<=20; i++) { + if (\$("#radio_"+i+"_1").is(":checked") && \$("#day_"+i).val()) { + full_day_exists++ ; + } else if (\$("#radio_"+i+"_2").is(":checked") && \$("#day_"+i).val()) { + half_day_exists++ ; + } + } + + console.log("full_day_exists : "+full_day_exists) ; + + return [full_day_exists,half_day_exists] ; + + } + + function cnt_selected_systems_per_cost_item () { + + let i = 0 ; + cnt_systems_per_cost_item = {} ; + while (true) { + i++ ; + + let system_id = \$("#selectSystem_name_"+i).val() ; + + if (!cnt_systems_per_cost_item[get_event_cost_id[system_id]]) { + cnt_systems_per_cost_item[get_event_cost_id[system_id]] = 0 ; + } + if (!\$("#system_name_row_"+i).html()) { + i-- ; + break ; + } + if (system_id && get_event_cost_id[system_id]) { + cnt_systems_per_cost_item[get_event_cost_id[system_id]]++ ; + } + } + } + + function auto_deselect_cost_items_in_quote_tab (row_nr) { + + let orig_system_id = orig_selected_system_names[row_nr] ; + let orig_cost_item = get_event_cost_id[orig_system_id] ; // Check whether get_event_cost_id exists + + if (!orig_system_id || (orig_system_id && !orig_cost_item)) { + return ; + } + let i = 0 ; + // Chech if the corresponding cost item exists for a diffent selected system + + while (true) { + i++ ; + if (!\$("#system_name_row_"+i).html()) { + break ; + } + if (i == row_nr) { + continue ; + } + if (orig_cost_item == get_event_cost_id[\$("#selectSystem_name_"+i).val()]) { + return ; + } + } + + i = 0 ; let j = 0 ; let select_new_values = {} ; let input_new_values = {} ; let checkbox_new_values = {} ; + + while (true) { + + i++ ; j++ ; + if (!\$("#costing_event_"+i).html()) { + i-- ; j-- ; + break ; + } + + let hidden_input = (\$("input[name='added_full_day_cost_item_"+i+"']").val()) ? \$("input[name='added_full_day_cost_item_"+i+"']").val() : (\$("input[name='added_half_day_cost_item_"+i+"']").val()) ? \$("input[name='added_full_day_cost_item_"+i+"']").val() : "" ; + + if (typeof hidden_input !== "undefined" && (hidden_input.includes("-1") || hidden_input.includes("-2"))) { + continue ; + } + + if (orig_cost_item == \$("#selectDescription_costing_event_"+i).val()) { + + j-- ; + \$("#selectDescription_costing_event_"+i).val("").trigger("chosen:updated") ; + \$("#inputQty_costing_event_"+i).val("") ; + \$("#inputAmount_usd_costing_event_"+i).val("") ; + + // calc_totals(i,"costing_event") ; + } else { + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = \$("input[name='qty_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; ; + input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = \$("input[name='amount_ttl_costing_event_"+i+"']").val() ; ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + } + + if (i != j) { + \$("input[name='added_full_day_cost_item_"+i+"']").remove() ; + \$("input[name='added_half_day_cost_item_"+i+"']").remove() ; + } + + } + + for (let key in select_new_values) { + console.log("select_new_values : "+key) ; + if (select_new_values[key] != \$(key).val()) { + \$(key).val(select_new_values[key]).trigger("chosen:updated") ; + } + } + + for (let key in input_new_values) { + if (typeof \$(key).val() == 'undefined' && input_new_values[key]) { + // let display = (hidden_input_name[key].includes("_day_cost_item_")) ? "" : "" ; + let display = (hidden_input_name[key].includes("_day_cost_item_") && "$username" == "handre") ? "" : "style='display:none;'" ; + \$(hidden_input_to_html_row[key]).append("") ; + } + + if (input_new_values[key] != \$(key).val()) { + \$(key).val(input_new_values[key]) ; + } + } + + for (let key in checkbox_new_values) { + if (\$(key).is(":checked") && !checkbox_new_values[key]) { + \$(key).prop("checked",false) ; + } else if (!\$(key).is(":checked") && checkbox_new_values[key]) { + \$(key).prop("checked",true) ; + } + } + + if (j < i) { + for (let k=j+1;k<=i+1;k++) { + if ((j == 0 && k > 1) || j > 0) { + \$("#costing_event_"+k).html("") ; + } + if ((k == j+1 && j > 0) || (j == 0 && k == 2)) { + console.log("SHOW : #btn_row_costing_event_"+k) ; + \$("#btn_row_costing_event_"+k).show() ; + \$("#btn_costing_event_"+k).show() ; + } else if (j > 0 || (j == 0 && k > 2)) { + console.log("HIDE : #btn_row_costing_event_"+k) ; + \$("#btn_row_costing_event_"+k).hide() ; + \$("#btn_costing_event_"+k).hide() ; + } + } + } + + } + + function auto_select_cost_items_in_quote_tab (id,row_number) { + + cnt_selected_systems_per_cost_item() ; + + let system_id = \$("#"+id).val() ; + + let row_nr = (row_number) ? row_number : get_row_nr(id) ; + + if (orig_selected_system_names[row_nr] && get_event_cost_id[orig_selected_system_names[row_nr]] != get_event_cost_id[system_id]) { + auto_deselect_cost_items_in_quote_tab(row_nr) ; + } + + let event_cost_id = get_event_cost_id[system_id] ; + + console.log("event_cost_id : "+event_cost_id) ; + + let i = 0 ; + + if (!event_cost_id) { + + while (true) { + i++ ; + if (!\$("#costing_event_"+i).html()) { + break ; + } + if (\$("#selectDescription_costing_event_"+i).val() && \$("#selectDescription_costing_event_"+i).val() == get_event_cost_id[orig_selected_system_names[row_nr]] && i != row_nr) { + event_cost_id = get_event_cost_id[orig_selected_system_names[row_nr]] ; + } + } + + if (!event_cost_id) { + orig_selected_system_names[row_nr] = \$("#selectSystem_name_"+row_nr).val() ; + return ; + } + + } else if (event_cost_id && get_event_cost_id[orig_selected_system_names[row_nr]] && get_event_cost_id[orig_selected_system_names[row_nr]] != event_cost_id) { + + while (true) { + i++ ; + if (!\$("#costing_event_"+i).html()) { + break ; + } + if (\$("#selectDescription_costing_event_"+i).val() && \$("#selectDescription_costing_event_"+i).val() == get_event_cost_id[orig_selected_system_names[row_nr]]) { + + let hidden_input_val = (\$("input[name='added_full_day_cost_item_"+i+"']").val()) ? \$("input[name='added_full_day_cost_item_"+i+"']").val() : (\$("input[name='added_half_day_cost_item_"+i+"']").val()) ? \$("input[name='added_half_day_cost_item_"+i+"']").val() : "" ; + if (hidden_input_val && !hidden_input_val.includes("-2")) { + let hidden_input_fh = (\$("input[name='added_full_day_cost_item_"+i+"']").val()) ? "full" : (\$("input[name='added_half_day_cost_item_"+i+"']").val()) ? "half" : "" ; + if (hidden_input_fh) { + \$("#inputQty_costing_event_"+i).val(nr_days[hidden_input_fh]*cnt_systems_per_cost_item[get_event_cost_id[orig_selected_system_names[row_nr]]]) ; + calc_totals(i,"costing_event") ; + } + } + + } + } + } + + orig_selected_system_names[row_nr] = \$("#selectSystem_name_"+row_nr).val() ; + + let default_full_day_cost_item_rate = default_cost_item_rates["full,"+event_cost_id] ; + let default_half_day_cost_item_rate = default_cost_item_rates["half,"+event_cost_id] ; + + if (!default_full_day_cost_item_rate && !default_half_day_cost_item_rate) { + return ; + } + + if (!nr_days["full"] && !nr_days["half"]) { + return ; + } + + if (nr_days["full"] && !default_full_day_cost_item_rate && !nr_days["half"] && default_half_day_cost_item_rate) { + return ; + } + + if (!nr_days["full"] && default_full_day_cost_item_rate && nr_days["half"] && !default_half_day_cost_item_rate) { + return ; + } + + let last_used_row = 0 ; i = 0 ; let cnt_systems = cnt_systems_per_cost_item[event_cost_id] ; + + if (\$("#costing_event_1").html() && !\$("#costing_event_2").html() && !\$("#selectDescription_costing_event_1").val()) { + last_used_row = 0 ; + } else { + + let nr_of_blank_rows_needed = (nr_days["full"] && nr_days["half"]) ? 2 : 1 ; + + while (true) { + i++ ; + let j = 1 + i ; + if (\$("#selectDescription_costing_event_"+i).val() && \$("#selectDescription_costing_event_"+i).val() != event_cost_id) { + last_used_row = i ; + // console.log(" 5.1 last_used_row : "+last_used_row) ; + } else if (\$("#costing_event_"+i).html() && \$("#selectDescription_costing_event_"+i).val() && \$("#selectDescription_costing_event_"+i).val() == event_cost_id) { + last_used_row = i - 1 ; + break ; + } else if ((!\$("#selectDescription_costing_event_"+i).val() && nr_of_blank_rows_needed == 1) || (nr_of_blank_rows_needed == 2 && !\$("#selectDescription_costing_event_"+i).val() && !\$("#selectDescription_costing_event_"+j).val())) { + i-- ; + break ; + } + } + } + + let full_half_loop = (nr_days["full"] && nr_days["half"]) ? ["full","half"] : (nr_days["full"]) ? ["full"] : (nr_days["half"]) ? ["half"] : [] ; + + let = f_t_h = {"full":"half","half":"full"} ; + + i = 0 ; let j = 0 ; last_used_row++ ; let need_to_shift_data_below_down = 0 ; let select_new_values = {} ; let input_new_values = {} ; let checkbox_new_values = {} ; let hidden_input_to_html_row = {} ;let hidden_input_name = {} ; let add_html_row = {} ; let already_moved_this_row = {} ; let break_loop = 0 ; let cals_totals_row = {} ; + + while (true) { + + i++ ; j++ ; + + if (last_used_row > i) { + continue ; + } + + let k = last_used_row ; + + if (j > i && \$("#selectDescription_costing_event_"+i).val() && !already_moved_this_row[i]) { + + need_to_shift_data_below_down = 1 ; + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = \$("input[name='qty_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = \$("input[name='amount_ttl_costing_event_"+i+"']").val() ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + let hidden_input_value = (\$("input[name='added_full_day_cost_item_"+i+"']").val()) ? "full" : (\$("input[name='added_half_day_cost_item_"+i+"']").val()) ? "half" : "" ; + if (hidden_input_value && hidden_input_value != "") { + input_new_values["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = \$("input[name='added_"+hidden_input_value+"_day_cost_item_"+i+"']").val() ; + hidden_input_to_html_row["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = "added_"+hidden_input_value+"_day_cost_item_"+j ; + \$("input[name='added_"+hidden_input_value+"_day_cost_item_"+i+"']").remove() ; + } + + if (!\$("#costing_event_"+j).html()) { + add_html_row[j] = 1 ; + } + cals_totals_row[j] = 1 ; + + } + + if (i == last_used_row) { + + for (let f_h in full_half_loop) { + + let default_rate = (full_half_loop[f_h] == "full") ? default_full_day_cost_item_rate : default_half_day_cost_item_rate ; + + if (nr_days[full_half_loop[f_h]] && default_rate) { + + i++ ; j++ ; + if (f_h == 0 && full_half_loop[1] && \$("#selectDescription_costing_event_"+i).val() && \$("#selectDescription_costing_event_"+i).val() != event_cost_id) { + + j++ ; + already_moved_this_row[i] = 1 ; + need_to_shift_data_below_down = 1 ; + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = \$("input[name='qty_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = \$("input[name='amount_ttl_costing_event_"+i+"']").val() ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + let hidden_input_value = (\$("input[name='added_full_day_cost_item_"+i+"']").val()) ? "full" : (\$("input[name='added_half_day_cost_item_"+i+"']").val()) ? "half" : "" ; + if (hidden_input_value && hidden_input_value != "") { + input_new_values["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = \$("input[name='added_"+hidden_input_value+"_day_cost_item_"+i+"']").val() ; + hidden_input_to_html_row["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = "added_"+hidden_input_value+"_day_cost_item_"+j ; + \$("input[name='added_"+hidden_input_value+"_day_cost_item_"+i+"']").remove() ; + } + cals_totals_row[j] = 1 ; + } + i-- ; j-- ; + + if (!\$("#costing_event_"+k).html()) { + add_quote_expenses_row_all("costing_event_"+k,"costing_event") ; + \$("#selectDescription_costing_event_"+k+"_chosen").css("width","90%") ; + \$("#costing_event_"+k).append("") ; + break_loop = 1 ; + } else if (\$("#costing_event_"+k).html() && typeof \$("input[name='added_"+full_half_loop[f_h]+"_day_cost_item_"+k+"']").val() == 'undefined') { + \$("#costing_event_"+k).append("") ; + \$("input[name='added_"+f_t_h[full_half_loop[f_h]]+"_day_cost_item_"+k+"']").remove() ; + } else { + \$("input[name='added_"+full_half_loop[f_h]+"_day_cost_item_"+k+"']").val(event_cost_id) ; + } + + \$("#selectDescription_costing_event_"+k).val(event_cost_id).trigger("chosen:updated") ; + \$("#inputQty_costing_event_"+k).val(nr_days[full_half_loop[f_h]]*cnt_systems) ; + \$("#inputAmount_usd_costing_event_"+k).val(default_rate) ; + calc_totals(k,"costing_event") ; + + k++ ; + + } + } + } + + if (!\$("#costing_event_"+i).html() || break_loop) { + i-- ; j-- ; + break ; + } + + } + + if (need_to_shift_data_below_down) { + + for (let row_nr in add_html_row) { + add_quote_expenses_row_all("costing_event_"+row_nr,"costing_event") ; + \$("#selectDescription_costing_event_"+row_nr+"_chosen").css("width","90%") ; + } + + for (let key in select_new_values) { + if (select_new_values[key] != \$(key).val()) { + \$(key).val(select_new_values[key]).trigger("chosen:updated") ; + } + } + + for (let key in input_new_values) { + if (typeof \$(key).val() == 'undefined' && input_new_values[key]) { + // let display = (hidden_input_name[key].includes("_day_cost_item_")) ? "" : "" ; + let display = (hidden_input_name[key].includes("_day_cost_item_") && "$username" == "handre") ? "" : "style='display:none;'" ; + \$(hidden_input_to_html_row[key]).append("") ; + } + if (input_new_values[key] != \$(key).val()) { + \$(key).val(input_new_values[key]) ; + } + } + + for (let key in checkbox_new_values) { + if (\$(key).is(":checked") && !checkbox_new_values[key]) { + \$(key).prop("checked",false) ; + } else if (!\$(key).is(":checked") && checkbox_new_values[key]) { + \$(key).prop("checked",true) ; + } + } + + for (let key in cals_totals_row) { + calc_totals(key,"costing_event") ; + } + + if (j > i) { + for (let k=i+1;k<=j;k++) { + \$("#costing_event_"+k).show() ; + \$("#btn_row_costing_event_"+k).hide() ; + \$("#btn_costing_event_"+k).hide() ; + } + let k = j+1 ; + \$("#btn_row_costing_event_"+k).show() ; + \$("#btn_costing_event_"+k).show() ; + } + + // let [sub_total,vat_total] = add_up_totals ("costing_event",j,\$("input[name='roe']").val(),0) ; + // \$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; + // update_overall_totals(sub_total,vat_total,"costing_event") ; + + } + } + + \$("#content").on("change","[id^='radio_']", function () { + + // [nr_days["full"],nr_days["half"]] = count_nr_of_full_day_and_half_days() ; + + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days () ; + + }) ; + + function update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days () { + + console.log("update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days") ; + + [nr_days["full"],nr_days["half"]] = count_nr_of_full_day_and_half_days() ; + + let opp_add = {"full":"half","half":"full"} ; + + let i = 0 ; let j = 0 ; let select_new_values = {} ; let input_new_values = {} ; let checkbox_new_values = {} ; + + if (!prev_nr_days["full"] && !prev_nr_days["half"] && (nr_days["full"] || nr_days["half"])) { + // return ; + } + + let add = + (!prev_nr_days["full"] && !prev_nr_days["half"] && nr_days["full"]) ? "blank_full" : + (!prev_nr_days["half"] && !prev_nr_days["full"] && nr_days["half"]) ? "blank_half" : + (!prev_nr_days["full"] && nr_days["full"]) ? "full" : + (!prev_nr_days["half"] && nr_days["half"]) ? "half" : + "" ; + + let remove = + (prev_nr_days["full"] && !nr_days["full"]) ? "full" : + (prev_nr_days["half"] && !nr_days["half"]) ? "half" : + "" ; + + let change = + (prev_nr_days["full"] != nr_days["full"] && prev_nr_days["half"] != nr_days["half"] && prev_nr_days["full"] && nr_days["full"] && prev_nr_days["half"] && nr_days["half"]) ? "both" : + (prev_nr_days["full"] && nr_days["full"] && prev_nr_days["full"] != nr_days["full"]) ? "full" : + (prev_nr_days["half"] != nr_days["half"] && prev_nr_days["half"] && nr_days["half"]) ? "half" : + "" ; + + let hidden_input_to_html_row = {} ; let hidden_input_name = {} ; let add_html_row = {} ; let remove_input = {} ; let cals_totals_row = {} ; + + while (true) { + + i++ ; j++ ; + + if (!\$("#costing_event_"+i).html()) { + i-- ; j-- ; + break ; + } + + let added_full_cost_item = \$("input[name='added_full_day_cost_item_"+i+"']").val() ; + let added_half_cost_item = \$("input[name='added_half_day_cost_item_"+i+"']").val() ; + + let event_cost_id = (added_full_cost_item) ? added_full_cost_item : (added_half_cost_item) ? added_half_cost_item : "" ; + + let event_cost_id_extract = (event_cost_id.includes("_")) ? get_row_nr(event_cost_id) : event_cost_id ; + + let added = (added_full_cost_item) ? "full" : (added_half_cost_item) ? "half" : "" ; + + if ((added && add && added == add) || (add == "blank_full" && add == "full") || (add == "blank_half" && add == "half")) { + continue ; + } + + let do_not_remove_this_row = (event_cost_id.includes("-1") || event_cost_id.includes("-2")) ? 1 : 0 ; + + if (event_cost_id && event_cost_id != "") { + + let change_row = (change && (change == added || change == "both")) ? added : 0 ; + + let rate = (event_cost_id.includes("-1")) ? \$("input[name='amount_usd_costing_event_"+i+"']").val() : default_cost_item_rates[added+","+event_cost_id_extract] ; + // let rate = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; + let qty = (event_cost_id.includes("-2")) ? \$("input[name='qty_costing_event_"+i+"']").val() : (!cnt_systems_per_cost_item[event_cost_id_extract]) ? nr_days[added] : nr_days[added]*cnt_systems_per_cost_item[event_cost_id_extract] ; + + if (!qty) { qty = 0 ; } + + if (change_row) { + input_new_values["input[name='qty_costing_event_"+j+"']"] = qty ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = rate ; + // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (qty*rate).toFixed(2) ; + if (i != j) { + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + input_new_values["input[name='added_"+change_row+"_day_cost_item_"+j+"']"] = event_cost_id ; + hidden_input_to_html_row["input[name='added_"+change_row+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+change_row+"_day_cost_item_"+j+"']"] = "added_"+change_row+"_day_cost_item_"+j ; + \$("input[name='added_"+change_row+"_day_cost_item_"+i+"']").remove() ; + } + cals_totals_row[j] = 1 ; + if (!add || event_cost_id.includes("-3")) { + continue ; + } + } + + if (add == "full") { + \$("input[name='added_"+added+"_day_cost_item_"+i+"']").remove() ; + j++ ; + } + + if (i != j && ((add && add != added && added != remove) || (!do_not_remove_this_row && remove && remove != added))) { + + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = qty ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = rate ; + // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (qty*rate).toFixed(2) ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + if (!\$("#costing_event_"+j).html()) { + add_html_row[j] = 1 ; + console.log("add_html_row : "+j) ; + input_new_values["input[name='added_"+added+"_day_cost_item_"+j+"']"] = event_cost_id ; + hidden_input_to_html_row["input[name='added_"+added+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+added+"_day_cost_item_"+j+"']"] = "added_"+added+"_day_cost_item_"+j ; + } + cals_totals_row[j] = 1 ; + + } + + if (add == "half") { + if (i != j) { + \$("input[name='added_full_day_cost_item_"+i+"']").remove() ; + input_new_values["input[name='added_"+added+"_day_cost_item_"+j+"']"] = event_cost_id ; + hidden_input_to_html_row["input[name='added_"+added+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+added+"_day_cost_item_"+j+"']"] = "added_"+added+"_day_cost_item_"+j ; + } + + j++ ; + } + + if (remove && remove == added && !add) { + if (do_not_remove_this_row) { + continue ; + } + j-- ; + \$("#selectDescription_costing_event_"+i).val("").trigger("chosen:updated") ; + \$("input[name='qty_costing_event_"+i+"']").val("") ; + \$("input[name='amount_usd_costing_event_"+i+"']").val("") ; + \$("input[name='amount_ttl_costing_event_"+i+"']").val("") ; + \$("input[name='added_"+remove+"_day_cost_item_"+i+"']").remove() ; + continue ; + } else if (!do_not_remove_this_row && remove && remove == added && add) { + if (add == "half") { + j-- ; + } + \$("input[name='added_"+remove+"_day_cost_item_"+i+"']").remove() ; + } + + let jj = (add == "full") ? j - 1 : (add == "half") ? j : j ; + + if (add) { + if (!\$("#costing_event_"+jj).html()) { + add_html_row[jj] = 1 ; + // console.log("add : "+add) ; + } + if (!do_not_remove_this_row && remove == "half") { + j-- ; + } + + rate = default_cost_item_rates[add+","+event_cost_id_extract] ; + qty = (!cnt_systems_per_cost_item[event_cost_id_extract]) ? nr_days[add] : nr_days[add]*cnt_systems_per_cost_item[event_cost_id_extract] ; + + // select_new_values["#selectDescription_costing_event_"+jj] = \$("#selectDescription_costing_event_"+i).val() ; + select_new_values["#selectDescription_costing_event_"+jj] = event_cost_id_extract ; + input_new_values["input[name='qty_costing_event_"+jj+"']"] = qty ; + input_new_values["input[name='amount_usd_costing_event_"+jj+"']"] = rate ; + // input_new_values["input[name='amount_ttl_costing_event_"+jj+"']"] = (rate*qty).toFixed(2) ; + input_new_values["input[name='added_"+add+"_day_cost_item_"+jj+"']"] = (event_cost_id.includes("-3")) ? "-3_"+event_cost_id_extract : event_cost_id_extract ; + hidden_input_to_html_row["input[name='added_"+add+"_day_cost_item_"+jj+"']"] = "#costing_event_"+jj ; + hidden_input_name["input[name='added_"+add+"_day_cost_item_"+jj+"']"] = "added_"+add+"_day_cost_item_"+jj ; + if (add != added && \$("input[name='added_"+added+"_day_cost_item_"+jj+"']").val()) { + // \$("input[name='added_"+added+"_day_cost_item_"+jj+"']").remove() ; + remove_input["input[name='added_"+added+"_day_cost_item_"+jj+"']"] = 1 ; + } + cals_totals_row[jj] = 1 ; + } + } else if (!event_cost_id && i != j) { + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = \$("input[name='qty_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = \$("input[name='amount_ttl_costing_event_"+i+"']").val() ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + if (!\$("#costing_event_"+j).html()) { + add_html_row[j] = 1 ; + } + // cals_totals_row[j] = 1 ; + + } else if (!event_cost_id && (add == "blank_full" || add == "blank_half")) { + + let k = j + 1 ; + + if (\$("#selectDescription_costing_event_"+j).val() && !\$("#costing_event_"+k).html()) { + j++ ; + } + + if (!\$("#selectDescription_costing_event_"+j).val()) { + + let ij = 0 ; let add_type = (add == "blank_full") ? "full" : "half" ; + + while (true) { + + ij++ ; + if (!\$("#system_name_row_"+ij).html()) { + break ; + } + + if (default_cost_item_rates[add_type+","+get_event_cost_id[\$("#selectSystem_name_"+ij).val()]]) { + + if (!\$("#costing_event_"+j).html()) { + add_html_row[j] = 1 ; + } else { + \$("#checkboxExcl_costing_event_"+j).prop("checked",false) ; + } + + select_new_values["#selectDescription_costing_event_"+j] = get_event_cost_id[\$("#selectSystem_name_"+ij).val()] ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = nr_days[add_type] ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = default_cost_item_rates[add_type+","+get_event_cost_id[\$("#selectSystem_name_"+ij).val()]] ; + // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (nr_days[add_type]*default_cost_item_rates[add_type+","+get_event_cost_id[\$("#selectSystem_name_"+ij).val()]]).toFixed(2) ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = 1 ; + input_new_values["input[name='added_"+add_type+"_day_cost_item_"+j+"']"] = get_event_cost_id[\$("#selectSystem_name_"+ij).val()] ; ; + hidden_input_to_html_row["input[name='added_"+add_type+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+add_type+"_day_cost_item_"+j+"']"] = "added_"+add_type+"_day_cost_item_"+j ; + cals_totals_row[j] = 1 ; + j++ ; + } + } + j-- ; + break ; + + } + } else if (event_cost_id.includes("-3")) { + + let rate = (event_cost_id.includes("-1")) ? \$("input[name='amount_usd_costing_event_"+i+"']").val() : default_cost_item_rates[added+","+event_cost_id_extract] ; + // let rate = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; + let qty = (event_cost_id.includes("-2")) ? \$("input[name='qty_costing_event_"+i+"']").val() : (!cnt_systems_per_cost_item[event_cost_id_extract]) ? nr_days[added] : nr_days[added]*cnt_systems_per_cost_item[event_cost_id_extract] ; + + if (!qty) { qty = 0 ; } + + input_new_values["input[name='qty_costing_event_"+j+"']"] = qty ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = rate ; + // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (qty*rate).toFixed(2) ; + cals_totals_row[j] = 1 ; + + } + } + + for (let key in remove_input) { + \$(key).remove() ; + } + + for (let row_nr in add_html_row) { + add_quote_expenses_row_all("costing_event_"+row_nr,"costing_event") ; + \$("#selectDescription_costing_event_"+row_nr+"_chosen").css("width","90%") ; + } + + for (let key in select_new_values) { + if (select_new_values[key] != \$(key).val()) { + \$(key).val(select_new_values[key]).trigger("chosen:updated") ; + } + } + + for (let key in input_new_values) { + if (typeof \$(key).val() == 'undefined' && input_new_values[key]) { + let display = (hidden_input_name[key].includes("_day_cost_item_") && "$username" == "handre") ? "" : "style='display:none;'" ; + \$(hidden_input_to_html_row[key]).append("") ; + } + if (input_new_values[key] != \$(key).val()) { + \$(key).val(input_new_values[key]) ; + } + } + + for (let key in checkbox_new_values) { + if (\$(key).is(":checked") && !checkbox_new_values[key]) { + \$(key).prop("checked",false) ; + } else if (!\$(key).is(":checked") && checkbox_new_values[key]) { + \$(key).prop("checked",true) ; + } + } + + for (let key in cals_totals_row) { + calc_totals(key,"costing_event") ; + } + + if (remove && !j) { + j++ ; + } + + if (j < i) { + for (let k=j+1;k<=i+1;k++) { + \$("#costing_event_"+k).html("") ; + if (k == j+1) { + \$("#btn_row_costing_event_"+k).show() ; + \$("#btn_costing_event_"+k).show() ; + } else { + \$("#btn_row_costing_event_"+k).hide() ; + \$("#btn_costing_event_"+k).hide() ; + } + } + } else if (j > i) { + for (let k=i+1;k<=j;k++) { + \$("#costing_event_"+k).show() ; + \$("#btn_row_costing_event_"+k).hide() ; + \$("#btn_costing_event_"+k).hide() ; + } + let k = j+1 ; + \$("#btn_row_costing_event_"+k).show() ; + \$("#btn_costing_event_"+k).show() ; + } + + let [sub_total,vat_total] = add_up_totals ("costing_event",j,\$("input[name='roe']").val(),0) ; + \$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; + update_overall_totals(sub_total,vat_total,"costing_event") ; + + prev_nr_days["full"] = nr_days["full"] ; + prev_nr_days["half"] = nr_days["half"] ; + + } + + \$("#content").on("change","[id^='selectSystem_name_']", function () { + + let corresponding_cost_item_exists = ((default_cost_item_rates["full,"+get_event_cost_id[\$(this).val()]] && nr_days["full"]) || (default_cost_item_rates["half,"+get_event_cost_id[\$(this).val()]] && nr_days["half"])) ? 1 : 0 ; + + if (corresponding_cost_item_exists) { + system_with_cost_item_rates_selected = 1 ; + } else if (system_with_cost_item_rates_selected && (!\$(this).val() || (\$(this).val() && !corresponding_cost_item_exists))) { + system_with_cost_item_rates_selected = 0 ; + let ij = 0 ; + while (true) { + ij++ ; + if (!\$("#system_name_row_"+ij).html()) { + break ; + } + if (!\$("#selectSystem_name_"+ij).val()) { + continue ; + } + if ((default_cost_item_rates["full,"+get_event_cost_id[\$("#selectSystem_name_"+ij).val()]] && nr_days["full"]) || (default_cost_item_rates["half,"+get_event_cost_id[\$("#selectSystem_name_"+ij).val()]] && nr_days["half"])) { + system_with_cost_item_rates_selected = 1 ; + } + } + } + + auto_select_cost_items_in_quote_tab(this.id) ; + + }) ; + + // \$("#content").on("change","[id^='selectDescription_']", async function () { + + // let this_id = this.id ; + + // let row_nr = get_row_nr(this_id) ; + + // let tab = (this_id.includes("_costing_event_")) ? "costing_event" : (this_id.includes("_workings_event_")) ? "workings_event" : "" ; + + // // if (!\$("input[name='added_half_day_cost_item_"+row_nr+"']").val() && !\$("input[name='added_half_day_cost_item_"+row_nr+"']")val() && ((nr_days["full"] && default_cost_item_rates["full,"+\$("#"+this_id).val()]) || (nr_days["full"] && default_cost_item_rates["full,"+\$("#"+this_id).val()]))) { + + // // if (nr_days["full"] && default_cost_item_rates["full,"+\$("#"+this_id).val()]) { + + // // "input[name='qty_costing_event_"+j+"']" + + // // } + + + // // if (nr_days["full"] && default_cost_item_rates["full,"+\$("#"+this_id).val()] && nr_days["half"] && default_cost_item_rates["half,"+\$("#"+this_id).val()]) { + + // // let j = row_nr + 1 ; + // // select_new_values["#selectDescription_costing_event_"+j] = \$(this).val() ; + // // input_new_values["input[name='qty_costing_event_"+j+"']"] = nr_days["half"] ; + // // input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = default_cost_item_rates["half,"+\$(this).val()] ; + // // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (nr_days["half"]*default_cost_item_rates["half,"+\$(this).val()]).toFixed(2) ; + // // checkbox_new_values["#checkboxVat_costing_event_"+j] = 1 ; + // // input_new_values["input[name='added_half_day_cost_item_"+j+"']"] = \$(this).val() ; + // // hidden_input_to_html_row["input[name='added_half_day_cost_item_"+j+"']"] = "#costing_half"+add_type+"_day_cost_item_"+j ; + // // \$("input[name='added_full_day_cost_item_"+j+"']").remove() ; + + // // // let ij = j ; + + // // // while (true) { + // // // select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+j).val() ; + // // // input_new_values["input[name='qty_costing_event_"+j+"']"] = \$("input[name='qty_costing_event_"+j+"']").val() ; + // // // input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = \$("input[name='amount_usd_costing_event_"+j+"']") ; + // // // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (nr_days["half"]*default_cost_item_rates["half,"+\$(this).val()]).toFixed(2) ; + // // // checkbox_new_values["#checkboxVat_costing_event_"+j] = 1 ; + // // // input_new_values["input[name='added_half_day_cost_item_"+j+"']"] = \$(this).val() ; + // // // hidden_input_to_html_row["input[name='added_half_day_cost_item_"+j+"']"] = "#costing_half"+add_type+"_day_cost_item_"+j ; + // // // \$("input[name='added_full_day_cost_item_"+j+"']").remove() ; + // // // } + + // // } + + // // } + + + + // if (\$("input[name='amount_usd_"+tab+"_"+row_nr+"']").val()) { + // // return ; + // } + + // let full_day_exists = nr_days["full"] ; let half_day_exists = nr_days["half"] ; + + // // [full_day_exists,half_day_exists] = count_nr_of_full_day_and_half_days() ; + + // let already_loaded_full_day = (\$("#"+this_id).val()) ? \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val() : "" ; + // let already_loaded_half_day = (\$("#"+this_id).val()) ? \$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val() : "" ; + + // already_loaded_full_day = (typeof already_loaded_full_day == 'undefined') ? "" : 1 ; + // already_loaded_half_day = (typeof already_loaded_half_day == 'undefined') ? "" : 1 ; + + // if (already_loaded_full_day && already_loaded_half_day) { + // return ; + // } + + // if (already_loaded_full_day == 1) { + // full_day_exists = 0 ; + // } + + // if (already_loaded_half_day == 1) { + // half_day_exists = 0 ; + // } + + // let date_from = \$("input[name='date_from']").val() ; + + // date_from = date_from.substring(0,10) ; + + // let full_half_day = 0 ; + + // // if (full_day_exists || (!already_loaded_full_day && already_loaded_half_day && !full_day_exists)) { + // if (full_day_exists != 0) { + // if ((typeof \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val() == 'undefined' || \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val()) && \$("#"+this_id).val()) { + // \$("#content").append("") ; + // } + // full_half_day = 1 ; + // // } else if (half_day_exists || (already_loaded_full_day && !half_day_exists && !already_loaded_half_day)) { + // } else if (half_day_exists != 0) { + // if ((typeof \$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val() == 'undefined' || !\$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val()) && \$("#"+this_id).val()) { + // \$("#content").append("") ; + // } + // full_half_day = 2 ; + // } + + // let rate_ = "" ; + + // if (default_cost_item_rates["full,"+\$("#"+this_id).val()] && full_half_day == 1) { + // rate_ = default_cost_item_rates["full,"+\$("#"+this_id).val()] ; + // } else if (default_cost_item_rates["half,"+\$("#"+this_id).val()] && full_half_day == 2) { + // rate_ = default_cost_item_rates["half,"+\$("#"+this_id).val()] ; + // } else if (full_half_day) { + // let rate_url = "$useropts{scripts}/get/get_event_cost_item_rates.pl?"+\$("#"+this_id).val()+"&"+date_from+"&"+full_half_day+"&"+this_id ; + // await \$.get(rate_url, function(json) { + // \$.each(json, function(key, data) { + // rate_ = data.rate ; + // }); + // },'json') ; + // } + + // if (rate_ == "") { + // return ; + // } + + // // let tab = "" ; + + // // if (this_id.includes("_costing_event_")) { + // // tab = "costing_event" ; + // // } else if (this_id.includes("_workings_event_")) { + // // tab = "workings_event" ; + // // } + + // full_half_day = (full_half_day == 1) ? "full" : (full_half_day == 2) ? "half" : "" ; + + // \$("input[name='qty_"+tab+"_"+row_nr+"']").val(nr_days[full_half_day]) ; + // \$("input[name='amount_usd_"+tab+"_"+row_nr+"']").val(rate_) ; + // \$("input[name='amount_ttl_"+tab+"_"+row_nr+"']").val((rate_*nr_days[full_half_day]).toFixed(2)) ; + // \$("#"+tab+"_"+row_nr).append("") ; + // calc_totals(row_nr,tab) ; + + // // amount_usd_costing_event_1 + // // amount_usd_workings_event_1 + + // }) ; + + + // \$("#content").on("change","[id^='selectSystem_name_']", function () { + + // }) ; + + ~ ; + + # --------------- END COSTING ---------------------------------------------------------------------------------------------------------------- + } + + if ($tab == 5) { # Notes + + # --------------- START NOTES ---------------------------------------------------------------------------------------------------------------- + + # # my $sec = '_notes' ; + + # # my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + # # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # # return if $ret ; + + # # $add_form_fields = '' ; + + # # &db_min_ro('quote_event_notes','*','','','') ; + + # # $add_form_fields .= qq~ + # #
    + # #
    + # #

    + # # Notes: + # #

    + # #
    + # #
    ~ ; + + # # &tab_build_terms_headers ; + + # # $cntnoteloop = 1 ; + # # for (1 .. 5) { + # # &tab_build_terms_fields('note',$_,$id) ; + # # } + + # # $add_form_fields .= qq~ + # #
    + # #
    + # #

    + # # Payment Terms: + # #

    + # #
    + # #
    ~ ; + # # &tab_build_terms_headers ; + + # # $cntnoteloop = 1 ; + # # for (1 .. 5) { + # # &tab_build_terms_fields('payment_term',$_,$id) ; + # # } + # # &event_tabs_content_box($sec_name,$sec_col) ; + + # --------------- END NOTES ---------------------------------------------------------------------------------------------------------------- + } + + if ($tab == 6) { # Workings + + # --------------- START Working ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + $lcol = 1 ; + $fcol = 2 ; + + my @docs = ('Slip') ; + + $add_form_fields .= qq~ +
    + ~ ; + + $file_cnt = 3 ; + + foreach (@docs) { + my $doc = lc $_ ; $doc =~ s/ /\_/ ; $doc =~ s/&/\_/ ; + $event_uploads = &common_get_field_uploads($id,"$doc",'id','delete-attached-slip') ; + if ($event_uploads) { + $add_form_fields .= qq~ +
    + $event_uploads +
    ~; + } else { + $add_form_fields .= qq~ +
    +
    + + +

    Upload file from PC.

    +
    +
    + ~; + } + } + + $trigger_jquery_raw .= qq( + \$('#delete-attached-slip').click(function (e) { + BootstrapDialog.confirm({ + title: 'Confirm Delete', + message: 'Are you sure you want to delete $doc?', + type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + callback: function(result) { + if (result) { + var url = "$useropts{scripts}/get/get_delete_attach.pl?slips/$id&$db{$table}{$id}{slip}&$table&$id&slip" ; + \$.get(url); + \$('#attach-$id-4').hide() ; + \$('#delete-attached-slip').hide() ; + } else { + // alert('Nope.'); + } + } + }); + }); + ) ; + + $event_uploads = '' ; + # $add_form_fields .= &common_min_form_label_col("Custom Set") ; + + my $custom_set_checked = ($db{$table}{$id}{custom_set} || $db{$table}{$id}{demo_id}) ? "CHECKED" : "" ; + + $add_form_fields .= qq~ +
    + + +
    + ~ ; # class="control-label" + # $add_form_fields .= &common_min_form_checkbox_col('custom_set','') ; + + $add_form_fields .= qq~ +
    + ~ ; + + our %sec_cnt = ('a_event' => "50-List Expenses") ; + + my $sec = 'workings' ; + my ($sec_name, $sec_cnt_workings, $sec_col) = &tab_sec_det($sec) ; + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt_workings . '|' ; + + return if $ret ; + + &event_tabs_build_sec($sec,$tab) ; + + foreach (sort keys %sec_cnt) { + $_k = substr($_, 1) ; + my @parts = split(/\-/, $sec_cnt{$_}) ; + $add_form_fields .= qq~ +
    +
    +

    + $parts[1] : +

    +
    +
    + ~ if $parts[1] ne 'Operators'; + + $add_form_fields .= qq~ +
    +
    +
    +

    + $parts[1] : +

    +
    + $icon_casuals +
    +
    + ~ if $parts[1] eq 'Operators' ; + + &tab_build_qt_col_headers_workings("$sec$_k") ; + # # # &db_min_ro('event_quotes_min', 'id, remarks_workings_event, supplier_workings_event, ref_nr_workings_event, qty_workings_event, amount_usd_workings_event, amount_workings_event, vat_workings_event, description_workings_event', "id = $id", '', '') if $id ; + &event_tabs_build_costs_forms($id,$tab,$parts[0],"$sec$_k") ; + } + + $add_form_fields .= qq~ +
    +
    +   +
    +
    ~ ; + $add_form_fields .= qq~ +
    +
    +   +
    + ~ ; + + my @ttlarr = ("sub_total", "vat_total", "grand_total") ; + $lcol = 1; + $fcol = 1; + foreach (@ttlarr) { + $lcol = 1; + $add_form_fields .= &common_min_form_label_col($_) ; + } + + $add_form_fields .= qq~
    ~ ; + + $trigger_jquery_raw .= qq~ + \$("#textareaAdditional_notes").change(function () { + if (\$(this).val()) { + \$('label[for="additional_notes_expenses"]').text('Additional Notes : ') ; + \$("#textareaAdditional_notes_expenses_input").html(\$(this).val()) ; + } else if (!\$(this).val() && \$('label[for="additional_notes_expenses"]').text()) { + \$('label[for="additional_notes_expenses"]').text('') ; + \$("#textareaAdditional_notes_expenses_input").html('') ; + } + }) ; + ~ ; + + my $add1 = ($db{$table}{$id}{additional_notes}) ? "Additional Notes : " : "" ; + my $add2 = ($db{$table}{$id}{additional_notes}) ? "$db{$table}{$id}{additional_notes}" : "" ; + + $add_form_fields .= qq~

    $add2

    ~ ; + $lcol = 2; + $add_form_fields .= &common_min_form_label_col('Total') ; + $lcol = 1; + + my @ttlarr = ("total_amount_workings_event","total_vat_amount_workings_event","total_grand_amount_workings_event"); + $lcol = 1 ; $fcol = 1 ; + + my %renamed_totals = ("total_amount_workings_event" => "sub_total_workings_event", "total_vat_amount_workings_event" => "vat_total_workings_event" , "total_grand_amount_workings_event" => "grand_total_workings_event") ; + + foreach (@ttlarr) { + $readonly{$renamed_totals{$_}} = "READONLY"; + $input_style{$renamed_totals{$_}} = qq~style="text-align:right;"~ ; + my $val = $db{$table}{$id}{$_} ? $db{$table}{$id}{$_} : '0.00' ; + $add_form_fields .= &common_min_form_input_col($renamed_totals{$_},$val) ; + } + + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= qq~ +
    +
    +   +
    +
    ~ ; + + &event_tabs_content_box($sec_name,$sec_col) ; + + # --------------- END WORKING ---------------------------------------------------------------------------------------------------------------- + } + + if ($tab == 7) { # Invoice Details + + # --------------- START INVOICE DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_invoice_details' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + $lcol = 3 ; + $fcol = 5 ; + + $add_form_fields = '' ; + + $add_form_fields .= &common_min_form_input('invoice_nr',$db{$table}{$id}{invoice_nr},'') ; + my $checked = 'CHECKED' if $db{$table}{$id}{annual_invoice} ; + $add_form_fields .= &common_min_form_input('po_nr',$db{$table}{$id}{po_nr},'') ; + $add_form_fields .= &common_min_form_datepicker('invoice_date',$db{$table}{$id}{invoice_date}) ; + + &event_tabs_content_box($sec_name,$sec_col); + + # --------------- END INVOICE DETAILS ---------------------------------------------------------------------------------------------------------- + } + +} #------------------------------------------------------------------------------------ + +sub event_tabs_build_sec { + + my ($sec_,$tab) = @_ ; + + # # # &db_min_ro('event_quotes_min', 'id,description_workings_event,operator_workings_event', "id = $i{id}", '', '') if $i{id}; + + my @saved_des = () ; my @saved_op = () ; + + # my %casual_name_dropdown_hash = () ; + + if ($sec_ eq "workings") { + @saved_des = split(";", $db{event_quotes_min}{$i{id}}{description_workings_event}) ; + @saved_op = split(";", $db{event_quotes_min}{$i{id}}{operator_workings_event}) ; + &db_min_ro('users','*',"user_type LIKE 'casual%' AND block <> 1 AND inactive <> 1",'','') if $iaction eq 'add' ; + foreach my $uid (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + # $casual_name_dropdown_hash{$uid} = $db{users}{$uid}{name} ; + $opts{operator_field} .= qq~~ ; + } + } else { + @saved_des = split(";", $db{event_quotes_min}{$i{id}}{item_costing_event}) ; + } + + unless ($opts{description_field}) { + $opts{description_field} = qq~~ ; + my $other_id = 0 ; + foreach (sort {$db{event_cost_items}{$a}{name} cmp $db{event_cost_items}{$b}{name}} keys %event_list_name_array_expenses) { + next if $db{event_cost_items}{$_}{excl_from_expenses} ; + if (lc $db{event_cost_items}{$_}{name} eq "other") { + $other_id = $_ ; + next ; + } + $opts{description_field} .= qq~~ ; + } + $opts{description_field} .= qq~~ ; + + } + + my @description_chosen_field_ids = () ; my @operator_chosen_field_ids = () ; my @desriptions_that_are_operators = () ; + + foreach (sort keys %sec_cnt) { + + $_k = substr($_,1) ; $k = substr($_,2) ; + + my @parts = split(/\-/,$sec_cnt{$_}) ; + + for my $p_ (1 .. $parts[0]) { # item_1_costing_systems + + my $field = "$sec_$_k\_$p_" ; + my $saved_val = $saved_des[$p_ - 1] ; + next if $p_ > 1 && !$saved_val ; + my $saved_val_2 = $saved_op[$p_ - 1] ; + + if ($_k eq '_event') { + $opts{"description_$field"} = $opts{description_field} ; + $trigger_jquery_raw .= qq~\$("#selectDescription_$field").val("$saved_val") ; \$("#selectDescription_$field").trigger("chosen:updated") ; ~ if $saved_val and $saved_val ne "14" ; + push @desriptions_that_are_operators,"#selectDescription_$field" if $saved_val eq "14" ; + + if ($sec_ eq "workings") { + $opts{"operator_$field"} = $opts{operator_field} ; + $trigger_jquery_raw .= qq~\$("#selectOperator_$field").val("$saved_val_2") ; \$("#selectOperator_$field").trigger("chosen:updated") ; ~ if $saved_val_2 ; + } + } + + $item_type = 'input' ; + + unless ($got{$field}) { + + $got{$field} = 1 ; + push @excl_field_ids,"#checkboxExcl_$field" ; + push @description_field_ids,"#selectDescription_$field" ; + push @operator_field_ids,"#selectOperator_$field" ; + push @description_chosen_field_ids,"#selectDescription_$field\_chosen" ; + push @operator_chosen_field_ids,"#selectOperator_$field\_chosen" ; + push @vat_field_ids,"#checkboxVat_$field" ; + push @qty_field_ids,"#inputQty_$field" ; + push @amount_usd_field_ids,"#inputAmount_usd_$field" ; + + } + } + } + + my $desriptions_that_are_operators_string = join (",",@desriptions_that_are_operators) ; + + $trigger_jquery_raw .= qq~\$("$desriptions_that_are_operators_string").val("14") ; \$("$desriptions_that_are_operators_string").trigger("chosen:updated") ; ~ if $desriptions_that_are_operators_string ; + + # if ($sec_ eq "demo_expenses") { + + $trigger_jquery .= qq~ + \$("#$cntxt{$tab} [id^='select']").filter( function() { + return this.id.endsWith("_chosen") ; + }).css("width","90%"); + ~ ; + + # $trigger_jquery .= qq~\$("#$cntxt{$tab} [id^='select']").css("width","90%");~ ; + # return ; + # } + + # my $description_chosen_field_ids_string = join(",",@description_chosen_field_ids) ; + + # $trigger_jquery .= qq~\$("$description_chosen_field_ids_string").css("width","90%");~ ; + + # if ($sec_ eq "workings") { + # my $operator_chosen_field_ids_string = join(",",@operator_chosen_field_ids) ; + # $trigger_jquery .= qq~\$("$operator_chosen_field_ids_string").css("width","90%");~ ; + # } + +} #------------------------------------------------------------------------------------------ + +sub event_tabs_customer_select_opts { + + my ($table,$dispfield,$where,$field) = @_ ; + + $where .= " AND " if $where ; + $where .= "events='1'" ; + + &db_min_ro($table,'*',$where,'','') ; + + foreach my $id (sort { $db{$table}{$a}{name} cmp $db{$table}{$b}{name} } keys %{$db{$table}}) { + + my $saved_val = $db{event_quotes}{$i{id}}{$field} ; + + if ($saved_val) { my @valarr = split(/\:/,$saved_val) ; $saved_val = $valarr[0] ; } + + if ($saved_val eq $id) { $selected = 'SELECTED' ; } else { $selected = '' ; } + + $opts{$field} .= qq~~ ; + unless ($got{$field}) { + $trigger_jquery .= qq~\$("#selectQuote_to_chosen").css( "width", "96%" );~ ; + $got{$field} = 1 ; + # $trigger_jquery_raw .= qq~ + # \$("#selectQuote_to").change(function() { + # dispCustomer() ; + # }); + # ~; + + + } + } + + $trigger_jquery_raw .= qq~ + function dispCustomer() { + var custval = \$("#selectQuote_to").val(); + var arrP = custval.split(":"); + \$("#inputContact_name").val(arrP[1]); + \$("#inputAddress").val(arrP[4]); + \$("#inputEmail").val(arrP[2]); + \$("#inputTel").val(arrP[3]); + } + ~; + +} #------------------------------------------------------------------------------------------ + +sub tab_build_terms_headers { + + $add_form_fields .= qq~ +
    +
    + +
    +
    + +
    +
    + ~ ; +} #------------------------------------------------------------------------------------ + +sub tab_build_terms_fields { + + my ($sec,$cnt,$id) = @_ ; + + my $exfield = "excl_$cnt\_$sec\s" ; + my $inpfield = "$sec\_$cnt" ; + + unless ($db{quote_event_notes}{1}{$inpfield}) { + $checkit{$exfield} = 1 ; + } + + if ($db{$table}{$id}{$inpfield}) { + $val = $db{$table}{$id}{$inpfield} ; + } else { + $val = $db{quote_event_notes}{1}{$inpfield} ; + } + + $note_display_style = '' ; $note_display_plus_btn = '' ; + unless ($cnt==1 or $db{quote_event_notes}{1}{$inpfield}) { + $note_display_style = qq~style='display:none;'~ ; + $trigger_jquery_raw .= qq~ \$("#btn_$cnt\_$sec").click(function () { + \$("#$cnt\_$sec").toggle(); + \$("#btn_$cnt\_$sec").hide(); + var v = $cnt + 1 ; + \$("#btn_"+v+"\_$sec").show(); + });~ ; + if ($cnt>$cntnoteloop) { + $note_display_butt = qq~display:none;~ ; + } else { + $note_display_butt = '' ; + } + $note_display_plus_btn = qq~~; + } else { + $cntnoteloop++ ; + } + + $add_form_fields .= qq~
    ~ ; + + if ($db{$table}{$id}{$exfield} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + + $label{$exfield} = 1 ; + $fcol=1 ; + $add_form_fields .= &common_min_form_checkbox_col($exfield,$checkit{$exfield},$checked) ; + $fcol=6 ; + $input_style{$inpfield} = qq~style='margin-bottom:4px;margin-top:-2px;'~ ; # add spaces between boxes + $add_form_fields .= &common_min_form_input_col($inpfield,$val,'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~ +
    +
    + $note_display_plus_btn +
    +
    + ~ ; + +} #------------------------------------------------------------------------------------ + +sub tab_build_qt_right { + + my ($id,$tab,$ret) = @_ ; + + if ($tab==1) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_office_details' ; + my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + $lcol = 3 ; + + $add_form_fields = '' ; + + $fcol = 8 ; + # $textarea_height{notes} = ($is_schools_manager) ? 102 : 93 ; + # $textarea_height{notes} = ($glod_user_level < 4) ? 102 : 93 ; + $textarea_height{notes} = ($glod_user_level < 3) ? 102 : 93 ; + $add_form_fields .= &common_min_form_textarea('notes',$db{$table}{$id}{notes},'') ; + $add_form_fields .= qq~
     
    ~ ; + + # unless ($is_schools_manager) { + if ($glod_user_level > 3) { + $textarea_height{office_notes} = 93 ; + $add_form_fields .= &common_min_form_textarea('office_notes',$db{$table}{$id}{office_notes},'') ; + $add_form_fields .= qq~
     
    ~ ; + } + + &event_tabs_content_box($sec_name,$sec_col); + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + + if ($tab==7) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + + my $sec = '_profit_loss' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + $lcol = 3 ; $fcol = 5 ; + + my $expenses = $db{$table}{$id}{total_grand_amount_workings_event} ? sprintf("%0.2f",$db{$table}{$id}{total_grand_amount_workings_event}) : '0.00' ; + # my $income = $db{$table}{$id}{grand_total} ? $db{$table}{$id}{grand_total} : '0.00' ; + my $income = $db{$table}{$id}{sub_total} ? sprintf("%0.2f",$db{$table}{$id}{sub_total}) : '0.00' ; + # my $profit_or_loss = $income - $expenses ; + my $profit_or_loss = sprintf("%0.2f",($income - $expenses)) ; + + $add_form_fields = '' ; + + $lcol = 3; + $fcol = 3; + + $readonly{income} = "READONLY"; + $readonly{expenses} = "READONLY"; + $readonly{profit_loss} = "READONLY"; + + $add_form_fields .= &common_min_form_input('income',$income,'') ; + $add_form_fields .= &common_min_form_input('expenses',$expenses,'') ; + $add_form_fields .= &common_min_form_input('profit_loss',$profit_or_loss,'') ; + + &event_tabs_content_box($sec_name,$sec_col); + + # my $sec = '_overall_revenue' ; + # my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + # my @ttlarr = ("total_grand_amount_workings_event", "grand_total") ; + + # foreach (@ttlarr) { + # $readonly{$_} = "READONLY"; + # $input_style{$_} = qq~style="text-align:right;"~; + # my $val = $db{$table}{$id}{$_} ? $db{$table}{$id}{$_} : '0.00' ; + # $add_form_fields .= &common_min_form_input_col($_,$val) ; + # } + + # &event_tabs_content_box($sec_name,$sec_col) ; + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + + } + +} #------------------------------------------------------------------------------------ + +sub tab_curr_symbols { + + $curr_symb{ZAR} = 'R'; + $curr_symb{USD} = '$'; + $curr_symb{GBP} = 'GBP'; + $curr_symb{EUR} = 'EUR'; + + our $js_curr_arr = '' ; + + foreach (keys %curr_symb) { + $js_curr_arr .= qq(currArr['$_'] = "$curr_symb{$_}";) ; + } + +} #------------------------------------------------------------------------------------ + +sub tab_build_qt_col_headers { + + my ($sec) = @_ ; + + my $style_vat = '' ; + + $style_vat = 'style="display:none;"' if $no_vat{$sec} ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ if $sec eq 'costing_event'; + $add_form_fields .= qq~
    ~ if $sec eq 'costing_casual_users'; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + %cost_desc = () ; + %def_qty = () ; + %def_zar = () ; + %min_zar = () ; + %vat_tick = () ; + %excl_tick = () ; + +} #---------------------------------------------------------------------------------------- + +sub tab_build_qt_col_headers_workings { + + my ($sec) = @_ ; + + my $style_vat = '' ; + + $style_vat = 'style="display:none;"' if $no_vat{$sec} ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ if $sec ne 'workings_casual_users'; + $add_form_fields .= qq~
    ~ if $sec ne 'workings_casual_users'; + # $add_form_fields .= qq~
    ~ if $sec eq '_workings_casual_users'; + $add_form_fields .= qq~
    ~ if $sec ne 'workings_casual_users'; + # $add_form_fields .= qq~
    ~ if $sec eq '_workings_casual_users'; + $add_form_fields .= qq~
    ~ if $sec ne 'workings_casual_users'; + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + %cost_desc = () ; + %def_qty = () ; + %def_zar = () ; + %min_zar = () ; + %vat_tick = () ; + %excl_tick = () ; + +} #---------------------------------------------------------------------------------------- + +sub event_tabs_content_box { + + my ($sec_name,$sec_col) = @_ ; + + $fcol=9 ; + $print_box_content_rows .= &common_min_box_top('indent-left',$sec_name,$sec_col,$cam_box_icon); + $print_box_content_rows .= qq~$add_form_fields~; + $print_box_content_rows .= &common_min_box_foot; + +} #---------------------------------------------------------------------------------------- + +sub tab_cnt { + + our %cntxt = () ; + + $cntxt{1} = 'one' ; + $cntxt{2} = 'two' ; + $cntxt{3} = 'three' ; + # return if $is_schools_manager ; + return if $glod_user_level < 4 ; + $cntxt{4} = 'four' ; + # $cntxt{5} = 'five' ; + $cntxt{6} = 'six' ; + $cntxt{7} = 'seven' ; + +} #---------------------------------------------------------------------------------------- + +sub tab_names { + + my ($tab) = @_ ; + + my $tabname = '' ; + + if ($tab==1) { $tabname = 'Customer Details' ; } + elsif ($tab==2) { $tabname = 'Event Details' ; } + elsif ($tab==3) { $tabname = 'Event Specifics' ; } + elsif ($tab==4) { $tabname = 'Quote' ; } + # elsif ($tab==5) { $tabname = 'Notes' ; } + elsif ($tab==6) { $tabname = 'Expenses' ; } + elsif ($tab==7) { $tabname = 'Invoice Details' ; } + + return ($tabname) ; + +} #------------------------------------------------------------------------------------ + +sub tab_hash { + + # &db_min_ro('users',"id","user_type like '%casual%'",'','') ; + # &db_min_ro('events',"id,event_quote_nr,user_id,category",'','','') ; + # &db_min_ro('event_cost_items','*','','name asc','') ; + + our @excl_field_ids = () ; our @description_field_ids = () ; our @operator_field_ids = () ; our @vat_field_ids = () ; our @qty_field_ids = () ; our @amount_usd_field_ids = () ; our @excl_field_ids = () ; our @btn_ids = () ; + + &tab_load_vars; + + for (1 .. 7) { + + next if $_ == 5 ; + + my $tname = &tab_names($_) ; + our $ret_pdf_link_sec = '' ; # _sa_out+16|_cl_del+13|_sa_in+17|_des_sa+13| + + &event_tabs_build_qt_left('',$_,1) ; + &tab_build_qt_right('',$_,1) ; + + $tabcnt{$tname} = $_ ; + $tabsec{$tname} = $ret_pdf_link_sec ; + } + + # &build_workings_costings_forms_jquery ; + +} #------------------------------------------------------------------------------------ + +sub tab_load_vars { + + # our %casuals = (); + our %available_casuals = () ; + our %not_available_casuals = () ; + + # unless (defined %casuals) { + unless (scalar keys %casuals > 0) { + &db_min_ro('users',"id","user_type like '%casual%'",'','') ; + + foreach my $user_id (keys %{$db{users}}){ + $casuals{$user_id} = 1 ; + } + } + + &db_min_ro('events',"id,event_quote_nr,user_id,category",'','','') ; + + foreach my $event_id (keys %{$db{events}}){ + next unless $casuals{$db{events}{$event_id}{user_id}} ; + if ($db{events}{$event_id}{event_quote_nr} == $id and $db{events}{$event_id}{category} eq 'available'){ + $available_casuals{$db{events}{$event_id}{user_id}} = 1 ; + } elsif ($db{events}{$event_id}{event_quote_nr} == $id and $db{events}{$event_id}{category} eq 'unavailable'){ + $not_available_casuals{$db{events}{$event_id}{user_id}} = 1 ; + } + } + + our %dlg_operator = () ; + + for (1 .. 50) { + next unless $db{$table}{$id}{"operator_workings_event_$_"} ; + if ($available_casuals{$db{$table}{$id}{"operator_workings_event_$_"}}) { + $dlg_operator{"operator_workings_event_$_"} = qq~
    ~ ; + } elsif ($not_available_casuals{$db{$table}{$id}{"operator_workings_event_$_"}}) { + $dlg_operator{"operator_workings_event_$_"} = qq~ ~ ; + } else { + $dlg_operator{"operator_workings_event_$_"} = qq~~ ; + } + } + + # &db_min_ro('event_cost_items','*','','name asc','') ; + &db_min_ro('event_cost_items','*',"excl_from_expenses < 1",'name asc','') ; + + our %event_list_name_array_quote = () ; + our %event_list_name_array_expenses = () ; + my @spl = () ; + + foreach my $iid (keys %{$db{event_cost_items}}) { + @spl = split(" ", $db{event_cost_items}{$iid}{name}); + for (@spl) {$_ = ucfirst $_ ; } + $db{event_cost_items}{$iid}{name} = join (" ", @spl) ; + $event_list_name_array_quote{$iid} = $db{event_cost_items}{$iid}{name} ; + $event_list_name_array_expenses{$iid} = $db{event_cost_items}{$iid}{name} ; + } + +} #------------------------------------------------------------------------------------ + +sub tab_sec_det { + + my ($sec) = @_ ; + + my ($sec_nam,$sec_cnt,$sec_col) ; + + $sec_col = '71919b' ; # '85acb8' ; + $sec_cnt = 20 ; + $sec_nam = substr($sec,1) ; + @array = split(/\_/,$sec_nam); + my @sec_nam = map ucfirst, @array; + $sec_nam = join(" ", @sec_nam) ; + + if ($sec eq 'costing') { + $sec_nam = 'Event Costings' ; + for (1 .. 30) { $vat_tick{$_} = 1 ; } + } + + if ($sec eq 'workings') { + $sec_nam = 'Event Expenses' ; + for (1 .. 50) { $vat_tick{$_} = 1 ; } + } + + return ($sec_nam,$sec_cnt,$sec_col) ; + +} #------------------------------------------------------------------------------------ + +sub event_tabs_build_boxes_top { + + my ($id,$demo_page) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(3,6) ; + + $add_form_fields = '' ; + + $fcol=8 ; + + $add_form_fields .= qq~
    ~ ; + $preferred_title{quote_nr} = "Nr" ; + $add_form_fields .= &common_min_form_input('quote_nr',$db{$table}{$id}{quote_nr},'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + if (($db{$table}{$id}{quote_date} eq '') or ($db{$table}{$id}{quote_date} eq '0000-00-00')) { + $db{$table}{$id}{quote_date} = $now_ccyy_mm_dd ; + } + $preferred_title{quote_date} = "Date" ; + $add_form_fields .= &common_min_form_datepicker('quote_date',$db{$table}{$id}{quote_date}) ; + my $plus_n_days_ccyy_mm_dd = &common_add_delta_days(14) ; + + $add_form_fields .= qq~
    ~ ; + + if (!$demo_page) { + $add_form_fields .= qq~
    ~ ; + $preferred_title{quote_to} = "Client" ; + $add_form_fields .= &common_min_form_select('quote_to',$db{$table}{$id}{quote_to},'') ; + $add_form_fields .= qq~
    ~ ; + $dlg{quote_to} = qq~ + ~ ; + } + + $fcol = 7; + + $add_form_fields .= qq~
    ~ ; + + $allow_deselect{country_id} = 1 ; + $add_form_fields .= &common_min_form_select('country_id',$db{$table}{$id}{country_id},'') ; + $trigger_jquery_raw .= qq~\$("#selectCountry_id").chosen({ allow_single_deselect:true });~ ; + $add_form_fields .= qq~
    ~ ; + + if ($demo_page) { + $add_form_fields .= qq~
    ~ ; + $allow_deselect{region_id} = '' ; + $add_form_fields .= &common_min_form_select('region_id',$db{$table}{$id}{region_id},'') ; + $add_form_fields .= qq~
    ~ ; + } + + $fcol = 8; + $print_box_content_rows .= &common_min_box_top('qrcode',"Quote",'BABEC2'); + $print_box_content_rows .= qq~ +
    +
    + $add_form_fields +
    +
    ~; + $print_box_content_rows .= qq~ +
    +
    +   +
    +
    ~ ; + $print_box_content_rows .= &common_min_box_foot; + +} #------------------------------------------------------------------------------------ + +sub event_tabs_build_costs_forms { + + my ($id,$tab,$rcnt,$suffix) = @_ ; + + $tab_sections{$tab} .= "$suffix+$rcnt|" ; + + $jq_work_cal = qq~ + var vat_totalW$suffix = 0 ; + var total_totalW$suffix = 0 ; + var subtotalW$suffix = 0 ; + var vat_amountW = 0 ; + ~ ; + $jq_fs = '' ; + + %cnt_specific_jquery = () ; + + &set_check_boxes_checked($id,$rcnt,"excl",$suffix); + &set_check_boxes_checked($id,$rcnt,"vat",$suffix); + + my $cntloop = 1 ; + my $field = "" ; + my $val = 0 ; + + my $table_ = "event_quotes_min" ; + + my @excl_old = split(";", $db{$table_}{$id}{"excl_$suffix"}) ; + my @qty_old = split(";", $db{$table_}{$id}{"qty_$suffix"}) ; + my @vat_old = split(";", $db{$table_}{$id}{"vat_$suffix"}) ; + my @remarks_old = () ; + my @supplier_old = () ; + my @ref_nr_old = () ; + my @amount_usd_old = () ; + my @amount_ttl_old = () ; + my @des_old = () ; + my @ops_old = () ; + my @curr_amnt_cost = () ; + + if ($suffix eq "workings_event") { + @remarks_old = split(";",$db{$table_}{$id}{remarks_workings_event}) ; + @supplier_old = split(";",$db{$table_}{$id}{supplier_workings_event}) ; + @ref_nr_old = split(";",$db{$table_}{$id}{ref_nr_workings_event}) ; + @amount_usd_old = split(";",$db{$table_}{$id}{amount_usd_workings_event}); + @amount_ttl_old = split(";",$db{$table_}{$id}{amount_workings_event}); + @des_old = split(";",$db{$table_}{$id}{description_workings_event}) ; + @ops_old = split(";",$db{$table_}{$id}{operator_workings_event}) ; + } else { + @amount_usd_old = split(";",$db{$table_}{$id}{usd_amnt_costing_event}); + @amount_ttl_old = split(";",$db{$table_}{$id}{item_ttl_costing_event}); + @des_old = split(";",$db{$table_}{$id}{item_costing_event}); + @curr_amnt_cost = split(";",$db{$table_}{$id}{curr_amnt_costing_event}); + } + + for (1 .. $rcnt) { + + $display_style = '' ; + $display_plus_btn = '' ; + my $style_display_butt = "" ; + unless ($_ == 1 or $des_old[$_ - 1]) { + $display_style = qq~style='display:none;'~ ; + push @btn_ids,"#btn_$suffix\_$_" ; + if ( $_>$cntloop ) { + $display_butt = qq~display:none;~ ; + $style_display_butt = qq~style="display:none;"~ ; + } else { + $display_butt = '' ; + } + $display_plus_btn = ($_>$cntloop) ? qq~~ : qq~~; + } else { + $cntloop++ ; + } + + $add_form_fields .= qq~
    ~ ; + + #---------------------------------------------------------------------------------------------------- + + if ($des_old[$_-1] || $_ == 1) { + + push @all_select_ids,"#selectDescription_$suffix\_$_" ; + push @all_select_ids,"#selectOperator_$suffix\_$_" if $suffix eq "workings_event" ; + + $field = "excl_$suffix\_$_" ; + $fcol = 1; + # if ($checkit{$field} == 1) { + if ($excl_old[$_ - 1]){ + $checked = 'CHECKED'; + } elsif (($excl_tick{$_}) and ($iaction eq 'add')) { + $checked = 'CHECKED'; + } else { + $checked = ''; + } + $label{$field} = 1; + $add_form_fields .= &common_min_form_checkbox_col($field,$checkit{$field},$checked) ; + + #---------------------------------------------------------------------------------------------------- + + $field = "description_$suffix\_$_" ; + $fcol = 2; + # $allow_deselect{$field} = 1; + $preferred_title{$field} = "Description $_" ; #if $suffix ne '_workings_casual_users'; + + $opts{$field} = $opts{description_field} unless $opts{$field} ; + + if ($des_old[$_-1] && $opts{$field} !~ /SELECTED/ && $opts{$field} !~ /selected/) { + $opts{$field} =~ s/\"/\'/g ; + $opts{$field} =~ s/value='$des_old[$_-1]'/value='$des_old[$_-1]' SELECTED/g ; + } + + $add_form_fields .= &common_min_form_select_col($field,'') ; + + #---------------------------------------------------------------------------------------------------- + + if ($suffix eq "workings_event") { + + $field = "operator_$suffix\_$_" ; + $fcol = 2; + # $allow_deselect{$field} = 1; + $preferred_title{$field} = "Operator $_" ; + + $opts{$field} = $opts{operators_field} unless $opts{$field} ; + + if ($ops_old[$_-1] && $opts{$field} !~ /SELECTED/ && $opts{$field} !~ /selected/) { + $opts{$field} =~ s/\"/\'/g ; + $opts{$field} =~ s/value='$ops_old[$_-1]'/value='$ops_old[$_-1]' SELECTED/g ; + } + + $add_form_fields .= &common_min_form_select_col($field,'') ; + + #---------------------------------------------------------------------------------------------------- + + $field = "remarks_$suffix\_$_" ; + $fcol = 1; + # $allow_deselect{$field} = 1; + $preferred_placeholder{$field} = "Remarks $_" ; + $add_form_fields .= &common_min_form_input_col($field, $remarks_old[$_ - 1]) ; + + #---------------------------------------------------------------------------------------------------- + + $field = "supplier_$suffix\_$_" ; + $fcol = 1; + # $allow_deselect{$field} = 1; + $preferred_placeholder{$field} = "Supplier $_" ; + $add_form_fields .= &common_min_form_input_col($field,$supplier_old[$_ - 1]) if $suffix ne '_workings_casual_users'; + + #---------------------------------------------------------------------------------------------------- + + $field = "ref_nr_$suffix\_$_" ; + $fcol = 1; + # $allow_deselect{$field} = 1; + $preferred_placeholder{$field} = "Ref Nr $_" ; + $add_form_fields .= &common_min_form_input_col($field,$ref_nr_old[$_ - 1]) ; + + #---------------------------------------------------------------------------------------------------- + + } + + $field = "qty_$suffix\_$_" ; + # $field .= '_costing_event'; + $fcol = 1; + $input_style{$field} = qq(style="text-align:right;"); + $preferred_placeholder{$field} = "Qty $_" ; + $val = $qty_old[$_ - 1] ; + unless ($val) { + $val = $def_qty{$_} ; + } + $val = &q_get_val($val) ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + + #---------------------------------------------------------------------------------------------------- + + $field = "amount_usd_$suffix\_$_" ; + $fcol = 1; + $input_style{$field} = qq(style="text-align:right;"); + $val = $amount_usd_old[$_ - 1] ; + unless ($val) { + $val = $def_usd{$_} ; + } + $val = &q_get_val($val) ; + $preferred_placeholder{$field} = "Amount $_" ; + # $excl_on_change{$field} = 1 ; + $val = '0.00' unless $val ; + $add_form_fields .= &common_min_form_input_col($field,$val,1) ; + + $add_form_fields .= qq~~ if $des_old[$_-1] && $amount_usd_old[$_ - 1] eq $default_cost_item_rates{$des_old[$_-1]}{half} ; + $add_form_fields .= qq~~ if $des_old[$_-1] && $amount_usd_old[$_ - 1] eq $default_cost_item_rates{$des_old[$_-1]}{full} ; + #---------------------------------------------------------------------------------------------------- + + # if ($suffix eq "costing_event") { + + # $field = "curr_amnt_$suffix\_$_" ; + # # $field .= '_costing_event'; + # $input_style{$field} = qq(style="text-align:right;"); + # $readonly{$field} = 'READONLY' ; # $fcol=2 ; + # $preferred_placeholder{$field} = "ZAR Amnt $_" ; + # # $val = &q_get_val($db{$table}{$id}{$field}) ; + # $val = &q_get_val($curr_amnt_cost[$_ -1]) ; + # our $type = 'hidden' ; + # $add_form_fields .= &common_min_form_input_col($field,$val,1) ; $type = '' ; + # $type = '' ; + + # } + + # #---------------------------------------------------------------------------------------------------- + + $field = "amount_ttl_$suffix\_$_" ; + $input_style{$field} = qq(style="text-align:right;"); + $val = $amount_ttl_old[$_ - 1] ; + $val = &q_get_val($val) ; + # $val = &common_commify($val) ; + # $val = sprintf("%0.2f",$val) ; + $preferred_placeholder{$field} = "Total Amount $_" ; + # $excl_on_change{$field} = 1 ; + $readonly{$field} = 'READONLY' ; + $val = '0.00' unless $val ; + $add_form_fields .= &common_min_form_input_col($field,$val,1) ; + + #---------------------------------------------------------------------------------------------------- + + $field = "vat_$suffix\_$_" ; + $fcol=1 ; + # if ($checkit{$field} == 1) { + if($vat_old[$_ - 1]){ + $checked = 'CHECKED'; + } elsif ($iaction eq 'add') { + $checked = 'CHECKED'; + } else { + $checked = ''; + } + $label{$field} = 1 ; + if ($no_vat{$suffix}) { + $style_field{$field} = 'style="display:none;"' ; + } + # $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_checkbox_col($field,$checkit{$field},$checked) ; + + #---------------------------------------------------------------------------------------------------- + + } else { + $tindex+=10 if $suffix eq "workings_event" ; + $tindex+=7 if $suffix eq "costing_event" ; + } + + my $f_h_val = substr($quote_tab_default_full_half_items[$_-1],2) ; + + $add_form_fields .= (substr($quote_tab_default_full_half_items[$_-1],0,2) eq '1:') ? qq~~ : (substr($quote_tab_default_full_half_items[$_-1],0,2) eq '2:') ? qq~~ : qq~~ ; + + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= qq~ +
    +
    + $display_plus_btn +
    +
    + ~ ; + + my $style_disp_row = ($des_old[$_-1]) ? "" : "style='display:none;'" ; + $add_form_fields .= qq~ +
    +
    +
    +
    + ~ ; + + } + +} #---------------------------------------------------------------------------------------- + +1; diff --git a/libs/modules/event_tabs_test_demo_temp.pm b/libs/modules/_FromProd/event_tabs_test_demo_temp.pm similarity index 100% rename from libs/modules/event_tabs_test_demo_temp.pm rename to libs/modules/_FromProd/event_tabs_test_demo_temp.pm diff --git a/libs/modules/_FromProd/fixedsystem.pm b/libs/modules/_FromProd/fixedsystem.pm new file mode 100644 index 0000000..3754db8 --- /dev/null +++ b/libs/modules/_FromProd/fixedsystem.pm @@ -0,0 +1,430 @@ +sub fixedsystem_build_table_and_or_excel { + + my ($report) = @_ ; + + our @sql_col_display = ("cnt","event","start_date","start_time","venue","region","system_name","online_status","network_test","system_test","test_event","sound_test","overall_status","additional_comments") ; + + &report_xlsx_export_header("$xlsxreportname",$xlsxdir,'',$xlsx_title_heading) ; + + $xlsxrow-- ; + + my $event_cnt = 0 ; our $found_after_date = 0 ; + + # $format84->set_align('center'); + # $format88->set_align('center'); + # $format89->set_align('center'); + # $format90->set_align('center'); + # $format91->set_align('center'); + + my %defualt_color = () ; + $defualt_color{-1} = "#F90D0D" ; + $defualt_color{1} = "#51B529" ; + + my %defualt_color2 = () ; + $defualt_color2{1} = "#51B529" ; + $defualt_color2{2} = "#F6E305" ; + $defualt_color2{3} = "#F90D0D" ; + + + foreach my $id (sort {$db{$table}{$a}{date_from} cmp $db{$table}{$b}{date_from}} keys %{$db{$table}}) { + + next unless $id ; + unless (&common_check_if_string_contains_an_integer($db{$table}{$id}{event_system_id_multiple})) { + $db{$table}{$id}{event_system_id_multiple} = ";-1;" ; + } + + my $now_date = int("$now_year$now_mm$now_dd") ; + my $end_date = substr($db{$table}{$id}{date_to},0,10) ; + $end_date =~ s/\-//g ; + $end_date = int($end_date) ; + my $is_in_future = ($now_date < $end_date) ? 1 : 0 ; + + my @system_name_ids = split(/\;/,$db{$table}{$id}{event_system_id_multiple}) ; + + my @fixed_system_online_status = split(/\;/,$db{$table}{$id}{fixed_system_online_status}) ; + my @fixed_system_network_test = split(/\;/,$db{$table}{$id}{fixed_system_network_test}) ; + my @fixed_system_system_test = split(/\;/,$db{$table}{$id}{fixed_system_system_test}) ; + my @fixed_system_test_event = split(/\;/,$db{$table}{$id}{fixed_system_test_event}) ; + my @fixed_system_sound_test = split(/\;/,$db{$table}{$id}{fixed_system_sound_test}) ; + my @fixed_system_overall_status = split(/\;/,$db{$table}{$id}{fixed_system_overall_status}) ; + my @fixed_system_additional_comments = split(/\;/,$db{$table}{$id}{fixed_system_additional_comments}) ; + + my $cnt_sys_ids = -1 ; + + # my @table_op_ids = () ; + + # for (1 .. $cnt_rows) { + # push @table_op_ids,$op_ids[$_ - 1] if $op_ids[$_ - 1] ; + # push @table_op_ids,0 unless $op_ids[$_ - 1] ; + # } + + my $system_count = 0 ; + + # foreach my $event_id (split(";",$db{$table}{$id}{event_system_id_multiple})) { + foreach my $event_id (@system_name_ids) { + + $cnt_sys_ids++ ; + + next unless $event_id ; + next unless $db{event_systems}{$event_id}{system_type} eq 'fixed' ; + next if $i{overall_status} ne 'all' and $i{overall_status} and $i{overall_status} ne $fixed_system_overall_status[$cnt_sys_ids] ; + + $event_cnt++ ; + $system_count++ ; + $xlsxcol = 0 ; + $print_tbody .= qq~~ if $report ; + + foreach (@sql_col_display) { + + next unless $_ ; # blank for the buttons column + + my $formatting = $format84 ; + my $val = $db{$table}{$id}{$_} ; + my $val_min = $val ; + my $align = '' ; + my $nowrap = '' ; + + if ($_ eq 'cnt') { + $val = $event_cnt ; + } elsif ($_ eq 'event') { + $val = "$db{$table}{$id}{ref} ($id)" ; + } elsif ($_ eq 'start_date') { + $nowrap = 'nowrap' ; + $val = substr($db{$table}{$id}{date_from},0,10) ; $align = qq~ class="dt-center"~ ; + } elsif ($_ eq 'venue') { + my @oids = split(/\,/,$db{$table}{$id}{organisation_ids}) ; + foreach $_oid (@oids) { + $val .= $db{organisations}{$_oid}{name} . '
    ' ; + } + $val = substr($val,0,-4) if $val ; ; + } elsif ($_ eq 'region') { + $val = $db{regions}{$db{$table}{$id}{region_id}}{code} ; $align = qq~ class="dt-center"~ ; + } elsif ($_ eq 'system_name') { + $val = '' ; + $val = qq~$db{event_systems}{$event_id}{name}~ ; + $val .= qq~ ($db{event_systems}{$event_id}{description})~ if $db{event_systems}{$event_id}{description} ; + } elsif ($_ eq 'sport') { + $val = '' ; + foreach my $sport_id (split(",",$db{$table}{$id}{sport_type_ids})) { + $db{sport_types}{$sport_id}{name} = uc $db{sport_types}{$sport_id}{name} ; + $val .= qq~$db{sport_types}{$sport_id}{name}
    ~ ; + } + $val = substr($val,0,-4) if $val ; + } elsif ($_ eq 'operator') { + $val = '' ; + $val = $db{users}{$op_ids[$system_count - 1]}{name} if $op_ids[$system_count - 1] ; + } elsif ($_ eq 'start_time') { + $val = substr($db{$table}{$id}{date_from},11,5) ; $align = qq~ class="dt-center"~ ; + } elsif ($_ eq 'online_status') { + if ($is_in_future && $report && ($glod_user_level > 2 || $is_installation_partner || $is_schools_manager)) { + my $field = "online_status_$id\_$event_id" ; $align = qq~ class="dt-center $_"~ ; + $preferred_title{$field} = "Online Status" ; + $opts{$field} = $opts{$_} ; + $allow_deselect{$field} = 1 ; + $useropts{'common'}{'css'} .= qq~.$_ { min-width:170px; } ~ ; + my $ucfirstfield = ucfirst $field ; + $val = qq~~ ; + + if ($fixed_system_online_status[$cnt_sys_ids]) { + $trigger_jquery_raw .= qq~ + \$("#select$ucfirstfield").val("$fixed_system_online_status[$cnt_sys_ids]") ; + \$("#select$ucfirstfield").trigger("chosen:updated") ; + ~ ; + } + $trigger_jquery_raw .= qq~\$("#select$ucfirstfield").chosen({ allow_single_deselect:true });~ ; + $val_min = "Online" if $fixed_system_online_status[$cnt_sys_ids] eq '1' ; + $val_min = "Offline" if $fixed_system_online_status[$cnt_sys_ids] eq '-1' ; + $val_min = "None" unless $val_min ; + } else { + $val = "Online" if $fixed_system_online_status[$cnt_sys_ids] eq '1' ; + $val = "Offline" if $fixed_system_online_status[$cnt_sys_ids] eq '-1' ; + $val = "None" unless $val ; + $val_min = $val ; + } + $trigger_jquery_raw .= qq~\$("#itv-table tr:eq($event_cnt) td:nth-last-child(7)").css("background-color","$defualt_color{$fixed_system_online_status[$cnt_sys_ids]}");~ if $fixed_system_online_status[$cnt_sys_ids] ; + $formatting = $format94 if $fixed_system_online_status[$cnt_sys_ids] eq '1' ; + $formatting = $format96 if $fixed_system_online_status[$cnt_sys_ids] eq '-1' ; + } elsif ($_ eq 'network_test') { + if ($is_in_future && $report && ($glod_user_level > 2 || $is_installation_partner || $is_schools_manager)) { + my $field = "network_test_$id\_$event_id" ; $align = qq~ class="dt-center $_"~ ; + $preferred_title{$field} = "Test Network" ; + $opts{$field} = $opts{$_} ; + $allow_deselect{$field} = 1 ; + $useropts{'common'}{'css'} .= qq~.$_ { min-width:170px; } ~ ; + my $ucfirstfield = ucfirst $field ; + $val = qq~~ ; + if ($fixed_system_network_test[$cnt_sys_ids]) { + $trigger_jquery_raw .= qq~ + \$("#select$ucfirstfield").val("$fixed_system_network_test[$cnt_sys_ids]") ; + \$("#select$ucfirstfield").trigger("chosen:updated") ; + ~ ; + } + $trigger_jquery_raw .= qq~\$("#select$ucfirstfield").chosen({ allow_single_deselect:true });~ ; + $val_min = "Passed" if $fixed_system_network_test[$cnt_sys_ids] eq '1' ; + $val_min = "Failed" if $fixed_system_network_test[$cnt_sys_ids] eq '-1' ; + $val_min = "None" unless $val_min ; + } else { + $val = "Passed" if $fixed_system_network_test[$cnt_sys_ids] eq '1' ; + $val = "Failed" if $fixed_system_network_test[$cnt_sys_ids] eq '-1' ; + $val = "None" unless $val ; + $val_min = $val ; + } + $trigger_jquery_raw .= qq~\$("#itv-table tr:eq($event_cnt) td:nth-last-child(6)").css("background-color","$defualt_color{$fixed_system_network_test[$cnt_sys_ids]}");~ if $fixed_system_network_test[$cnt_sys_ids] ; + $formatting = $format94 if $fixed_system_network_test[$cnt_sys_ids] eq '1' ; + $formatting = $format96 if $fixed_system_network_test[$cnt_sys_ids] eq '-1' ; + } elsif ($_ eq 'system_test') { + if ($is_in_future && $report && ($glod_user_level > 2 || $is_installation_partner || $is_schools_manager)) { + my $field = "system_test_$id\_$event_id" ; $align = qq~ class="dt-center $_"~ ; + $preferred_title{$field} = "System Test" ; + $opts{$field} = $opts{$_} ; + $allow_deselect{$field} = 1 ; + $useropts{'common'}{'css'} .= qq~.$_ { min-width:170px; } ~ ; + # $val = &common_min_form_select_col($field,'') ; + my $ucfirstfield = ucfirst $field ; + $val = qq~~ ; + if ($fixed_system_system_test[$cnt_sys_ids]) { + $trigger_jquery_raw .= qq~ + \$("#select$ucfirstfield").val("$fixed_system_system_test[$cnt_sys_ids]") ; + \$("#select$ucfirstfield").trigger("chosen:updated") ; + ~ ; + } + $trigger_jquery_raw .= qq~\$("#select$ucfirstfield").chosen({ allow_single_deselect:true });~ ; + $val_min = "Passed" if $fixed_system_system_test[$cnt_sys_ids] eq '1' ; + $val_min = "Failed" if $fixed_system_system_test[$cnt_sys_ids] eq '-1' ; + $val_min = "None" unless $val_min ; + + } else { + $val = "Passed" if $fixed_system_system_test[$cnt_sys_ids] eq '1' ; + $val = "Failed" if $fixed_system_system_test[$cnt_sys_ids] eq '-1' ; + $val = "None" unless $val ; + $val_min = $val ; + } + $trigger_jquery_raw .= qq~\$("#itv-table tr:eq($event_cnt) td:nth-last-child(5)").css("background-color","$defualt_color{$fixed_system_system_test[$cnt_sys_ids]}");~ if $fixed_system_system_test[$cnt_sys_ids] ; + $formatting = $format94 if $fixed_system_system_test[$cnt_sys_ids] eq '1' ; + $formatting = $format96 if $fixed_system_system_test[$cnt_sys_ids] eq '-1' ; + } elsif ($_ eq 'test_event') { + if ($is_in_future && $report && ($glod_user_level > 2 || $is_installation_partner || $is_schools_manager)) { + my $field = "test_event_$id\_$event_id" ; $align = qq~ class="dt-center $_"~ ; + $preferred_title{$field} = "Test Event" ; + $opts{$field} = $opts{$_} ; + $allow_deselect{$field} = 1 ; + $useropts{'common'}{'css'} .= qq~.$_ { min-width:170px; } ~ ; + # $val = &common_min_form_select_col($field,'') ; + my $ucfirstfield = ucfirst $field ; + $val = qq~~ ; + if ($fixed_system_test_event[$cnt_sys_ids]) { + $trigger_jquery_raw .= qq~ + \$("#select$ucfirstfield").val("$fixed_system_test_event[$cnt_sys_ids]") ; + \$("#select$ucfirstfield").trigger("chosen:updated") ; + ~ ; + } + $trigger_jquery_raw .= qq~\$("#select$ucfirstfield").chosen({ allow_single_deselect:true });~ ; + $val_min = "Good" if $fixed_system_test_event[$cnt_sys_ids] eq '1' ; + $val_min = "Not Good" if $fixed_system_test_event[$cnt_sys_ids] eq '-1' ; + $val_min = "None" unless $val_min ; + } else { + $val = "Good" if $fixed_system_test_event[$cnt_sys_ids] eq '1' ; + $val = "Not Good" if $fixed_system_test_event[$cnt_sys_ids] eq '-1' ; + $val = "None" unless $val ; + $val_min = $val ; + } + $trigger_jquery_raw .= qq~\$("#itv-table tr:eq($event_cnt) td:nth-last-child(4)").css("background-color","$defualt_color{$fixed_system_test_event[$cnt_sys_ids]}");~ if $fixed_system_test_event[$cnt_sys_ids] ; + $formatting = $format94 if $fixed_system_test_event[$cnt_sys_ids] eq '1' ; + $formatting = $format96 if $fixed_system_test_event[$cnt_sys_ids] eq '-1' ; + } elsif ($_ eq 'sound_test') { + if ($is_in_future && $report && ($glod_user_level > 2 || $is_installation_partner || $is_schools_manager)) { + my $field = "sound_test_$id\_$event_id" ; $align = qq~ class="dt-center $_"~ ; + $preferred_title{$field} = "Test Sound" ; + $opts{$field} = $opts{$_} ; + $allow_deselect{$field} = 1 ; + $useropts{'common'}{'css'} .= qq~.$_ { min-width:170px; } ~ ; + # $val = &common_min_form_select_col($field,'') ; + my $ucfirstfield = ucfirst $field ; + $val = qq~~ ; + if ($fixed_system_sound_test[$cnt_sys_ids]) { + $trigger_jquery_raw .= qq~ + \$("#select$ucfirstfield").val("$fixed_system_sound_test[$cnt_sys_ids]") ; + \$("#select$ucfirstfield").trigger("chosen:updated") ; + ~ ; + } + $trigger_jquery_raw .= qq~\$("#select$ucfirstfield").chosen({ allow_single_deselect:true });~ ; + $val = "None" unless $val ; + $val_min = $db{fixed_system_sound_test}{$fixed_system_sound_test[$cnt_sys_ids]}{name} if $fixed_system_sound_test[$cnt_sys_ids] ; + $val_min = "None" unless $val_min ; + } else { + $val = $db{fixed_system_sound_test}{$fixed_system_sound_test[$cnt_sys_ids]}{name} if $fixed_system_sound_test[$cnt_sys_ids] ; + $val = "None" unless $val ; + $val_min = $val ; + } + $trigger_jquery_raw .= qq~\$("#itv-table tr:eq($event_cnt) td:nth-last-child(3)").css("background-color","$defualt_color2{$fixed_system_sound_test[$cnt_sys_ids]}");~ if $fixed_system_sound_test[$cnt_sys_ids] ; + $formatting = $format94 if $fixed_system_sound_test[$cnt_sys_ids] eq '1' ; + $formatting = $format95 if $fixed_system_sound_test[$cnt_sys_ids] eq '2' ; + $formatting = $format96 if $fixed_system_sound_test[$cnt_sys_ids] eq '3' ; + } elsif ($_ eq 'overall_status') { + if ($is_in_future && $report && ($glod_user_level > 2 || $is_installation_partner || $is_schools_manager)) { + $found_after_date = 1 ; + my $field = "overall_status_$id\_$event_id" ; $align = qq~ class="dt-center $_"~ ; + $preferred_title{$field} = "Overall Status" ; + $opts{$field} = $opts{$_} ; + $allow_deselect{$field} = 1 ; + $useropts{'common'}{'css'} .= qq~.$_ { min-width:170px; } ~ ; + # $val = &common_min_form_select_col($field,'') ; + my $ucfirstfield = ucfirst $field ; + $val = qq~~ ; + if ($fixed_system_overall_status[$cnt_sys_ids]) { + $trigger_jquery_raw .= qq~ + \$("#select$ucfirstfield").val("$fixed_system_overall_status[$cnt_sys_ids]") ; + \$("#select$ucfirstfield").trigger("chosen:updated") ; + ~ ; + } + $trigger_jquery_raw .= qq~\$("#select$ucfirstfield").chosen({ allow_single_deselect:true });~ ; + $val_min = $db{fixed_system_status}{$fixed_system_overall_status[$cnt_sys_ids]}{status} if $fixed_system_overall_status[$cnt_sys_ids] ; + $val_min = "None" unless $val_min ; + } else { + $val = $db{fixed_system_status}{$fixed_system_overall_status[$cnt_sys_ids]}{status} if $fixed_system_overall_status[$cnt_sys_ids] ; + $val = "None" unless $val ; + $val_min = $val ; + } + $trigger_jquery_raw .= qq~\$("#itv-table tr:eq($event_cnt) td:nth-last-child(2)").css("background-color","$defualt_color2{$fixed_system_overall_status[$cnt_sys_ids]}");~ if $fixed_system_overall_status[$cnt_sys_ids] ; + $formatting = $format94 if $fixed_system_overall_status[$cnt_sys_ids] eq '1' ; + $formatting = $format95 if $fixed_system_overall_status[$cnt_sys_ids] eq '2' ; + $formatting = $format96 if $fixed_system_overall_status[$cnt_sys_ids] eq '3' ; + } elsif ($_ eq 'additional_comments') { + if ($is_in_future && $report && ($glod_user_level > 2 || $is_installation_partner || $is_schools_manager)) { + my $field = "additional_comments_$id\_$event_id" ; my $ucfirstfield = ucfirst $field ; $align = qq~ class="dt-center $_ controls"~ ; + $preferred_title{$field} = "Additional Comments" ; $useropts{'common'}{'css'} .= qq~.$_ { min-width:170px; } ~ ; + # $val = &common_min_form_input_col($field,'') ; + $val = qq~~ ; + if ($fixed_system_additional_comments[$cnt_sys_ids]) { + $trigger_jquery_raw .= qq~ + \$("#inputAdditional_comments_$id\_$event_id").val("$fixed_system_additional_comments[$cnt_sys_ids]") ; + ~ ; + } + $val_min = $fixed_system_additional_comments[$cnt_sys_ids] ; + $val_min = "None" unless $val_min ; + } else { + $val = $fixed_system_additional_comments[$cnt_sys_ids] ; + $val = "None" unless $val ; + $val_min = $val ; + } + } + + if ($_ ne 'online_status' && $_ ne 'network_test' && $_ ne 'system_test' && $_ ne 'test_event' && $_ ne 'sound_test' && $_ ne 'overall_status' && $_ ne 'additional_comments') { + $val_min = $val ; + $val_min =~ s/\
    /\;/g ; + } + $print_tbody .= qq~$val~ if $report ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$formatting) ; + $xlsxcol++ ; + } + $print_tbody .= qq~~ if $report ; + $xlsxrow++ ; + } + } + + $worksheet{$ws}->set_column(0,0,10); + $worksheet{$ws}->set_column(1,1,30); + $worksheet{$ws}->set_column(2,3,15); + $worksheet{$ws}->set_column(4,4,45); + $worksheet{$ws}->set_column(5,5,15); + $worksheet{$ws}->set_column(6,6,45); + $worksheet{$ws}->set_column(7,12,15); + $worksheet{$ws}->set_column(13,13,45); + + &report_xlsx_export_footer('N',15,$xlsxdir) ; + +} #------------------------------------------------------------------------------- + +sub fixedsystem_check_for_overlapping_dates { + + my ($check_table,$checked_column,$date_from_input,$date_to_input,$sys_ids_input,$get_periods) = @_ ; + + my %seen_system_id = () ; my %checked_system_id = () ; my %system_start_date = () ; my %system_end_date = () ; + + my $sys_ids = "" ; + + if ($get_periods) { + $sys_ids = $sys_ids_input ; + } + + + foreach my $id (sort keys %{$db{$table}}) { + + unless ($get_periods) { + $sys_ids = $db{$table}{$id}{$checked_column} ; + } + foreach (split(";",$sys_ids)) { + + $system_start_date{$_}{$id} = $db{$table}{$id}{date_from} ; + $system_end_date{$_}{$id} = $db{$table}{$id}{date_to} ; + } + } + + if ($date_from_input and $date_to_input and $sys_ids_input) { + + foreach (split(";",$sys_ids_input)) { + + $system_start_date{$_}{-1} = $date_from_input ; + $system_end_date{$_}{-1} = $date_to_input ; + } + } + + foreach my $id (sort keys %{$db{$table}}) { + + unless ($get_periods) { + $sys_ids = $db{$table}{$id}{$checked_column} ; + } + + foreach my $sys_id (split(";",$sys_ids)) { + + next unless $sys_id ; + + if ($seen_system_id{$sys_id} and not $checked_system_id{$sys_id}) { + + $checked_system_id{$sys_id} = 1 ; + foreach my $id2 (keys %{$system_start_date{$sys_id}}) { + + next if $id2 eq $id ; + my $t1 = &common_check_if_time_is_greater($system_start_date{$sys_id}{$id2},$db{$table}{$id}{date_to}) ; ## 21<12 + my $t2 = &common_check_if_time_is_greater($system_end_date{$sys_id}{$id2},$db{$table}{$id}{date_to}) ; ## 22<12 + my $t3 = &common_check_if_time_is_greater($system_start_date{$sys_id}{$id2},$db{$table}{$id}{date_from}) ; ## 21<11 + my $t4 = &common_check_if_time_is_greater($system_end_date{$sys_id}{$id2},$db{$table}{$id}{date_from}) ; ## 22<11 + + if (($t1 and not $t2) or ($t3 and not $t4) or (not $t3 and $t2) or ($t3 and not $t2)) { + my $system_name = qq~$db{$check_table}{$sys_id}{name}~ ; + $system_name .= qq~ ($db{$check_table}{$sys_id}{description})~ if $db{$check_table}{$sys_id}{description} ; + + if ($get_periods) { + $overlap_dates{$sys_id}{$id2} = "$db{$table}{$id2}{date_from} - $db{$table}{$id2}{date_to}" ; + } else { + $trigger_jquery_raw .= qq~ + noty({text:'System $system_name and cannot be used in both event $db{$table}{$id}{ref} and $db{$table}{$id2}{ref} as the times ovelap!!',layout:"center",type:"error",timeout:30000}) ; + ~ ; + } + } + } + } + $seen_system_id{$sys_id} = 1 ; + } + } +} #------------------------------------------------------------------------------- + +1 ; \ No newline at end of file diff --git a/libs/modules/_FromProd/getmail.pm b/libs/modules/_FromProd/getmail.pm new file mode 100644 index 0000000..15870f5 --- /dev/null +++ b/libs/modules/_FromProd/getmail.pm @@ -0,0 +1,287 @@ +sub getmail_fetch { + +# $mail_psw = 'znMpCa6pikZF' ; +# $mail_host = 'pop.yandex.com' ; +# $mail_user = 'itv.k@re8it.com' ; + +# $mail_psw = 'vf1VBE6AGuPE' ; +$mail_psw = $send_mail_psw ; +# $mail_host = 'envoy.aserv.co.za' ; +$mail_host = 'pop3.interactivetvafrica.com' ; +$mail_user = 'tickets@interactivetvafrica.com' ; + +# $mail_psw = "Jat20161" ; +# $mail_host = "outlook.office365.com" ; +# $mail_user = "tickets\@aisport.africa" ; + +use IO::Socket::SSL; + +$socket = IO::Socket::SSL->new( PeerAddr => $mail_host, + PeerPort => 995, + SSL_verify_mode => SSL_VERIFY_NONE, + Proto => 'tcp') || die "No socket!"; + +$pop = new Mail::POP3Client( USER => $mail_user, PASSWORD => $mail_psw, HOST => $mail_host, USESSL => true, SOCKET => $socket ) || die $pop->Message(); +# $pop = new Mail::POP3Client( USER => $mail_user, PASSWORD => $mail_psw, HOST => $mail_host, PORT => 995, AUTH_MODE => 'PASS', USESSL => true, SOCKET => $socket ) || die $pop->Message(); + +# # OR with SSL +# $pop = new Mail::POP3Client( USER => $mail_user, + # PASSWORD => $mail_psw, + # HOST => $mail_host, + # USESSL => true, + # ) || die $pop->Message(); + +#connect to POP3 sever +# my $pop = new Mail::POP3Client( HOST => $mail_host ); +# $pop->User($mail_user); +# $pop->Pass($mail_psw); +# $pop->Connect() || die "Unable to connect to POP3 server: ".$pop->Message()."\n"; + +if ($debug) { + use Data::Dumper; + print Dumper(\$pop); + &common_debug ("get_mail : office_user = $mail_user") ; + } + +$nummsgs = $pop->Count; + +&common_debug ("get_mail : nummsgs [$nummsgs]") ; + +for ($i = 1; $i <= $pop->Count(); $i++) { + + # # sometimes the 'To' is like this : 'graham evens <12345+gevens-bookings@eccotours.co.za>' + # # sometimes the 'To' is like this : '12345+gevens-bookings@eccotours.co.za' + # # so we split it by '<' to just get the bit we want + # my @to_array = split (/\Head( $i ) ; + $head = &getmail_clean($head) ; + + &common_debug ("get_mail : head [$head]") ; + + %mailcontent = () ; + + my $subject_auto_conf = '' ; + my $subject_auto_decline = '' ; + + # if ($head =~ /[\d]+\++[\w]+-bookings@[\w\.\-]+\w+/) { # 18398+autoreq-bookings@ecco.co.za + # $to = $& ; + # } + # elsif ($head =~ /AUTO+\s+CONFIRMATION+\s:\s+[\d]+\s:\s+[\w]+-+[\w]+\s+\(+[\w]+\)/) { # If subject = AUTO CONFIRMATION : 123456 : hotelcode-room (789123) + # $subject_auto_conf = $& ; + # } + # else + # { + foreach ( $pop->Head( $i ) ) { + chomp; + /^(From|Subject|To|Cc):\s+/i; + my ($index,$value) = split(/:/); + $mailcontent{$index} = $value; + } + + my @to_array = split (/\//g ; + # } + + # $mailaccount = '' ; + # $junk = '' ; + + &common_debug ("get_mail : to [$to]") ; + + $uniqueid = $pop->Uidl($i); + $uniqueid =~ s/\s//g; # strip whitespace + + $headandbody = $pop->HeadAndBody( $i ) ; + + # &common_debug ("get_mail : uniqueid [$uniqueid] headandbody [$headandbody]") ; + &common_debug ("get_mail : uniqueid [$uniqueid]") ; + + &getmail_mailparse ; + + $pop->Delete( $i ) ; # temp comment out + + } + +$pop->Close(); + +} #------------------------------------------------------------------------------------------ + +sub getmail_clean { + +my ($item) = @_ ; + +$item =~ s/\|/-/g; # remove any pipes +$item =~ s/\n//g; # remove any newlines +$item =~ s/\r//g; # remove any carriage returns +$item =~ s/\"//g; # remove " marks +$item =~ s/\'//g; # remove ' marks + +return ($item) ; + +} #------------------------------------------------------------------------------------------ + +sub getmail_mailparse { + +$parser = MIME::Parser->new; + +### Keep parsed message bodies in core (default outputs to disk): +# $parser->output_to_core(1); # don't write attachments to disk +$parser->output_to_core('NONE') ; # or die "can't output_to_core: $!" ; + +### Change how nameless message-component files are named: +$parser->output_prefix("msg") or die "can't output_prefix: $!" ; + +&getmail_make_dir ; + +binmode(STDOUT, ":utf8"); + +### Output each message body to the same directory: +# $parser->output_under($outputdir); +$parser->output_dir($outputdir) or die "can't output into $outputdir: $!" ; + +# $entity->dump_skeleton; # for debugging + +$entity = $parser->parse_data($headandbody) or die "can't parse_data $headandbody: $!" ; + +&getmail_process_entity_header ; +&getmail_process_output_dir ; + +} #------------------------------------------------------------------------------------------ + +sub getmail_process_output_dir { + +$i{unique_id} = $uniqueid ; +$i{date_time} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; +$i{client_id} = '0' ; +$i{staff_id} = '0' ; +$i{sent_date} = $mailparsedate ; +$i{doctype} = 'ticket' ; +$i{mailtype} = 'EMAILI' ; +$i{subject} = $mailparsesubject ; +$i{sent_from} = $mailparsefrom ; +$i{sent_to} = $to ; +$i{cc} = $mailcontent{'Cc'} ; +$i{bcc} = $mailcontent{'Bcc'} ; +$i{reply_to} = $mailparsereplyto ; +# $i{action_time} = ; +$i{completed} = '0' ; + +&db_min_insert('tickets') ; + +my @hash_split = split /\#\#/, $mailparsesubject ; +my @subj_uid = split / /, $hash_split[1] ; +my $suid = $subj_uid[0] ; + +if ($suid && length($suid)>5) { + %i = () ; + $i{completed} = '0' ; + &db_min_upd('tickets',"suid='$suid' OR unique_id='$suid' OR suid='$uniqueid' OR unique_id='$uniqueid'") ; +} + +} #------------------------------------------------------------------------------------------ + +sub getmail_make_dir { + +our $outputdir = "$mailpath/tickets/$uniqueid" ; + +return if -d $outputdir ; + +mkdir ($outputdir,0777) or die "mkdir $outputdir: $!" ; +chmod (0777, $outputdir) ; + +} #------------------------------------------------------------------------------------------ + +sub getmail_process_entity_header { + +use Encode qw(decode); + +$mailparsesubject = $entity->head->get('subject'); + +&common_debug ("getmail_process_entity_header : subject [$mailparsesubject]") ; + +$mailparsesubject = decode("MIME-Header", $mailparsesubject) ; + +&common_debug ("getmail_process_entity_header : subject [$mailparsesubject]") ; + +$mailparsesubject =~ s/\|/-/g; # remove any pipes +$mailparsesubject =~ s/\n//g; # remove any newlines +$mailparsesubject =~ s/\r//g; # remove any carriage returns +$mailparsesubject =~ s/\'//g; # remove any apostrophes + +$mailparsesubject =~ s/\/\///g; # remove the '//' from TLF chasers +$mailparsesubject =~ s/\\//g; # remove the '\' from TLF chasers + +unless ($mailparsesubject) { $mailparsesubject = "(No Subject)" ; } + +$mailparsefrom = $entity->head->get('from'); +$mailparsefrom =~ s/\|/-/g; # remove any pipes +$mailparsefrom =~ s/\n//g; # remove any newlines +$mailparsefrom =~ s/\r//g; # remove any carriage returns +$mailparsefrom =~ s/\"//g; # remove " marks +$mailparsefrom =~ s/\'//g; # remove ' marks + +$mailpamailparsefrom = decode("MIME-Header", $mailparsefrom) ; + +$mailparsereplyto = $entity->head->get('Reply-To'); +$mailparsereplyto =~ s/\|/-/g; # remove any pipes +$mailparsereplyto =~ s/\n//g; # remove any newlines +$mailparsereplyto =~ s/\r//g; # remove any carriage returns +$mailparsereplyto =~ s/\"//g; # remove " marks +$mailparsereplyto =~ s/\'//g; # remove ' marks + +$mailparsedate = $entity->head->get('date'); + +my ($dayofweek, $day, $month, $ccyy, $time, $gmt) = split /\s/, $mailparsedate ; + +$day = sprintf("%02d", ($day)) ; + +$m{jan} = '01' ; $m{feb} = '02' ; $m{mar} = '03' ; $m{apr} = '04' ; $m{may} = '05' ; $m{jun} = '06' ; $m{jul} = '07' ; $m{aug} = '08' ; $m{sep} = '09' ; $m{oct} = '10' ; $m{nov} = '11' ; $m{dec} = '12' ; + +my $hashkey = lc $month ; +# $mailparsedate = "$day." . $m{$hashkey} ."." . substr($ccyy,2,2) . " (" . substr($time,0,5) . ")" ; # 15.06.22 (12:49) +$mailparsedate = "$ccyy-$m{$hashkey}-$day " . substr($time,0,8) ; # 2022-06-21 12:49:35 + +chomp $mailparsesubject ; +chomp $mailparsedate ; +chomp $mailparsefrom ; +chomp $mailparsereplyto ; + +unless ($mailparsereplyto) { + $mailparsereplyto = $mailparsefrom ; + } + +&getmail_auto_reply ; + +&common_debug ("getmail_process_entity_header : mailparsereplyto [$mailparsereplyto]") ; + +} #------------------------------------------------------------------------------------------ + +sub getmail_auto_reply { + + my @hash_split = split /\#\#/, $mailparsesubject ; + my @subj_uid = split / /, $hash_split[1] ; + + &common_debug ("getmail_auto_reply : subj_uid=[$subj_uid[0]]") ; + + unless ($subj_uid[0] && length($subj_uid[0])>5) { + my $resubject = ($mailparsesubject =~ /Re:/iog) ? '' : 'Re: ' ; + my $resubject .= "$mailparsesubject ##$uniqueid##" ; + my $remsg = qq~Hello, thank you for contacting ITV. + +Your ticket ID is $uniqueid. + +One of our consultants will reply to you shortly to assist you with your query - typically within a few hours. + +For after-hour emergencies please contact Technical Support on support\@aisport.africa or telephonically on (+27) 10 534 7011. + +Best regards, + +The ITV Africa Team~ ; + &common_debug ("getmail_auto_reply : to=[$mailparsefrom] subject=[$resubject]") ; + &common_send_mail($mailparsefrom,'','','','',"$remsg","$resubject") ; + } + +} #------------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/_FromProd/logistics.pm b/libs/modules/_FromProd/logistics.pm new file mode 100644 index 0000000..51cea75 --- /dev/null +++ b/libs/modules/_FromProd/logistics.pm @@ -0,0 +1,710 @@ +sub logistics_load_db_vars { + + &db_min_ro('organisations','*',"",'','') ; + &db_min_ro('logistics_locations','*',"",'','') ; + &db_min_ro('logistics_suppliers','*',"active = '1'",'','') ; + &db_min_ro('logistics_items','*',"",'','') ; + &db_min_ro('event_systems','id,logistics_location_id',"(`system_type` = 'mobile' OR `system_type` = 'solo' OR `description` lIKE 'cricket%')",'','') ; + + foreach (keys %i) { + local @abc = split("_",$_) ; + if (substr($_,0,7) eq 'update_') { + $seen_event_id{$abc[-1]} = 1 ; + } + } + # create_waybill_out_5136 + local @event_ids = () ; + foreach (keys %seen_event_id) { + push @event_ids , "`id` = '$_'" ; + } + local $e_q_sql = join (" OR ",@event_ids) ; + + &db_min_ro($table,'id,event_system_id_multiple,logistics_suppliers,logistics_waybill_nrs,logistics_status_ids,logistics_venue_id,logistics_item_ids,poc_id,recipient_id,logistics_special_instructions,logistics_complete,logistics_dcb_waybill,date_from,date_to,logistics_delivery_datetime,logistics_received_by,logistics_location_other,logistics_system_location_id,logistics_last_changed_by,logistics_dcb_comments,logistics_shipment_operator_id',"$e_q_sql",'','') ; + +} #------------------------------------------------------------------------------------------ + +sub logistics_dates { + + my ($from_to,$id) = @_ ; + + $nowrap = 'nowrap' ; + my ($year1,$month1,$day1) = split(/\-/,substr($db{$table}{$id}{date_from},0,10)) ; + my ($year2,$month2,$day2) = split(/\-/,substr($db{$table}{$id}{date_to},0,10)) ; + $val = qq~~ ; + if ($year1 ne $year2 && $month1 ne $month2 && $day1 ne $day2) { + $val = qq~ $day1 $month_names[$month1] $year1 -
    $day2 $month_names[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 ne $month2) { + $val = qq~ $day1 $month_names[$month1] -
    $day2 $month_names[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 eq $month2 && $day1 ne $day2) { + $val = qq~ $day1 - $day2 $month_names[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 eq $month2 && $day1 eq $day2) { + $val = qq~ $day2 $month_names[$month2] $year2~ ; + } + my $stime = substr($db{$table}{$id}{date_from},11,5) ; + my $etime = substr($db{$table}{$id}{date_to},11,5) ; + $valxlsx = $val ; + $valxlsx =~ s/
    //g ; + # $val = qq~$val~ ; + + # &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol+1,$stime,$formatting) ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol+2,$etime,$formatting) ; + +} #------------------------------------------------------------------------------------------ + +sub logistics_venue { + + my ($from_to,$id) = @_ ; + + $val = '' ; $nowrap = 'nowrap' ; + foreach my $_oid (@venue_ids) { + $val .= qq~$db{organisations}{$_oid}{name}~ ; + $val .= qq~ [$db{organisations}{$_oid}{region_code}]~ if $db{organisations}{$_oid}{region_code} ; + $val .= ',' ; + } + $val = substr($val,0,-1) if $val ; + $valxlsx = $val ; + $valxlsx =~ s/\,/\;/g ; + if (length($val) > 30) { + $val =~ s/\,/\
    /g ; + $val = substr($val,0,27) . qq~~ ; + } else { + $val =~ s/\,/\
    /g ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_system { + + my ($from_to,$id) = @_ ; + + $val = '' ; my $tooltip = '' ; + + foreach my $event_sys_id (@system_name_ids) { + next unless $event_sys_id ; + next unless $db{event_systems}{$event_sys_id}{system_type} ; + $system_count++ ; + $tooltip .= qq~
    $db{event_systems}{$event_sys_id}{name}~ ; + $tooltip .= qq~ [$db{event_systems}{$event_sys_id}{description}]~ if $db{event_systems}{$event_sys_id}{description} ; + } + + $tooltip = substr($tooltip,4) if $tooltip ; + $val = $tooltip ; + # $val = ($system_count > 1) ? qq~~ : ($system_count == 1) ? qq~~ : "" ; + $valxlsx = $tooltip ; + $valxlsx =~ s/\
    /\;/g ; + +} #------------------------------------------------------------------------------------------ + +sub logistics_from_to { + + my ($from_to,$id) = @_ ; + + $val = '' ; $valxlsx = 'MUSTBEBLANK' ; + + if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + $found_editable = 1 ; + $trigger_jquery_raw .= qq~\$("#$ucfirstfield{1},#$ucfirstfield{2}").chosen({allow_single_deselect:true}) ; ~ ; + + my $col_venue = ($from_to eq 'to') ? 10 : 11 ; + my $col_log_loc = ($from_to eq 'to') ? 11 : 10 ; + + if (($_ eq 'to' && $from_to eq 'to') || ($_ eq 'from' && $iaction eq 'report_from')) { # && $iaction eq 'report') || ($_ eq 'from' && $_ eq 'report_from') + $val = qq~ + + ~ ; + $trigger_jquery_raw .= qq~ + \$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child($col_venue)").css("z-index","$cali_cnt") ; + ~ ; + if ($db{$table}{$id}{logistics_venue_id}) { + $valxlsx = "$db{organisations}{$db{$table}{$id}{logistics_venue_id}}{name} [$db{organisations}{$db{$table}{$id}{logistics_venue_id}}{region_code}]" if $db{organisations}{$db{$table}{$id}{logistics_venue_id}}{region_code} ; + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{1}").val("$db{$table}{$id}{logistics_venue_id}") ; + ~ ; + push @selects_with_default_ids,"#$ucfirstfield{1}" if $ucfirstfield{1} ; + push @table_with_default_ids,"#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child($col_venue)" ; + + $default_javascript .= qq~"$field{1}":"$db{$table}{$id}{logistics_venue_id}",~ ; + } elsif ($venue_ids[0]) { + $valxlsx = "$db{organisations}{$venue_ids[0]}{name} [$db{organisations}{$venue_ids[0]}{region_code}]" if $db{organisations}{$venue_ids[0]}{region_code} ; + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{1}").val("$venue_ids[0]") ; + ~ ; + push @selects_with_default_ids,"#$ucfirstfield{1}" if $ucfirstfield{1} ; + $default_javascript .= qq~"$field{1}":"$venue_ids[0]",~ ; + } else { + $default_javascript .= qq~"$field{1}":"",~ ; + } + } else { + $val = qq~ + + ~ ; + my $found_loc = 0 ; + + $trigger_jquery_raw .= qq~ + \$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child($col_log_loc)").css("z-index","$cali_cnt") ; + ~ ; + foreach my $event_sys_id (@system_name_ids) { + next unless $event_sys_id ; + next unless $db{event_systems}{$event_sys_id}{system_type} ; + if ($db{event_systems}{$event_sys_id}{logistics_location_id}) { + $valxlsx = $db{logistics_locations}{$db{event_systems}{$event_sys_id}{logistics_location_id}}{location} ; + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{2}").val("$db{event_systems}{$event_sys_id}{logistics_location_id}") ; + ~ ; + $found_loc = 1 ; + push @selects_with_default_ids,"#$ucfirstfield{2}" if $ucfirstfield{2} ; + push @table_with_default_ids,"#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child($col_log_loc)" ; + $default_javascript .= qq~"$field{2}":"$db{event_systems}{$event_sys_id}{logistics_location_id}",~ ; + } + last ; + } + if (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Johannesburg/) { + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{2}").val("1") ; + ~ ; + $default_javascript .= qq~"$field{2}":"1",~ ; + push @selects_with_default_ids,"#$ucfirstfield{2}" if $ucfirstfield{2} ; + } elsif (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Cape Town/) { + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{2}").val("2") ; + ~ ; + $default_javascript .= qq~"$field{2}":"2",~ ; + push @selects_with_default_ids,"#$ucfirstfield{2}" if $ucfirstfield{2} ; + } elsif (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Durban/) { + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{2}").val("3") ; + ~ ; + push @selects_with_default_ids,"#$ucfirstfield{2}" if $ucfirstfield{2} ; + $default_javascript .= qq~"$field{2}":"3",~ ; + } elsif (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Bloemfontein/) { + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{2}").val("4") ; + ~ ; + push @selects_with_default_ids,"#$ucfirstfield{2}" if $ucfirstfield{2} ; + $default_javascript .= qq~"$field{2}":"4",~ ; + } elsif (!$found_loc) { + $default_javascript .= qq~"$field{2}":"",~ ; + } + } + push @dropdown_chosen_ids,"#$ucfirstfield{1}\_chosen,#$ucfirstfield{2}\_chosen" if $ucfirstfield{1} && $ucfirstfield{2} ; + } else { + if (($_ eq 'to' && $from_to eq 'to') || ($_ eq 'from' && $iaction eq 'report_from')) { + if ($db{$table}{$id}{logistics_venue_id}) { + $val = qq~$db{organisations}{$db{$table}{$id}{logistics_venue_id}}{name}~ ; + $val .= qq~ [$db{organisations}{$db{$table}{$id}{logistics_venue_id}}{region_code}]~ if $db{organisations}{$db{$table}{$id}{logistics_venue_id}}{region_code} ; + } elsif ($venue_ids[0]) { + $val = qq~$db{organisations}{$venue_ids[0]}{name}~ ; + $val .= qq~ [$db{organisations}{$venue_ids[0]}{region_code}]~ if $db{organisations}{$venue_ids[0]}{region_code} ; + } + } else { + my $found_loc = 0 ; + foreach my $event_sys_id (@system_name_ids) { + next unless $event_sys_id ; + next unless $db{event_systems}{$event_sys_id}{system_type} ; + if ($db{event_systems}{$event_sys_id}{logistics_location_id}) { + $val = $db{logistics_locations}{$db{event_systems}{$event_sys_id}{logistics_location_id}}{location} ; + $found_loc = 1 ; + last ; + } + } + if (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Johannesburg/) { + $val = $db{logistics_locations}{1}{location} ; + } elsif (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Cape Town/) { + $val = $db{logistics_locations}{2}{location} ; + } elsif (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Durban/) { + $val = $db{logistics_locations}{3}{location} ; + } elsif (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Bloemfontein/) { + $val = $db{logistics_locations}{4}{location} ; + } + } + $valxlsx = $val ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_supplier { + + my ($from_to,$id) = @_ ; + + $val = '' ; $valxlsx = 'MUSTBEBLANK' ; + if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + $found_editable = 1 ; + $preferred_title{$field{supplier}} = "Supplier" ; + $opts{$field{supplier}} = $opts{logistics_supplier} ; + $trigger_jquery_raw .= qq~\$("#$ucfirstfield{supplier}").chosen({ allow_single_deselect:true });~ ; + $val = qq~~ ; + + $trigger_jquery_raw .= qq~ + \$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(9)").css("z-index","$cali_cnt") ; + ~ ; + + if ($logistics_supplier_ids_hash{$id}{$from_to}) { + $valxlsx = $db{logistics_suppliers}{$logistics_supplier_ids_hash{$id}{$from_to}}{supplier} ; + push @selects_with_default_ids,"#$ucfirstfield{supplier}" if $ucfirstfield{supplier} ; + push @table_with_default_ids,"#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(9)" ; + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{supplier}").val("$logistics_supplier_ids_hash{$id}{$from_to}") ; + // \$("#$ucfirstfield{supplier}").trigger("chosen:updated") ; + // \$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(9)").css("background-color","#424949") ; + ~ ; + } + push @dropdown_chosen_ids,"#$ucfirstfield{supplier}\_chosen" if $ucfirstfield{supplier} ; + } elsif ($logistics_supplier_ids_hash{$id}{$from_to}) { + $val = $db{logistics_suppliers}{$logistics_supplier_ids_hash{$id}{$from_to}}{supplier} ; + $valxlsx = $val ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_status { + + my ($from_to,$id) = @_ ; + + local %status_hash = (1 =>"Booked",2 => "Pending",3=>"In Transit",4 =>"Delivered") ; + $val = '' ; $valxlsx = 'MUSTBEBLANK' ; + # if (($from_to eq 'to' && $current_date <= $end_date) || ($from_to eq 'from' && $current_date <= $start_date)) { + if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + $found_editable = 1 ; + $preferred_title{$field{status}} = "Status" ; + $opts{$field{status}} = $opts{status} ; + $trigger_jquery_raw .= qq~\$("#$ucfirstfield{status}").chosen({ allow_single_deselect:true });~ ; + $val = qq~~ ; + + $trigger_jquery_raw .= qq~ + \$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(8)").css("z-index","$cali_cnt") ; + ~ ; + + $val = &common_min_form_select_col($field{status},'') ; ########### >= OR > + if ($logistics_status_ids_hash{$id}{$from_to}) { + $valxlsx = $status_hash{$logistics_status_ids_hash{$id}{$from_to}} ; + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{status}").val("$logistics_status_ids_hash{$id}{$from_to}") ; + // \$("#$ucfirstfield{status}").trigger("chosen:updated") ; + ~ ; + $default_javascript .= qq~"$field{status}":"$logistics_status_ids_hash{$id}{$from_to}",~ ; + push @selects_with_default_ids,"#$ucfirstfield{status}" if $ucfirstfield{status} ; + if ($logistics_status_ids_hash{$id}{$from_to} eq '1') { #Booked + $trigger_jquery_raw .= qq~\$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(8)").css("background-color","rgb(81,203,242)") ; ~ ; + } elsif ($logistics_status_ids_hash{$id}{$from_to} eq '2') { #Pending + $trigger_jquery_raw .= qq~\$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(8)").css("background-color","rgb(66,73,73)") ; ~ ; + } elsif ($logistics_status_ids_hash{$id}{$from_to} eq '3') { #In Transit + $trigger_jquery_raw .= qq~\$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(8)").css("background-color","rgb(255,165,0) ") ; ~ ; + } elsif ($logistics_status_ids_hash{$id}{$from_to} eq '4') { #Delivered + $trigger_jquery_raw .= qq~\$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(8)").css("background-color","rgb(46,204,113)") ; ~ ; + } + } else { + $default_javascript .= qq~"$field{status}":"2",~ ; + } + push @dropdown_chosen_ids,"#$ucfirstfield{status}\_chosen" if $ucfirstfield{status} ; + } elsif ($logistics_status_ids_hash{$id}{$from_to}) { + $val = $logistics_status_ids_hash{$logistics_status_ids_hash{$id}{$from_to}} ; + $valxlsx = $status_hash{$logistics_status_ids_hash{$id}{$from_to}} ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_waybill_nr { + + my ($from_to,$id) = @_ ; + + my $fname = 'waybill_nr' ; $val = '' ; $valxlsx = 'MUSTBEBLANK' ; + my $wb_code = 'AIS' . uc substr($from_to,0,1) . '_' ; + + if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + $found_editable = 1 ; + my $print_field = &common_min_print_field($field{$fname}) ; $tindex++ ; + my $wb_nr = ($logistics_waybill_ids_hash{$id}{$from_to}) ? $logistics_waybill_ids_hash{$id}{$from_to} : $wb_code . $id ; + $default_javascript .= qq~"$field{$fname}":"$wb_nr",~ ; + $val = qq~
    +
    ~ ; + $valxlsx = $wb_nr ; + $trigger_jquery .= qq~ \$("#$ucfirstfield{$fname}").css("width","100%") ;~ ; + $trigger_jquery_raw .= qq~\$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(7)").css("background-color","#424949") ; ~ if $logistics_waybill_ids_hash{$id}{$from_to} ; + } else { + $val = ($logistics_waybill_ids_hash{$id}{$from_to}) ? $logistics_waybill_ids_hash{$id}{$from_to} : (!$readlonly_row) ? $id : "" ; + print "\n logistics_waybill_nr" ; + $valxlsx = $val ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_item { + + my ($from_to,$id) = @_ ; + + $val = '' ; $valxlsx = 'MUSTBEBLANK' ; + if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + + $all_ids .= qq~,$id~ ; + $found_editable = 1 ; + $preferred_title{$field{item}} = "Item" ; + $opts{$field{item}} = $opts{logistics_items} ; + $trigger_jquery_raw .= qq~\$("#$ucfirstfield{item}").chosen({ allow_single_deselect:true });~ ; + + if ($logistics_item_ids_hash{$id}) { + push @table_with_default_ids,"#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(6)" ; + foreach my $item_id (split(/\,/,$logistics_item_ids_hash{$id})) { + next unless $item_id ; + $opts{$field{item}} =~ s/\Q"$item_id"/"$item_id" SELECTED/g ; + } + $valxlsx = join (';', map { $db{logistics_items}{$_}{name} } split /,/, $logistics_item_ids_hash{$id}); + } + + $val = qq~ + + ~ ; + + $trigger_jquery .= qq~ \$("#$ucfirstfield{item}\_chosen").css("width","100%") ;~ if $ucfirstfield{item} ; + + $extra_form_fields .= qq~~; + + $jquery_chosen_sel .= qq~ + item_val = \$("#selectItem_$id").chosen().val() ; + \$('#item-$id').val(item_val) ; + ~ ; + } elsif ($logistics_item_ids_hash{$id}) { + $val = join (',', map { $db{logistics_items}{$_}{name} } split /,/, $logistics_item_ids_hash{$id}); + $valxlsx = $val ; + $valxlsx =~ s/\,/\;/g ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_poc { + + my ($from_to,$id) = @_ ; + + $val = '' ; $valxlsx = 'MUSTBEBLANK' ; + if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + $found_editable = 1 ; + $preferred_title{$field{poc}} = "poc" ; + $opts{$field{poc}} = $opts{poc}{$id} ; + + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{poc}").chosen({ allow_single_deselect:true }) ; \$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(5)").css("z-index","$cali_cnt") ; + ~ ; + $val = qq~ + + ~ ; + + if ($logistics_poc_hash{$id}) { + $valxlsx = $logistics_poc_hash{$id} ; + $valxlsx =~ s/\_/ \[/g ; + $valxlsx .= qq~]~ ; + push @table_with_default_ids,"#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(5)" ; + push @selects_with_default_ids,"#$ucfirstfield{poc}" ; + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{poc}").val("$logistics_poc_hash{$id}") ; + ~ ; + $default_javascript .= qq~"$field{poc}":"$logistics_poc_hash{$id}",~ ; + } else { + $default_javascript .= qq~"$field{poc}":"",~ ; + } + push @dropdown_chosen_ids,"#$ucfirstfield{poc}\_chosen" if $ucfirstfield{poc} ; + + } elsif ($logistics_poc_hash{$id}) { + $val = $logistics_poc_hash{$id} ; + $val =~ s/\_/\[/g ; + $val .= qq~]~ ; + $valxlsx = $val ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_special_instructions { + + my ($from_to,$id) = @_ ; + + $val = '' ; $valxlsx = 'MUSTBEBLANK' ; + # if (($from_to eq 'to' && $current_date <= $end_date) || ($from_to eq 'from' && $current_date <= $start_date)) { + if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + $found_editable = 1 ; + my $print_field = &common_min_print_field($field{special_instructions}) ; + $tindex++ ; + + my $defualt = ($logistics_special_instructions_hash{$id}{$from_to}) ? $logistics_special_instructions_hash{$id}{$from_to} : "" ; + + $valxlsx = $defualt if $defualt ; + $val = qq~ +
    +
    + +
    +
    + ~ ; + + $trigger_jquery .= qq~ + \$("#$ucfirstfield{special_instructions}").css("width","100%") ; + ~ ; + $trigger_jquery_raw .= qq~ + \$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(4)").css("background-color","#424949") ; + ~ if $logistics_special_instructions_hash{$id}{$from_to} ; + } elsif ($logistics_special_instructions_hash{$id}{$from_to}) { + $val = $logistics_special_instructions_hash{$id}{$from_to} ; + $valxlsx = $val ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_create_waybill { + + my ($from_to,$id) = @_ ; + + # if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + if (!$readlonly_row) { + + $ignore{"$_\_$id"} = 1 ; + $valxlsx = '' ; + + # if ($_ eq 'process_complete') { + # $val = qq~~ ; + # } elsif (!$dcb_waybill_nr{$from_to} && $logistics_waybill_ids_hash{$id}{$from_to} && $items && $supp{$from_to} == 2) { # 2 = DCB Logistics + + if ($logistics_waybill_ids_hash{$id}{$from_to} && $db{$table}{$id}{logistics_item_ids} && $supp{$from_to} == 2) { + # if ($waybill_nr_default_val && $item_default_val && $supplier_default_val == 2) { + if ($dcb_waybill_nr{$from_to}) { + my $arrow_class = ($dcb_waybill_nr{$from_to} && $logistics_waybill_ids_hash{$id}{$from_to}) ? 'success' : 'danger' ; + my $arrow_direction = ($from_to eq 'to') ? 'right' : 'left' ; + my $dlg = qq~javascript:dlgMdl('$useropts{'scripts'}/dialog/dcb_trackntrace.pl?debug=1&waybillnr~; + my $uc_from_to = uc $from_to ; + $val = qq~~ ; + $nowrap = 'nowrap' ; + } else { + $val = qq~~ ; + } + } elsif ($waybill_nr_default_val && $item_default_val && $supplier_default_val == 2) { + $val = qq~~ ; + } else { + + my $tool_tip = qq~~ ; + + $tool_tip .= qq~
    - Add WayBillNr~ unless $waybill_nr_default_val ; + $tool_tip .= qq~
    - Add Item(s)~ unless $item_default_val ; + $tool_tip .= qq~
    - Set Supplier to DCB~ if $supplier_default_val != 2 ; + + $val = qq~~ ; + } + + # # # if (!$dcb_waybill_nr{$from_to} && $logistics_waybill_ids_hash{$id}{$from_to} && $db{$table}{$id}{logistics_item_ids} && $supp{$from_to} == 2) { # 2 = DCB Logistics + # # # $val = qq~~ ; + # # # } elsif ($dcb_waybill_nr{$from_to} && $logistics_waybill_ids_hash{$id}{$from_to} && $db{$table}{$id}{logistics_item_ids} && $supp{$from_to} == 2) { # 2 = DCB Logistics + + # # # my $arrow_class = ($dcb_waybill_nr{$from_to} && $logistics_waybill_ids_hash{$id}{$from_to}) ? 'success' : 'danger' ; + # # # # my $to_arrow_class = ($dcb_waybill_nr{to} && $logistics_waybill_ids_hash{$id}{to}) ? 'success' : 'danger' ; + # # # # my $from_arrow_class = ($dcb_waybill_nr{from} && $logistics_waybill_ids_hash{$id}{from}) ? 'success' : 'danger' ; + + # # # my $arrow_direction = ($from_to eq 'to') ? 'rigth' : 'left' ; + + # # # my $dlg = qq~javascript:dlgMdl('$useropts{'scripts'}/dialog/dcb_trackntrace.pl?debug=1&waybillnr~; + + # # # my $uc_from_to = uc $from_to ; + + # # # $val = qq~~ ; + # # # # $val = qq~ + # # # # ~ ; + # # # $nowrap = 'nowrap' ; + # # # } else { + # # # $val = qq~~ ; + # # # } + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_jquery { + + my ($from_to) = @_ ; + + foreach my $system_id (keys %seen_system_cnt) { + chop $all_location_ids_per_system{$system_id} if $all_location_ids_per_system{$system_id} ; + } + + my $update_ids_str = join(',',@update_ids) ; + my $selects_with_default_ids_str = join(',',@selects_with_default_ids) ; + my $table_with_default_ids_str = join(',',@table_with_default_ids) ; + my $dropdown_chosen_ids_str = join(',',@dropdown_chosen_ids) ; +# + my $plus_item = ($is_dcb_partner) ? qq~ITEM~ : qq~ITEM~ ; + + $trigger_jquery .= qq~ + \$("#$useropts{table_id} tr th:nth-last-child($last_child{item})").html("$plus_item") ; + \$("#$useropts{table_id} tr th:nth-last-child($last_child{from})").html("FROM") ; + \$("#$useropts{table_id} tr th:nth-last-child($last_child{to})").html("TO") ; + \$('[data-toggle="tooltip"]').tooltip({ + container: 'body' + }); + ~ ; + + my $plus_poc = ($is_dcb_partner) ? 'POC' : qq~POC~ ; + + $trigger_jquery .= qq~ + \$("#$useropts{table_id} tr th:nth-last-child($last_child{poc})").html("$plus_poc") ; + ~ ; + + my $icon = qq~~ ; + + $trigger_jquery .= qq~ + \$("#$useropts{table_id}_wrapper").css("overflow","scroll"); + \$("#$useropts{table_id}_wrapper").css("height","60vh"); + // \$("#$useropts{table_id}_wrapper").css("overflow-y","hidden"); + \$("#$useropts{table_id}").css("width","175%") ; + \$("#$useropts{table_id}").css("max-width","175%"); + \$("#$useropts{table_id} tr th").slice(-3, -1).css("width","0%"); + \$("#$useropts{table_id} tr th:nth-last-child(1)").css("width","0%"); + ~ ; + + # if ($from_to eq 'to') { + + # $icon = qq~~ ; + + # $trigger_jquery .= qq~ + # \$("#$useropts{table_id} tr th:nth-last-child(3)").html("$icon") ; + # \$("#$useropts{table_id} tr th:nth-last-child(3) .glyphicons-disk-open").tooltip(); + # ~ ; + + # $trigger_jquery .= qq~ + # \$("#$useropts{table_id} tr th").slice(-7, -3).css("width","7.5%"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{item})").css("width","13%"); + # \$("#$useropts{table_id} tr th").slice(-15, -10).css("width","7.5%"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_time})").css("width","4%"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_date})").css("width","4.5%"); + # ~ ; + + # $icon = qq~~ ; + + # } else { + + # $icon = qq~~ ; + # $icon = qq~~ ; + + # $trigger_jquery .= qq~ + # \$("#$useropts{table_id} tr th:nth-last-child(3)").html("$icon") ; + # \$("#$useropts{table_id} tr th:nth-last-child(3) .glyphicons-disk-save").tooltip(); + # ~ ; + + # foreach (keys %last_child) { $trigger_jquery .= qq~\$("#$useropts{table_id} tr th:nth-last-child($last_child{$_})").css("width","7.5%");~ ; } + + $trigger_jquery .= qq~ + \$("#$useropts{table_id} tr th:nth-last-child($last_child{other_from})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{other_to})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{system})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{from})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{to})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{supplier})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{poc})").css("width","7%"); + // \$("#$useropts{table_id} tr th:nth-last-child($last_child{item})").css("width","16%"); + // \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_time})").css("width","4%"); + // \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_date})").css("width","4.5%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{special_instructions})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{other_special_instructions})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{waybill_nr})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{status})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{received_by})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{dcb_comments})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{shipment_operator})").css("width","7%"); + ~ ; + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{other_from})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{other_to})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{system})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{from})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{to})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{supplier})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{poc})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{item})").css("min-width","320px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{item})").css("max-width","320px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_time})").css("min-width","105px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_time})").css("max-width","105px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_date})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_date})").css("max-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{special_instructions})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{other_special_instructions})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{waybill_nr})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{status})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{received_by})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{dcb_comments})").css("min-width","120px"); + # ~ ; + + # $icon = qq~~ ; + # } + + # $icon = ($from_to eq 'from') ? qq~~ : qq~~ ; + + $icon = qq~~ ; + + $trigger_jquery .= qq~ + \$("#$useropts{table_id} tr th:nth-last-child(2)").html("$icon").trigger("chosen:updated") ; + \$("#$useropts{table_id} tr th:nth-last-child(2) .glyphicons-disk-open").tooltip(); + ~ ; + + $icon = qq~~ ; + + $trigger_jquery .= qq~ + \$("#$useropts{table_id} tr th:nth-last-child(1)").html("$icon") ; + \$("#$useropts{table_id} tr th:nth-last-child(1) .glyphicons-ok").tooltip() ; + ~ ; + + chop $quote_and_ops_ids if $quote_and_ops_ids ; + + $trigger_jquery_raw .= qq~ + function selectAll(col) { + + let from_to = \$("#from_to").text() ; + let col_id = "" ; + if (col == '1') { + col_id = "create_waybill_out_" ; + } else if (col == '2') { + col_id = "create_waybill_in_" ; + } + // else if (col == '3') { + // col_id = "process_complete_from_" ; + // } else if (col == '4') { + // col_id = "process_complete_to_" ; + // } + let jsObject = { + $quote_and_ops_ids + }; + for (let key in jsObject) { + let event_id = key ; + \$(\$("#$useropts{table_id}").dataTable().fnGetNodes()).find(\$("input[name='"+col_id+""+event_id+"']")).each(function () { + if(!\$(this).is(':checked')) { + \$(this).prop('checked',true); + } else { + \$(this).prop('checked',false); + } + }) ; + } + } + ~ ; + + $trigger_jquery .= qq~ + \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_date})").html("DELIVERY DATE BY") ; + // \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_date})").html("$icon") ; + // \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_date}) .glyphicons-calendar").tooltip() ; + ~ ; + + $trigger_jquery .= qq~ + \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_time})").html("DELIVERY TIME BY") ; + // \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_time})").html("$icon") ; + // \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_time}) .glyphicon-time").tooltip() ; + ~ ; + +} #------------------------------------------------------------------------------------------ + +1 ; \ No newline at end of file diff --git a/libs/modules/_FromProd/mailsend.pm b/libs/modules/_FromProd/mailsend.pm new file mode 100644 index 0000000..aa58a37 --- /dev/null +++ b/libs/modules/_FromProd/mailsend.pm @@ -0,0 +1,89 @@ +sub mailsend { + +my ($from,$to,$subject,$emailmsg) = @_ ; + +use Mail::Sendmail; + +#------------------------------------------------------------------------------- + +my $boundary = "====" . time() . "===="; + +#--------------------------------------------------------------------------------- + +my %mail = () ; + +# if ($username eq 'rory') { $to = 'rory@kre8it.co.za' ; } + +unless ($from) { $from = qq(Film Freight ) ; } +# unless ($from) { $from = 'Film Freight ' ; } + +%mail = ( + smtp => 'localhost', + From => $from, + To => $to, + Subject => $subject + ); + +#--------------------------------------------------------------------------------- + +$mail{'content-type'} = "multipart/alternative; boundary=\"$boundary\""; + +# filmfreight + + +$boundary = '--'.$boundary; + +$mail{body} = < + + + + + + +

    + +

    +

    +$emailmsg +

    + + + +$boundary-- + +END_OF_BODY + +sendmail(%mail) ; + +# $mail{'content-type'} = "multipart/mixed; boundary=\"$boundary\""; + +# $boundary = '--'.$boundary; + +# $mail{body} = < +# +# +# $subject +# +# +# $email_msg +# +# + +# $boundary-- + +# END_OF_BODY + +# sendmail(%mail) ; + +} #------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/_FromProd/match_event_production_time.pm b/libs/modules/_FromProd/match_event_production_time.pm new file mode 100644 index 0000000..9f934c6 --- /dev/null +++ b/libs/modules/_FromProd/match_event_production_time.pm @@ -0,0 +1,603 @@ +sub read_db_to_match_events_and_systems { + + &common_date_array($last_start_ccyymmdd,$last_end_ccyymmdd); + + &db_min_ro('event_systems','id,name,description,system_type','','','') ; + foreach my $id (keys %{$db{event_systems}}) { + $event_system_description{$id} = $db{event_systems}{$id}{description} ; + $event_system_name{$id} = $db{event_systems}{$id}{name} ; + } + + $start_sql = substr($start_sql,0,11) . '00:00:00' ; + $end_sql = substr($end_sql,0,11) . '23:59:59' ; + + # &db_min_ro('event_quotes','id,ref,event_system_id_multiple,format_of_title,date_from,date_to',"(date_from BETWEEN '$start_sql' AND '$end_sql') OR (date_to BETWEEN '$start_sql' AND '$end_sql')",'','') ; + + &db_min_ro('event_quotes','id,ref,event_system_id_multiple,format_of_title,date_from,date_to,sport_type_ids,club_ids',"((date_from BETWEEN '$start_sql' AND '$end_sql') OR (date_to BETWEEN '$start_sql' AND '$end_sql')) AND event_system_id_multiple IS NOT NULL AND event_system_id_multiple <> ''",'','') ; + + our %seen_event_system_in_event_quotes = () ; + + foreach my $event_id (keys %{$db{event_quotes}}) { + + $db{event_quotes}{$event_id}{ref} =~ s/\'//g ; + + $db{event_quotes}{$event_id}{event_system_id_multiple} =~ s/;+/;/g; # Replace multiple semicolons with one + $db{event_quotes}{$event_id}{event_system_id_multiple} =~ s/^;+|;+$//g; # Remove leading or trailing semicolons + + # next unless $db{event_quotes}{$event_id}{event_system_id_multiple} ; + + $opts{matched_event} .= qq~~ ; + + foreach (split(";",$db{event_quotes}{$event_id}{event_system_id_multiple})) { + + # $opts{matched_system} .= $seen_event_system_in_event_quotes{$_} + $seen_event_system_in_event_quotes{$_} = 1 ; + + } + } + + foreach (sort {$seen_event_system_in_event_quotes{$a} cmp $seen_event_system_in_event_quotes{$b}} keys %seen_event_system_in_event_quotes) { + $opts{matched_system} .= qq~~ ; + } + + $opts{matched_system_none} .= qq~~ ; + + &db_min_ro('sport_types','*','','','') ; + + our %sport_name_to_id = () ; + + foreach (keys %{$db{sport_types}}) { + $db{sport_types}{$_}{name} = lc $db{sport_types}{$_}{name} ; + $db{sport_types}{$_}{name} =~ s/ //g ; + $sport_name_to_id{$db{sport_types}{$_}{name}} = $_ ; + } + + &db_min_ro('clubs','id,name','','','') ; + + foreach (keys %{$db{clubs}}) { + my $c_name = lc $db{clubs}{$_}{name} ; + $c_name =~ s/\'//g ; + $club_name_to_id{$c_name} = $_ ; + } + + # foreach my $id (keys %{$db{event_quotes}}) { + # # $match_bank_trans{$db{event_quotes}{$id}{trans_date}}{$db{event_quotes}{$id}{description}} = 1 ; + + # foreach my $event_id (split(";",$db{$tables}{$id}{event_system_id_multiple})) { + # $val .= qq~$db{event_systems}{$event_id}{name} [$db{event_systems}{$event_id}{description}], ~ ; + # } + # } + +} #------------------------------------------------------------------------------------------ + +sub process_matched_events_and_systems { + + my %system_match = () ; my %matched_event_name = () ; my %csv_line_possible_match = () ; my %matched_events = () ; + + $system_match{"None"}{"None"} = -1 ; + + foreach my $event_code (keys %csv_line) { + + next if $matched_event{$event_code} ; + + my ($club_name,$system_desc_clue) = split("-",$csv_line{$event_code}{club_name}) ; + $club_name =~ s/ $//g ; $system_desc_clue =~ s/^ //g ; # remove whitespace + $club_name =~ s/\'//g ; + + $system_desc_clue = "None" unless $system_desc_clue ; + + my @eventdetails = split(/ /,$club_name) ; + + my $system_name_clue = $eventdetails[-1] ; $system_name_clue = "None" if $system_name_clue !~ /\d+/ ; + + if ($system_desc_clue =~ /\d+/ && length($system_desc_clue) == 5) { + $system_name_clue = $system_desc_clue ; + $system_desc_clue = 'None' ; + } + + if ($system_desc_clue =~ /AISA/ && $system_desc_clue =~ /SOLO/) { + my @sysparts = split(/\_/,$system_desc_clue) ; + $system_name_clue = $sysparts[2] ; + $system_desc_clue =~ s/\_/ /g ; + } + + $csv_line{$event_code}{system_id} = -1 if $system_name_clue eq 'None' && $system_desc_clue eq 'None' ; + + $system_desc_clue = lc $system_desc_clue ; + + $csv_line{$event_code}{system_id} = $system_match{$system_name_clue}{$system_desc_clue} if $system_match{$system_name_clue}{$system_desc_clue} ; + + if (!$csv_line{$event_code}{system_id}) { + + foreach my $system_id (keys %{$db{event_systems}}) { + # foreach my $system_id (keys %seen_event_system_in_event_quotes) { + + my $sys_desc = lc $db{event_systems}{$system_id}{description} ; + my $sys_name = $db{event_systems}{$system_id}{name} ; + + if (($sys_name =~ /\b$system_name_clue\b/ || $sys_name =~ /_$system_name_clue\b/) && $sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue ne 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + last ; + } elsif (($sys_name =~ /\b$system_name_clue\b/ || $sys_name =~ /_$system_name_clue\b/) && $system_name_clue ne 'None' && $system_desc_clue eq 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + last ; + } elsif ($sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue eq 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + last ; + } + } + } + + my @sport_split = split(":",$csv_line{$event_code}{event_name}) ; + + $sport_split[0] =~ s/ //g ; + $sport_split[0] = lc $sport_split[0] ; + + my $sport_id = ($csv_line{$event_code}{event_name} =~ /:/) ? $sport_name_to_id{$sport_split[0]} : '' ; + + my @event_name_details = split(/-/,$csv_line{$event_code}{event_name}) ; + + my $to_match_event_name = $event_name_details[-1] ; + + $to_match_event_name =~ s/^ //g ; + $to_match_event_name =~ s/ $//g ; + + $to_match_event_name = ($csv_line{$event_code}{event_name} =~ /:/ && $csv_line{$event_code}{event_name} !~ /-/) ? $sport_split[1] : $to_match_event_name ; + + $to_match_event_name =~ s/\'//g ; + + my $club_id = $club_name_to_id{$club_name} ; + + $club_name = ($csv_line{$event_code}{club_name} =~ /AISA/ && $csv_line{$event_code}{club_name} =~ /SOLO/) ? lc $club_name : lc $csv_line{$event_code}{club_name} ; + + if (!$csv_line{$event_code}{system_id}) { + + foreach my $id (keys %{$db{event_quotes}}) { + + next unless $id ; + + next if $sport_id && $db{event_quotes}{$id}{sport_type_ids} !~ /\b$sport_id\b/ ; + + next if $club_id && $db{event_quotes}{$id}{club_ids} !~ /\b$club_id\b/ ; + + next if !$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ ; + + my $event_end = substr($db{event_quotes}{$id}{date_to},0,11) . '23:59:59' ; + + my $event_start = substr($db{event_quotes}{$id}{date_from},0,11) . '00:00:00' ; + + my $after_event_end = &greater_date_time($event_end,$csv_line{$event_code}{start_time}) ; + next if $after_event_end ; + + my $before_event_start = &greater_date_time($csv_line{$event_code}{end_time},$event_start) ; + next if $before_event_start ; + + if ($to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + $csv_line{$event_code}{event_id} = $id ; + $matched_events{$event_code} .= qq~$id;~ ; + } + + my $found_match = 0 ; + + foreach my $system_id (split(";",$db{event_quotes}{$id}{event_system_id_multiple})) { + + my $sys_desc = lc $db{event_systems}{$system_id}{description} ; + my $sys_name = $db{event_systems}{$system_id}{name} ; + + if ($sys_name =~ /\b$system_name_clue\b/ && $sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue ne 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + } elsif ($sys_name =~ /\b$system_name_clue\b/ && $system_name_clue ne 'None' && $system_desc_clue eq 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + } elsif ($sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue eq 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + } + + # my $sys_desc = $db{event_systems}{$system_id}{description} ; + # my $sys_name = $db{event_systems}{$system_id}{name} ; + + # # my @sysparts = split(/\_/,$system) ; + + # if ($sys_name =~ /\b$sysno\b/ && $sys_desc =~ /\b$system\b/iog) { + # $csv_line{$event_code}{system_id} = $system_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } elsif ($system =~ /\d+/ && $sys_name =~ /\b$system\b/) { + # $csv_line{$event_code}{system_id} = $system_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } elsif ($system =~ /AISA/ && $system =~ /SOLO/ && $sysparts[2] && $sys_name =~ /\b$sysparts[2]\b/) { + # $csv_line{$event_code}{system_id} = $system_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } elsif ($sys_desc eq 'St Stithians Hockey Red' && $clubname =~ /Red/i && $clubname =~ /Stithians/i) { + # $csv_line{$event_code}{system_id} = $event_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } + } + + if ($found_match && !$csv_line{$event_code}{event_id}) { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + } + } + + if ($csv_line{$event_code}{system_id} && !$csv_line{$event_code}{event_id}) { + + foreach my $id (keys %{$db{event_quotes}}) { + + next if $sport_id && $db{event_quotes}{$id}{sport_type_ids} && $db{event_quotes}{$id}{sport_type_ids} !~ /\b$sport_id\b/ ; + + next if $club_id && $db{event_quotes}{$id}{club_ids} !~ /\b$club_id\b/ ; + + my $event_end = substr($db{event_quotes}{$id}{date_to},0,11) . '23:59:59' ; + + my $event_start = substr($db{event_quotes}{$id}{date_from},0,11) . '00:00:00' ; + + my $after_event_end = &greater_date_time($event_end,$csv_line{$event_code}{start_time}) ; + next if $after_event_end ; + + my $before_event_start = &greater_date_time($csv_line{$event_code}{end_time},$event_start) ; + next if $before_event_start ; + + if (!$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\b$csv_line{$event_code}{system_id}\b/) { + if ($csv_line{$event_code}{system_id} && !$seen_event_system_in_event_quotes{$csv_line{$event_code}{system_id}}) { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + next ; + } + + # if ($to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + if ($db{event_quotes}{$id}{sport_type_ids} && $to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } elsif ($db{event_quotes}{$id}{sport_type_ids}) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } else { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + } + } + + if ((!$csv_line{$event_code}{system_id}) && !$csv_line{$event_code}{event_id}) { + + foreach my $id (keys %{$db{event_quotes}}) { + + next if $sport_id && $db{event_quotes}{$id}{sport_type_ids} && $db{event_quotes}{$id}{sport_type_ids} !~ /\b$sport_id\b/ ; + + next if $club_id && $db{event_quotes}{$id}{club_ids} !~ /\b$club_id\b/ ; + + next if !$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ ; + + my $event_end = substr($db{event_quotes}{$id}{date_to},0,11) . '23:59:59' ; + + my $event_start = substr($db{event_quotes}{$id}{date_from},0,11) . '00:00:00' ; + + my $after_event_end = &greater_date_time($event_end,$csv_line{$event_code}{start_time}) ; + next if $after_event_end ; + + my $before_event_start = &greater_date_time($csv_line{$event_code}{end_time},$event_start) ; + next if $before_event_start ; + + # if (!$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\b$csv_line{$event_code}{system_id}\b/) { + # if ($csv_line{$event_code}{system_id} && !$seen_event_system_in_event_quotes{$csv_line{$event_code}{system_id}}) { + # $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + # } + # next ; + # } + + if ($db{event_quotes}{$id}{sport_type_ids} && $to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } elsif ($db{event_quotes}{$id}{sport_type_ids}) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } else { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + } + } + + chop $csv_line_possible_match{$event_code}{event_id} if $csv_line_possible_match{$event_code}{event_id} ; + + } + + $print_box_content_rows .= &common_min_forms_start("$lcpage") ; + + our @sql_col_display = ("club_system","system_nr","matched_system","production_hours","production_seconds","cloud_recording_seconds","club_name","start","end","event_name","matched_event","match") ; + + my $row_cnt = 0 ; my %no_system_or_event = () ; + + foreach my $event_code (sort {$csv_line{$a}{line_cnt} cmp $csv_line{$b}{line_cnt}} keys %csv_line) { + + next if $matched_event{$event_code} ; + + $row_cnt++ ; + + $print_tbody .= qq~~ ; + + my $cell_id = qq~~ ; + + my ($system,$sysno) = split(" - ",$csv_line{$event_code}{club_name}) ; + + my @get_sport = (!$csv_line{$event_code}{system_id} || (!$csv_line{$event_code}{event_id} && !$csv_line_possible_match{$event_code}{event_id}) || (!$csv_line{$event_code}{event_id} && $csv_line_possible_match{$event_code}{event_id} =~ /;/)) ? split(/\:/,$csv_line{$event_code}{event_name}) : () ; + + $extra_form_fields .= qq~~ if !$csv_line{$event_code}{system_id} || !$csv_line{$event_code}{event_id} ; + + foreach my $col (@sql_col_display) { + + my $val = '' ; $nowrap = '' ; + + if ($col eq 'club_name') { + $val = $csv_line{$event_code}{club_name} ; + } elsif ($col eq 'system_nr') { + $val = $sysno ; + } elsif ($col eq 'start') { + $val = $csv_line{$event_code}{start_time} ; + $nowrap = 'nowrap' ; + } elsif ($col eq 'end') { + $val = $csv_line{$event_code}{end_time} ; + $nowrap = 'nowrap' ; + } elsif ($col eq 'club_system') { + $val = $system ; + } elsif ($col eq 'matched_system') { + + $preferred_placeholder{"system_$row_cnt"} = "Select System" ; + + $found_system_drop_down = 1 if !$csv_line{$event_code}{system_id} || $csv_line{$event_code}{system_id} eq '-1' ; + + # $allow_deselect{"system_$row_cnt"} = 1 ; + + $val = ($csv_line{$event_code}{system_id} && $csv_line{$event_code}{system_id} ne '-1') ? "$db{event_systems}{$csv_line{$event_code}{system_id}}{name} [$db{event_systems}{$csv_line{$event_code}{system_id}}{description}]" : ($csv_line{$event_code}{system_id} eq '-1') ? &common_min_table_select("system_$row_cnt","",'','','','','',"matched_system_none") : &common_min_table_select("system_$row_cnt","",'','','','','',"matched_system") ; + # $val = ($csv_line{$event_code}{system_id} && $csv_line{$event_code}{system_id} ne '-1') ? "$db{event_systems}{$csv_line{$event_code}{system_id}}{name} [$db{event_systems}{$csv_line{$event_code}{system_id}}{description}]" : &common_min_table_select("system_$row_cnt","",'','','','','',"matched_system") ; + + if (!$csv_line{$event_code}{system_id} || $csv_line{$event_code}{system_id} eq '-1') { + + my $sport_name = ($csv_line{$event_code}{event_name} =~ /:/) ? $get_sport[0] : $csv_line{$event_code}{event_name} ; + $no_system_or_event{$csv_line{$event_code}{club_name}}{substr($csv_line{$event_code}{start_time},0,10)}{$sport_name}{system} .= qq~"#selectSystem_$row_cnt",~ ; + + } + + $cell_id = qq~id="matched_system_$row_cnt"~ ; + + } elsif ($col eq 'production_hours') { + $val = $csv_line{$event_code}{production_hours} ; + $val =~ s/\,/\./g ; + } elsif ($col eq 'production_seconds') { + $val = &common_commify($csv_line{$event_code}{production_seconds}) ; + } elsif ($col eq 'cloud_recording_seconds') { + $val = &common_commify($csv_line{$event_code}{cloud_seconds}) ; + } elsif ($col eq 'event_name') { + $val = $csv_line{$event_code}{event_name} ; + } elsif ($col eq 'matched_event') { + + $csv_line_possible_match{$event_code}{event_id} =~ s/\;/\_/g ; + + my $col_name = (!$csv_line{$event_code}{event_id} && $csv_line_possible_match{$event_code}{event_id}) ? "matched_event_$csv_line_possible_match{$event_code}{event_id}" : "matched_event" ; + + $opts{$col_name} = + ($csv_line_possible_match{$event_code}{event_id} && !$csv_line{$event_code}{event_id}) ? join "~ ; + + foreach (split(";",$db{event_quotes}{$event_id}{event_system_id_multiple})) { + + # $opts{matched_system} .= $seen_event_system_in_event_quotes{$_} + $seen_event_system_in_event_quotes{$_} = 1 ; + + } + } + + foreach (sort {$seen_event_system_in_event_quotes{$a} cmp $seen_event_system_in_event_quotes{$b}} keys %seen_event_system_in_event_quotes) { + $opts{matched_system} .= qq~~ ; + } + + $opts{matched_system_none} .= qq~~ ; + + &db_min_ro('sport_types','*','','','') ; + + our %sport_name_to_id = () ; + + foreach (keys %{$db{sport_types}}) { + $db{sport_types}{$_}{name} = lc $db{sport_types}{$_}{name} ; + $db{sport_types}{$_}{name} =~ s/ //g ; + $sport_name_to_id{$db{sport_types}{$_}{name}} = $_ ; + } + + &db_min_ro('clubs','id,name','','','') ; + + foreach (keys %{$db{clubs}}) { + my $c_name = lc $db{clubs}{$_}{name} ; + $c_name =~ s/\'//g ; + $club_name_to_id{$c_name} = $_ ; + } + + # foreach my $id (keys %{$db{event_quotes}}) { + # # $match_bank_trans{$db{event_quotes}{$id}{trans_date}}{$db{event_quotes}{$id}{description}} = 1 ; + + # foreach my $event_id (split(";",$db{$tables}{$id}{event_system_id_multiple})) { + # $val .= qq~$db{event_systems}{$event_id}{name} [$db{event_systems}{$event_id}{description}], ~ ; + # } + # } + +} #------------------------------------------------------------------------------------------ + +sub production_time_process_matched_events_and_systems { + + my %system_match = () ; my %matched_event_name = () ; my %csv_line_possible_match = () ; my %matched_events = () ; + + $system_match{"None"}{"None"} = -1 ; + + foreach my $event_code (keys %csv_line) { + + next if $matched_event{$event_code} ; + + my ($club_name,$system_desc_clue) = split("-",$csv_line{$event_code}{club_name}) ; + $club_name =~ s/ $//g ; $system_desc_clue =~ s/^ //g ; # remove whitespace + $club_name =~ s/\'//g ; + + $system_desc_clue = "None" unless $system_desc_clue ; + + my @eventdetails = split(/ /,$club_name) ; + + my $system_name_clue = $eventdetails[-1] ; $system_name_clue = "None" if $system_name_clue !~ /\d+/ ; + + if ($system_desc_clue =~ /\d+/ && length($system_desc_clue) == 5) { + $system_name_clue = $system_desc_clue ; + $system_desc_clue = 'None' ; + } + + if ($system_desc_clue =~ /AISA/ && $system_desc_clue =~ /SOLO/) { + my @sysparts = split(/\_/,$system_desc_clue) ; + $system_name_clue = $sysparts[2] ; + $system_desc_clue =~ s/\_/ /g ; + } + + $csv_line{$event_code}{system_id} = -1 if $system_name_clue eq 'None' && $system_desc_clue eq 'None' ; + + $system_desc_clue = lc $system_desc_clue ; + + $csv_line{$event_code}{system_id} = $system_match{$system_name_clue}{$system_desc_clue} if $system_match{$system_name_clue}{$system_desc_clue} ; + + if (!$csv_line{$event_code}{system_id}) { + + foreach my $system_id (keys %{$db{event_systems}}) { + # foreach my $system_id (keys %seen_event_system_in_event_quotes) { + + my $sys_desc = lc $db{event_systems}{$system_id}{description} ; + my $sys_name = $db{event_systems}{$system_id}{name} ; + + if (($sys_name =~ /\b$system_name_clue\b/ || $sys_name =~ /_$system_name_clue\b/) && $sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue ne 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + last ; + } elsif (($sys_name =~ /\b$system_name_clue\b/ || $sys_name =~ /_$system_name_clue\b/) && $system_name_clue ne 'None' && $system_desc_clue eq 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + last ; + } elsif ($sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue eq 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + last ; + } + } + } + + my @sport_split = split(":",$csv_line{$event_code}{event_name}) ; + + $sport_split[0] =~ s/ //g ; + $sport_split[0] = lc $sport_split[0] ; + + my $sport_id = ($csv_line{$event_code}{event_name} =~ /:/) ? $sport_name_to_id{$sport_split[0]} : '' ; + + my @event_name_details = split(/-/,$csv_line{$event_code}{event_name}) ; + + my $to_match_event_name = $event_name_details[-1] ; + + $to_match_event_name =~ s/^ //g ; + $to_match_event_name =~ s/ $//g ; + + $to_match_event_name = ($csv_line{$event_code}{event_name} =~ /:/ && $csv_line{$event_code}{event_name} !~ /-/) ? $sport_split[1] : $to_match_event_name ; + + $to_match_event_name =~ s/\'//g ; + + my $club_id = $club_name_to_id{$club_name} ; + + $club_name = ($csv_line{$event_code}{club_name} =~ /AISA/ && $csv_line{$event_code}{club_name} =~ /SOLO/) ? lc $club_name : lc $csv_line{$event_code}{club_name} ; + + if (!$csv_line{$event_code}{system_id}) { + + foreach my $id (keys %{$db{event_quotes}}) { + + next unless $id ; + + next if $sport_id && $db{event_quotes}{$id}{sport_type_ids} !~ /\b$sport_id\b/ ; + + next if $club_id && $db{event_quotes}{$id}{club_ids} !~ /\b$club_id\b/ ; + + next if !$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ ; + + my $event_end = substr($db{event_quotes}{$id}{date_to},0,11) . '23:59:59' ; + + my $event_start = substr($db{event_quotes}{$id}{date_from},0,11) . '00:00:00' ; + + my $after_event_end = &greater_date_time($event_end,$csv_line{$event_code}{start_time}) ; + next if $after_event_end ; + + my $before_event_start = &greater_date_time($csv_line{$event_code}{end_time},$event_start) ; + next if $before_event_start ; + + if ($to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + $csv_line{$event_code}{event_id} = $id ; + $matched_events{$event_code} .= qq~$id;~ ; + } + + my $found_match = 0 ; + + foreach my $system_id (split(";",$db{event_quotes}{$id}{event_system_id_multiple})) { + + my $sys_desc = lc $db{event_systems}{$system_id}{description} ; + my $sys_name = $db{event_systems}{$system_id}{name} ; + + if ($sys_name =~ /\b$system_name_clue\b/ && $sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue ne 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + } elsif ($sys_name =~ /\b$system_name_clue\b/ && $system_name_clue ne 'None' && $system_desc_clue eq 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + } elsif ($sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue eq 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + } + + # my $sys_desc = $db{event_systems}{$system_id}{description} ; + # my $sys_name = $db{event_systems}{$system_id}{name} ; + + # # my @sysparts = split(/\_/,$system) ; + + # if ($sys_name =~ /\b$sysno\b/ && $sys_desc =~ /\b$system\b/iog) { + # $csv_line{$event_code}{system_id} = $system_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } elsif ($system =~ /\d+/ && $sys_name =~ /\b$system\b/) { + # $csv_line{$event_code}{system_id} = $system_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } elsif ($system =~ /AISA/ && $system =~ /SOLO/ && $sysparts[2] && $sys_name =~ /\b$sysparts[2]\b/) { + # $csv_line{$event_code}{system_id} = $system_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } elsif ($sys_desc eq 'St Stithians Hockey Red' && $clubname =~ /Red/i && $clubname =~ /Stithians/i) { + # $csv_line{$event_code}{system_id} = $event_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } + } + + if ($found_match && !$csv_line{$event_code}{event_id}) { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + } + } + + if ($csv_line{$event_code}{system_id} && !$csv_line{$event_code}{event_id}) { + + foreach my $id (keys %{$db{event_quotes}}) { + + next if $sport_id && $db{event_quotes}{$id}{sport_type_ids} && $db{event_quotes}{$id}{sport_type_ids} !~ /\b$sport_id\b/ ; + + next if $club_id && $db{event_quotes}{$id}{club_ids} !~ /\b$club_id\b/ ; + + my $event_end = substr($db{event_quotes}{$id}{date_to},0,11) . '23:59:59' ; + + my $event_start = substr($db{event_quotes}{$id}{date_from},0,11) . '00:00:00' ; + + my $after_event_end = &greater_date_time($event_end,$csv_line{$event_code}{start_time}) ; + next if $after_event_end ; + + my $before_event_start = &greater_date_time($csv_line{$event_code}{end_time},$event_start) ; + next if $before_event_start ; + + if (!$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\b$csv_line{$event_code}{system_id}\b/) { + if ($csv_line{$event_code}{system_id} && !$seen_event_system_in_event_quotes{$csv_line{$event_code}{system_id}}) { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + next ; + } + + # if ($to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + if ($db{event_quotes}{$id}{sport_type_ids} && $to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } elsif ($db{event_quotes}{$id}{sport_type_ids}) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } else { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + } + } + + if ((!$csv_line{$event_code}{system_id}) && !$csv_line{$event_code}{event_id}) { + + foreach my $id (keys %{$db{event_quotes}}) { + + next if $sport_id && $db{event_quotes}{$id}{sport_type_ids} && $db{event_quotes}{$id}{sport_type_ids} !~ /\b$sport_id\b/ ; + + next if $club_id && $db{event_quotes}{$id}{club_ids} !~ /\b$club_id\b/ ; + + next if !$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ ; + + my $event_end = substr($db{event_quotes}{$id}{date_to},0,11) . '23:59:59' ; + + my $event_start = substr($db{event_quotes}{$id}{date_from},0,11) . '00:00:00' ; + + my $after_event_end = &greater_date_time($event_end,$csv_line{$event_code}{start_time}) ; + next if $after_event_end ; + + my $before_event_start = &greater_date_time($csv_line{$event_code}{end_time},$event_start) ; + next if $before_event_start ; + + # if (!$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\b$csv_line{$event_code}{system_id}\b/) { + # if ($csv_line{$event_code}{system_id} && !$seen_event_system_in_event_quotes{$csv_line{$event_code}{system_id}}) { + # $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + # } + # next ; + # } + + if ($db{event_quotes}{$id}{sport_type_ids} && $to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } elsif ($db{event_quotes}{$id}{sport_type_ids}) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } else { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + } + } + + chop $csv_line_possible_match{$event_code}{event_id} if $csv_line_possible_match{$event_code}{event_id} ; + + } + + $print_box_content_rows .= &common_min_forms_start("$lcpage") ; + + our @sql_col_display = ("club_system","system_nr","matched_system","production_hours","production_seconds","cloud_recording_seconds","club_name","start","end","event_name","matched_event","match") ; + + my $row_cnt = 0 ; my %no_system_or_event = () ; + + foreach my $event_code (sort {$csv_line{$a}{line_cnt} cmp $csv_line{$b}{line_cnt}} keys %csv_line) { + + next if $matched_event{$event_code} ; + + $row_cnt++ ; + + $print_tbody .= qq~~ ; + + my $cell_id = qq~~ ; + + my ($system,$sysno) = split(" - ",$csv_line{$event_code}{club_name}) ; + + my @get_sport = (!$csv_line{$event_code}{system_id} || (!$csv_line{$event_code}{event_id} && !$csv_line_possible_match{$event_code}{event_id}) || (!$csv_line{$event_code}{event_id} && $csv_line_possible_match{$event_code}{event_id} =~ /;/)) ? split(/\:/,$csv_line{$event_code}{event_name}) : () ; + + $extra_form_fields .= qq~~ if !$csv_line{$event_code}{system_id} || !$csv_line{$event_code}{event_id} ; + + foreach my $col (@sql_col_display) { + + my $val = '' ; $nowrap = '' ; + + if ($col eq 'club_name') { + $val = $csv_line{$event_code}{club_name} ; + } elsif ($col eq 'system_nr') { + $val = $sysno ; + } elsif ($col eq 'start') { + $val = $csv_line{$event_code}{start_time} ; + $nowrap = 'nowrap' ; + } elsif ($col eq 'end') { + $val = $csv_line{$event_code}{end_time} ; + $nowrap = 'nowrap' ; + } elsif ($col eq 'club_system') { + $val = $system ; + } elsif ($col eq 'matched_system') { + + $preferred_placeholder{"system_$row_cnt"} = "Select System" ; + + $found_system_drop_down = 1 if !$csv_line{$event_code}{system_id} || $csv_line{$event_code}{system_id} eq '-1' ; + + # $allow_deselect{"system_$row_cnt"} = 1 ; + + $val = ($csv_line{$event_code}{system_id} && $csv_line{$event_code}{system_id} ne '-1') ? "$db{event_systems}{$csv_line{$event_code}{system_id}}{name} [$db{event_systems}{$csv_line{$event_code}{system_id}}{description}]" : ($csv_line{$event_code}{system_id} eq '-1') ? &common_min_table_select("system_$row_cnt","",'','','','','',"matched_system_none") : &common_min_table_select("system_$row_cnt","",'','','','','',"matched_system") ; + # $val = ($csv_line{$event_code}{system_id} && $csv_line{$event_code}{system_id} ne '-1') ? "$db{event_systems}{$csv_line{$event_code}{system_id}}{name} [$db{event_systems}{$csv_line{$event_code}{system_id}}{description}]" : &common_min_table_select("system_$row_cnt","",'','','','','',"matched_system") ; + + if (!$csv_line{$event_code}{system_id} || $csv_line{$event_code}{system_id} eq '-1') { + + my $sport_name = ($csv_line{$event_code}{event_name} =~ /:/) ? $get_sport[0] : $csv_line{$event_code}{event_name} ; + $no_system_or_event{$csv_line{$event_code}{club_name}}{substr($csv_line{$event_code}{start_time},0,10)}{$sport_name}{system} .= qq~"#selectSystem_$row_cnt",~ ; + + } + + $cell_id = qq~id="matched_system_$row_cnt"~ ; + + } elsif ($col eq 'production_hours') { + $val = $csv_line{$event_code}{production_hours} ; + $val =~ s/\,/\./g ; + } elsif ($col eq 'production_seconds') { + $val = &common_commify($csv_line{$event_code}{production_seconds}) ; + } elsif ($col eq 'cloud_recording_seconds') { + $val = &common_commify($csv_line{$event_code}{cloud_seconds}) ; + } elsif ($col eq 'event_name') { + $val = $csv_line{$event_code}{event_name} ; + } elsif ($col eq 'matched_event') { + + $csv_line_possible_match{$event_code}{event_id} =~ s/\;/\_/g ; + + my $col_name = (!$csv_line{$event_code}{event_id} && $csv_line_possible_match{$event_code}{event_id}) ? "matched_event_$csv_line_possible_match{$event_code}{event_id}" : "matched_event" ; + + $opts{$col_name} = + ($csv_line_possible_match{$event_code}{event_id} && !$csv_line{$event_code}{event_id}) ? join "~ ; + # $opts{head_operator} .= qq~~ ; + foreach my $_uid (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + next if $useropts{it}{$db{users}{$_uid}{username}} ; + + my $regions = qq~~ ; + foreach (split(/\,/,$db{users}{$_uid}{region_ids})) { + $regions .= qq~$db{regions}{$_}{code},~ ; + } + chop $regions if $regions ; + $regions = qq~[$regions]~ if $regions ; + + # if ($db{users}{$_uid}{user_type} eq 'support' || $db{users}{$_uid}{user_type} eq 'manager' || $db{users}{$_uid}{user_type} eq 'casual_calibrator' || $monitoring_report) { + if ($db{users}{$_uid}{user_type} eq 'casual_calibrator' || (($monitoring_report || $troubleshoot_monitoring_report) && $db{users}{$_uid}{user_type} ne 'casual_c' && $db{users}{$_uid}{user_type} ne 'schools_manager' && $db{users}{$_uid}{user_type} ne 'support' && $db{users}{$_uid}{user_type} ne 'permanent')) { + $opts{schedule_users} .= qq~~ ; + } + + if (($db{users}{$_uid}{user_type} eq 'support' || $db{users}{$_uid}{user_type} eq 'casual_calibrator') && $temp_calibrator_report) { + $opts{support_users} .= qq~~ ; + $tot_support_users_cnt++; + } + + if ($db{users}{$_uid}{user_type} eq 'casual_c') { + $opts{fixture_check} .= qq~~ ; + } + } + + my $event_systems_sql_where = ($monitoring_report || $troubleshoot_monitoring_report) ? "" : "system_type = 'mobile'" ; + + &db_min_ro('event_systems','*',$event_systems_sql_where,'','') ; + + &db_min_ro($table,"id,club_ids,qty,ref,organisation_ids,quote_accepted,event_system_id_multiple,region_id,sport_type_ids,operator_ids,date_from,date_to,times_from,times_to,daily_operator_ids,days_active,monitor_ids,temp_calibrator_ids$extra_column","$where AND `quote_accepted` = '1'",'','') ; + + my $min_id = 0 ; my $max_id = 0 ; + + foreach my $id (keys %{$db{$table}}) { + + next unless $id ; my $cnt = 0 ; + + my @ed_from = &common_split_sql_time($db{$table}{$id}{date_from}) ; + my @ed_to = &common_split_sql_time($db{$table}{$id}{date_to}) ; + + &common_date_array("$ed_from[0]$ed_from[1]$ed_from[2]","$ed_to[0]$ed_to[1]$ed_to[2]") ; + + $sort_calibration_by_time_ref{"$ed_from[0]$ed_from[1]$ed_from[2]$ed_from[3]$ed_from[4]-$id"} = $id ; + + } + + &db_min_ro('sport_types','*','','','') ; + &db_min_ro('organisations','id,name','','','') ; + &db_min_ro('clubs','id,name','','','') if $monitoring_report || $troubleshoot_monitoring_report ; + + our $table_ = "shift_operator_ids" ; + my $col_ = ($monitoring_report) ? "monitor_ids" : ($troubleshoot_monitoring_report) ? "troubleshoot_monitor_ids" : "temp_calibrator_ids,temp_calibrator_support_shifts" ; + my $col2_ = ($monitoring_report) ? ",monitor_notes" : ($troubleshoot_monitoring_report) ? ",troubleshoot_monitor_notes" : "" ; + + &db_min_ro($table_,"date$col2_,$col_","`date` >= '$i{date_from}' AND `date` <= '$i{date_to}'") ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_build_extra_table { + + my ($field_name,$table_name,$table_col_name,$table_col_name_notes,$table_id) = @_ ; + + my $ws2 = join ' ', map { ucfirst $_ } split /_/, $field_name ; + $ws2 .= "s" ; + + &xlsxcreator_add_worksheet($ws2) ; + + my $col2 = 0 ; + foreach (@sql_col_display_extra) { + next if $_ eq "update" || !$_ || $_ eq 'notes' ; + my $coltitle = $_ ; + $coltitle =~ s/\_id//g ; + $coltitle =~ s/\_/ /g ; + my $ucfirst = join '', map { ucfirst lc } split /(\s+)/, $coltitle; + &xlsxcreator_write_xlsx($ws2,0,$col2,$ucfirst,$format_management_report_headings) ; + $col2++; + } + $col2=0 ; + &xlsxcreator_freeze_panes($ws2,1,0) ; # Freeze the first 3 rows + + my $uc_field_name = ucfirst $field_name ; + + # $db{$table_name}{$i{date}}{$table_col_name} = qq~147;132|||~ ; + + # for (0 .. 3) { $schedule_ids[$_] = "null" unless $schedule_ids[$_] ; } + $format84 -> set_left('1') ; + + my ($s_year,$s_mon,$s_day) = split("-",$i{date_from}) ; + my ($e_year,$e_mon,$e_day) = split("-",$i{date_to}) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + + our $date_cnt = 1 ; my $row_cnt = 0 ; + + return if int("$s_year$s_mon$s_day") > int("$e_year$e_mon$e_day") ; + + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + my %row_cnt_shifts = () ; my $max_row_cnt = 0 ; + + while (int("$s_year$s_mon$s_day") <= int("$e_year$e_mon$e_day")) { + + $db{$table_name}{"$s_year-$s_mon-$s_day"}{$table_col_name} =~ s/\;/\,/g ; + my @schedule_ids = split(/\|/,$db{$table_name}{"$s_year-$s_mon-$s_day"}{$table_col_name}) ; + + my $date = "$s_year-$s_mon-$s_day" ; + + my $date_str = &common_min_date_as_string($date) ; + + our $default_javascript = "" ; my %default_javascript_short = () ; + + my $val_notes = qq~~ ; + + foreach my $col (@sql_col_display_extra) { + + my $formatting = $format92 ; + next if substr($col,0,5) eq 'shift' && substr($col,0,7) ne 'shift_1' ; + my $val = '' ; my $nowrap = '' ; my $align = qq~~ ; my $val_min = "" ; + + my $row_span = '' ; + + if ($col eq 'date') { + + $row_cnt++ ; + $row_span = qq~rowspan="2"~ if $monitoring_report || $troubleshoot_monitoring_report ; + $val = $date_str . qq~~ ; + $nowrap = "nowrap" ; + &xlsxcreator_write_xlsx($ws2,$max_row_cnt+1,0,$date_str ,$formatting) ; + + } elsif (substr($col,0,7) eq 'shift_1') { + + $align = qq~ class="dt-center"~ ; + + local $place_holder = substr($ws2,0,-1) ; + + for (1 .. 4) { + $row_cnt_shifts{$_} = $max_row_cnt + 1 ; + } + + for my $shift_cnt (1 .. 4) { + + # $row_cnt_shifts{$shift_cnt} = ($max_row_cnt && $shift_cnt == 1) ? $max_row_cnt + 1 : 1 ; + my $field = "$field_name\_$shift_cnt\_1_1_$date_cnt" ; + $opts{$field} = $opts{schedule_users} ; + $preferred_placeholder{$field} = ($troubleshoot_monitoring_report) ? "Shift Troubleshoot Monitor $shift_cnt $date_cnt" : "$place_holder $shift_cnt $date_cnt" ; + $multiple{$field} = 1 ; + + my $table_col = 6-$shift_cnt ; + push @first_table_multi_select_table_cells,"#$table_id tr:eq($row_cnt) td:nth-last-child($table_col)" ; + + $val .= &common_min_table_select($field,$schedule_ids[$shift_cnt - 1],'',$row_cnt,$table_col,'',$schedule_ids[$shift_cnt - 1],'shift',$table_id) ; + foreach (split(/\,/,$schedule_ids[$shift_cnt - 1])) { + next unless $_ ; + $trigger_jquery_raw .= qq~\$("#select$uc_field_name\_$shift_cnt\_1_1_$date_cnt option[value='$_']").prop("selected",true);~ ; + &xlsxcreator_write_xlsx($ws2,$row_cnt_shifts{$shift_cnt},$shift_cnt,"$db{users}{$_}{name}",$formatting) ; + $row_cnt_shifts{$shift_cnt}++ ; + } + $max_row_cnt = $row_cnt_shifts{$shift_cnt} if !$max_row_cnt || $max_row_cnt < $row_cnt_shifts{$shift_cnt} ; + $val .= qq~~ if $shift_cnt < 4 ; + } + + } elsif ($col eq 'notes') { + + $row_cnt++ ; + + my @notes = split(/\:\|\:/,$db{$table_name}{$date}{$table_col_name_notes}) ; + # $max_row_cnt-- ; + # $max_row_cnt++ if $db{$table_name}{$date}{$table_col_name_notes} =~ /(\d+)/g || $db{$table_name}{$date}{$table_col_name_notes} =~ /[a-zA-Z]/ ; + + for my $shift_cnt (1 .. 4) { + + my $field = "$field_name\_notes_$shift_cnt\_1_1_$date_cnt" ; + $preferred_placeholder{$field} = ($troubleshoot_monitoring_report) ? "Shift Troubleshoot Monitor Notes $shift_cnt $date_cnt" : "Shift Monitor Notes $shift_cnt $date_cnt" ; + $val_notes .= &common_min_table_textarea($field,$notes[$shift_cnt-1],'',$row_cnt,5-$shift_cnt,'',$notes[$shift_cnt-1],'',$table_id) ; + &xlsxcreator_write_xlsx($ws2,$max_row_cnt,$shift_cnt,$notes[$shift_cnt-1],$format97) if $db{$table_name}{$date}{$table_col_name_notes} =~ /(\d+)/g || $db{$table_name}{$date}{$table_col_name_notes} =~ /[a-zA-Z]/ ; + $val_notes .= qq~~ if $shift_cnt < 4 ; + + } + + $val_notes = qq~$val_notes~ ; + + } elsif ($col eq "update") { + + $row_span = qq~rowspan="2"~ if $monitoring_report || $troubleshoot_monitoring_report ; + $align = qq~ class="dt-center"~ ; + my $field = "update_1_1_$date_cnt" ; + $val = &common_min_form_checkbox_col($field,'') ; + + chop $default_javascript if $default_javascript ; + + if ($default_javascript) { + + push @default_javascript_by_id, qq~"1_1_$date_cnt":{$default_javascript}~ ; ## ??? + + for (1 .. 4) { + my $field = "#textarea" . ucfirst "$field_name\_notes\_$_\_1_1_$date_cnt" ; + push @all_update_field_ids,"$field" if $monitoring_report || $troubleshoot_monitoring_report ; + $field = "#select" . ucfirst "$field_name\_$_\_1_1_$date_cnt" ; + push @all_update_field_ids,"$field" ; + } + } + } + + $print_tbody_extra .= qq~$val~ if $col ne 'notes' ; + + $print_tbody_extra .= qq~$val_notes~ if $col eq 'update' ; + + } + + ($s_year,$s_mon,$s_day) = Add_Delta_Days($s_year,$s_mon,$s_day,1) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + $date_cnt++ ; + } + + $date_cnt-- ; + + # &common_min_table_select_fixed_width_jquery(1) ; + # &common_min_table_select_default_values_jquery ; + + # @all_select_ids = () ; @selects_with_default_ids = () ; %col_name_select_ids = () ; %table_with_default_ids = () ; %selects_by_def_val = () ; + + @sql_col_display_extra = ("date","shift_1_(08:00-11:00)","shift_2_(11:00-14:00)","shift_3_(14:00-17:00)","shift_4_(17:00-21:00)","update") if $monitoring_report || $troubleshoot_monitoring_report ; + + $worksheet{$ws2}->set_column(0,0,10) ; + $worksheet{$ws2}->set_column(1,5,50) if $monitoring_report || $troubleshoot_monitoring_report ; + $worksheet{$ws2}->set_column(1,5,20) if $temp_calibrator_report ; + + $trigger_jquery_raw .= qq~\$("#$table_id tr:eq(0) th:nth-last-child(2),#$table_id tr th:nth-last-child(3),#$table_id tr th:nth-last-child(4),#$table_id tr th:nth-last-child(5)").css("width","23%")~ ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_build_extra_second_table { + + my ($field_name,$table_name,$table_col_name) = @_ ; + + my $ws2 = join ' ', map { ucfirst $_ } split /_/, $field_name ; + $ws2 .= "s" ; + + &xlsxcreator_add_worksheet($ws2) ; + + my $col2 = 0 ; + foreach (@sql_col_display_2) { + next if $_ eq "update" || !$_ ; + my $coltitle = $_ ; + $coltitle =~ s/\_id//g ; + $coltitle =~ s/\_/ /g ; + my $ucfirst = join '', map { ucfirst lc } split /(\s+)/, $coltitle; + &xlsxcreator_write_xlsx($ws2,0,$col2,$ucfirst,$format_management_report_headings) ; + $col2++; + } + $col2=0 ; + &xlsxcreator_freeze_panes($ws2,1,0) ; # Freeze the first 3 rows + + my ($s_year,$s_mon,$s_day) = split("-",$i{date_from}) ; + my ($e_year,$e_mon,$e_day) = split("-",$i{date_to}) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + + $opts{name} = $opts{support_users} ; + + $radio_opts{shift} = "Half Day (<7 hours);Full Day (7 hours+)" ; + + my $nr_of_options = scalar split("option> int("$e_year$e_mon$e_day") ; + + my $date1 = "$s_year-$s_mon-$s_day" ; + my $date2 = "$e_year-$e_mon-$e_day" ; + my $d1 = Time::Piece->strptime($date1, "%Y-%m-%d") ; + my $d2 = Time::Piece->strptime($date2, "%Y-%m-%d") ; + my $diff_in_days = ($d2 - $d1)->days + 1; + + my $date_cnt= 0 ; + + &common_min_thead_2 ; + + for my $day_cnt (1 .. $diff_in_days) { + + my $date = "$s_year-$s_mon-$s_day" ; + + $db{$table_name}{$date}{$table_col_name} = "None" unless $db{$table_name}{$date}{$table_col_name} ; + + $date_cnt++ ; + + push @second_table_ids,"#select_temp_calibrators_2_$date_cnt" ; + push @second_table_ids_2,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(2)" ; + push @second_table_ids_3,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(3)" ; + push @second_table_ids_4,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(4)" ; + push @second_table_ids_5,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(5)" ; + + $print_tbody_extra_2 .= qq~~ ; + $print_tbody_extra_2 .= qq~$print_thead_2~ if $date_cnt == 1 ; + $print_tbody_extra_2 .= qq~~ ; + + my $row_cnt = 0 ; + + $opts{name} = $opts{support_users} ; + + my $z_index = $tot_support_users_cnt * ($diff_in_days - $day_cnt + 1) + 1 ; + + foreach my $row (split(/\|/,$db{$table_name}{$date}{$table_col_name})) { + + $z_index-- ; + + next unless $row ; + + $row_cnt++ ; + $print_tbody_extra_2 .= qq~~ ; + + our $default_javascript = qq~~ ; + + $xlsxrow++ ; $xlsxcol = 0 ; + + foreach my $col (@sql_col_display_2) { + + my $formatting = $format84 ; + my $val = '' ; my $nowrap = '' ; my $align = qq~class="dt-center"~ ; + + my $field_id = "$col\_2_$row_cnt\_$date_cnt" ; + + my $default_val_html = qq~~ ; + + if ($col eq 'date') { + my $date_str = &common_min_date_as_string($date) ; + $val = $date_str ; + $nowrap = "nowrap" ; + $align = qq~class="dt-left"~ ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow,$xlsxcol,"$date_str",$formatting) ; + } elsif ($col eq 'name') { + my @abc = split(/\:/,$row) ; + $abc[0] = "" if $abc[0] eq "None" ; + $default_val = $abc[0] ; + $default_val_is_saved = ($default_val) ? 1 : 0 ; + $preferred_placeholder{$field_id} = "Select Temp Support Name $row_cnt" ; + $opts{$field_id} = $opts{name} ; + + my $table_row_cnt = ($date_cnt == 1) ? $row_cnt + 1 : $row_cnt - 1 ; + + $val = &common_min_table_select($field_id,$default_val,'',$table_row_cnt,4,'',$default_val_is_saved,'',"select_temp_calibrators_2_$date_cnt") ; + # $default_val_html = qq~~ ; + + $trigger_jquery_raw .= qq~ + \$("#select_temp_calibrators_2_$date_cnt tr:eq($table_row_cnt) td:nth-last-child(4)").css("z-index","$z_index") ; + ~ ; + $support_users_cnt-- ; + $opts{name} =~ s/.*?<\/option>// if $default_val ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow,$xlsxcol,$db{users}{$default_val}{name},$formatting) ; + } elsif ($col eq 'shift') { + $radio_opts{$field_id} = $radio_opts{shift} ; + my @abc = split(/\:/,$row) ; + $default_val = $abc[1] ; + $default_val_is_saved = ($default_val) ? 1 : 0 ; + # $default_val_html = qq~~ ; + our $val_min = "" ; + my $table_row_cnt = ($date_cnt == 1) ? $row_cnt + 1 : $row_cnt - 1 ; + $val = &table_radio_button($field_id,$default_val,'',$table_row_cnt,3,'',$default_val_is_saved,$col,"select_temp_calibrators_2_$date_cnt") ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow,$xlsxcol,$val_min,$formatting) ; + } elsif ($col eq 'update') { + $val = &common_min_table_checkbox($field_id) ; + chop $default_javascript if $default_javascript ; + if ($default_javascript) { + push @default_javascript_by_id, qq~"2_$row_cnt\_$date_cnt":{$default_javascript}~ ; + push @all_update_field_ids, "#shift_1_2_$row_cnt\_$date_cnt,#shift_2_2_$row_cnt\_$date_cnt,#selectName_2_$row_cnt\_$date_cnt" ; + } + } elsif (!$col) { + $val = ($row ne 'None') ? qq~ ~ : qq~~ ; + } + + my $styling = ($col eq 'date' && $row_cnt == 1) ? qq~style="width:7%;"~ : ($col eq 'name' && $row_cnt == 2) ? qq~style="width:35%;"~ : '' ; + + $print_tbody_extra_2 .= qq~~ ; + $xlsxcol++ ; + } + $print_tbody_extra_2 .= qq~~ ; + } + + ($s_year,$s_mon,$s_day) = Add_Delta_Days($s_year,$s_mon,$s_day,1) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + + if ($nr_of_options <= $row_cnt) { + $trigger_jquery_raw .= qq~\$("#add_row_table_2_$date_cnt").css("display","none");~ ; + } + + my $plus_button_color = ($db{shift_operator_ids}{$date}{temp_calibrator_support_shifts} =~ /\|\|/ || $db{shift_operator_ids}{$date}{temp_calibrator_support_shifts} =~ /\|\:/ || $db{shift_operator_ids}{$date}{temp_calibrator_support_shifts} eq "None") ? "grey" : "blue" ; + + push @plus_btn_ids,"#add_row_table_2_$date_cnt" ; + + $plus_button = qq~ + +
    +
    + + +
    +
    +
    +
    +
    + ~ ; + + $print_tbody_extra_2 .= qq~
    $val
    $plus_button~ ; + } + + $worksheet{$ws2}->set_column('A:C',20); + + &common_min_table_update_checkbox_col_default ; + + our $trigger_jquery_raw_default_alt = qq~ + // let all_def_vals = {} ; + + // all_def_vals[row_nr] = {} ; + + // let def_name = \$("#default_name_"+row_nr ).text() ; + // let def_shift = \$("#default_shift_"+row_nr ).text() ; + + // all_def_vals[row_nr]["selectName_"+row_nr] = def_name ; + + // if (def_shift == "1") { + // all_def_vals[row_nr]["shift_1_"+row_nr ] = "true" ; + // all_def_vals[row_nr]["shift_2_"+row_nr ] = "false" ; + // } else if (def_shift == "2") { + // all_def_vals[row_nr]["shift_1_"+row_nr ] = "false" ; + // all_def_vals[row_nr]["shift_2_"+row_nr ] = "true" ; + // } + ~ ; + + my $plus_btn_ids_str = join(",",@plus_btn_ids) ; + + $trigger_jquery_raw .= qq~ + + function add_Days (date_string,num_days,as_num) { + let date = new Date(date_string) ; + date.setDate(date.getDate() + num_days) ; + let year = date.getFullYear() ; + let month = String(date.getMonth() + 1).padStart(2,'0') ; + let day = String(date.getDate()).padStart(2,'0') ; + if (as_num) { + return ""+year+"-"+month+"-"+day+"" ; + } else { + let month_names = ["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] ; + month = month_names[month] ; + return ""+day+"-"+month+"-"+year+"" ; + } + } + + function deleteTempSupport (row_cnt) { + + BootstrapDialog.confirm({ + title: 'Confirm Delete', + message: 'Are you sure you want to delete '+name+'?', + type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + callback: function(result) { + + let [cnt_for_date,table_cnt] = row_cnt.split('_').map(Number) ; + + if (result) { + // if (\$("#update_data_base_"+row_cnt).text()) { + + let curr_date = add_Days("$i{date_from}",table_cnt-1,1) ; + + let url_delete = "$useropts{scripts}/get/get_db_delete_temp_support.pl?date="+curr_date+"&row_cnt="+cnt_for_date ; + + console.log("url_delete : "+url_delete) ; + + // console.log("#select_temp_calibrators_2_"+table_cnt+" #second_table_"+cnt_for_date+"_"+table_cnt) ; + + \$("#select_temp_calibrators_2_"+table_cnt+" #second_table_"+cnt_for_date+"_"+table_cnt).remove() ; + + \$.get(url_delete) ; + // } + // $("select#selectOriginalId").attr("id", "selectNewId"); + + let table_row_cnt = \$("#select_temp_calibrators_2_"+table_cnt).find('tr').length - 2 ; + + // let start_row_nr = 2 ; let end_row_nr = table_row_cnt + 1 ; + + if (table_cnt != '1') { + table_row_cnt += 2 ; + // start_row_nr = 0 ; + // end_row_nr -= 2 ; + } + + let all_def_vals_new = {} ; + + for (let i=2;i<=table_row_cnt+1;i++) { + + let row_nr = i-1 ; + let row_val = i ; + if (table_cnt != '1') { + row_val -= 2 ; + } + + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+")").attr("id","second_table_"+row_nr+"_"+table_cnt); + + let zIndex = \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(4)").css('z-index'); + zIndex++ ; + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(4)").css('z-index',zIndex); + if (\$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(1)").html()) { + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(1)").html(" "); + } + + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+")").find("select[id^='selectName_']").each(function() { + + var oldId = \$(this).attr("id"); + let old_row_val = get_row_nr(oldId,2) ; + let new_row_val = row_nr+"_"+table_cnt ; + + if (typeof all_def_vals["2_"+old_row_val] !== 'undefined') { + + all_def_vals_new["2_"+new_row_val] = {}; + all_def_vals_new["2_"+new_row_val]["selectName_2_"+new_row_val] = all_def_vals["2_"+old_row_val]["selectName_2_"+old_row_val] ; + all_def_vals_new["2_"+new_row_val]["shift_1_2_"+new_row_val] = all_def_vals["2_"+old_row_val]["shift_1_2_"+old_row_val] ; + all_def_vals_new["2_"+new_row_val]["shift_2_2_"+new_row_val] = all_def_vals["2_"+old_row_val]["shift_2_2_"+old_row_val] ; + + } + + let old_select_val = \$("#"+oldId).val() ; + + \$(this).attr("id", "selectName_2_"+new_row_val); + \$(this).attr("name", "name_2_"+new_row_val); + \$(this).attr("data-placeholder", "Select Temp Support Name "+row_nr); + var chosenElementId = oldId + "_chosen"; + \$("#" + chosenElementId).attr("id", "selectName_2_"+row_nr+"_"+table_cnt+"_chosen"); + \$("#selectName_2_"+row_nr+"_"+table_cnt+"_chosen .chosen-single span").text("Select Temp Support Name "+row_nr); + + \$("#shift_1_2_"+old_row_val).attr("name","shift_2_"+new_row_val); + \$("#shift_1_2_"+old_row_val).attr("id","shift_1_2_"+new_row_val); + \$("#shift_2_2_"+old_row_val).attr("name","shift_2_"+new_row_val); + \$("#shift_2_2_"+old_row_val).attr("id","shift_2_2_"+new_row_val); + \$("#checkboxUpdate_2_"+old_row_val).attr("name","update_2_"+new_row_val); + \$("#checkboxUpdate_2_"+old_row_val).attr("id","checkboxUpdate_2_"+new_row_val); + + // \$("#default_name_"+old_row_nr).attr("id","default_name_"+row_nr); + // \$("#default_shift_"+old_row_nr).attr("id","default_shift_"+row_nr); + + \$("#selectName_2_"+new_row_val).val(old_select_val) ; + \$("#selectName_2_"+new_row_val).trigger("chosen:updated") ; + + if (\$("#add_row_table_2_"+table_cnt).is(":hidden")) { + \$("#add_row_table_2_"+table_cnt).css("display","") ; + } + + }) ; + + } + + all_def_vals = all_def_vals_new ; + + if (!\$("#second_table_1_"+table_cnt).html()) { + + let options = "$opts{support_users}" ; + let select = add_select("name_2_1_"+table_cnt,"selectName_2_1_"+table_cnt,"Select Temp Support Name 1","$opts{support_users}",1,90) ; + let radio_butt = "  " ; + let update_butt = "" ; + let newRow = ""+curr_date+""+select+""+radio_butt+""+update_butt+"" ; + \$("#select_temp_calibrators_2_"+table_cnt+" tbody").append(newRow) ; + \$("#selectName_2_1_"+table_cnt).chosen({allow_single_deselect:true}) ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("position","absolute") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("width","90%") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("left","5%") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("top","50%") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("transform","translateY(-50%)") ; + + let optionCount = \$("#selectName_2_1_"+table_cnt+" option").length - 1 ; + + let date_cnt = daysBetween("$i{date_from}","$i{date_to}") ; + + let z_index = (date_cnt - table_cnt + 1)*optionCount ; + + let row_val = 2 ; + if (table_cnt != '1') { + row_val = 0 ; + } + + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(4)").css("z-index",z_index) ; + + \$("#selectName_2_1_"+table_cnt+",#shift_1_2_1_"+table_cnt+",#shift_2_2_1_"+table_cnt).change( function () { + + let found_blank = 0 ; + + if ((!\$("#selectName_2_1_"+table_cnt).val() || (!\$("#shift_1_2_1_"+table_cnt).is(":checked") && !\$("#shift_2_2_1_"+table_cnt).is(":checked"))) && \$("#second_table_1_"+table_cnt).html()) { + found_blank = 1 ; + } + + if (!found_blank) { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('grey').addClass('blue'); + } else { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('blue').addClass('grey'); + } + + let tick_update = 0 ; + + if ((\$("#"+this.id).attr('type') == 'radio' && \$("#"+this.id).is(":checked")) || (\$("#"+this.id).val() && \$("#"+this.id).attr('type') != 'radio')) { + tick_update = 1 ; + } + + if (tick_update && !\$("#checkboxUpdate_2_1_"+table_cnt).is(":checked")) { + \$("#checkboxUpdate_2_1_"+table_cnt).prop("checked",true) ; + } else if (!tick_update && \$("#checkboxUpdate_2_1_"+table_cnt).is(":checked")) { + \$("#checkboxUpdate_2_1_"+table_cnt).prop("checked",false) ; + } + + }) ; + } + } + } + }); + } + + ~ ; + + $trigger_jquery_raw .= qq~ + + function daysBetween(date1,date2) { + + const oneDay = 24 * 60 * 60 * 1000 ; + const firstDate = new Date(date1) ; + const secondDate = new Date(date2) ; + const diffInTime = Math.abs(secondDate - firstDate) ; + + return Math.ceil(diffInTime/oneDay) + 1 ; + + } + + function add_select (field_name,field_id,placeholder,options,tindex,width) { + + let select_raw = "" ; + + return select_raw ; + } + + \$("$plus_btn_ids_str").click( function () { + + let table_nr = get_row_nr(this.id) ; + + let table_row_cnt = \$("#select_temp_calibrators_2_"+table_nr).find('tr').length ; + + if (table_nr == '1') { + table_row_cnt -= 2 ; + } + + let found_blank = 0 ; + // console.log("table_row_cnt : "+table_row_cnt) ; + + // let lastRowId = \$("#select_temp_calibrators_2 tr:last").attr("id"); + // let table_row_cnt = get_row_nr(lastRowId) ; + + for (i=1;i<=table_row_cnt;i++) { + if ((!\$("#selectName_2_"+i+"_"+table_nr).val() || \$("#selectName_2_"+i+"_"+table_nr).val() == null || (!\$("#shift_1_2_"+i+"_"+table_nr).is(":checked") && !\$("#shift_2_2_"+i+"_"+table_nr).is(":checked"))) && \$("#second_table_"+i+"_"+table_nr).html()) { + found_blank = 1 ; + } + } + + if (!found_blank) { + + \$('#add_row_table_2_'+table_nr).find('i').removeClass('blue').addClass('grey'); + + table_row_cnt++ ; + + let options = "$opts{support_users}" ; + + let select = add_select("name_2_"+table_row_cnt+"_"+table_nr,"selectName_2_"+table_row_cnt+"_"+table_nr,"Select Temp Support Name "+table_row_cnt,"$opts{support_users}",1,90) ; + // "Half Day (<7 hours);Full Day (7 hours+)" + let radio_butt = "  " ; + + // let delete_butt = " " ; + let delete_butt = "" ; + + let update_butt = "" ; + + let curr_date = add_Days("$i{date_from}",table_nr-1) ; + + let newRow = ""+curr_date+""+select+""+radio_butt+""+update_butt+""+delete_butt+"" ; + + \$("#select_temp_calibrators_2_"+table_nr+" tbody").append(newRow) ; + + // let optionCount = \$("#selectName_2_"+table_row_cnt+"_"+table_nr+" option").length - 1 ; + let optionCount = \$("#selectName_2_1_"+table_nr+" option").length - 1 ; + + let date_cnt = daysBetween("$i{date_from}","$i{date_to}") ; + + // my $support_users_cnt = $potential_support_users_cnt - ($day_cnt - 1)*$tot_support_users_cnt ; + + let z_index = (date_cnt - table_nr + 1)*optionCount - table_row_cnt + 1 ; + + // let optionCount = "$tot_support_users_cnt" ; + + // \$("#selectName_"+table_row_cnt).chosen({allow_single_deselect:true}) ; + + for (i=1;i 1) { + // let row_nr = get_row_nr(this.id) ; + // for (i=1;i<=table_row_cnt;i++) { + // for (j=1;j<=table_row_cnt;j++) { + + // } + // } + + } + + if (!found_blank) { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('grey').addClass('blue'); + } else { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('blue').addClass('grey'); + } + + }) ; + + ~ ; + + my $second_table_ids_str = join(",",@second_table_ids) ; + my $second_table_ids_str_2 = join(",",@second_table_ids_2) ; + my $second_table_ids_str_3 = join(",",@second_table_ids_3) ; + our $second_table_ids_str_4 = join(",",@second_table_ids_4) ; + my $second_table_ids_str_5 = join(",",@second_table_ids_5) ; + + &common_min_table_select_fixed_width_jquery("$second_table_ids_str_4") ; + + &common_min_table_select_default_values_jquery ; + + # &common_min_table_select_jquery("#select_temp_calibrators_2 td:nth-last-child(4)","") ; + + &common_min_table_update_checkbox_col_jquery("3") ; + + $trigger_jquery .= qq~ + \$("#select_temp_calibrators_2_length").css("display","none") ; + \$("#select_temp_calibrators_2_filter").css("display","none") ; + \$("#select_temp_calibrators_2_info").css("display","none") ; + \$("#select_temp_calibrators_2_paginate").css("display","none") ; + ~ ; + + $trigger_jquery .= qq~ + // \$("#select_temp_calibrators_2").css("width","66.66666%"); + \$("$second_table_ids_str_5").css("width","7%") ; + \$("$second_table_ids_str_4").css("width","40%") ; + // \$("$second_table_ids_str_4").css("position","relative") ; + // \$("$second_table_ids_str_4").css("text-align","center") ; + \$("$second_table_ids_str_3").css("width","40%") ; + \$("$second_table_ids_str_2").css("width","10%") ; + ~ ; + + +} #------------------------------------------------------------------------------------------ + +sub table_radio_button { + +my ($field,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved,$col_name,$table_id) = @_ ; + +return unless $col_name ; + +$field = "$col_name\_$table_row" unless $field ; + +my $field_cnt = $field ; +$field_cnt =~ s/$col_name\_//g ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +my @opts = ($radio_opts{$field}) ? split(/\;/,$radio_opts{$field}) : split(/\;/,$options); + +my $row = qq~~ ; + +my $cnt = 0 ; + +if ($default_val && $default_val_is_saved) { + $background_color = "#424949" unless $background_color ; + $table_with_default_ids{$background_color} .= "#$table_id tr:eq($table_row) td:nth-last-child($table_col)," ; +} + +foreach (@opts) { + $cnt++ ; + my $checked = ($cnt eq $default_val) ? 'CHECKED' : '' ; + $val_min = ($checked) ? $_ : $val_min ; + $row .= qq(  ) ; + if (!$default_val_is_saved || !$default_val) { + $default_javascript .= qq~"$col_name\_$cnt\_$field_cnt":"false",~ ; + } else { + my $default_val_boolian = ($cnt eq $default_val) ? "true" : "false" ; + $default_javascript .= qq~"$col_name\_$cnt\_$field_cnt":"$default_val_boolian",~ ; + } + push @all_radio_ids,"#shift_$cnt\_$field_cnt" ; +} + +$row = substr($row,0,-12) ; + +# my $row = qq($print_radios) ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_build_table { + + my ($table_col_name,$field_name) = @_ ; + + my $cali_cnt = 0 ; my $found_editable = 0 ; my @all_select_ids = () ; + + $format84 -> set_align("center") ; + + my $table_row = 0 ; my %default_vals = () ; + + # foreach my $id (sort {$db{$table}{$a}{date_from} cmp $db{$table}{$b}{date_from}} keys %{$db{$table}}) { + foreach my $date_ref (sort keys %sort_calibration_by_time_ref) { + + my $id = $sort_calibration_by_time_ref{$date_ref} ; + + next unless $id ; + + my $system_count = 0 ; my $system_day_cnt = 0 ; + + my %default_monitors = () ; + + my $day_cnt = 0 ; + my $sql_col = "$table_col_name" ; + my $inp_field = substr($sql_col,0,-1) ; + my $found_inp_field = 0 ; + foreach my $day_row (split(/\|/,$db{$table}{$id}{$sql_col})) { + $day_cnt++ ; $system_count = 0 ; + foreach my $system_row (split(/\;/,$day_row)) { + $system_count++ ; my $shift_cnt = 0 ; + foreach my $shift_monitor (split(/\:/,$system_row)) { + $shift_cnt++ ; + $default_monitors{$day_cnt}{$system_count}{$shift_cnt} = $shift_monitor ; + $found_inp_field = 1 if $shift_monitor eq $i{$inp_field} ; + } + } + } + $system_count = 0 ; + + my %system_has_daily_op = () ; my %default_op_ids = () ; + + foreach my $system_row (split(/\|/,$db{$table}{$id}{daily_operator_ids})) { + $system_count++ ; + next unless $system_row ; + $system_day_cnt = 0 ; + foreach my $col (split(/\;/,$system_row)) { + $system_day_cnt++ ; + next unless $col ; + $default_op_ids{$system_count}{$system_day_cnt} = $col if $col ; + $system_has_daily_op{$system_count} = 1 if $col ; + } + } + $system_count = 0 ; + + unless (&common_check_if_string_contains_an_integer($db{$table}{$id}{event_system_id_multiple})) { + $db{$table}{$id}{event_system_id_multiple} = ";none;" ; + } + + # my @system_name_ids = split(";",$db{$table}{$id}{event_system_id_multiple}) ; + + my @system_name_ids = split(/\;/,$db{$table}{$id}{event_system_id_multiple}) ; + my @club_ids = split(/\;/,$db{$table}{$id}{club_ids}) ; + my @op_ids = split(/\,/,$db{$table}{$id}{operator_ids}) ; + my @days_active = split(/\;/,$db{$table}{$id}{days_active}) ; + my @start_times = ($db{$table}{$id}{qty} eq '1' && $days_active[0]) ? () : split(/\;/,";".$db{$table}{$id}{times_from}) ; + my @end_times = ($db{$table}{$id}{qty} eq '1' && $days_active[0]) ? () : split(/\;/,$db{$table}{$id}{times_to}) ; + + my $cnt_rows = 0 ; + for (1 .. 50) { + $cnt_rows = $_ if $system_name_ids[$_ - 1] or $club_ids[$_ - 1] ; + } + + my $system_count = 0 ; my $system_day_cnt = 0 ; + + foreach my $event_sys_id (@system_name_ids) { + + $system_count++ ; + + next unless $event_sys_id ; + next if $db{event_systems}{$event_sys_id}{system_type} ne 'mobile' && !$monitoring_report && !$troubleshoot_monitoring_report ; + + # &common_debug(">>>>>>>>> 2. $system_count [$id] $db{$table}{$id}{ref} [$db{event_systems}{$event_sys_id}{system_type}]") ; + + # $event_cnt++ ; + + # foreach my $cal_date (sort {$day_of_week{$a} cmp $day_of_week{$b}} keys %day_of_week) { + + $system_day_cnt = 0 ; + + foreach my $cal_date (sort keys %day_of_week) { + + # my $srch_date_from_comp = $i{date_from} ; $srch_date_from_comp =~ s/\-//g ; + # my $srch_date_to_comp = $i{date_to} ; $srch_date_to_comp =~ s/\-//g ; + my $date_from_comp = substr($db{$table}{$id}{date_from},0,10) ; $date_from_comp =~ s/\-//g ; + my $date_to_comp = substr($db{$table}{$id}{date_to},0,10) ; $date_to_comp =~ s/\-//g ; + my $cal_date_comp = $cal_date ; # $cal_date_comp =~ s/\-//g ; + $cal_date = substr($cal_date,0,4) . '-' . substr($cal_date,4,2) . '-' . substr($cal_date,6,2) ; + my $date_from = substr($db{$table}{$id}{date_from},0,10) ; + $system_day_cnt++ ; + + # &common_debug("[$cnt{$event_sys_id}{$id}] : $event_sys_id [$id] $cal_date") ; + + # &common_debug("1. DATE >>> $cal_date_comp < $date_from_comp") if !$report ; + next if $cal_date_comp < $date_from_comp ; + # &common_debug("2. DATE >>> $cal_date_comp > $date_to_comp") if !$report ; + next if $cal_date_comp > $date_to_comp ; + + $cnt{$event_sys_id}{$id}++ ; + + next if $db{$table}{$id}{days_active} && !$days_active[$cnt{$event_sys_id}{$id}-1] ; + + my $cal_date_val = $cal_date ; my $date_from_val = $i{date_from} ; my $date_to_val = $i{date_to} ; + + $cal_date_val =~ s/\-//g ; $date_from_val =~ s/\-//g ; $date_to_val =~ s/\-//g ; + + next if $cal_date_val < $date_from_val || $cal_date_val > $date_to_val ; + + # # &common_debug("3. DATE >>> $cal_date_comp > $srch_date_to_comp") if !$report ; + # next if ($calibration_report) && $cal_date_comp > $srch_date_to_comp ; + # # &common_debug("4. DATE >>> $cal_date_comp < $srch_date_from_comp") if !$report ; + # next if ($calibration_report) && $cal_date_comp < $srch_date_from_comp ; + + # &common_debug(">>>>>>>>> 3. $system_count [$id] $db{$table}{$id}{ref} [$db{event_systems}{$event_sys_id}{system_type}]") ; + + # &common_debug("[$cnt{$event_sys_id}{$id}] : $event_sys_id [$id] $cal_date [$cal_date_comp > $srch_date_to_comp]") ; + + $cali_cnt++; + + $xlsxcol = 0 ; + $print_tbody .= qq~~ ; + $table_row++ ; + + our $default_javascript = "" ; + + foreach (@sql_col_display) { + + # &common_debug("1. XLSX >>> $_") if !$report ; + + next unless $_ ; # blank for the buttons column + + my $formatting = $format84 ; + my $val = $db{$table}{$id}{$_} ; + my $val_min = $val ; + my $align = qq~ class="dt-center"~ ; + my $nowrap = '' ; + + # &common_debug("2. XLSX >>> val_min=$val_min") if !$report ; + + my $sys_day_cnt = $cnt{$event_sys_id}{$id} ; + + if ($_ eq 'count') { + # $val = $event_cnt ; + $val = $cali_cnt ; + } elsif ($_ eq 'event_nr') { + $val = "$id" ; + } elsif ($_ eq 'event') { + $val = "$db{$table}{$id}{ref} [$id]" ; + } elsif ($_ eq 'calibration_date' || $_ eq 'date') { + # $val = "$cal_date [$day_of_week{$cal_date}]" ; + $val = &common_min_date_as_string($cal_date) ; + $nowrap = "nowrap" ; + } elsif ($_ eq 'day') { + $val = "$sys_day_cnt" ; + } elsif ($_ eq 'start_date') { + $nowrap = "nowrap" ; + $val = &common_min_date_as_string($date_from) ; + } elsif ($_ eq 'venue') { + my @oids = split(/\,/,$db{$table}{$id}{organisation_ids}) ; + foreach $_oid (@oids) { + $val .= $db{organisations}{$_oid}{name} . '
    ' ; + } + $val = substr($val,0,-4) if $val ; ; + } elsif ($_ eq 'region') { + $val = $db{regions}{$db{$table}{$id}{region_id}}{code} ; + } elsif ($_ eq 'type') { + $val = (lc $db{event_systems}{$event_sys_id}{description} =~ /cricket/) ? "C" : + ($db{event_systems}{$event_sys_id}{system_type} eq 'mobile') ? "M" : + ($db{event_systems}{$event_sys_id}{system_type} eq 'fixed') ? "F" : ""; + } elsif ($_ eq 'system') { + $val = '' ; + $val = qq~$db{event_systems}{$event_sys_id}{name}~ ; + $val .= qq~ ($db{event_systems}{$event_sys_id}{description})~ if $db{event_systems}{$event_sys_id}{description} ; + } elsif ($_ eq 'sport') { + $val = '' ; + foreach my $sport_id (split(",",$db{$table}{$id}{sport_type_ids})) { + $db{sport_types}{$sport_id}{name} = uc $db{sport_types}{$sport_id}{name} ; + $val .= qq~$db{sport_types}{$sport_id}{name}
    ~ ; + } + $val = substr($val,0,-4) if $val ; + } elsif ($_ eq 'club_name') { + $val = $db{clubs}{$club_ids[$system_count - 1]}{name} ; + } elsif ($_ eq 'operator') { + $val = '' ; + # $val = $db{users}{$table_op_ids[$system_count - 1]}{name} if $table_op_ids[$system_count - 1] ; + $val = ($default_op_ids{$system_count}{$cnt{$event_sys_id}{$id}}) ? $db{users}{$default_op_ids{$system_count}{$cnt{$event_sys_id}{$id}}}{name} : (!$default_op_ids{$system_count}{$system_day_cnt} && $system_has_daily_op{$system_count}) ? "None" : $db{users}{$op_ids[$system_count - 1]}{name} ; + # $formatting = $format92 if $event_cnt == 2 ; + $formatting = $format92 if $cali_cnt == 2 ; + } elsif ($_ eq 'start_time') { + if (!$start_times[$sys_day_cnt-1]) { + $val = substr($db{$table}{$id}{date_from},11,5) ; + } else { + $val = substr($start_times[$sys_day_cnt-1],0,5) ; + } + } elsif ($_ eq 'end_time') { + if (!$end_times[$sys_day_cnt-1]) { + $val = substr($db{$table}{$id}{date_to},11,5) ; + } else { + $val = substr($end_times[$sys_day_cnt-1],0,5) ; + } + } elsif ($_ eq 'status' || $_ eq 'fixture_check') { + push @first_table_multi_select_table_cells,"#$useropts{table_id} tr:eq($table_row) td:nth-last-child($last_child{$_})" ; + $field{$_} = "$_\_event$event_sys_id\_$sys_day_cnt\_$id" ; + $opts{$field{$_}} = $opts{$_} ; + my $background_color = qq~~ ; + if ($_ eq 'status' && $default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}) { + $val_min = $db{monitor_status}{$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}}{status} ; + if ($default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id} eq '1') { + $background_color = qq~rgb(81, 181, 41)~ ; + $formatting = $format94 ; + } elsif ($default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id} eq '2') { + $background_color = qq~rgb(246, 227, 5)~ ; + $formatting = $format95 ; + } else { + $background_color = qq~rgb(249, 13, 13)~ ; + $formatting = $format96 ; + } + } elsif ($default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}) { + $val_min = $db{users}{$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}}{name} ; + } + + $val = &common_min_table_select($field{$_},$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},'',$table_row,$last_child{$_},$background_color,$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},$_) ; + } elsif ($_ eq 'update') { + + my $field = "update_event$event_sys_id\_$sys_day_cnt\_$id" ; + $val = &common_min_form_checkbox_col($field,'') ; + + chop $default_javascript if $default_javascript ; + # 12=s:;t:|s:1;t:1|s:2;t:2-13=|s:3;t:3|s:4;t:4 + if ($default_javascript) { + push @default_javascript_by_id, qq~"event$event_sys_id\_$sys_day_cnt\_$id":{$default_javascript}~ ; + } + } + if ($_ ne 'status' && $_ ne 'calibrator' && substr($_,0,5) ne 'shift' && $_ ne 'update' && $_ ne 'status' && $_ ne 'fixture_check') { + $val_min = $val ; + $val_min =~ s/\
    /\;/g ; + } + $print_tbody .= qq~$val~ ; + + # &common_debug("XLSX >>> $event_system_calibration_ids{$id}{$event_sys_id}{$sys_day_cnt} [$id] [$event_sys_id] [$sys_day_cnt] [$field]") ; + + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$formatting) ; + $xlsxcol++ ; + } + + $print_tbody .= qq~~ ; + + $xlsxrow++ ; + } + + # next if $i{calibration_status} ne 'all' and $i{calibration_status} and $i{calibration_status} ne $db{event_systems}{$event_sys_id}{calibration_status} ; + # next if $i{calibrator_id} ne 'all' and $i{calibrator_id} and $i{calibrator_id} ne $db{event_systems}{$event_sys_id}{calibrator_id} ; + + } + } +# || $troubleshoot_monitoring_report ; + my $html_id = ($monitoring_report) ? "selectShift_monitor_" : ($troubleshoot_monitoring_report) ? "selectShift_troubleshoot_monitor_" : "selectShift_temp_calibrator_" ; + my $html_id2 = ($monitoring_report) ? "shift-monitor-id-" : ($troubleshoot_monitoring_report) ? "shift-troubleshoot-monitor-id-" : "shift-temp-calibrator-id-" ; + $row_cnt++ if $monitoring_report || $troubleshoot_monitoring_report ; + + $trigger_jquery_raw .= ($monitoring_report || $troubleshoot_monitoring_report) ? qq~ + + \$("#savebutt").click(function() { + for (let table_cnt = 1; table_cnt<= $date_cnt; table_cnt++) { + for (let i=1; i<=4; i++) { + let mon_id = \$("#$html_id"+i+"_1_1_"+table_cnt).chosen().val() ; + if (mon_id && typeof(mon_id) !== 'undefined') { + \$("#$html_id2"+i+"-"+table_cnt).val(mon_id) ; + } + } + } + \$("#$lcpage-form").submit() ; + }) ; + + ~ : qq~ + \$("#savebutt").click(function() { + + for (let table_cnt = 1; table_cnt<= $date_cnt; table_cnt++) { + + for (let i=1; i<=4; i++) { + let mon_id = \$("#$html_id"+i+"_1_1_"+table_cnt).chosen().val() ; + if (mon_id) { + \$("#$html_id2"+i+"-"+table_cnt).val(mon_id) ; + } + } + + let table_row_cnt = \$("#select_temp_calibrators_2_"+table_cnt).find('tr').length - 2 ; + + if (table_cnt > 1) { + table_row_cnt += 2 ; + } + + let seen_support = {} ; + + for (i=1;i<=table_row_cnt;i++) { + + let sel_val = \$("#selectName_2_"+i+"_"+table_cnt).val() ; + // if (!sel_val) { + // noty({text:'Please Select a Temp Support Name in all Rows',layout:"center",type:"error",timeout:3000}) ; + // return ; + // } else + if (seen_support[sel_val]) { + noty({text:'Please do not Select the same Temp Support Name in Multiple Rows for the Same Date',layout:"center",type:"error",timeout:3000}) ; + return ; + } else if (sel_val) { + seen_support[sel_val] = 1 ; + } + } + } + \$("#$lcpage-form").submit() ; + }) ; + ~ ; + + $worksheet{$ws}->set_column(0,0,10) ; + $worksheet{$ws}->set_column(1,1,30) ; + $worksheet{$ws}->set_column(2,2,15) ; + $worksheet{$ws}->set_column(3,3,5) ; + $worksheet{$ws}->set_column(4,4,15) ; + $worksheet{$ws}->set_column(5,6,10) ; + $worksheet{$ws}->set_column(7,7,30) ; + $worksheet{$ws}->set_column(8,9,10) ; + $worksheet{$ws}->set_column(10,10,30) ; + $worksheet{$ws}->set_column(11,11,15) ; + $worksheet{$ws}->set_column(12,16,20) ; + + &report_xlsx_export_footer('L',15,$xlsxdir) ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_update { + + my ($table,$table_field,$other_field,$table_field_2) = @_ ; + + unless ($table_field_2) { + $table_field_2 = "blank" ; + $ignore{$table_field_2} = 1 ; + } + + my ($s_year,$s_mon,$s_day) = split("-",$i{date_from}) ; + my ($e_year,$e_mon,$e_day) = split("-",$i{date_to}) ; + + our $date_counter = 1 ; + + while (int("$s_year$s_mon$s_day") <= int("$e_year$e_mon$e_day")) { + $date_cnt_to_date{$date_counter} = "$s_year-$s_mon-$s_day" ; + $date_counter++ ; + ($s_year,$s_mon,$s_day) = Add_Delta_Days ($s_year,$s_mon,$s_day,1) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + } + + $date_cnt_to_date{$date_counter} = "$s_year-$s_mon-$s_day" ; + $date_counter-- ; + + my %i_per_date = () ; my $temp_support_diff = 0 ; + + if ($temp_calibrator_report) { + + &db_min_ro($table,"date,temp_calibrator_support_shifts,$table_field","`date` >= '$i{date_from}' AND`date` <= '$i{date_to}'") ; + + for my $date_cnt (1 .. $date_counter) { + + my $table_pos = 0 ; my $cnt_per_date = 0 ; my $table_cnt = 0 ; + + # $db{$table}{1}{temp_calibrator_support_shifts} =~ s/\|\|/\|/g ; + # $db{$table}{1}{temp_calibrator_support_shifts} =~ s/^\|//; + # $db{$table}{1}{temp_calibrator_support_shifts} =~ s/\|$//; + + my @temp_calibrator_support_shifts_split = split(/\|/,$db{$table}{$date_cnt_to_date{$date_cnt}}{temp_calibrator_support_shifts}) ; + + foreach (sort keys %i) { + + $ignore{$_} = 1 ; + + if ($_ =~ /^name_2_.*_$date_cnt$/) { + + my @aaa = split(/\_/,$_) ; + $table_pos = $aaa[-3] ; + $cnt_per_date = $aaa[-2] ; + # $table_cnt = $aaa[-1] ; + + my $update_field = "update_$table_pos\_$cnt_per_date\_$date_cnt" ; + my $name_field = "name_$table_pos\_$cnt_per_date\_$date_cnt" ; + my $shift_field = "shift_$table_pos\_$cnt_per_date\_$date_cnt" ; + + if ($i{$update_field} && $i{$name_field} && $i{$shift_field}) { + $i_per_date{$date_cnt}{temp_calibrator_support_shifts} .= qq~$i{$name_field}:$i{$shift_field}|~ ; + } elsif ($temp_calibrator_support_shifts_split[$cnt_per_date-1]) { + my $abcde = $temp_calibrator_support_shifts_split[$cnt_per_date-1] ; + $i_per_date{$date_cnt}{temp_calibrator_support_shifts} .= qq~$abcde|~ ; + } + } + } + + chop $i_per_date{$date_cnt}{temp_calibrator_support_shifts} if $i_per_date{$date_cnt}{temp_calibrator_support_shifts} ; + # $temp_support_exists = 1 if $i_per_date{$date_cnt}{temp_calibrator_support_shifts} ; + $temp_support_diff = 1 if $i_per_date{$date_cnt}{temp_calibrator_support_shifts} && $i_per_date{$date_cnt}{temp_calibrator_support_shifts} ne $db{$table}{$date_cnt_to_date{$date_cnt}}{temp_calibrator_support_shifts} ; + } + + } else { + # return unless $i{update_table_1} ; + &db_min_ro($table,"date,$table_field,$table_field_2","`date` >= '$i{date_from}' AND `date` <= '$i{date_to}'") ; + } + + my $some_update = 0 ; + + for my $date_cnt (1 .. $date_counter) { + $some_update = 1 if $i{"update_1_1_$date_cnt"} || ($i{"update_2_1_$date_cnt"} || $temp_calibrator_report) ; + } + + + # return if !$i{update_table_1} && $temp_calibrator_report && $i{temp_calibrator_support_shifts} eq $db{$table}{1}{temp_calibrator_support_shifts} ; + return if !$some_update && !$temp_support_diff ; + + &hidden_fields ; + my %ii = %i ; + + # $ignore{blank} = 1 ; + + for my $date_cnt (1 .. $date_counter) { + + %i = () ; + + # my $date_val = $ii{"date_$date_cnt"} ; + my $date_val = $date_cnt_to_date{$date_cnt} ; + + # my $update_field = "update_1_1_$date_cnt" ; + + next if !$ii{"update_1_1_$date_cnt"} && !$ii{"update_2_1_$date_cnt"} ; + + if ($ii{"update_1_1_$date_cnt"}) { + + my $ops_exists = 0 ; my $notes_exists = 0 ; + + for my $shift_cnt (1 .. 4) { + $ii{"$other_field\_$shift_cnt\_$date_cnt"} =~ s/\,/\;/g ; + $i{$table_field} .= qq~$ii{"$other_field\_$shift_cnt\_$date_cnt"}|~ ; + $ops_exists = 1 if $ii{"$other_field\_$shift_cnt\_$date_cnt"} ; + $notes_exists = 1 if $table_field_2 && $ii{"shift_$table_field_2\_$shift_cnt\_1_1_$date_cnt"} ; + + my $field_ = "shift_$table_field_2\_$shift_cnt\_1_1_$date_cnt" ; + + $i{$table_field_2} .= qq~$ii{"shift_$table_field_2\_$shift_cnt\_1_1_$date_cnt"}:|:~ if $table_field_2 ; + } + chop $i{$table_field} ; + + $i{$table_field} = qq~~ unless $ops_exists ; + $i{$table_field_2} = qq~~ if $table_field_2 && !$notes_exists ; + + $i{$table_field_2} = substr($i{$table_field_2},0,-3) if $table_field_2 && $i{$table_field_2} ; + $ignore{$table_field} = 0 ; + $ignore{$table_field_2} = 0 if $table_field_2 && $table_field_2 ne 'blank' ; + } else { + $ignore{$table_field} = 1 ; + $ignore{$table_field_2} = 1 ; + } + # my $table_field_old = $table_field ; + + # $table_field = $table_field_old ; + + $i{temp_calibrator_support_shifts} = $i_per_date{$date_cnt}{temp_calibrator_support_shifts} if $temp_calibrator_report ; + + if (!$db{$table}{$date_val}{date}) { + + &db_min_ro($table,"1,MAX(id) + 1 AS 'max_id'","","","") ; + + $i{id} = $db{$table}{1}{max_id} ; + $i{id} = 1 unless $i{id} ; + $i{date} = $date_val ; + + $ignore{date} = 0 ; + $ignore{$table_field} = 1 unless $i{$table_field} ; + $ignore{temp_calibrator_support_shifts} = 1 if !$temp_calibrator_report || !$i{temp_calibrator_support_shifts} ; + + &db_min_insert("$table") ; + + } else { + + $ignore{$table_field} = 1 if $db{$table}{$date_val}{$table_field} eq $i{$table_field} ; + $ignore{temp_calibrator_support_shifts} = 1 if $db{$table}{$date_val}{temp_calibrator_support_shifts} eq $i{temp_calibrator_support_shifts} || !$temp_calibrator_report ; + &db_min_upd($table,"`date`='$date_val'") if !$ignore{$table_field} || !$ignore{$table_field_2}|| !$ignore{temp_calibrator_support_shifts} ; + + } + } + + %i = %ii ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_update { + + my ($field) = @_ ; + + my %iii = %i ; + my %ii = () ; + local $min_date = 0 ; local $max_date = 0 ; + foreach (sort keys %i) { + + local $cell_name = $_ ; + local @a = split("_") ; + next if $a[-2] ne int($a[-2]) ; + + if ($i{"paid_$a[-2]\_$a[-1]"} and $i{"amount_payble_$a[-2]\_$a[-1]"}) { + # my $date = substr($a[-1],0,4) . '-' . substr($a[-1],4,2) . '-' . substr($a[-1],6,2) ; + if ($a[0] eq 'amount') { + $i{$_} = sprintf("%.2f",$i{$_}) ; + $ii{$a[-1]}{"$field\_amounts_paid"} .= ($ii{$a[-1]}{"$field\_amounts_paid"}) ? qq~;$a[-2]:$i{$_}~ : qq~$a[-2]:$i{$_}~ ; + } elsif ($a[0] eq 'date') { + $ii{$a[-1]}{"$field\_dates_paid"} .= ($ii{$a[-1]}{"$field\_dates_paid"}) ? qq~;$i{$_}~ : qq~$i{$_}~ ; + } + } + $min_date = $a[-1] if ($min_id and $a[-1] < $min_id) or not $min_id ; + $max_date = $a[-1] if $a[-1] > $max_id ; + } + + $min_date = substr($min_date,0,4) . '-' . substr($min_date,4,2) . '-' . substr($min_date,6,2) ; + $max_date = substr($max_date,0,4) . '-' . substr($max_date,4,2) . '-' . substr($max_date,6,2) ; + + &db_min_ro($table,"date,$field\_dates_paid,$field\_amounts_paid","`date` <= '$max_date' AND `date` >= '$min_date'",'','') ; + + foreach my $date (sort keys %ii) { + + %i = () ; + + # $i{"$field\_dates_paid"} .= qq~$ii{$date}{"$field\_dates_paid"}~ ; + + my $date_string = substr($date,0,4) . '-' . substr($date,4,2) . '-' . substr($date,6,2) ; + + $i{"$field\_amounts_paid"} = qq~$db{$table}{$date_string}{"$field\_amounts_paid"}~ ; + $i{"$field\_amounts_paid"} .= qq~;~ if $db{$table}{$date_string}{"$field\_amounts_paid"} && $ii{$date}{"$field\_amounts_paid"} ; + $i{"$field\_amounts_paid"} .= qq~$ii{$date}{"$field\_amounts_paid"}~ ; + + $ignore{"$field\_amounts_paid"} = 1 if $i{"$field\_amounts_paid"} eq $db{$table}{$date_string}{"$field\_amounts_paid"} || !$i{"$field\_amounts_paid"} ; + + $i{"$field\_dates_paid"} = qq~$db{$table}{$date_string}{"$field\_dates_paid"}~ ; + $i{"$field\_dates_paid"} .= qq~;~ if $db{$table}{$date_string}{"$field\_dates_paid"} && $ii{$date}{"$field\_dates_paid"} ; + $i{"$field\_dates_paid"} .= qq~$ii{$date}{"$field\_dates_paid"}~ ; + + $ignore{"$field\_dates_paid"} = 1 if $i{"$field\_dates_paid"} eq $db{$table}{$date_string}{"$field\_dates_paid"} || !$i{"$field\_dates_paid"} ; + + &db_min_upd($table,"`date`='$date_string'") if $i{"$field\_dates_paid"} || $i{"$field\_amounts_paid"} ; + + } + + %i = %iii ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_report_ifields { + + my ($field) = @_ ; + + my $field2 = join(/ /, map { uc($_) } split(/\_/,$field)) ; + + if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { + $error = qq~'$i{date_from}' > '$i{date_to}'~ ; &report_screen ; + } + push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` <= '$i{date_to} 23:59:59' AND `date_to` >= '$i{date_from} 00:00:00'))" ; + push @report_results, "(BETWEEN '$i{date_from}' AND '$i{date_to}')" ; + } elsif (not $i{date_from}) { + $error = qq~PLEASE ENTER A START DATE!~ ; + } elsif (not $i{date_to}) { + $error = qq~PLEASE ENTER A END DATE!~ ; + } + + our $where_min = qq~~ ; + if ($i{"$field\_id"}) { + my $ifield = "$field\_id" ; + &db_min_ro('users','1,name',"`id` = '$i{$ifield}'",'','') ; + $where_min = " AND `$field\_ids` LIKE '%$i{$ifield}%'" ; + push @report_results,"$field2 = $db{users}{1}{name}" ; + } + + if ($i{paid_status} eq 'paid') { + push @report_results,"$field2 AMOUNTS PAID" ; + } elsif ($i{paid_status} eq 'outstanding') { + push @report_results,"$field2 PAY OUTSTANDING" ; + } + + $report_results_msg = uc join(', ', @report_results) ; + + if (not $report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); + &report_screen ; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_list_screen { + + my ($field) = @_ ; + + my $field2 = $field ; + + $field2 =~ s/\_/\-/g ; + + # &db_min_ro('event_cost_items','1,rates',"`name` LIKE '$field3%'",'','') ; + + our @sql_col_display = ($i{paid_status} eq 'paid') ? ("date","$field\_names","shifts_count","dates_paid","amounts_paid","all_paid") : ($i{paid_status} eq 'all') ? ("date","$field\_names","shifts_count","dates_paid","amounts_paid","date_payable","amount_payable","paid") : ("date","$field\_names","shifts_count","date_payable","amount_payable","paid") ; + + my $table_colspan = 0 ; + + foreach (@sql_col_display) { + $table_colspan += 1 ; + } + + local @month_arr = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + my ($year1,$month1,$day1) = split(/\-/,$i{date_from}) ; + my ($year2,$month2,$day2) = split(/\-/,$i{date_to}) ; + + my $date_string = qq~~ ; + + if ($year1 ne $year2 && $month1 ne $month2 && $day1 ne $day2) { + $date_string = qq~ $day1 $month_arr[$month1] $year1 - $day2 $month_arr[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 ne $month2) { + $date_string = qq~ $day1 $month_arr[$month1] - $month_arr[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 eq $month2 && $day1 ne $day2) { + $date_string = qq~ $day1 - $day2 $month_arr[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 eq $month2 && $day1 eq $day2) { + $date_string = qq~ $day2 $month_arr[$month2] $year2~ ; + } + + my $field_heading = join(" ", map { ucfirst($_) } split(/\_/,$field)) ; + + our $xlsxheading = "$field_heading Payments Report$xlsreportname$date_string" ; + + &report_xlsx_export_header("$field_heading Payments$xlsreportname","$field\_payments_report") ; + + &schedule_payments_load_list_vars("$where_min","$field") ; + + my @qty_work = () ; + my @amnt_usd_work = () ; + my @amnt_work = () ; + my @op_work = () ; + my @description = () ; + my @paid_work = () ; + my $row_cnt = 0 ; + my $first_id = 0 ; + my $last_id = 0 ; + my %row_cnt_to_id = () ; + + $fcol = 12 ; my $val_min = 0 ; $row_cnt = 0 ; + + my $date_pay = qq~~ ; my $quote_and_ops_ids = qq~~ ; my $op_ids = qq~~ ; + + my ($next_year,$next_month,$next_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,1) ; + + my $row_cnt = 0 ; my $quote_and_ops_ids = qq~~ ; + + my %amnt_tots = () ; + + foreach my $date (sort {$a <=> $b} keys %{$db{$table}}) { + + my @date_pay = split(/\;/,$db{$table}{$date}{"$field\_paid"}) ; + my @amount_pay = split(/\;/,$db{$table}{$date}{"$field\_amounts_paid"}) ; + my $date_val = $date ; + $date_val =~ s/\-//g ; + + foreach my $temp_id (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$operator_count{$date}}) { + + next if $i{"$field\_id"} && $i{"$field\_id"} ne $temp_id ; + + next if $temp_id eq 'none' ; + + my $amnt_owed = ($db{event_cost_items}{1}{rates}) ? $db{event_cost_items}{1}{rates} * $operator_count{$date}{$temp_id} : ($field =~ /calibrator/) ? 500 * $operator_count{$date}{$temp_id} : ($field =~ /monitor/ && $field !~ /troubleshoot/) ? 300 * $operator_count{$date}{$temp_id} : 450 * $operator_count{$date}{$temp_id} ; + $amnt_owed += $temp_support_rates{half_day}*$temp_calibrator_support{shift_count}{$date}{$temp_id}{1} ; + $amnt_owed += $temp_support_rates{full_day}*$temp_calibrator_support{shift_count}{$date}{$temp_id}{2} ; + # $temp_calibrator_support{count}{$date}{1} += ($abc[1] eq '1') ? 0.5 : 1 ; + # $temp_calibrator_support{shift_count}{$date}{1} += 1 ; + + $amnt_owed = $amnt_owed - $amounts_paid{$date}{$temp_id} ; + + $amnt_owed = 0 if $amounts_paid{$date}{$temp_id} ; + + next if $i{paid_status} eq 'outstanding' && $amnt_owed == 0 ; + next if $i{paid_status} eq 'paid' && $amounts_paid{$date}{$temp_id} == 0 ; + + $amnt_owed = sprintf("%0.2f",$amnt_owed) ; + $xlsxcol = 0 ; + + foreach my $col (@sql_col_display) { + + next unless $col ; # blank for the buttons column + $display = 1 ; + my $val = '' ; + my $align = '' ; + my $center = qq~ class="dt-center"~ ; + $align = $center ; + my $val_min = '' ; + + if ($col eq 'date') { + $val = $date ; + } elsif ($col eq "$field\_names") { + $val = $db{users}{$temp_id}{name} ; + $val .= " [Support]" if $support_user{$temp_id} ; + } elsif ($col eq 'shifts_count') { + chop $operator_shifts_string{$date}{$temp_id} if $operator_shifts_string{$date}{$temp_id} ; + my $shifts_cnt = $operator_count{$date}{$temp_id} + $temp_calibrator_support{count}{$date}{$temp_id}{1} + $temp_calibrator_support{count}{$date}{$temp_id}{2} ; + $val_min = "$shifts_cnt" ; + $val_min .= " [$operator_shifts_string{$date}{$temp_id}]" if $operator_shifts_string{$date}{$temp_id} ; + $operator_shifts_string{$date}{$temp_id} =~ s/\;/\
    /g ; + $val = ($operator_shifts_string{$date}{$temp_id}) ? qq~$shifts_cnt~ : $shifts_cnt ; + # $val = $operator_shifts{$date}{$temp_id} + } elsif ($col eq 'dates_paid') { + foreach (sort keys %{$dates_amounts_paid{$temp_id}}) { + $val .= ($val) ? qq~
    $_~ : qq~$_~ ; + } + $val = "None" unless $val ; + $val_min = $val ; + $val_min =~ s/\
    /\;/g ; + $val = qq~~ if $val =~ /
    / ; + } elsif ($col eq 'amounts_paid') { + foreach (sort keys %{$dates_amounts_paid{$temp_id}}) { + $dates_amounts_paid{$temp_id}{$_} = sprintf("%0.2f",$dates_amounts_paid{$temp_id}{$_}) ; + $val .= ($val) ? qq~
    $dates_amounts_paid{$temp_id}{$_}~ : qq~$dates_amounts_paid{$temp_id}{$_}~ ; + $amnt_tots{"amounts_paid"} += $dates_amounts_paid{$temp_id}{$_} ; + } + $val = "None" unless $val ; + $val_min = $val ; + $val_min =~ s/\
    /\;/g ; + $val = qq~~ if $val =~ /
    / ; + } elsif ($col eq 'date_payable') { + my $date_payable = "$now_year-$now_mm-$now_dd" ; + $val = ($amnt_owed != 0) ? &common_min_form_input_col("date_$temp_id\_$date_val",$date_payable) : "N/A" ; + $val_min = ($amnt_owed != 0) ? $date_payable : "N/A" ; + } elsif ($col eq 'amount_payable') { #dates_amounts_paid + $count_outstanding++ if $amnt_owed > 0 ; + $amnt_tots{"amount_payable"} += $amnt_owed ; + $val = ($amnt_owed != 0) ? &common_min_form_input_col("amount_payble_$temp_id\_$date_val",$amnt_owed) : "None" ; + $val_min = $amnt_owed ; + } elsif ($col eq 'paid') { + $val = ($amnt_owed != 0) ? &common_min_form_checkbox_col("paid_$temp_id\_$date_val",0) : '' ; + $val_min = ($amnt_owed != 0) ? "No" : "Yes" ; + } elsif ($col eq 'all_paid') { + $val = ($amnt_owed != 0) ? '' : '' ; + $val_min = ($amnt_owed != 0) ? "No" : "Yes" ; + } + $val_min = $val if $col eq 'date' || $col eq "$field\_names" ; + + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format_management_report_data) if $col ne 'shifts_count' ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format_management_report_data_ref_nr) if $col eq 'shifts_count' ; + $xlsxcol++ ; + # if ($_ eq 'ref_nr' or $_ eq 'camera_nr') { $val = &common_camera_links($tables,$id,$val) ;} + $print_tbody .= qq~$val~ ; + + } + $print_tbody .= qq~~ ; + $xlsxrow++ ; + $row_cnt++ ; + $quote_and_ops_ids .= qq~"$row_cnt\_$temp_id":"$date_val",~ ; + } + # chop $op_ids if $op_ids ; + # $quote_and_ops_ids .= qq~"$row_cnt_$id":[$op_ids],~ if $op_ids ; + } + + my $col_cnt = 0 ; + + foreach my $col (@sql_col_display) { + + if ($col eq 'date') { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$col_cnt,"TOTALS",$format_management_report_total) ; + } elsif ($col eq "amounts_paid" || $col eq "amount_payable") { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$col_cnt,"$amnt_tots{$col}",$format_management_report_totals) ; + } else { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$col_cnt,"-",$format_management_report_totals) ; + } + $col_cnt++ ; + } + + chop $quote_and_ops_ids if $quote_and_ops_ids ; + + # $print_tbody .= qq~~ ; + # $print_tbody .= qq~~ ; + $worksheet{$ws} -> set_column(0,0,15) ; + $worksheet{$ws} -> set_column(1,1,25) ; + $worksheet{$ws} -> set_column(2,7,20) if $i{paid_status} eq 'all' ; + $worksheet{$ws} -> set_column(2,5,20) if $i{paid_status} ne 'all' ; + + $box_icon .= qq~
    ~ if $i{paid_status} ne 'paid' && $count_outstanding > 0 ; + + &report_xlsx_export_footer('L',15,"$field\_payments_report") ; + + $fnsortcol = 0; + $fnsortorder = 'asc' ; + &common_min_extra_crumb("$lcpage\s","Search Screen") ; + + $trigger_jquery_raw .= qq~ + function selectAll() { + let jsObject = { + $quote_and_ops_ids + } ; + for (let key in jsObject) { + let op_id = jsObject[key] ; + let parts = key.split("_") ; + let event_id = parts[1] ; + \$(\$("#itv-table").dataTable().fnGetNodes()).find(\$("input[name=paid_"+event_id+"_"+op_id+"]")).each(function () { + // console.log("input[name=paid_"+event_id+"_"+op_id+"]") ; + if(\$(this).is(':checked')) { + \$(this).prop('checked',false) ; + } else { + \$(this).prop('checked',true) ; + } + }) ; + } + } + ~; + + my $field_id = "#$field2\-payment-form" ; + + # my $savebuttjs = ($count_outstanding > 0) ? qq~$("$field_id").submit();' : 'noty({text:"There are no calibrators to pay!",layout:"center",type:"error",timeout:3000});return;~ ; + + $trigger_jquery_raw .= qq~ + \$("#savebutt").click(function() { + // $savebuttjs + \$("$field_id").submit(); + }) ; + ~ ; + + $fcol = 2 ; + + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= &common_min_form_input_col("date_from",$i{date_from}) ; #date_from_i_field + $print_box_content_rows .= &common_min_form_input_col("date_to",$i{date_to}) ; #date_to_i_field + $print_box_content_rows .= &common_min_form_input_col("$field\_id",$i{"$field\_id"}) ; #temp_calibrator_id_i_field + $print_box_content_rows .= &common_min_form_input_col("$field\s_paid",$i{"$field\s_paid"}) ; + $print_box_content_rows .= qq~
    ~ ; + + $print_box_content_rows .= &common_min_forms_start("$field2\-payment") if $count_outstanding ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_load_list_vars { + + my ($where,$field) = @_ ; + + my $users_sql = ($field =~ /calibrator/) ? "`user_type` = 'casual_calibrator' OR `user_type` = 'support'" : "" ; + + &db_min_ro('users','id,name',"$users_sql",'','') ; + + &db_min_ro($table,"date,$field\_ids,$field\_dates_paid,$field\_amounts_paid,temp_calibrator_support_shifts","`date`>='$i{date_from}' AND `date`<='$i{date_to}' $where",'','') ; + + # &db_min_ro('shift_monitor_ids','date,monitor_ids',"`date`>='$i{date_from}' AND `date`<='$i{date_to}' $where",'','') ; + + our %operator_count = () ; our %amounts_paid = () ; our %dates_amounts_paid = () ; our %operator_shifts_string = () ; + + # my @monitor_shifts = ("","08:00-11:00","11:00-14:00","14:00-17:00","17:00-21:00") ; + my @operator_shifts = ($field =~ /calibrator/) ? ("","07:00-10:00","10:00-13:00","13:00-16:00","16:00-19:00") : ("","08:00-11:00","11:00-14:00","14:00-17:00","17:00-21:00") ; + + foreach my $date (keys %{$db{$table}}) { + my $shift_cnt = 0 ; + foreach my $shift (split(/\|/,$db{$table}{$date}{"$field\_ids"})) { + $shift_cnt++ ; + next unless $shift ; + foreach my $temp_id (split(/\;/,$shift)) { + next unless $temp_id ; + $operator_count{$date}{$temp_id} += 1 ; + $operator_shifts_string{$date}{$temp_id} .= qq~$operator_shifts[$shift_cnt];~ ; + } + } + $shift_cnt = 0 ; + # foreach my $shift (split(/\|/,$db{$table}{$date}{monitor_ids})) { + # $shift_cnt++ ; + # next unless $shift ; + # foreach my $temp_id (split(/\;/,$shift)) { + # next unless $temp_id ; + # $operator_count{$date}{$temp_id} += 1 ; + # $operator_shifts{$date}{$temp_id} .= qq~$monitor_shifts[$shift_cnt],~ ; + # } + # } + my @date_pay = split(/\;/,$db{$table}{$date}{"$field\_dates_paid"}) ; + my @amount_pay = split(/\;/,$db{$table}{$date}{"$field\_amounts_paid"}) ; + my $cnt = 0 ; + foreach my $temp_id_amnt (@amount_pay) { + my @temp_amnt = split(/\:/,$temp_id_amnt) ; + $amounts_paid{$date}{$temp_amnt[0]} += $temp_amnt[1] ; + $dates_amounts_paid{$temp_amnt[0]}{$date_pay[$cnt]} += $temp_amnt[1] ; + $cnt++ ; + } + + if ($temp_calibrator_payments_report && $db{$table}{$date}{temp_calibrator_support_shifts}) { + + foreach my $shift (split(/\|/,$db{$table}{$date}{temp_calibrator_support_shifts})) { + + $shift_cnt++ ; + next unless $shift ; + my @abc = split(/\:/,$shift) ; + next unless $abc[0] ; + + $operator_count{$date}{$abc[0]} += 0 ; + # $operator_count{$date}{$abc[0]} += ($abc[1] eq '1') ? 0.5 : 1 ; + $temp_calibrator_support{count}{$date}{$abc[0]}{$abc[1]} += ($abc[1] eq '1') ? 0.5 : 1 ; + $temp_calibrator_support{shift_count}{$date}{$abc[0]}{$abc[1]} += 1 ; + $operator_shifts_string{$date}{$abc[0]} .= ($abc[1] eq '1') ? qq~Half Day (<7 hours);~ : qq~Full Day (7 hours+);~ ; + $support_user{$abc[0]} = 1 ; + } + } + } + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_report_screen { + + my ($field) = @_ ; + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + &common_min_select_opts("$field\_id",'users',"name",$i{"$field\_id"},'','',"`name` NOT LIKE 'Rory%' AND `name` NOT LIKE 'Handre%'") ; + # &common_min_select_opts('event_quote_id','event_quotes',"ref",$i{event_quote_id},'','',"") ; + + $first_day_month = sprintf("%02d",$first_day_month) ; $first_day = sprintf("%02d",$first_day) ; + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-$now_mm-01") unless $i{date_from} ; + + my $days_in_month = Days_in_Month($now_year,$now_mm) ; + + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$days_in_month") ; + + # my ($sql_next_day) = &common_add_delta_days(1) ; + # my ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + # $print_box_content_rows .= &common_min_form_datepicker('date',"$next_year-$next_month-$next_day") ; #unless $i{date_from} ; + + $opts{paid_status} .= qq~~ ; + $opts{paid_status} .= qq~~ ; + $opts{paid_status} .= qq~~ ; + + $print_box_content_rows .= &common_min_form_select("$field\_id",'') ; + # $print_box_content_rows .= &common_min_form_select('event_quote_id','') ; + $print_box_content_rows .= &common_min_form_select('paid_status','') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------------------ + +1 ; \ No newline at end of file diff --git a/libs/modules/_FromProd/schedule_test.pm b/libs/modules/_FromProd/schedule_test.pm new file mode 100644 index 0000000..def5eb0 --- /dev/null +++ b/libs/modules/_FromProd/schedule_test.pm @@ -0,0 +1,1892 @@ +sub schedule_load_list_vars { + + my ($where) = @_ ; + + &db_min_ro('regions','*','','','') ; + + &db_min_ro('users','id,name,user_type,username,region_ids',"`name` NOT LIKE 'Rory%' AND `name` NOT LIKE 'Handre%'",'','') ; + $opts{schedule_users} .= qq~~ ; + # $opts{head_operator} .= qq~~ ; + foreach my $_uid (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + next if $useropts{it}{$db{users}{$_uid}{username}} ; + + my $regions = qq~~ ; + foreach (split(/\,/,$db{users}{$_uid}{region_ids})) { + $regions .= qq~$db{regions}{$_}{code},~ ; + } + chop $regions if $regions ; + $regions = qq~[$regions]~ if $regions ; + + # if ($db{users}{$_uid}{user_type} eq 'support' || $db{users}{$_uid}{user_type} eq 'manager' || $db{users}{$_uid}{user_type} eq 'casual_calibrator' || $monitoring_report) { + if ($db{users}{$_uid}{user_type} eq 'casual_calibrator' || (($monitoring_report || $troubleshoot_monitoring_report) && $db{users}{$_uid}{user_type} ne 'casual_c' && $db{users}{$_uid}{user_type} ne 'schools_manager' && $db{users}{$_uid}{user_type} ne 'support' && $db{users}{$_uid}{user_type} ne 'permanent')) { + $opts{schedule_users} .= qq~~ ; + } + + if (($db{users}{$_uid}{user_type} eq 'support' || $db{users}{$_uid}{user_type} eq 'casual_calibrator') && $temp_calibrator_report) { + $opts{support_users} .= qq~~ ; + $tot_support_users_cnt++; + } + + if ($db{users}{$_uid}{user_type} eq 'casual_c') { + $opts{fixture_check} .= qq~~ ; + } + } + + my $event_systems_sql_where = ($monitoring_report || $troubleshoot_monitoring_report) ? "" : "system_type = 'mobile'" ; + + &db_min_ro('event_systems','*',$event_systems_sql_where,'','') ; + + &db_min_ro($table,"id,club_ids,qty,ref,organisation_ids,quote_accepted,event_system_id_multiple,region_id,sport_type_ids,operator_ids,date_from,date_to,times_from,times_to,daily_operator_ids,days_active,monitor_ids,temp_calibrator_ids$extra_column","$where AND `quote_accepted` = '1'",'','') ; + + my $min_id = 0 ; my $max_id = 0 ; + + foreach my $id (keys %{$db{$table}}) { + + next unless $id ; my $cnt = 0 ; + + my @ed_from = &common_split_sql_time($db{$table}{$id}{date_from}) ; + my @ed_to = &common_split_sql_time($db{$table}{$id}{date_to}) ; + + &common_date_array("$ed_from[0]$ed_from[1]$ed_from[2]","$ed_to[0]$ed_to[1]$ed_to[2]") ; + + $sort_calibration_by_time_ref{"$ed_from[0]$ed_from[1]$ed_from[2]$ed_from[3]$ed_from[4]-$id"} = $id ; + + } + + &db_min_ro('sport_types','*','','','') ; + &db_min_ro('organisations','id,name','','','') ; + &db_min_ro('clubs','id,name','','','') if $monitoring_report || $troubleshoot_monitoring_report ; + + our $table_ = "shift_operator_ids" ; + my $col_ = ($monitoring_report) ? "monitor_ids" : ($troubleshoot_monitoring_report) ? "troubleshoot_monitor_ids" : "temp_calibrator_ids,temp_calibrator_support_shifts" ; + my $col2_ = ($monitoring_report) ? ",monitor_notes" : ($troubleshoot_monitoring_report) ? ",troubleshoot_monitor_notes" : "" ; + + &db_min_ro($table_,"date$col2_,$col_","`date` >= '$i{date_from}' AND `date` <= '$i{date_to}'") ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_build_extra_table { + + my ($field_name,$table_name,$table_col_name,$table_col_name_notes,$table_id) = @_ ; + + my $ws2 = join ' ', map { ucfirst $_ } split /_/, $field_name ; + $ws2 .= "s" ; + + &xlsxcreator_add_worksheet($ws2) ; + + my $col2 = 0 ; + foreach (@sql_col_display_extra) { + next if $_ eq "update" || !$_ || $_ eq 'notes' ; + my $coltitle = $_ ; + $coltitle =~ s/\_id//g ; + $coltitle =~ s/\_/ /g ; + my $ucfirst = join '', map { ucfirst lc } split /(\s+)/, $coltitle; + &xlsxcreator_write_xlsx($ws2,0,$col2,$ucfirst,$format_management_report_headings) ; + $col2++; + } + $col2=0 ; + &xlsxcreator_freeze_panes($ws2,1,0) ; # Freeze the first 3 rows + + my $uc_field_name = ucfirst $field_name ; + + # $db{$table_name}{$i{date}}{$table_col_name} = qq~147;132|||~ ; + + # for (0 .. 3) { $schedule_ids[$_] = "null" unless $schedule_ids[$_] ; } + $format84 -> set_left('1') ; + + my ($s_year,$s_mon,$s_day) = split("-",$i{date_from}) ; + my ($e_year,$e_mon,$e_day) = split("-",$i{date_to}) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + + our $date_cnt = 1 ; my $row_cnt = 0 ; + + return if int("$s_year$s_mon$s_day") > int("$e_year$e_mon$e_day") ; + + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + my %row_cnt_shifts = () ; my $max_row_cnt = 0 ; + + while (int("$s_year$s_mon$s_day") <= int("$e_year$e_mon$e_day")) { + + $db{$table_name}{"$s_year-$s_mon-$s_day"}{$table_col_name} =~ s/\;/\,/g ; + my @schedule_ids = split(/\|/,$db{$table_name}{"$s_year-$s_mon-$s_day"}{$table_col_name}) ; + + my $date = "$s_year-$s_mon-$s_day" ; + + my $date_str = &common_min_date_as_string($date) ; + + our $default_javascript = "" ; my %default_javascript_short = () ; + + my $val_notes = qq~~ ; + + foreach my $col (@sql_col_display_extra) { + + my $formatting = $format92 ; + next if substr($col,0,5) eq 'shift' && substr($col,0,7) ne 'shift_1' ; + my $val = '' ; my $nowrap = '' ; my $align = qq~~ ; my $val_min = "" ; + + my $row_span = '' ; + + if ($col eq 'date') { + + $row_cnt++ ; + $row_span = qq~rowspan="2"~ if $monitoring_report || $troubleshoot_monitoring_report ; + $val = $date_str . qq~~ ; + $nowrap = "nowrap" ; + &xlsxcreator_write_xlsx($ws2,$max_row_cnt+1,0,$date_str ,$formatting) ; + + } elsif (substr($col,0,7) eq 'shift_1') { + + $align = qq~ class="dt-center"~ ; + + local $place_holder = substr($ws2,0,-1) ; + + for (1 .. 4) { + $row_cnt_shifts{$_} = $max_row_cnt + 1 ; + } + + for my $shift_cnt (1 .. 4) { + + # $row_cnt_shifts{$shift_cnt} = ($max_row_cnt && $shift_cnt == 1) ? $max_row_cnt + 1 : 1 ; + my $field = "$field_name\_$shift_cnt\_1_1_$date_cnt" ; + $opts{$field} = $opts{schedule_users} ; + $preferred_placeholder{$field} = ($troubleshoot_monitoring_report) ? "Shift Troubleshoot Monitor $shift_cnt $date_cnt" : "$place_holder $shift_cnt $date_cnt" ; + $multiple{$field} = 1 ; + + my $table_col = 6-$shift_cnt ; + push @first_table_multi_select_table_cells,"#$table_id tr:eq($row_cnt) td:nth-last-child($table_col)" ; + + $val .= &common_min_table_select($field,$schedule_ids[$shift_cnt - 1],'',$row_cnt,$table_col,'',$schedule_ids[$shift_cnt - 1],'shift',$table_id) ; + foreach (split(/\,/,$schedule_ids[$shift_cnt - 1])) { + next unless $_ ; + $trigger_jquery_raw .= qq~\$("#select$uc_field_name\_$shift_cnt\_1_1_$date_cnt option[value='$_']").prop("selected",true);~ ; + &xlsxcreator_write_xlsx($ws2,$row_cnt_shifts{$shift_cnt},$shift_cnt,"$db{users}{$_}{name}",$formatting) ; + $row_cnt_shifts{$shift_cnt}++ ; + } + $max_row_cnt = $row_cnt_shifts{$shift_cnt} if !$max_row_cnt || $max_row_cnt < $row_cnt_shifts{$shift_cnt} ; + $val .= qq~~ if $shift_cnt < 4 ; + } + + } elsif ($col eq 'notes') { + + $row_cnt++ ; + + my @notes = split(/\:\|\:/,$db{$table_name}{$date}{$table_col_name_notes}) ; + # $max_row_cnt-- ; + # $max_row_cnt++ if $db{$table_name}{$date}{$table_col_name_notes} =~ /(\d+)/g || $db{$table_name}{$date}{$table_col_name_notes} =~ /[a-zA-Z]/ ; + + for my $shift_cnt (1 .. 4) { + + my $field = "$field_name\_notes_$shift_cnt\_1_1_$date_cnt" ; + $preferred_placeholder{$field} = ($troubleshoot_monitoring_report) ? "Shift Troubleshoot Monitor Notes $shift_cnt $date_cnt" : "Shift Monitor Notes $shift_cnt $date_cnt" ; + $val_notes .= &common_min_table_textarea($field,$notes[$shift_cnt-1],'',$row_cnt,5-$shift_cnt,'',$notes[$shift_cnt-1],'',$table_id) ; + &xlsxcreator_write_xlsx($ws2,$max_row_cnt,$shift_cnt,$notes[$shift_cnt-1],$format97) if $db{$table_name}{$date}{$table_col_name_notes} =~ /(\d+)/g || $db{$table_name}{$date}{$table_col_name_notes} =~ /[a-zA-Z]/ ; + $val_notes .= qq~~ if $shift_cnt < 4 ; + + } + + $val_notes = qq~$val_notes~ ; + + } elsif ($col eq "update") { + + $row_span = qq~rowspan="2"~ if $monitoring_report || $troubleshoot_monitoring_report ; + $align = qq~ class="dt-center"~ ; + my $field = "update_1_1_$date_cnt" ; + $val = &common_min_form_checkbox_col($field,'') ; + + chop $default_javascript if $default_javascript ; + + if ($default_javascript) { + + push @default_javascript_by_id, qq~"1_1_$date_cnt":{$default_javascript}~ ; ## ??? + + for (1 .. 4) { + my $field = "#textarea" . ucfirst "$field_name\_notes\_$_\_1_1_$date_cnt" ; + push @all_update_field_ids,"$field" if $monitoring_report || $troubleshoot_monitoring_report ; + $field = "#select" . ucfirst "$field_name\_$_\_1_1_$date_cnt" ; + push @all_update_field_ids,"$field" ; + } + } + } + + $print_tbody_extra .= qq~$val~ if $col ne 'notes' ; + + $print_tbody_extra .= qq~$val_notes~ if $col eq 'update' ; + + } + + ($s_year,$s_mon,$s_day) = Add_Delta_Days($s_year,$s_mon,$s_day,1) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + $date_cnt++ ; + } + + $date_cnt-- ; + + # &common_min_table_select_fixed_width_jquery(1) ; + # &common_min_table_select_default_values_jquery ; + + # @all_select_ids = () ; @selects_with_default_ids = () ; %col_name_select_ids = () ; %table_with_default_ids = () ; %selects_by_def_val = () ; + + @sql_col_display_extra = ("date","shift_1_(08:00-11:00)","shift_2_(11:00-14:00)","shift_3_(14:00-17:00)","shift_4_(17:00-21:00)","update") if $monitoring_report || $troubleshoot_monitoring_report ; + + $worksheet{$ws2}->set_column(0,0,10) ; + $worksheet{$ws2}->set_column(1,5,50) if $monitoring_report || $troubleshoot_monitoring_report ; + $worksheet{$ws2}->set_column(1,5,20) if $temp_calibrator_report ; + + $trigger_jquery_raw .= qq~\$("#$table_id tr:eq(0) th:nth-last-child(2),#$table_id tr th:nth-last-child(3),#$table_id tr th:nth-last-child(4),#$table_id tr th:nth-last-child(5)").css("width","23%")~ ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_build_extra_second_table { + + my ($field_name,$table_name,$table_col_name) = @_ ; + + my $ws2 = join ' ', map { ucfirst $_ } split /_/, $field_name ; + $ws2 .= "s" ; + + &xlsxcreator_add_worksheet($ws2) ; + + my $col2 = 0 ; + foreach (@sql_col_display_2) { + next if $_ eq "update" || !$_ ; + my $coltitle = $_ ; + $coltitle =~ s/\_id//g ; + $coltitle =~ s/\_/ /g ; + my $ucfirst = join '', map { ucfirst lc } split /(\s+)/, $coltitle; + &xlsxcreator_write_xlsx($ws2,0,$col2,$ucfirst,$format_management_report_headings) ; + $col2++; + } + $col2=0 ; + &xlsxcreator_freeze_panes($ws2,1,0) ; # Freeze the first 3 rows + + my ($s_year,$s_mon,$s_day) = split("-",$i{date_from}) ; + my ($e_year,$e_mon,$e_day) = split("-",$i{date_to}) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + + $opts{name} = $opts{support_users} ; + + $radio_opts{shift} = "Half Day (<7 hours);Full Day (7 hours+)" ; + + my $nr_of_options = scalar split("option> int("$e_year$e_mon$e_day") ; + + my $date1 = "$s_year-$s_mon-$s_day" ; + my $date2 = "$e_year-$e_mon-$e_day" ; + my $d1 = Time::Piece->strptime($date1, "%Y-%m-%d") ; + my $d2 = Time::Piece->strptime($date2, "%Y-%m-%d") ; + my $diff_in_days = ($d2 - $d1)->days + 1; + + my $date_cnt= 0 ; + + &common_min_thead_2 ; + + for my $day_cnt (1 .. $diff_in_days) { + + my $date = "$s_year-$s_mon-$s_day" ; + + $db{$table_name}{$date}{$table_col_name} = "None" unless $db{$table_name}{$date}{$table_col_name} ; + + $date_cnt++ ; + + push @second_table_ids,"#select_temp_calibrators_2_$date_cnt" ; + push @second_table_ids_2,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(2)" ; + push @second_table_ids_3,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(3)" ; + push @second_table_ids_4,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(4)" ; + push @second_table_ids_5,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(5)" ; + + $print_tbody_extra_2 .= qq~~ ; + $print_tbody_extra_2 .= qq~$print_thead_2~ if $date_cnt == 1 ; + $print_tbody_extra_2 .= qq~~ ; + + my $row_cnt = 0 ; + + $opts{name} = $opts{support_users} ; + + my $z_index = $tot_support_users_cnt * ($diff_in_days - $day_cnt + 1) + 1 ; + + foreach my $row (split(/\|/,$db{$table_name}{$date}{$table_col_name})) { + + $z_index-- ; + + next unless $row ; + + $row_cnt++ ; + $print_tbody_extra_2 .= qq~~ ; + + our $default_javascript = qq~~ ; + + $xlsxrow++ ; $xlsxcol = 0 ; + + foreach my $col (@sql_col_display_2) { + + my $formatting = $format84 ; + my $val = '' ; my $nowrap = '' ; my $align = qq~class="dt-center"~ ; + + my $field_id = "$col\_2_$row_cnt\_$date_cnt" ; + + my $default_val_html = qq~~ ; + + if ($col eq 'date') { + my $date_str = &common_min_date_as_string($date) ; + $val = $date_str ; + $nowrap = "nowrap" ; + $align = qq~class="dt-left"~ ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow,$xlsxcol,"$date_str",$formatting) ; + } elsif ($col eq 'name') { + my @abc = split(/\:/,$row) ; + $abc[0] = "" if $abc[0] eq "None" ; + $default_val = $abc[0] ; + $default_val_is_saved = ($default_val) ? 1 : 0 ; + $preferred_placeholder{$field_id} = "Select Temp Support Name $row_cnt" ; + $opts{$field_id} = $opts{name} ; + + my $table_row_cnt = ($date_cnt == 1) ? $row_cnt + 1 : $row_cnt - 1 ; + + $val = &common_min_table_select($field_id,$default_val,'',$table_row_cnt,4,'',$default_val_is_saved,'',"select_temp_calibrators_2_$date_cnt") ; + # $default_val_html = qq~~ ; + + $trigger_jquery_raw .= qq~ + \$("#select_temp_calibrators_2_$date_cnt tr:eq($table_row_cnt) td:nth-last-child(4)").css("z-index","$z_index") ; + ~ ; + $support_users_cnt-- ; + $opts{name} =~ s/.*?<\/option>// if $default_val ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow,$xlsxcol,$db{users}{$default_val}{name},$formatting) ; + } elsif ($col eq 'shift') { + $radio_opts{$field_id} = $radio_opts{shift} ; + my @abc = split(/\:/,$row) ; + $default_val = $abc[1] ; + $default_val_is_saved = ($default_val) ? 1 : 0 ; + # $default_val_html = qq~~ ; + our $val_min = "" ; + my $table_row_cnt = ($date_cnt == 1) ? $row_cnt + 1 : $row_cnt - 1 ; + $val = &table_radio_button($field_id,$default_val,'',$table_row_cnt,3,'',$default_val_is_saved,$col,"select_temp_calibrators_2_$date_cnt") ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow,$xlsxcol,$val_min,$formatting) ; + } elsif ($col eq 'update') { + $val = &common_min_table_checkbox($field_id) ; + chop $default_javascript if $default_javascript ; + if ($default_javascript) { + push @default_javascript_by_id, qq~"2_$row_cnt\_$date_cnt":{$default_javascript}~ ; + push @all_update_field_ids, "#shift_1_2_$row_cnt\_$date_cnt,#shift_2_2_$row_cnt\_$date_cnt,#selectName_2_$row_cnt\_$date_cnt" ; + } + } elsif (!$col) { + $val = ($row ne 'None') ? qq~ ~ : qq~~ ; + } + + my $styling = ($col eq 'date' && $row_cnt == 1) ? qq~style="width:7%;"~ : ($col eq 'name' && $row_cnt == 2) ? qq~style="width:35%;"~ : '' ; + + $print_tbody_extra_2 .= qq~~ ; + $xlsxcol++ ; + } + $print_tbody_extra_2 .= qq~~ ; + } + + ($s_year,$s_mon,$s_day) = Add_Delta_Days($s_year,$s_mon,$s_day,1) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + + if ($nr_of_options <= $row_cnt) { + $trigger_jquery_raw .= qq~\$("#add_row_table_2_$date_cnt").css("display","none");~ ; + } + + my $plus_button_color = ($db{shift_operator_ids}{$date}{temp_calibrator_support_shifts} =~ /\|\|/ || $db{shift_operator_ids}{$date}{temp_calibrator_support_shifts} =~ /\|\:/ || $db{shift_operator_ids}{$date}{temp_calibrator_support_shifts} eq "None") ? "grey" : "blue" ; + + push @plus_btn_ids,"#add_row_table_2_$date_cnt" ; + + $plus_button = qq~ + +
    +
    + + +
    +
    +
    +
    +
    + ~ ; + + $print_tbody_extra_2 .= qq~
    $val
    $plus_button~ ; + } + + $worksheet{$ws2}->set_column('A:C',20); + + &common_min_table_update_checkbox_col_default ; + + our $trigger_jquery_raw_default_alt = qq~ + // let all_def_vals = {} ; + + // all_def_vals[row_nr] = {} ; + + // let def_name = \$("#default_name_"+row_nr ).text() ; + // let def_shift = \$("#default_shift_"+row_nr ).text() ; + + // all_def_vals[row_nr]["selectName_"+row_nr] = def_name ; + + // if (def_shift == "1") { + // all_def_vals[row_nr]["shift_1_"+row_nr ] = "true" ; + // all_def_vals[row_nr]["shift_2_"+row_nr ] = "false" ; + // } else if (def_shift == "2") { + // all_def_vals[row_nr]["shift_1_"+row_nr ] = "false" ; + // all_def_vals[row_nr]["shift_2_"+row_nr ] = "true" ; + // } + ~ ; + + my $plus_btn_ids_str = join(",",@plus_btn_ids) ; + + $trigger_jquery_raw .= qq~ + + function add_Days (date_string,num_days,as_num) { + let date = new Date(date_string) ; + date.setDate(date.getDate() + num_days) ; + let year = date.getFullYear() ; + let month = String(date.getMonth() + 1).padStart(2,'0') ; + let day = String(date.getDate()).padStart(2,'0') ; + if (as_num) { + return ""+year+"-"+month+"-"+day+"" ; + } else { + let month_names = ["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] ; + month = month_names[month] ; + return ""+day+"-"+month+"-"+year+"" ; + } + } + + function deleteTempSupport (row_cnt) { + + BootstrapDialog.confirm({ + title: 'Confirm Delete', + message: 'Are you sure you want to delete '+name+'?', + type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + callback: function(result) { + + let [cnt_for_date,table_cnt] = row_cnt.split('_').map(Number) ; + + if (result) { + // if (\$("#update_data_base_"+row_cnt).text()) { + + let curr_date = add_Days("$i{date_from}",table_cnt-1,1) ; + + let url_delete = "$useropts{scripts}/get/get_db_delete_temp_support.pl?date="+curr_date+"&row_cnt="+cnt_for_date ; + + console.log("url_delete : "+url_delete) ; + + // console.log("#select_temp_calibrators_2_"+table_cnt+" #second_table_"+cnt_for_date+"_"+table_cnt) ; + + \$("#select_temp_calibrators_2_"+table_cnt+" #second_table_"+cnt_for_date+"_"+table_cnt).remove() ; + + \$.get(url_delete) ; + // } + // $("select#selectOriginalId").attr("id", "selectNewId"); + + let table_row_cnt = \$("#select_temp_calibrators_2_"+table_cnt).find('tr').length - 2 ; + + // let start_row_nr = 2 ; let end_row_nr = table_row_cnt + 1 ; + + if (table_cnt != '1') { + table_row_cnt += 2 ; + // start_row_nr = 0 ; + // end_row_nr -= 2 ; + } + + let all_def_vals_new = {} ; + + for (let i=2;i<=table_row_cnt+1;i++) { + + let row_nr = i-1 ; + let row_val = i ; + if (table_cnt != '1') { + row_val -= 2 ; + } + + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+")").attr("id","second_table_"+row_nr+"_"+table_cnt); + + let zIndex = \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(4)").css('z-index'); + zIndex++ ; + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(4)").css('z-index',zIndex); + if (\$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(1)").html()) { + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(1)").html(" "); + } + + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+")").find("select[id^='selectName_']").each(function() { + + var oldId = \$(this).attr("id"); + let old_row_val = get_row_nr(oldId,2) ; + let new_row_val = row_nr+"_"+table_cnt ; + + if (typeof all_def_vals["2_"+old_row_val] !== 'undefined') { + + all_def_vals_new["2_"+new_row_val] = {}; + all_def_vals_new["2_"+new_row_val]["selectName_2_"+new_row_val] = all_def_vals["2_"+old_row_val]["selectName_2_"+old_row_val] ; + all_def_vals_new["2_"+new_row_val]["shift_1_2_"+new_row_val] = all_def_vals["2_"+old_row_val]["shift_1_2_"+old_row_val] ; + all_def_vals_new["2_"+new_row_val]["shift_2_2_"+new_row_val] = all_def_vals["2_"+old_row_val]["shift_2_2_"+old_row_val] ; + + } + + let old_select_val = \$("#"+oldId).val() ; + + \$(this).attr("id", "selectName_2_"+new_row_val); + \$(this).attr("name", "name_2_"+new_row_val); + \$(this).attr("data-placeholder", "Select Temp Support Name "+row_nr); + var chosenElementId = oldId + "_chosen"; + \$("#" + chosenElementId).attr("id", "selectName_2_"+row_nr+"_"+table_cnt+"_chosen"); + \$("#selectName_2_"+row_nr+"_"+table_cnt+"_chosen .chosen-single span").text("Select Temp Support Name "+row_nr); + + \$("#shift_1_2_"+old_row_val).attr("name","shift_2_"+new_row_val); + \$("#shift_1_2_"+old_row_val).attr("id","shift_1_2_"+new_row_val); + \$("#shift_2_2_"+old_row_val).attr("name","shift_2_"+new_row_val); + \$("#shift_2_2_"+old_row_val).attr("id","shift_2_2_"+new_row_val); + \$("#checkboxUpdate_2_"+old_row_val).attr("name","update_2_"+new_row_val); + \$("#checkboxUpdate_2_"+old_row_val).attr("id","checkboxUpdate_2_"+new_row_val); + + // \$("#default_name_"+old_row_nr).attr("id","default_name_"+row_nr); + // \$("#default_shift_"+old_row_nr).attr("id","default_shift_"+row_nr); + + \$("#selectName_2_"+new_row_val).val(old_select_val) ; + \$("#selectName_2_"+new_row_val).trigger("chosen:updated") ; + + if (\$("#add_row_table_2_"+table_cnt).is(":hidden")) { + \$("#add_row_table_2_"+table_cnt).css("display","") ; + } + + }) ; + + } + + all_def_vals = all_def_vals_new ; + + if (!\$("#second_table_1_"+table_cnt).html()) { + + let options = "$opts{support_users}" ; + let select = add_select("name_2_1_"+table_cnt,"selectName_2_1_"+table_cnt,"Select Temp Support Name 1","$opts{support_users}",1,90) ; + let radio_butt = "  " ; + let update_butt = "" ; + let newRow = ""+curr_date+""+select+""+radio_butt+""+update_butt+"" ; + \$("#select_temp_calibrators_2_"+table_cnt+" tbody").append(newRow) ; + \$("#selectName_2_1_"+table_cnt).chosen({allow_single_deselect:true}) ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("position","absolute") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("width","90%") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("left","5%") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("top","50%") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("transform","translateY(-50%)") ; + + let optionCount = \$("#selectName_2_1_"+table_cnt+" option").length - 1 ; + + let date_cnt = daysBetween("$i{date_from}","$i{date_to}") ; + + let z_index = (date_cnt - table_cnt + 1)*optionCount ; + + let row_val = 2 ; + if (table_cnt != '1') { + row_val = 0 ; + } + + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(4)").css("z-index",z_index) ; + + \$("#selectName_2_1_"+table_cnt+",#shift_1_2_1_"+table_cnt+",#shift_2_2_1_"+table_cnt).change( function () { + + let found_blank = 0 ; + + if ((!\$("#selectName_2_1_"+table_cnt).val() || (!\$("#shift_1_2_1_"+table_cnt).is(":checked") && !\$("#shift_2_2_1_"+table_cnt).is(":checked"))) && \$("#second_table_1_"+table_cnt).html()) { + found_blank = 1 ; + } + + if (!found_blank) { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('grey').addClass('blue'); + } else { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('blue').addClass('grey'); + } + + let tick_update = 0 ; + + if ((\$("#"+this.id).attr('type') == 'radio' && \$("#"+this.id).is(":checked")) || (\$("#"+this.id).val() && \$("#"+this.id).attr('type') != 'radio')) { + tick_update = 1 ; + } + + if (tick_update && !\$("#checkboxUpdate_2_1_"+table_cnt).is(":checked")) { + \$("#checkboxUpdate_2_1_"+table_cnt).prop("checked",true) ; + } else if (!tick_update && \$("#checkboxUpdate_2_1_"+table_cnt).is(":checked")) { + \$("#checkboxUpdate_2_1_"+table_cnt).prop("checked",false) ; + } + + }) ; + } + } + } + }); + } + + ~ ; + + $trigger_jquery_raw .= qq~ + + function daysBetween(date1,date2) { + + const oneDay = 24 * 60 * 60 * 1000 ; + const firstDate = new Date(date1) ; + const secondDate = new Date(date2) ; + const diffInTime = Math.abs(secondDate - firstDate) ; + + return Math.ceil(diffInTime/oneDay) + 1 ; + + } + + function add_select (field_name,field_id,placeholder,options,tindex,width) { + + let select_raw = "" ; + + return select_raw ; + } + + \$("$plus_btn_ids_str").click( function () { + + let table_nr = get_row_nr(this.id) ; + + let table_row_cnt = \$("#select_temp_calibrators_2_"+table_nr).find('tr').length ; + + if (table_nr == '1') { + table_row_cnt -= 2 ; + } + + let found_blank = 0 ; + // console.log("table_row_cnt : "+table_row_cnt) ; + + // let lastRowId = \$("#select_temp_calibrators_2 tr:last").attr("id"); + // let table_row_cnt = get_row_nr(lastRowId) ; + + for (i=1;i<=table_row_cnt;i++) { + if ((!\$("#selectName_2_"+i+"_"+table_nr).val() || \$("#selectName_2_"+i+"_"+table_nr).val() == null || (!\$("#shift_1_2_"+i+"_"+table_nr).is(":checked") && !\$("#shift_2_2_"+i+"_"+table_nr).is(":checked"))) && \$("#second_table_"+i+"_"+table_nr).html()) { + found_blank = 1 ; + } + } + + if (!found_blank) { + + \$('#add_row_table_2_'+table_nr).find('i').removeClass('blue').addClass('grey'); + + table_row_cnt++ ; + + let options = "$opts{support_users}" ; + + let select = add_select("name_2_"+table_row_cnt+"_"+table_nr,"selectName_2_"+table_row_cnt+"_"+table_nr,"Select Temp Support Name "+table_row_cnt,"$opts{support_users}",1,90) ; + // "Half Day (<7 hours);Full Day (7 hours+)" + let radio_butt = "  " ; + + // let delete_butt = " " ; + let delete_butt = "" ; + + let update_butt = "" ; + + let curr_date = add_Days("$i{date_from}",table_nr-1) ; + + let newRow = ""+curr_date+""+select+""+radio_butt+""+update_butt+""+delete_butt+"" ; + + \$("#select_temp_calibrators_2_"+table_nr+" tbody").append(newRow) ; + + // let optionCount = \$("#selectName_2_"+table_row_cnt+"_"+table_nr+" option").length - 1 ; + let optionCount = \$("#selectName_2_1_"+table_nr+" option").length - 1 ; + + let date_cnt = daysBetween("$i{date_from}","$i{date_to}") ; + + // my $support_users_cnt = $potential_support_users_cnt - ($day_cnt - 1)*$tot_support_users_cnt ; + + let z_index = (date_cnt - table_nr + 1)*optionCount - table_row_cnt + 1 ; + + // let optionCount = "$tot_support_users_cnt" ; + + // \$("#selectName_"+table_row_cnt).chosen({allow_single_deselect:true}) ; + + for (i=1;i 1) { + // let row_nr = get_row_nr(this.id) ; + // for (i=1;i<=table_row_cnt;i++) { + // for (j=1;j<=table_row_cnt;j++) { + + // } + // } + + } + + if (!found_blank) { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('grey').addClass('blue'); + } else { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('blue').addClass('grey'); + } + + }) ; + + ~ ; + + my $second_table_ids_str = join(",",@second_table_ids) ; + my $second_table_ids_str_2 = join(",",@second_table_ids_2) ; + my $second_table_ids_str_3 = join(",",@second_table_ids_3) ; + our $second_table_ids_str_4 = join(",",@second_table_ids_4) ; + my $second_table_ids_str_5 = join(",",@second_table_ids_5) ; + + &common_min_table_select_fixed_width_jquery("$second_table_ids_str_4") ; + + &common_min_table_select_default_values_jquery ; + + # &common_min_table_select_jquery("#select_temp_calibrators_2 td:nth-last-child(4)","") ; + + &common_min_table_update_checkbox_col_jquery("3") ; + + $trigger_jquery .= qq~ + \$("#select_temp_calibrators_2_length").css("display","none") ; + \$("#select_temp_calibrators_2_filter").css("display","none") ; + \$("#select_temp_calibrators_2_info").css("display","none") ; + \$("#select_temp_calibrators_2_paginate").css("display","none") ; + ~ ; + + $trigger_jquery .= qq~ + // \$("#select_temp_calibrators_2").css("width","66.66666%"); + \$("$second_table_ids_str_5").css("width","7%") ; + \$("$second_table_ids_str_4").css("width","40%") ; + // \$("$second_table_ids_str_4").css("position","relative") ; + // \$("$second_table_ids_str_4").css("text-align","center") ; + \$("$second_table_ids_str_3").css("width","40%") ; + \$("$second_table_ids_str_2").css("width","10%") ; + ~ ; + + +} #------------------------------------------------------------------------------------------ + +sub table_radio_button { + +my ($field,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved,$col_name,$table_id) = @_ ; + +return unless $col_name ; + +$field = "$col_name\_$table_row" unless $field ; + +my $field_cnt = $field ; +$field_cnt =~ s/$col_name\_//g ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +my @opts = ($radio_opts{$field}) ? split(/\;/,$radio_opts{$field}) : split(/\;/,$options); + +my $row = qq~~ ; + +my $cnt = 0 ; + +if ($default_val && $default_val_is_saved) { + $background_color = "#424949" unless $background_color ; + $table_with_default_ids{$background_color} .= "#$table_id tr:eq($table_row) td:nth-last-child($table_col)," ; +} + +foreach (@opts) { + $cnt++ ; + my $checked = ($cnt eq $default_val) ? 'CHECKED' : '' ; + $val_min = ($checked) ? $_ : $val_min ; + $row .= qq(  ) ; + if (!$default_val_is_saved || !$default_val) { + $default_javascript .= qq~"$col_name\_$cnt\_$field_cnt":"false",~ ; + } else { + my $default_val_boolian = ($cnt eq $default_val) ? "true" : "false" ; + $default_javascript .= qq~"$col_name\_$cnt\_$field_cnt":"$default_val_boolian",~ ; + } + push @all_radio_ids,"#shift_$cnt\_$field_cnt" ; +} + +$row = substr($row,0,-12) ; + +# my $row = qq($print_radios) ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_build_table { + + my ($table_col_name,$field_name) = @_ ; + + my $cali_cnt = 0 ; my $found_editable = 0 ; my @all_select_ids = () ; + + $format84 -> set_align("center") ; + + my $table_row = 0 ; my %default_vals = () ; + + # foreach my $id (sort {$db{$table}{$a}{date_from} cmp $db{$table}{$b}{date_from}} keys %{$db{$table}}) { + foreach my $date_ref (sort keys %sort_calibration_by_time_ref) { + + my $id = $sort_calibration_by_time_ref{$date_ref} ; + + next unless $id ; + + my $system_count = 0 ; my $system_day_cnt = 0 ; + + my %default_monitors = () ; + + my $day_cnt = 0 ; + my $sql_col = "$table_col_name" ; + my $inp_field = substr($sql_col,0,-1) ; + my $found_inp_field = 0 ; + foreach my $day_row (split(/\|/,$db{$table}{$id}{$sql_col})) { + $day_cnt++ ; $system_count = 0 ; + foreach my $system_row (split(/\;/,$day_row)) { + $system_count++ ; my $shift_cnt = 0 ; + foreach my $shift_monitor (split(/\:/,$system_row)) { + $shift_cnt++ ; + $default_monitors{$day_cnt}{$system_count}{$shift_cnt} = $shift_monitor ; + $found_inp_field = 1 if $shift_monitor eq $i{$inp_field} ; + } + } + } + $system_count = 0 ; + + my %system_has_daily_op = () ; my %default_op_ids = () ; + + foreach my $system_row (split(/\|/,$db{$table}{$id}{daily_operator_ids})) { + $system_count++ ; + next unless $system_row ; + $system_day_cnt = 0 ; + foreach my $col (split(/\;/,$system_row)) { + $system_day_cnt++ ; + next unless $col ; + $default_op_ids{$system_count}{$system_day_cnt} = $col if $col ; + $system_has_daily_op{$system_count} = 1 if $col ; + } + } + $system_count = 0 ; + + unless (&common_check_if_string_contains_an_integer($db{$table}{$id}{event_system_id_multiple})) { + $db{$table}{$id}{event_system_id_multiple} = ";none;" ; + } + + # my @system_name_ids = split(";",$db{$table}{$id}{event_system_id_multiple}) ; + + my @system_name_ids = split(/\;/,$db{$table}{$id}{event_system_id_multiple}) ; + my @club_ids = split(/\;/,$db{$table}{$id}{club_ids}) ; + my @op_ids = split(/\,/,$db{$table}{$id}{operator_ids}) ; + my @days_active = split(/\;/,$db{$table}{$id}{days_active}) ; + my @start_times = ($db{$table}{$id}{qty} eq '1' && $days_active[0]) ? () : split(/\;/,";".$db{$table}{$id}{times_from}) ; + my @end_times = ($db{$table}{$id}{qty} eq '1' && $days_active[0]) ? () : split(/\;/,$db{$table}{$id}{times_to}) ; + + my $cnt_rows = 0 ; + for (1 .. 50) { + $cnt_rows = $_ if $system_name_ids[$_ - 1] or $club_ids[$_ - 1] ; + } + + my $system_count = 0 ; my $system_day_cnt = 0 ; + + foreach my $event_sys_id (@system_name_ids) { + + $system_count++ ; + + next unless $event_sys_id ; + next if $db{event_systems}{$event_sys_id}{system_type} ne 'mobile' && !$monitoring_report && !$troubleshoot_monitoring_report ; + + # &common_debug(">>>>>>>>> 2. $system_count [$id] $db{$table}{$id}{ref} [$db{event_systems}{$event_sys_id}{system_type}]") ; + + # $event_cnt++ ; + + # foreach my $cal_date (sort {$day_of_week{$a} cmp $day_of_week{$b}} keys %day_of_week) { + + $system_day_cnt = 0 ; + + foreach my $cal_date (sort keys %day_of_week) { + + # my $srch_date_from_comp = $i{date_from} ; $srch_date_from_comp =~ s/\-//g ; + # my $srch_date_to_comp = $i{date_to} ; $srch_date_to_comp =~ s/\-//g ; + my $date_from_comp = substr($db{$table}{$id}{date_from},0,10) ; $date_from_comp =~ s/\-//g ; + my $date_to_comp = substr($db{$table}{$id}{date_to},0,10) ; $date_to_comp =~ s/\-//g ; + my $cal_date_comp = $cal_date ; # $cal_date_comp =~ s/\-//g ; + $cal_date = substr($cal_date,0,4) . '-' . substr($cal_date,4,2) . '-' . substr($cal_date,6,2) ; + my $date_from = substr($db{$table}{$id}{date_from},0,10) ; + $system_day_cnt++ ; + + # &common_debug("[$cnt{$event_sys_id}{$id}] : $event_sys_id [$id] $cal_date") ; + + # &common_debug("1. DATE >>> $cal_date_comp < $date_from_comp") if !$report ; + next if $cal_date_comp < $date_from_comp ; + # &common_debug("2. DATE >>> $cal_date_comp > $date_to_comp") if !$report ; + next if $cal_date_comp > $date_to_comp ; + + $cnt{$event_sys_id}{$id}++ ; + + next if $db{$table}{$id}{days_active} && !$days_active[$cnt{$event_sys_id}{$id}-1] ; + + my $cal_date_val = $cal_date ; my $date_from_val = $i{date_from} ; my $date_to_val = $i{date_to} ; + + $cal_date_val =~ s/\-//g ; $date_from_val =~ s/\-//g ; $date_to_val =~ s/\-//g ; + + next if $cal_date_val < $date_from_val || $cal_date_val > $date_to_val ; + + # # &common_debug("3. DATE >>> $cal_date_comp > $srch_date_to_comp") if !$report ; + # next if ($calibration_report) && $cal_date_comp > $srch_date_to_comp ; + # # &common_debug("4. DATE >>> $cal_date_comp < $srch_date_from_comp") if !$report ; + # next if ($calibration_report) && $cal_date_comp < $srch_date_from_comp ; + + # &common_debug(">>>>>>>>> 3. $system_count [$id] $db{$table}{$id}{ref} [$db{event_systems}{$event_sys_id}{system_type}]") ; + + # &common_debug("[$cnt{$event_sys_id}{$id}] : $event_sys_id [$id] $cal_date [$cal_date_comp > $srch_date_to_comp]") ; + + $cali_cnt++; + + $xlsxcol = 0 ; + $print_tbody .= qq~~ ; + $table_row++ ; + + our $default_javascript = "" ; + + foreach (@sql_col_display) { + + # &common_debug("1. XLSX >>> $_") if !$report ; + + next unless $_ ; # blank for the buttons column + + my $formatting = $format84 ; + my $val = $db{$table}{$id}{$_} ; + my $val_min = $val ; + my $align = qq~ class="dt-center"~ ; + my $nowrap = '' ; + + # &common_debug("2. XLSX >>> val_min=$val_min") if !$report ; + + my $sys_day_cnt = $cnt{$event_sys_id}{$id} ; + + if ($_ eq 'count') { + # $val = $event_cnt ; + $val = $cali_cnt ; + } elsif ($_ eq 'event_nr') { + $val = "$id" ; + } elsif ($_ eq 'event') { + $val = "$db{$table}{$id}{ref} [$id]" ; + } elsif ($_ eq 'calibration_date' || $_ eq 'date') { + # $val = "$cal_date [$day_of_week{$cal_date}]" ; + $val = &common_min_date_as_string($cal_date) ; + $nowrap = "nowrap" ; + } elsif ($_ eq 'day') { + $val = "$sys_day_cnt" ; + } elsif ($_ eq 'start_date') { + $nowrap = "nowrap" ; + $val = &common_min_date_as_string($date_from) ; + } elsif ($_ eq 'venue') { + my @oids = split(/\,/,$db{$table}{$id}{organisation_ids}) ; + foreach $_oid (@oids) { + $val .= $db{organisations}{$_oid}{name} . '
    ' ; + } + $val = substr($val,0,-4) if $val ; ; + } elsif ($_ eq 'region') { + $val = $db{regions}{$db{$table}{$id}{region_id}}{code} ; + } elsif ($_ eq 'type') { + $val = (lc $db{event_systems}{$event_sys_id}{description} =~ /cricket/) ? "C" : + ($db{event_systems}{$event_sys_id}{system_type} eq 'mobile') ? "M" : + ($db{event_systems}{$event_sys_id}{system_type} eq 'fixed') ? "F" : ""; + } elsif ($_ eq 'system') { + $val = '' ; + $val = qq~($event_sys_id)$db{event_systems}{$event_sys_id}{name}~ ; + $val .= qq~ ($db{event_systems}{$event_sys_id}{description})~ if $db{event_systems}{$event_sys_id}{description} ; + } elsif ($_ eq 'sport') { + $val = '' ; + foreach my $sport_id (split(",",$db{$table}{$id}{sport_type_ids})) { + $db{sport_types}{$sport_id}{name} = uc $db{sport_types}{$sport_id}{name} ; + $val .= qq~$db{sport_types}{$sport_id}{name}
    ~ ; + } + $val = substr($val,0,-4) if $val ; + } elsif ($_ eq 'club_name') { + $val = $db{clubs}{$club_ids[$system_count - 1]}{name} ; + } elsif ($_ eq 'operator') { + $val = '' ; + # $val = $db{users}{$table_op_ids[$system_count - 1]}{name} if $table_op_ids[$system_count - 1] ; + $val = ($default_op_ids{$system_count}{$cnt{$event_sys_id}{$id}}) ? $db{users}{$default_op_ids{$system_count}{$cnt{$event_sys_id}{$id}}}{name} : (!$default_op_ids{$system_count}{$system_day_cnt} && $system_has_daily_op{$system_count}) ? "None" : $db{users}{$op_ids[$system_count - 1]}{name} ; + # $formatting = $format92 if $event_cnt == 2 ; + $formatting = $format92 if $cali_cnt == 2 ; + } elsif ($_ eq 'start_time') { + if (!$start_times[$sys_day_cnt-1]) { + $val = substr($db{$table}{$id}{date_from},11,5) ; + } else { + $val = substr($start_times[$sys_day_cnt-1],0,5) ; + } + } elsif ($_ eq 'end_time') { + if (!$end_times[$sys_day_cnt-1]) { + $val = substr($db{$table}{$id}{date_to},11,5) ; + } else { + $val = substr($end_times[$sys_day_cnt-1],0,5) ; + } + } elsif ($_ eq 'status' || $_ eq 'fixture_check') { + push @first_table_multi_select_table_cells,"#$useropts{table_id} tr:eq($table_row) td:nth-last-child($last_child{$_})" ; + $field{$_} = "$_\_event$event_sys_id\_$sys_day_cnt\_$id" ; + $opts{$field{$_}} = $opts{$_} ; + my $background_color = qq~~ ; + if ($_ eq 'status' && $default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}) { + $val_min = $db{monitor_status}{$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}}{status} ; + + print "\n $_ : $default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}" if $id eq '11913' || $_ eq 'status' ; + + if ($default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id} eq '1') { + $background_color = qq~rgb(81, 181, 41)~ ; + $formatting = $format94 ; + } elsif ($default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id} eq '2') { + $background_color = qq~rgb(246, 227, 5)~ ; + $formatting = $format95 ; + } else { + $background_color = qq~rgb(249, 13, 13)~ ; + $formatting = $format96 ; + } + } elsif ($default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}) { + $val_min = $db{users}{$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}}{name} ; + } + + $val = &common_min_table_select($field{$_},$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},'',$table_row,$last_child{$_},$background_color,$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},$_) ; + } elsif ($_ eq 'comments') { + $field{$_} = "$_\_event$event_sys_id\_$sys_day_cnt\_$id" ; + $val = &common_min_table_textarea($field{$_},$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},'',$table_row,$last_child{$_},$background_color,$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},$_) ; + } elsif ($_ eq 'update') { + + my $field = "update_event$event_sys_id\_$sys_day_cnt\_$id" ; + $val = &common_min_form_checkbox_col($field,'') ; + + chop $default_javascript if $default_javascript ; + + # print "\n default_javascript : $default_javascript" ; + + # 12=s:;t:|s:1;t:1|s:2;t:2-13=|s:3;t:3|s:4;t:4 + if ($default_javascript) { + push @default_javascript_by_id, qq~"event$event_sys_id\_$sys_day_cnt\_$id":{$default_javascript}~ ; + } + } + if ($_ ne 'status' && $_ ne 'calibrator' && substr($_,0,5) ne 'shift' && $_ ne 'update' && $_ ne 'status' && $_ ne 'fixture_check') { + $val_min = $val ; + $val_min =~ s/\
    /\;/g ; + } + $print_tbody .= qq~$val~ ; + + # &common_debug("XLSX >>> $event_system_calibration_ids{$id}{$event_sys_id}{$sys_day_cnt} [$id] [$event_sys_id] [$sys_day_cnt] [$field]") ; + + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$formatting) ; + $xlsxcol++ ; + } + + $print_tbody .= qq~~ ; + + $xlsxrow++ ; + } + + # next if $i{calibration_status} ne 'all' and $i{calibration_status} and $i{calibration_status} ne $db{event_systems}{$event_sys_id}{calibration_status} ; + # next if $i{calibrator_id} ne 'all' and $i{calibrator_id} and $i{calibrator_id} ne $db{event_systems}{$event_sys_id}{calibrator_id} ; + + } + } +# || $troubleshoot_monitoring_report ; + my $html_id = ($monitoring_report) ? "selectShift_monitor_" : ($troubleshoot_monitoring_report) ? "selectShift_troubleshoot_monitor_" : "selectShift_temp_calibrator_" ; + my $html_id2 = ($monitoring_report) ? "shift-monitor-id-" : ($troubleshoot_monitoring_report) ? "shift-troubleshoot-monitor-id-" : "shift-temp-calibrator-id-" ; + $row_cnt++ if $monitoring_report || $troubleshoot_monitoring_report ; + + $trigger_jquery_raw .= ($monitoring_report || $troubleshoot_monitoring_report) ? qq~ + + \$("#savebutt").click(function() { + for (let table_cnt = 1; table_cnt<= $date_cnt; table_cnt++) { + for (let i=1; i<=4; i++) { + let mon_id = \$("#$html_id"+i+"_1_1_"+table_cnt).chosen().val() ; + if (mon_id && typeof(mon_id) !== 'undefined') { + \$("#$html_id2"+i+"-"+table_cnt).val(mon_id) ; + } + } + } + \$("#$lcpage-form").submit() ; + }) ; + + ~ : qq~ + \$("#savebutt").click(function() { + + for (let table_cnt = 1; table_cnt<= $date_cnt; table_cnt++) { + + for (let i=1; i<=4; i++) { + let mon_id = \$("#$html_id"+i+"_1_1_"+table_cnt).chosen().val() ; + if (mon_id) { + \$("#$html_id2"+i+"-"+table_cnt).val(mon_id) ; + } + } + + let table_row_cnt = \$("#select_temp_calibrators_2_"+table_cnt).find('tr').length - 2 ; + + if (table_cnt > 1) { + table_row_cnt += 2 ; + } + + let seen_support = {} ; + + for (i=1;i<=table_row_cnt;i++) { + + let sel_val = \$("#selectName_2_"+i+"_"+table_cnt).val() ; + // if (!sel_val) { + // noty({text:'Please Select a Temp Support Name in all Rows',layout:"center",type:"error",timeout:3000}) ; + // return ; + // } else + if (seen_support[sel_val]) { + noty({text:'Please do not Select the same Temp Support Name in Multiple Rows for the Same Date',layout:"center",type:"error",timeout:3000}) ; + return ; + } else if (sel_val) { + seen_support[sel_val] = 1 ; + } + } + } + \$("#$lcpage-form").submit() ; + }) ; + ~ ; + + $worksheet{$ws}->set_column(0,0,10) ; + $worksheet{$ws}->set_column(1,1,30) ; + $worksheet{$ws}->set_column(2,2,15) ; + $worksheet{$ws}->set_column(3,3,5) ; + $worksheet{$ws}->set_column(4,4,15) ; + $worksheet{$ws}->set_column(5,6,10) ; + $worksheet{$ws}->set_column(7,7,30) ; + $worksheet{$ws}->set_column(8,9,10) ; + $worksheet{$ws}->set_column(10,10,30) ; + $worksheet{$ws}->set_column(11,11,15) ; + $worksheet{$ws}->set_column(12,16,20) ; + + &report_xlsx_export_footer('L',15,$xlsxdir) ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_update { + + my ($table,$table_field,$other_field,$table_field_2) = @_ ; + + unless ($table_field_2) { + $table_field_2 = "blank" ; + $ignore{$table_field_2} = 1 ; + } + + my ($s_year,$s_mon,$s_day) = split("-",$i{date_from}) ; + my ($e_year,$e_mon,$e_day) = split("-",$i{date_to}) ; + + our $date_counter = 1 ; + + while (int("$s_year$s_mon$s_day") <= int("$e_year$e_mon$e_day")) { + $date_cnt_to_date{$date_counter} = "$s_year-$s_mon-$s_day" ; + $date_counter++ ; + ($s_year,$s_mon,$s_day) = Add_Delta_Days ($s_year,$s_mon,$s_day,1) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + } + + $date_cnt_to_date{$date_counter} = "$s_year-$s_mon-$s_day" ; + $date_counter-- ; + + my %i_per_date = () ; my $temp_support_diff = 0 ; + + if ($temp_calibrator_report) { + + &db_min_ro($table,"date,temp_calibrator_support_shifts,$table_field","`date` >= '$i{date_from}' AND`date` <= '$i{date_to}'") ; + + for my $date_cnt (1 .. $date_counter) { + + my $table_pos = 0 ; my $cnt_per_date = 0 ; my $table_cnt = 0 ; + + # $db{$table}{1}{temp_calibrator_support_shifts} =~ s/\|\|/\|/g ; + # $db{$table}{1}{temp_calibrator_support_shifts} =~ s/^\|//; + # $db{$table}{1}{temp_calibrator_support_shifts} =~ s/\|$//; + + my @temp_calibrator_support_shifts_split = split(/\|/,$db{$table}{$date_cnt_to_date{$date_cnt}}{temp_calibrator_support_shifts}) ; + + foreach (sort keys %i) { + + $ignore{$_} = 1 ; + + if ($_ =~ /^name_2_.*_$date_cnt$/) { + + my @aaa = split(/\_/,$_) ; + $table_pos = $aaa[-3] ; + $cnt_per_date = $aaa[-2] ; + # $table_cnt = $aaa[-1] ; + + my $update_field = "update_$table_pos\_$cnt_per_date\_$date_cnt" ; + my $name_field = "name_$table_pos\_$cnt_per_date\_$date_cnt" ; + my $shift_field = "shift_$table_pos\_$cnt_per_date\_$date_cnt" ; + + if ($i{$update_field} && $i{$name_field} && $i{$shift_field}) { + $i_per_date{$date_cnt}{temp_calibrator_support_shifts} .= qq~$i{$name_field}:$i{$shift_field}|~ ; + } elsif ($temp_calibrator_support_shifts_split[$cnt_per_date-1]) { + my $abcde = $temp_calibrator_support_shifts_split[$cnt_per_date-1] ; + $i_per_date{$date_cnt}{temp_calibrator_support_shifts} .= qq~$abcde|~ ; + } + } + } + + chop $i_per_date{$date_cnt}{temp_calibrator_support_shifts} if $i_per_date{$date_cnt}{temp_calibrator_support_shifts} ; + # $temp_support_exists = 1 if $i_per_date{$date_cnt}{temp_calibrator_support_shifts} ; + $temp_support_diff = 1 if $i_per_date{$date_cnt}{temp_calibrator_support_shifts} && $i_per_date{$date_cnt}{temp_calibrator_support_shifts} ne $db{$table}{$date_cnt_to_date{$date_cnt}}{temp_calibrator_support_shifts} ; + } + + } else { + # return unless $i{update_table_1} ; + &db_min_ro($table,"date,$table_field,$table_field_2","`date` >= '$i{date_from}' AND `date` <= '$i{date_to}'") ; + } + + my $some_update = 0 ; + + for my $date_cnt (1 .. $date_counter) { + $some_update = 1 if $i{"update_1_1_$date_cnt"} || ($i{"update_2_1_$date_cnt"} || $temp_calibrator_report) ; + } + + + # return if !$i{update_table_1} && $temp_calibrator_report && $i{temp_calibrator_support_shifts} eq $db{$table}{1}{temp_calibrator_support_shifts} ; + return if !$some_update && !$temp_support_diff ; + + &hidden_fields ; + my %ii = %i ; + + # $ignore{blank} = 1 ; + + for my $date_cnt (1 .. $date_counter) { + + %i = () ; + + # my $date_val = $ii{"date_$date_cnt"} ; + my $date_val = $date_cnt_to_date{$date_cnt} ; + + # my $update_field = "update_1_1_$date_cnt" ; + + next if !$ii{"update_1_1_$date_cnt"} && !$ii{"update_2_1_$date_cnt"} ; + + if ($ii{"update_1_1_$date_cnt"}) { + + my $ops_exists = 0 ; my $notes_exists = 0 ; + + for my $shift_cnt (1 .. 4) { + $ii{"$other_field\_$shift_cnt\_$date_cnt"} =~ s/\,/\;/g ; + $i{$table_field} .= qq~$ii{"$other_field\_$shift_cnt\_$date_cnt"}|~ ; + $ops_exists = 1 if $ii{"$other_field\_$shift_cnt\_$date_cnt"} ; + $notes_exists = 1 if $table_field_2 && $ii{"shift_$table_field_2\_$shift_cnt\_1_1_$date_cnt"} ; + + my $field_ = "shift_$table_field_2\_$shift_cnt\_1_1_$date_cnt" ; + + $i{$table_field_2} .= qq~$ii{"shift_$table_field_2\_$shift_cnt\_1_1_$date_cnt"}:|:~ if $table_field_2 ; + } + chop $i{$table_field} ; + + $i{$table_field} = qq~~ unless $ops_exists ; + $i{$table_field_2} = qq~~ if $table_field_2 && !$notes_exists ; + + $i{$table_field_2} = substr($i{$table_field_2},0,-3) if $table_field_2 && $i{$table_field_2} ; + $ignore{$table_field} = 0 ; + $ignore{$table_field_2} = 0 if $table_field_2 && $table_field_2 ne 'blank' ; + } else { + $ignore{$table_field} = 1 ; + $ignore{$table_field_2} = 1 ; + } + # my $table_field_old = $table_field ; + + # $table_field = $table_field_old ; + + $i{temp_calibrator_support_shifts} = $i_per_date{$date_cnt}{temp_calibrator_support_shifts} if $temp_calibrator_report ; + + if (!$db{$table}{$date_val}{date}) { + + &db_min_ro($table,"1,MAX(id) + 1 AS 'max_id'","","","") ; + + $i{id} = $db{$table}{1}{max_id} ; + $i{id} = 1 unless $i{id} ; + $i{date} = $date_val ; + + $ignore{date} = 0 ; + $ignore{$table_field} = 1 unless $i{$table_field} ; + $ignore{temp_calibrator_support_shifts} = 1 if !$temp_calibrator_report || !$i{temp_calibrator_support_shifts} ; + + &db_min_insert("$table") ; + + } else { + + $ignore{$table_field} = 1 if $db{$table}{$date_val}{$table_field} eq $i{$table_field} ; + $ignore{temp_calibrator_support_shifts} = 1 if $db{$table}{$date_val}{temp_calibrator_support_shifts} eq $i{temp_calibrator_support_shifts} || !$temp_calibrator_report ; + &db_min_upd($table,"`date`='$date_val'") if !$ignore{$table_field} || !$ignore{$table_field_2}|| !$ignore{temp_calibrator_support_shifts} ; + + } + } + + %i = %ii ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_update { + + my ($field) = @_ ; + + my %iii = %i ; + my %ii = () ; + local $min_date = 0 ; local $max_date = 0 ; + foreach (sort keys %i) { + + local $cell_name = $_ ; + local @a = split("_") ; + next if $a[-2] ne int($a[-2]) ; + + if ($i{"paid_$a[-2]\_$a[-1]"} and $i{"amount_payble_$a[-2]\_$a[-1]"}) { + # my $date = substr($a[-1],0,4) . '-' . substr($a[-1],4,2) . '-' . substr($a[-1],6,2) ; + if ($a[0] eq 'amount') { + $i{$_} = sprintf("%.2f",$i{$_}) ; + $ii{$a[-1]}{"$field\_amounts_paid"} .= ($ii{$a[-1]}{"$field\_amounts_paid"}) ? qq~;$a[-2]:$i{$_}~ : qq~$a[-2]:$i{$_}~ ; + } elsif ($a[0] eq 'date') { + $ii{$a[-1]}{"$field\_dates_paid"} .= ($ii{$a[-1]}{"$field\_dates_paid"}) ? qq~;$i{$_}~ : qq~$i{$_}~ ; + } + } + $min_date = $a[-1] if ($min_id and $a[-1] < $min_id) or not $min_id ; + $max_date = $a[-1] if $a[-1] > $max_id ; + } + + $min_date = substr($min_date,0,4) . '-' . substr($min_date,4,2) . '-' . substr($min_date,6,2) ; + $max_date = substr($max_date,0,4) . '-' . substr($max_date,4,2) . '-' . substr($max_date,6,2) ; + + &db_min_ro($table,"date,$field\_dates_paid,$field\_amounts_paid","`date` <= '$max_date' AND `date` >= '$min_date'",'','') ; + + foreach my $date (sort keys %ii) { + + %i = () ; + + # $i{"$field\_dates_paid"} .= qq~$ii{$date}{"$field\_dates_paid"}~ ; + + my $date_string = substr($date,0,4) . '-' . substr($date,4,2) . '-' . substr($date,6,2) ; + + $i{"$field\_amounts_paid"} = qq~$db{$table}{$date_string}{"$field\_amounts_paid"}~ ; + $i{"$field\_amounts_paid"} .= qq~;~ if $db{$table}{$date_string}{"$field\_amounts_paid"} && $ii{$date}{"$field\_amounts_paid"} ; + $i{"$field\_amounts_paid"} .= qq~$ii{$date}{"$field\_amounts_paid"}~ ; + + $ignore{"$field\_amounts_paid"} = 1 if $i{"$field\_amounts_paid"} eq $db{$table}{$date_string}{"$field\_amounts_paid"} || !$i{"$field\_amounts_paid"} ; + + $i{"$field\_dates_paid"} = qq~$db{$table}{$date_string}{"$field\_dates_paid"}~ ; + $i{"$field\_dates_paid"} .= qq~;~ if $db{$table}{$date_string}{"$field\_dates_paid"} && $ii{$date}{"$field\_dates_paid"} ; + $i{"$field\_dates_paid"} .= qq~$ii{$date}{"$field\_dates_paid"}~ ; + + $ignore{"$field\_dates_paid"} = 1 if $i{"$field\_dates_paid"} eq $db{$table}{$date_string}{"$field\_dates_paid"} || !$i{"$field\_dates_paid"} ; + + &db_min_upd($table,"`date`='$date_string'") if $i{"$field\_dates_paid"} || $i{"$field\_amounts_paid"} ; + + } + + %i = %iii ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_report_ifields { + + my ($field) = @_ ; + + my $field2 = join(/ /, map { uc($_) } split(/\_/,$field)) ; + + if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { + $error = qq~'$i{date_from}' > '$i{date_to}'~ ; &report_screen ; + } + push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` <= '$i{date_to} 23:59:59' AND `date_to` >= '$i{date_from} 00:00:00'))" ; + push @report_results, "(BETWEEN '$i{date_from}' AND '$i{date_to}')" ; + } elsif (not $i{date_from}) { + $error = qq~PLEASE ENTER A START DATE!~ ; + } elsif (not $i{date_to}) { + $error = qq~PLEASE ENTER A END DATE!~ ; + } + + our $where_min = qq~~ ; + if ($i{"$field\_id"}) { + my $ifield = "$field\_id" ; + &db_min_ro('users','1,name',"`id` = '$i{$ifield}'",'','') ; + $where_min = " AND `$field\_ids` LIKE '%$i{$ifield}%'" ; + push @report_results,"$field2 = $db{users}{1}{name}" ; + } + + if ($i{paid_status} eq 'paid') { + push @report_results,"$field2 AMOUNTS PAID" ; + } elsif ($i{paid_status} eq 'outstanding') { + push @report_results,"$field2 PAY OUTSTANDING" ; + } + + $report_results_msg = uc join(', ', @report_results) ; + + if (not $report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); + &report_screen ; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_list_screen { + + my ($field) = @_ ; + + my $field2 = $field ; + + $field2 =~ s/\_/\-/g ; + + # &db_min_ro('event_cost_items','1,rates',"`name` LIKE '$field3%'",'','') ; + + our @sql_col_display = ($i{paid_status} eq 'paid') ? ("date","$field\_names","shifts_count","dates_paid","amounts_paid","all_paid") : ($i{paid_status} eq 'all') ? ("date","$field\_names","shifts_count","dates_paid","amounts_paid","date_payable","amount_payable","paid") : ("date","$field\_names","shifts_count","date_payable","amount_payable","paid") ; + + my $table_colspan = 0 ; + + foreach (@sql_col_display) { + $table_colspan += 1 ; + } + + local @month_arr = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + my ($year1,$month1,$day1) = split(/\-/,$i{date_from}) ; + my ($year2,$month2,$day2) = split(/\-/,$i{date_to}) ; + + my $date_string = qq~~ ; + + if ($year1 ne $year2 && $month1 ne $month2 && $day1 ne $day2) { + $date_string = qq~ $day1 $month_arr[$month1] $year1 - $day2 $month_arr[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 ne $month2) { + $date_string = qq~ $day1 $month_arr[$month1] - $month_arr[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 eq $month2 && $day1 ne $day2) { + $date_string = qq~ $day1 - $day2 $month_arr[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 eq $month2 && $day1 eq $day2) { + $date_string = qq~ $day2 $month_arr[$month2] $year2~ ; + } + + my $field_heading = join(" ", map { ucfirst($_) } split(/\_/,$field)) ; + + our $xlsxheading = "$field_heading Payments Report$xlsreportname$date_string" ; + + &report_xlsx_export_header("$field_heading Payments$xlsreportname","$field\_payments_report") ; + + &schedule_payments_load_list_vars("$where_min","$field") ; + + my @qty_work = () ; + my @amnt_usd_work = () ; + my @amnt_work = () ; + my @op_work = () ; + my @description = () ; + my @paid_work = () ; + my $row_cnt = 0 ; + my $first_id = 0 ; + my $last_id = 0 ; + my %row_cnt_to_id = () ; + + $fcol = 12 ; my $val_min = 0 ; $row_cnt = 0 ; + + my $date_pay = qq~~ ; my $quote_and_ops_ids = qq~~ ; my $op_ids = qq~~ ; + + my ($next_year,$next_month,$next_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,1) ; + + my $row_cnt = 0 ; my $quote_and_ops_ids = qq~~ ; + + my %amnt_tots = () ; + + foreach my $date (sort {$a <=> $b} keys %{$db{$table}}) { + + my @date_pay = split(/\;/,$db{$table}{$date}{"$field\_paid"}) ; + my @amount_pay = split(/\;/,$db{$table}{$date}{"$field\_amounts_paid"}) ; + my $date_val = $date ; + $date_val =~ s/\-//g ; + + foreach my $temp_id (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$operator_count{$date}}) { + + next if $i{"$field\_id"} && $i{"$field\_id"} ne $temp_id ; + + next if $temp_id eq 'none' ; + + my $amnt_owed = ($db{event_cost_items}{1}{rates}) ? $db{event_cost_items}{1}{rates} * $operator_count{$date}{$temp_id} : ($field =~ /calibrator/) ? 500 * $operator_count{$date}{$temp_id} : ($field =~ /monitor/ && $field !~ /troubleshoot/) ? 300 * $operator_count{$date}{$temp_id} : 450 * $operator_count{$date}{$temp_id} ; + $amnt_owed += $temp_support_rates{half_day}*$temp_calibrator_support{shift_count}{$date}{$temp_id}{1} ; + $amnt_owed += $temp_support_rates{full_day}*$temp_calibrator_support{shift_count}{$date}{$temp_id}{2} ; + # $temp_calibrator_support{count}{$date}{1} += ($abc[1] eq '1') ? 0.5 : 1 ; + # $temp_calibrator_support{shift_count}{$date}{1} += 1 ; + + $amnt_owed = $amnt_owed - $amounts_paid{$date}{$temp_id} ; + + $amnt_owed = 0 if $amounts_paid{$date}{$temp_id} ; + + next if $i{paid_status} eq 'outstanding' && $amnt_owed == 0 ; + next if $i{paid_status} eq 'paid' && $amounts_paid{$date}{$temp_id} == 0 ; + + $amnt_owed = sprintf("%0.2f",$amnt_owed) ; + $xlsxcol = 0 ; + + foreach my $col (@sql_col_display) { + + next unless $col ; # blank for the buttons column + $display = 1 ; + my $val = '' ; + my $align = '' ; + my $center = qq~ class="dt-center"~ ; + $align = $center ; + my $val_min = '' ; + + if ($col eq 'date') { + $val = $date ; + } elsif ($col eq "$field\_names") { + $val = $db{users}{$temp_id}{name} ; + $val .= " [Support]" if $support_user{$temp_id} ; + } elsif ($col eq 'shifts_count') { + chop $operator_shifts_string{$date}{$temp_id} if $operator_shifts_string{$date}{$temp_id} ; + my $shifts_cnt = $operator_count{$date}{$temp_id} + $temp_calibrator_support{count}{$date}{$temp_id}{1} + $temp_calibrator_support{count}{$date}{$temp_id}{2} ; + $val_min = "$shifts_cnt" ; + $val_min .= " [$operator_shifts_string{$date}{$temp_id}]" if $operator_shifts_string{$date}{$temp_id} ; + $operator_shifts_string{$date}{$temp_id} =~ s/\;/\
    /g ; + $val = ($operator_shifts_string{$date}{$temp_id}) ? qq~$shifts_cnt~ : $shifts_cnt ; + # $val = $operator_shifts{$date}{$temp_id} + } elsif ($col eq 'dates_paid') { + foreach (sort keys %{$dates_amounts_paid{$temp_id}}) { + $val .= ($val) ? qq~
    $_~ : qq~$_~ ; + } + $val = "None" unless $val ; + $val_min = $val ; + $val_min =~ s/\
    /\;/g ; + $val = qq~~ if $val =~ /
    / ; + } elsif ($col eq 'amounts_paid') { + foreach (sort keys %{$dates_amounts_paid{$temp_id}}) { + $dates_amounts_paid{$temp_id}{$_} = sprintf("%0.2f",$dates_amounts_paid{$temp_id}{$_}) ; + $val .= ($val) ? qq~
    $dates_amounts_paid{$temp_id}{$_}~ : qq~$dates_amounts_paid{$temp_id}{$_}~ ; + $amnt_tots{"amounts_paid"} += $dates_amounts_paid{$temp_id}{$_} ; + } + $val = "None" unless $val ; + $val_min = $val ; + $val_min =~ s/\
    /\;/g ; + $val = qq~~ if $val =~ /
    / ; + } elsif ($col eq 'date_payable') { + my $date_payable = "$now_year-$now_mm-$now_dd" ; + $val = ($amnt_owed != 0) ? &common_min_form_input_col("date_$temp_id\_$date_val",$date_payable) : "N/A" ; + $val_min = ($amnt_owed != 0) ? $date_payable : "N/A" ; + } elsif ($col eq 'amount_payable') { #dates_amounts_paid + $count_outstanding++ if $amnt_owed > 0 ; + $amnt_tots{"amount_payable"} += $amnt_owed ; + $val = ($amnt_owed != 0) ? &common_min_form_input_col("amount_payble_$temp_id\_$date_val",$amnt_owed) : "None" ; + $val_min = $amnt_owed ; + } elsif ($col eq 'paid') { + $val = ($amnt_owed != 0) ? &common_min_form_checkbox_col("paid_$temp_id\_$date_val",0) : '' ; + $val_min = ($amnt_owed != 0) ? "No" : "Yes" ; + } elsif ($col eq 'all_paid') { + $val = ($amnt_owed != 0) ? '' : '' ; + $val_min = ($amnt_owed != 0) ? "No" : "Yes" ; + } + $val_min = $val if $col eq 'date' || $col eq "$field\_names" ; + + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format_management_report_data) if $col ne 'shifts_count' ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format_management_report_data_ref_nr) if $col eq 'shifts_count' ; + $xlsxcol++ ; + # if ($_ eq 'ref_nr' or $_ eq 'camera_nr') { $val = &common_camera_links($tables,$id,$val) ;} + $print_tbody .= qq~$val~ ; + + } + $print_tbody .= qq~~ ; + $xlsxrow++ ; + $row_cnt++ ; + $quote_and_ops_ids .= qq~"$row_cnt\_$temp_id":"$date_val",~ ; + } + # chop $op_ids if $op_ids ; + # $quote_and_ops_ids .= qq~"$row_cnt_$id":[$op_ids],~ if $op_ids ; + } + + my $col_cnt = 0 ; + + foreach my $col (@sql_col_display) { + + if ($col eq 'date') { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$col_cnt,"TOTALS",$format_management_report_total) ; + } elsif ($col eq "amounts_paid" || $col eq "amount_payable") { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$col_cnt,"$amnt_tots{$col}",$format_management_report_totals) ; + } else { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$col_cnt,"-",$format_management_report_totals) ; + } + $col_cnt++ ; + } + + chop $quote_and_ops_ids if $quote_and_ops_ids ; + + # $print_tbody .= qq~~ ; + # $print_tbody .= qq~~ ; + $worksheet{$ws} -> set_column(0,0,15) ; + $worksheet{$ws} -> set_column(1,1,25) ; + $worksheet{$ws} -> set_column(2,7,20) if $i{paid_status} eq 'all' ; + $worksheet{$ws} -> set_column(2,5,20) if $i{paid_status} ne 'all' ; + + $box_icon .= qq~
    ~ if $i{paid_status} ne 'paid' && $count_outstanding > 0 ; + + &report_xlsx_export_footer('L',15,"$field\_payments_report") ; + + $fnsortcol = 0; + $fnsortorder = 'asc' ; + &common_min_extra_crumb("$lcpage\s","Search Screen") ; + + $trigger_jquery_raw .= qq~ + function selectAll() { + let jsObject = { + $quote_and_ops_ids + } ; + for (let key in jsObject) { + let op_id = jsObject[key] ; + let parts = key.split("_") ; + let event_id = parts[1] ; + \$(\$("#itv-table").dataTable().fnGetNodes()).find(\$("input[name=paid_"+event_id+"_"+op_id+"]")).each(function () { + // console.log("input[name=paid_"+event_id+"_"+op_id+"]") ; + if(\$(this).is(':checked')) { + \$(this).prop('checked',false) ; + } else { + \$(this).prop('checked',true) ; + } + }) ; + } + } + ~; + + my $field_id = "#$field2\-payment-form" ; + + # my $savebuttjs = ($count_outstanding > 0) ? qq~$("$field_id").submit();' : 'noty({text:"There are no calibrators to pay!",layout:"center",type:"error",timeout:3000});return;~ ; + + $trigger_jquery_raw .= qq~ + \$("#savebutt").click(function() { + // $savebuttjs + \$("$field_id").submit(); + }) ; + ~ ; + + $fcol = 2 ; + + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= &common_min_form_input_col("date_from",$i{date_from}) ; #date_from_i_field + $print_box_content_rows .= &common_min_form_input_col("date_to",$i{date_to}) ; #date_to_i_field + $print_box_content_rows .= &common_min_form_input_col("$field\_id",$i{"$field\_id"}) ; #temp_calibrator_id_i_field + $print_box_content_rows .= &common_min_form_input_col("$field\s_paid",$i{"$field\s_paid"}) ; + $print_box_content_rows .= qq~
    ~ ; + + $print_box_content_rows .= &common_min_forms_start("$field2\-payment") if $count_outstanding ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_load_list_vars { + + my ($where,$field) = @_ ; + + my $users_sql = ($field =~ /calibrator/) ? "`user_type` = 'casual_calibrator' OR `user_type` = 'support'" : "" ; + + &db_min_ro('users','id,name',"$users_sql",'','') ; + + &db_min_ro($table,"date,$field\_ids,$field\_dates_paid,$field\_amounts_paid,temp_calibrator_support_shifts","`date`>='$i{date_from}' AND `date`<='$i{date_to}' $where",'','') ; + + # &db_min_ro('shift_monitor_ids','date,monitor_ids',"`date`>='$i{date_from}' AND `date`<='$i{date_to}' $where",'','') ; + + our %operator_count = () ; our %amounts_paid = () ; our %dates_amounts_paid = () ; our %operator_shifts_string = () ; + + # my @monitor_shifts = ("","08:00-11:00","11:00-14:00","14:00-17:00","17:00-21:00") ; + my @operator_shifts = ($field =~ /calibrator/) ? ("","07:00-10:00","10:00-13:00","13:00-16:00","16:00-19:00") : ("","08:00-11:00","11:00-14:00","14:00-17:00","17:00-21:00") ; + + foreach my $date (keys %{$db{$table}}) { + my $shift_cnt = 0 ; + foreach my $shift (split(/\|/,$db{$table}{$date}{"$field\_ids"})) { + $shift_cnt++ ; + next unless $shift ; + foreach my $temp_id (split(/\;/,$shift)) { + next unless $temp_id ; + $operator_count{$date}{$temp_id} += 1 ; + $operator_shifts_string{$date}{$temp_id} .= qq~$operator_shifts[$shift_cnt];~ ; + } + } + $shift_cnt = 0 ; + # foreach my $shift (split(/\|/,$db{$table}{$date}{monitor_ids})) { + # $shift_cnt++ ; + # next unless $shift ; + # foreach my $temp_id (split(/\;/,$shift)) { + # next unless $temp_id ; + # $operator_count{$date}{$temp_id} += 1 ; + # $operator_shifts{$date}{$temp_id} .= qq~$monitor_shifts[$shift_cnt],~ ; + # } + # } + my @date_pay = split(/\;/,$db{$table}{$date}{"$field\_dates_paid"}) ; + my @amount_pay = split(/\;/,$db{$table}{$date}{"$field\_amounts_paid"}) ; + my $cnt = 0 ; + foreach my $temp_id_amnt (@amount_pay) { + my @temp_amnt = split(/\:/,$temp_id_amnt) ; + $amounts_paid{$date}{$temp_amnt[0]} += $temp_amnt[1] ; + $dates_amounts_paid{$temp_amnt[0]}{$date_pay[$cnt]} += $temp_amnt[1] ; + $cnt++ ; + } + + if ($temp_calibrator_payments_report && $db{$table}{$date}{temp_calibrator_support_shifts}) { + + foreach my $shift (split(/\|/,$db{$table}{$date}{temp_calibrator_support_shifts})) { + + $shift_cnt++ ; + next unless $shift ; + my @abc = split(/\:/,$shift) ; + next unless $abc[0] ; + + $operator_count{$date}{$abc[0]} += 0 ; + # $operator_count{$date}{$abc[0]} += ($abc[1] eq '1') ? 0.5 : 1 ; + $temp_calibrator_support{count}{$date}{$abc[0]}{$abc[1]} += ($abc[1] eq '1') ? 0.5 : 1 ; + $temp_calibrator_support{shift_count}{$date}{$abc[0]}{$abc[1]} += 1 ; + $operator_shifts_string{$date}{$abc[0]} .= ($abc[1] eq '1') ? qq~Half Day (<7 hours);~ : qq~Full Day (7 hours+);~ ; + $support_user{$abc[0]} = 1 ; + } + } + } + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_report_screen { + + my ($field) = @_ ; + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + &common_min_select_opts("$field\_id",'users',"name",$i{"$field\_id"},'','',"`name` NOT LIKE 'Rory%' AND `name` NOT LIKE 'Handre%'") ; + # &common_min_select_opts('event_quote_id','event_quotes',"ref",$i{event_quote_id},'','',"") ; + + $first_day_month = sprintf("%02d",$first_day_month) ; $first_day = sprintf("%02d",$first_day) ; + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-$now_mm-01") unless $i{date_from} ; + + my $days_in_month = Days_in_Month($now_year,$now_mm) ; + + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$days_in_month") ; + + # my ($sql_next_day) = &common_add_delta_days(1) ; + # my ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + # $print_box_content_rows .= &common_min_form_datepicker('date',"$next_year-$next_month-$next_day") ; #unless $i{date_from} ; + + $opts{paid_status} .= qq~~ ; + $opts{paid_status} .= qq~~ ; + $opts{paid_status} .= qq~~ ; + + $print_box_content_rows .= &common_min_form_select("$field\_id",'') ; + # $print_box_content_rows .= &common_min_form_select('event_quote_id','') ; + $print_box_content_rows .= &common_min_form_select('paid_status','') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------------------ + +1 ; \ No newline at end of file diff --git a/libs/modules/_FromProd/session.pm b/libs/modules/_FromProd/session.pm new file mode 100644 index 0000000..3fce5fa --- /dev/null +++ b/libs/modules/_FromProd/session.pm @@ -0,0 +1,51 @@ +sub check_session { + + use DBI; + use CGI::Session; + use CGI::Cookie; + + my %cookies = fetch CGI::Cookie ; + my $cgisessid = defined $cookies{'CGISESSID'} ? $cookies{'CGISESSID'}->value : undef; # This does + + use db ; + &db_open_ro ; + + $userid = 0 ; + $session = load CGI::Session("driver:MySQL", $cgisessid, {Handle=>$dbh}); + $userid = $session->param(-name=>'id'); + $is_logged_in = $session->param(-name=>'_IS_LOGGED_IN'); + $username = lc $session->param(-name=>'uname'); + $useremail = lc $session->param(-name=>'uemail'); + $usertype = lc $session->param(-name=>'utype'); + $orgids = $session->param(-name=>'oids'); + $regids = $session->param(-name=>'rids'); + $custids = $session->param(-name=>'cids'); + + my @orgids = split(/\,/,$orgids); + foreach (@orgids) { $glob_orgids{$userid}{$_} = 1 ; } + + my @regids = split(/\,/,$regids); + foreach (@regids) { next unless $_ > 0 ; $glob_regids{$userid}{$_} = 1 ; } + + my @custids = split(/\,/,$custids); + foreach (@custids) { next unless $_ > 0 ; $glob_custids{$userid}{$_} = 1 ; } + + $sessionid = $session->id(); + + if ($sessionid && $is_logged_in > 0 && $userid > 0) { # if $userid and $is_logged_in is -1 not allowed in + $session_state = 'active' ; + } elsif ($session->is_expired) { + $session_state = 'expired' ; + $session->delete() ; + } elsif ($session->is_empty) { + $session_state = 'empty' ; + } else { + $session_state = 'empty' ; + $session->delete() ; + } + + &db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +1 ; \ No newline at end of file diff --git a/libs/modules/_FromProd/tabs.pm b/libs/modules/_FromProd/tabs.pm new file mode 100644 index 0000000..771567b --- /dev/null +++ b/libs/modules/_FromProd/tabs.pm @@ -0,0 +1,1971 @@ +our %sec_cnt = ('a_systems' => "3-Systems", 'b_software_licence' => "3-Software Licence (Monthly Fee)", 'c_game_breakdown_analytics' => "2-Game Breakdown and Analytics (Annual Fee)", 'd_installation_kits' => "7-Installation Kits", 'e_hardware_add_ons' => "7-Hardware Add Ons", 'f_additional_services' => "7-Additional Services", 'g_match_credits' => "4-Match Credits", 'h_other' => "5-Other", 'i_rental' => "2-Rental" , "j_hardware" => "1-Hardware"); + +sub tabs_get_default_totals { + + my ($id) = @_ ; + + # our %sec_cnt = ('a_systems' => "3-Systems", 'b_software_licence' => "3-Software Licence (Monthly Fee)", 'c_game_breakdown_analytics' => "2-Game Breakdown and Analytics (Annual Fee)", 'd_installation_kits' => "7-Installation Kits", 'e_hardware_add_ons' => "7-Hardware Add Ons", 'f_additional_services' => "7-Additional Services", 'g_match_credits' => "4-Match Credits", 'h_other' => "5-Other", 'i_rental' => "2-Rental" , "j_hardware" => "1-Hardware"); + # our %sec_cnt = ('a_other' => "5-Other"); + our %sec_cnt = ('a_systems' => "3-Systems", 'b_software_licence' => "3-Software Licence (Monthly Fee)", 'c_game_breakdown_analytics' => "2-Game Breakdown and Analytics (Annual Fee)", 'd_installation_kits' => "7-Installation Kits", 'e_hardware_add_ons' => "7-Hardware Add Ons", 'f_additional_services' => "7-Additional Services", 'g_match_credits' => "4-Match Credits", 'h_rental' => "2-Rental" , "j_hardware" => "1-Hardware"); + + our %default_totals = () ; + + our @ttlarr = ("one_time_fee","monthly_recurring_fee","annual_fee") ; + our @ttlarr2 = ("subtotal","vat","total") ; + + my $needs_to_update_totals = ($db{$table}{$id}{total_one_time_fee} !~ /;/ && $db{quotes_min}{$id}{item_ttl_costing_other} =~ /(?
     
    ~ ; + + +$trigger_jquery_raw .= qq~ + + if (!\$("#checkboxQuote_accepted").is(":checked") && !\$("#checkboxQuote_pending").is(":checked") && !\$("#checkboxQuote_cancelled").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked","true") ; + } + \$("#checkboxQuote_accepted,#checkboxQuote_pending,#checkboxQuote_cancelled").click( function () { + + if (this.id != 'checkboxQuote_accepted' && \$("#checkboxQuote_accepted").is(":checked")) { + \$("#checkboxQuote_accepted").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_pending' && \$("#checkboxQuote_pending").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_cancelled' && \$("#checkboxQuote_cancelled").is(":checked")) { + \$("#checkboxQuote_cancelled").prop("checked",false) ; + } + + if (!\$("#checkboxQuote_accepted").is(":checked") && !\$("#checkboxQuote_pending").is(":checked") && !\$("#checkboxQuote_cancelled").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked","true") ; + } + + }); + +~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + +if ($tab == 2) { # Costing + + # --------------- START COSTING ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + $lcol = 1 ; $fcol = 2 ; + $preferred_title{currency} = 'Currency' ; + $add_form_fields .= &common_min_form_select('currency',$db{$table}{$id}{currency},1) ; + $trigger_jquery .= qq~\$("#selectCurrency_chosen").css( "width", "96%" );~ ; + $preferred_title{roe} = ' ROE ' ; $fcol = 1 ; + $add_form_fields .= &common_min_form_label_col('roe') ; + $add_form_fields .= &common_min_form_input_col('roe',$db{$table}{$id}{roe},1) ; + $add_form_fields .= qq~~ ; + my $sec = '_costing' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + &tab_costing_select_opts('price_list','description',"`excl`<>'1'",$sec) ; + + # &db_min_ro('quotes_pdf_titles', '*', "quote_id = $id", '', '') ; + foreach (keys %{$db{quotes_pdf_titles}}){ + next unless $db{quotes_pdf_titles}{$_}{quote_id} == $id ; + $old_title_to_new_title{$db{quotes_pdf_titles}{$_}{old_name}}{$db{quotes_pdf_titles}{$_}{quote_id}} = $db{quotes_pdf_titles}{$_}{new_name} ; + } + + foreach (sort keys %sec_cnt) { + $_k = substr($_,1) ; + next if $_k eq '_hardware' ; + my @parts = split(/\-/,$sec_cnt{$_}) ; + + $add_form_fields .= qq~

    $parts[1] :

    ~ ; + # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + $fcol = 3 ; + $add_form_fields .= qq~
    PDF title :
    ~ ; + # $add_form_fields .= qq~
    PDF TITLE :
    ~ ; + if ($old_title_to_new_title{$parts[1]}{$id} and $old_title_to_new_title{$parts[1]}{$id} ne $parts[1]){ + $add_form_fields .= &common_min_form_input_col($_k, $old_title_to_new_title{$parts[1]}{$id}) ; + } + else { + $add_form_fields .= &common_min_form_input_col($_k,'') ; + } + + $add_form_fields .= qq~
    ~ ; + &tab_build_qt_col_headers("$sec$_k") ; + &build_cost_form($id,$tab,$parts[0],"$sec$_k") ; + if ($_k eq '_systems') { + $preferred_title{'systems_included'} = ' ' ; $preferred_placeholder{'systems_included'} = 'Included' ; $fcol = 3 ; + $add_form_fields .= &common_min_form_textarea('systems_included',$db{$table}{$id}{systems_included},'') ; + } + if ($_k eq '_rental') { + $preferred_title{'rental_included'} = ' ' ; $preferred_placeholder{'rental_included'} = 'Included' ; $fcol = 3 ; + $add_form_fields .= &common_min_form_textarea('rental_included',$db{$table}{$id}{rental_included},'') ; + } + if ($_k eq '_other') { + $preferred_title{'other_included'} = ' ' ; $preferred_placeholder{'other_included'} = 'Included' ; $fcol = 3 ; + $add_form_fields .= &common_min_form_textarea('other_included',$db{$table}{$id}{other_included},'') ; + } + } + + $add_form_fields .= qq~
     
    ~ ; + $add_form_fields .= qq~
    PDF total :
    ~ ; + + $lcol = 3 ; + + if ($old_title_to_new_title{"Hardware"}{$id} and $old_title_to_new_title{"Hardware"}{$id} ne "Hardware"){ + $add_form_fields .= &common_min_form_input_col('_hardware', $old_title_to_new_title{"Hardware"}{$id}) ; + } + else { + $add_form_fields .= &common_min_form_input_col('_hardware','') ; + } + + my @ttlarr_labels = ("sub_total","vat_total","grand_total") ; + $lcol = 1 ; $fcol = 1 ; + foreach (@ttlarr_labels) { + $readonly{$_} = "READONLY" ; + my $val = $db{$table}{$id}{$_} ; $val = '0.00' unless $val ; + $type = 'hidden' ; $add_form_fields .= &common_min_form_input_col($_,$val) ; $type = '' ; + $lcol = 1 ; $add_form_fields .= &common_min_form_label_col($_) ; + } + + $add_form_fields .= qq~
    ~ ; + + $lcol = 1 ; $fcol = 1 ; + + foreach my $a (@ttlarr) { + + $readonly{$a} = "READONLY" ; + + $add_form_fields .= qq~
    ~ ; + + $lcol = 2 ; + $add_form_fields .= &common_min_form_label_col($a) ; + $lcol = 1 ; + + foreach my $b (@ttlarr2) { + $field = "$b\_$a\_1" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + my $val = ($default_totals{$field}{1}) ? $default_totals{$field}{1} : '0.00' ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + } + $add_form_fields .= qq~
    ~ ; + + } + + $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col) ; + + # --------------- END COSTING ---------------------------------------------------------------------------------------------------------------- + + + # $trigger_jquery_raw .= qq~ + + # function get_tab (id) { + # let tab = "" ; + # if (id.includes("workings_event")) { + # tab = "workings_event" ; + # } else if (id.includes("costing_event")) { + # tab = "costing_event" ; + # } + # return tab ; + # } + + # function changed_vat (id) { + # let tab = get_tab (id) ; + # let row_nr = get_row_nr(id) ; + # calc_totals(row_nr,tab) ; + # } + + # function changed_others (id) { + + # let row_nr = get_row_nr(id) ; + # let firstIndex = id.indexOf('_'); + # let col = id.substring(0,firstIndex); + # let tab = get_tab (id) ; + # if (col == "inputAmount") { + # let inp = parseFloat(\$("#"+id).val()) ; + # inp = parseFloat(inp) ; + # \$("#"+id).val(inp.toFixed(2)) ; + # } else if (\$("#selectDescription_"+tab+"_"+row_nr).val() && \$("#selectDescription_"+tab+"_"+row_nr).val() != 14 && \$("#selectOperator_"+tab+"_"+row_nr).val()) { + # // \$("#selectOperator_"+tab+"_"+row_nr).val("") ; + # // \$("#selectOperator_"+tab+"_"+row_nr).trigger("chosen:updated") ; + # } + # // else if (col == "selectOperator" && \$("#selectDescription"+tab+"_"+row_nr).val() != 14) { + + # // } + + # if (col == "selectOperator") { // || (col == "selectDescription" && \$("#selectDescription_"+tab+"_"+row_nr).val( + # return ; + # } + + # calc_totals(row_nr,tab) ; + # } + + # // \$("$vat_field_ids_string").change(function() { + # \$("#content").on("change","[id^='checkboxVat_']", function () { + # const id = this.id ; + # changed_vat(id) ; + # }); + + # // \$("$excl_field_ids_string,$description_field_ids_string,$qty_field_ids_string,$amount_usd_field_ids_string,$operator_field_ids_string").change(function() { + # \$("#content").on("change","[id^='checkboxExcl_'],[id^='selectDescription_'],[id^='inputQty_'],[id^='inputAmount_usd_'],[id^='selectOperator_workings_event_']", function () { + # const id = this.id ; + # changed_others(id) ; + # }); + # ~ ; + + # $trigger_jquery_raw .= qq~ + + # \$("#content").on("click","[id^='btn_workings_event_'],[id^='btn_costing_event_']", function () { + # // \$("$btn_ids_string").click(function () { + # const id = this.id ; + # let tab = get_tab (id) ; + + # console.log("id : "+id) ; + # console.log("tab : "+tab) ; + + # add_quote_expenses_row_all(id,tab) ; + # }); + + # function add_quote_expenses_row_all (id,tab) { + + # let row_nr = get_row_nr(id) ; + # \$("#"+tab+"_"+row_nr).show(); + # let row_html = "" ; + # if (tab == "workings_event") { + # row_html = add_quote_expenses_row(row_nr,tab,"$description_options_workings","$operator_options") ; + # } else if (tab == "costing_event") { + # row_html = add_quote_expenses_row(row_nr,tab,"$description_options_costing","") ; + # } + # \$("#"+tab+"_"+row_nr).html(row_html); + # // \$("#$suffix\_"+row_nr).trigger("chosen:updated") ; + + # \$("#selectDescription_"+tab+"_"+row_nr).chosen({ allow_single_deselect:true }) ; + + # if (tab == "workings_event") { + # \$("#selectOperator_workings_event_"+row_nr).chosen({ allow_single_deselect:true }); + # \$("#inputRemarks_workings_event_"+row_nr).css("text-align","") ; + # \$("#inputSupplier_workings_event_"+row_nr).css("text-align","") ; + # \$("#inputRef_nr_workings_event_"+row_nr).css("text-align","") ; + # } + + # \$("#btn_"+tab+"_"+row_nr).hide(); + # var v = row_nr + 1 ; + + # // \$("#btn_$suffix\_"+v).css("padding-left","16px") ; + # \$("#btn_"+tab+"_"+v).html("") ; + # \$("#btn_"+tab+"_"+v).show(); + # \$("#btn_row_"+tab+"_"+v).show() ; + # \$("#2_"+tab+"_"+row_nr).show() ; + + # \$("#checkboxExcl_"+tab+"_"+row_nr).prop('checked',false) ; + + # // \$("#"+tab+"_"+row_nr).on("change","#checkboxVat_"+tab+"_"+row_nr+"", function() { + # // const id = this.id ; + # // changed_vat(id) ; + # // }); + + # // \$("#"+tab+"_"+row_nr).on("change","#checkboxExcl_"+tab+"_"+row_nr+",#selectDescription_"+tab+"_"+row_nr+",#selectOperator_"+tab+"_"+row_nr+",#inputQty_"+tab+"_"+row_nr+",#inputAmount_usd_"+tab+"_"+row_nr+"", function() { + # // const id = this.id ; + # // changed_others(id) ; + # // }); + + # } + + # ~ if $btn_ids_string ; + + # $trigger_jquery_raw .= qq~ + + # \$("#selectCurrency").change(function () { + + # }) ; + + # \$("input[name='roe']").change(function () { + + # let roe = \$(this).val() ; + # if (roe < 0 || !roe) { + # roe = 1 ; + # } + # \$(this).val(parseFloat(roe).toFixed(2)) ; + + # var sub_total = 0 ; var vat_total = 0 ; var sub_total_quote = 0 ; var vat_total_quote = 0 ; + + # [sub_total,vat_total] = add_up_totals("workings_event",50,roe,1) ; + # [sub_total_quote,vat_total_quote] = add_up_totals("costing_event",30,roe,1) ; + + # // // // \$("input[name='income']").val((sub_total_quote+vat_total_quote).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # \$("input[name='income']").val((sub_total_quote+vat_total_quote).toFixed(2)) ; + # \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + # update_overall_totals(sub_total,vat_total,"workings_event") ; + # update_overall_totals(sub_total_quote,vat_total_quote,"costing_event") ; + + # }) ; + + # function add_up_totals (tab,nr_of_rows,roe,recalc_totals) { + + # let sub_total = 0 ; let vat_total = 0 ; + # for (let i=1; i<=nr_of_rows; i++) { + # if (!\$("#"+tab+"_"+i).html()) { break ; } + # if (\$("#selectDescription_"+tab+"_"+i).val()) { + # if (\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { continue ; } + # let ttl = 0 ; + # if (recalc_totals) { + # ttl = parseFloat(\$("#inputAmount_usd_"+tab+"_"+i).val()) * parseFloat(\$("#inputQty_"+tab+"_"+i).val()) * parseFloat(roe) ; + # } else { + # ttl = parseFloat(\$("#inputAmount_ttl_"+tab+"_"+i).val().replace(/,/g, '')) + # } + # // // // // \$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # \$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toFixed(2)) ; + # if (!\$("#inputAmount_ttl_"+tab+"_"+i).val() || \$("#inputAmount_ttl_"+tab+"_"+i).val() == "NaN") { + # \$("#inputAmount_ttl_"+tab+"_"+i).val("0.00") ; + # ttl = 0 ; + # } + # sub_total += ttl ; + # if (\$("#checkboxVat_"+tab+"_"+i).is(":checked")) { + # vat_total += ttl*0.15 ; + # } + # } else if (!\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { + # \$("#checkboxExcl_"+tab+"_"+i).prop('checked',true) ; + # } + # } + # return [sub_total,vat_total] ; + # } + + # // function getNum(val) { + + # // if (isNaN(val)) { + # // return 0; + # // } + # // return val; + # // } + + # function calc_totals (row_cnt,tab) { + + # var qty = \$("#inputQty_"+tab+"_"+row_cnt) ; + # var usd = \$("#inputAmount_usd_"+tab+"_"+row_cnt) ; + # var conv = \$("#inputAmount_ttl_"+tab+"_"+row_cnt) ; + # var excl = \$("#checkboxExcl_"+tab+"_"+row_cnt) ; + # var item = \$("#selectDescription_"+tab+"_"+row_cnt) ; + + # if (!usd.val() && !conv.val() && !usd.val()) { + # // console.log("skip calc_totals_workings") ; + # if (!item.val()) { + # excl.prop("checked",true) ; + # } + # return ; + # } + + # var vat = \$("#checkboxVat_"+tab+"_"+row_cnt) ; + + # if (!item.val()) { + + # excl.prop("checked",true) ; + # vat.prop("checked",true) ; + # qty.val("") ; + # usd.val("") ; + # conv.val(""); + # if (tab == "workings_event") { + # var rem = \$("#inputRemarks_"+tab+"_"+row_cnt) ; + # var sup = \$("#inputSupplier_"+tab+"_"+row_cnt) ; + # var ref = \$("#inputRef_nr_"+tab+"_"+row_cnt) ; + # var op = \$("#selectOperator_"+tab+"_"+row_cnt) ; + # rem.val("") ; + # sup.val("") ; + # ref.val("") ; + # op.val("") ; + # op.trigger("chosen:updated") ; + # } + # } else if (excl.is(":checked") && item.val() && conv.val() == "0.00") { + # excl.prop("checked",false) ; + # } + + # if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) ; } + + # let roe = parseFloat(\$("#inputRoe").val()) ; + + # let ttl = usd.val() * qty.val() * roe ; + + # // // // conv.val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # conv.val(ttl.toFixed(2)) ; + + # let sub_total = 0 ; let vat_total = 0 ; + + # let nr_of_rows = 50 ; + # if (tab == "costing_event") { + # nr_of_rows = 30 ; + # } + + # [sub_total,vat_total] = add_up_totals (tab,nr_of_rows,roe,0) ; + + # if (tab == "workings_event") { + # // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + # update_overall_totals(sub_total,vat_total,tab) ; + # } else { + # // // // \$("input[name='income']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # \$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; + # update_overall_totals(sub_total,vat_total,tab) ; + # // update_overall_totals_costings(sub_total,vat_total) ; + # } + # } + + # function update_overall_totals (sub_total,vat_total,tab) { + + # let profit_loss = parseFloat(\$("input[name='income']").val().replace(/,/g, '')) - parseFloat(\$("input[name='expenses']").val().replace(/,/g, '')) ; + + # // // // \$("input[name='profit_loss']").val(profit_loss.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # // // // \$("input[name='sub_total_"+tab+"']").val(sub_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # // // // \$("input[name='vat_total_"+tab+"']").val(vat_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # // // // \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + + # \$("input[name='profit_loss']").val(profit_loss.toFixed(2)) ; + # \$("input[name='sub_total_"+tab+"']").val(sub_total.toFixed(2)) ; + # \$("input[name='vat_total_"+tab+"']").val(vat_total.toFixed(2)) ; + # \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toFixed(2)) ; + # } + + # function add_quote_expenses_row (row_nr,tab,options1,options2) { + + # let tindex = $tindex ; + # tindex = parseInt(tindex) ; + # row_nr = parseInt(row_nr) ; + # tindex = tindex - 10*(1+50-row_nr) ; + + # let row = add_checkbox(row_nr,"excl_"+tab+"_"+row_nr,"checkboxExcl_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + + # row = row+""+add_select(row_nr,"description_"+tab+"_"+row_nr,"selectDescription_"+tab+"_"+row_nr,"Select Description "+row_nr,options1,tindex,2,90,'','') ; tindex++ ; + # if (tab == "workings_event") { + # row = row+add_select(row_nr,"operator_workings_event_"+row_nr,"selectOperator_workings_event_"+row_nr,"Select Operator "+row_nr,options2,tindex,2,90,'','') ; tindex++ ; + # row = row+add_input(row_nr,"remarks_workings_event_"+row_nr,"inputRemarks_workings_event_"+row_nr,"Remarks "+row_nr,tindex,'',1) ; tindex++ ; + # row = row+add_input(row_nr,"supplier_workings_event_"+row_nr,"inputSupplier_workings_event_"+row_nr,"Supplier "+row_nr,tindex,'',1) ; tindex++ ; + # row = row+add_input(row_nr,"ref_nr_workings_event_"+row_nr,"inputRef_nr_workings_event_"+row_nr,"Ref Nr "+row_nr,tindex,'',1) ; tindex++ ; + # } + # row = row+add_input(row_nr,"qty_"+tab+"_"+row_nr,"inputQty_"+tab+"_"+row_nr,"Qty "+row_nr,tindex,'',1) ; tindex++ ; + # row = row+add_input(row_nr,"amount_usd_"+tab+"_"+row_nr,"inputAmount_usd_"+tab+"_"+row_nr,"Amount "+row_nr,tindex,'',1) ; tindex++ ; + # row = row+add_input(row_nr,"amount_ttl_"+tab+"_"+row_nr,"inputAmount_ttl_"+tab+"_"+row_nr,"Total Amount "+row_nr,tindex,"readonly",1) ; tindex++ ; + # row = row+add_checkbox(row_nr,"vat_"+tab+"_"+row_nr,"checkboxVat_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + # return row ; + # } + # ~ ; + +} + +if ($tab==3) { # Costing + + # --------------- START COSTING ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + $lcol=1; $fcol=2; + + my $sec = '_costing' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + %sec_cnt = ('a_other' => "5-Other"); + + foreach (sort keys %sec_cnt) { + $_k = substr($_,1) ; + next if $_k eq '_hardware' ; + my @parts = split(/\-/,$sec_cnt{$_}) ; + $add_form_fields .= qq~

    $parts[1] :

    ~ ; + # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + $fcol = 3 ; + $add_form_fields .= qq~
    PDF title :
    ~ ; + # $add_form_fields .= qq~
    PDF TITLE :
    ~ ; + if ($old_title_to_new_title{$parts[1]}{$id} and $old_title_to_new_title{$parts[1]}{$id} ne $parts[1]){ + $add_form_fields .= &common_min_form_input_col($_k, $old_title_to_new_title{$parts[1]}{$id}) ; + } + else { + $add_form_fields .= &common_min_form_input_col($_k,'') ; + } + + $add_form_fields .= qq~
    ~ ; + &tab_build_qt_col_headers("$sec$_k") ; + &build_cost_form($id,$tab,$parts[0],"$sec$_k") ; + if ($_k eq '_systems') { + $preferred_title{'systems_included'} = ' ' ; $preferred_placeholder{'systems_included'} = 'Included' ; $fcol = 3 ; + $add_form_fields .= &common_min_form_textarea('systems_included',$db{$table}{$id}{systems_included},'') ; + } + if ($_k eq '_rental') { + $preferred_title{'rental_included'} = ' ' ; $preferred_placeholder{'rental_included'} = 'Included' ; $fcol = 3 ; + $add_form_fields .= &common_min_form_textarea('rental_included',$db{$table}{$id}{rental_included},'') ; + } + if ($_k eq '_other') { + $preferred_title{'other_included'} = ' ' ; $preferred_placeholder{'other_included'} = 'Included' ; $fcol = 3 ; + $add_form_fields .= &common_min_form_textarea('other_included',$db{$table}{$id}{other_included},'') ; + } + } + + $add_form_fields .= qq~
     
    ~ ; + + # $add_form_fields .= qq~
     
    ~ ; + + $add_form_fields .= qq~
    PDF total :
    ~ ; + $lcol = 3 ; + # if ($old_title_to_new_title{"Hardware"}{$id} and $old_title_to_new_title{"Hardware"}{$id} ne "Hardware") { + # $add_form_fields .= &common_min_form_input_col('_hardware', $old_title_to_new_title{"Hardware"}{$id}) ; + # } else { + # $add_form_fields .= &common_min_form_input_col('_hardware','') ; + # } + + # my @ttlarr = ("sub_total","vat_total","grand_total") ; + + # @ttlarr2 = ("subtotal","vat","total") ; + + $lcol = 1 ; $fcol = 1 ; + + print "\n Other Costing Tab " ; + + foreach (@ttlarr) { + print "\n 1 ttlarr : $_ " ; + $readonly{$_} = "READONLY" ; + my $val = $db{$table}{$id}{$_} ; $val = '0.00' unless $val ; + # $add_form_fields .= qq~
    ~ ; $lcol=2; + # $add_form_fields .= &common_min_form_label_col($_) ; $lcol = 1 ; + $type = 'hidden' ; $add_form_fields .= &common_min_form_input_col($_,$val) ; $type = '' ; + # $add_form_fields .= qq~
    ~ ; + + $lcol = 1 ; $add_form_fields .= &common_min_form_label_col($_) ; + # $add_form_fields .= qq~
    ~ ; + } + + $add_form_fields .= qq~
    ~ ; + + # $add_form_fields .= qq~
     
    ~ ; + + # my @ttlarr = ("one_time_fee","monthly_recurring_fee","annual_fee") ; + $lcol = 1 ; $fcol = 1 ; + + foreach my $a (@ttlarr) { + + $readonly{$a} = "READONLY" ; + + # if ($_ eq 'one_time_fee') { + + # $add_form_fields .= qq~
    PDF total :
    ~ ; + # $lcol = 1 ; + # if ($old_title_to_new_title{"Hardware"}{$id} and $old_title_to_new_title{"Hardware"}{$id} ne "Hardware"){ + # $add_form_fields .= &common_min_form_input_col('_hardware', $old_title_to_new_title{"Hardware"}{$id}) ; + # } + # else { + # $add_form_fields .= &common_min_form_input_col('_hardware','') ; + # } + # } + + # else { + $add_form_fields .= qq~
    ~ ; + # } + + $lcol = 2 ; + $add_form_fields .= &common_min_form_label_col($a) ; + $lcol = 1 ; + + foreach my $b (@ttlarr2) { + + $field = "$b\_$a\_2" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + my $val = $default_totals{$field}{2} ? $default_totals{$field}{2} : '0.00' ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + } + + # $field = "2_subtotal_$_" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + # my $val = $db{$table}{$id}{$field} ? $db{$table}{$id}{$field} : '0.00' ; + # $add_form_fields .= &common_min_form_input_col($field,$val) ; + + # $field = "2_vat_$_" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + # my $val = $db{$table}{$id}{$field} ? $db{$table}{$id}{$field} : '0.00' ; + # $add_form_fields .= &common_min_form_input_col($field,$val) ; + + # $field = "2_total_$_" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + # my $val = $db{$table}{$id}{$field} ? $db{$table}{$id}{$field} : '0.00' ; + # $add_form_fields .= &common_min_form_input_col($field,$val) ; + $add_form_fields .= qq~
    ~ ; + + } + + $add_form_fields .= qq~
     
    ~ ; + + # $print_box_content_rows .= qq~
    ~ ; + # $print_box_content_rows .= $add_form_fields ; + # $print_box_content_rows .= &common_min_box_foot; + + &tab_content_box($sec_name,$sec_col) ; + + # --------------- END COSTING ---------------------------------------------------------------------------------------------------------------- + + + $trigger_jquery_raw .= qq~ + + + + ~ ; + +} + +if ($tab==4) { # Purchase Summary + + # --------------- START PURCHASE SUMMARY ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + my $sec = '_purchase_summary' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + my $style_vat = '' ; if ($no_vat{$sec}) { $style_vat = 'style="display:none;"' ; } + + $add_form_fields .= qq~
     
    ~ ; + + my $field = "excl$sec" ; + if ($db{$table}{$id}{$field} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + $label{$field} = 1 ; + $add_form_fields .= qq~
    ~ ;$fcol=1 ; + $add_form_fields .= &common_min_form_checkbox_col($field,$db{$table}{$id}{$field},$checked) ; + $add_form_fields .= qq~

    Purchase Summary

    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + my $suffix = $sec ; my $rcnt = 3 ; + + # &set_check_boxes_checked($id,$rcnt,"excl",$suffix); + + $default_desc{1} = 'Hardware Purchase' ; + $default_desc{2} = 'Monthly Fees' ; + $default_desc{3} = 'Annual Fees' ; + + my @prefexes = ("excl", "item") ; + + foreach my $prefex (@prefexes) { + + $col_name = "$prefex" . "$suffix" ; + $cnt = 0 ; + # if($db{quotes_min}{$id}{$col_name}){ + for my $col_input (split(";", $db{quotes_min}{$id}{$col_name})){ + $cnt++ ; + $saved_field{$prefex}{$suffix}{$cnt} = $col_input ; + } + # } + } + for (1 .. $rcnt) { + $add_form_fields .= qq~
    ~ ; + #---------------------------------------------------------------------------------------------------- + $field = "excl_$_$suffix" ; $fcol=1 ; + # if ($checkit{$field} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + # if ($db{$table}{$id}{$field} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + if ($saved_field{"excl"}{$suffix}{$_} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + $label{$field} = 1 ; + # $add_form_fields .= &common_min_form_checkbox_col($field,$db{$table}{$id}{$field},$checked) ; + $add_form_fields .= &common_min_form_checkbox_col($field,$saved_field{"excl"}{$suffix}{$_},$checked) ; + #---------------------------------------------------------------------------------------------------- + my $field = "item_$_$suffix" ; $fcol=2 ; + $preferred_placeholder{$field} = "Item $_" ; + # my $val = $db{$table}{$id}{$field} ; + my $val = $saved_field{"item"}{$suffix}{$_} ; + $val = $default_desc{$_} unless $val ; + # $readonly{$field} = 'READONLY' ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + for my $year (1 .. 5) { + $field = "year_$year\_$_$suffix" ; $input_style{$field} = qq~style="text-align:right;"~; + + unless ($year==1 and $_==3) { + $readonly{$field} = 'READONLY' ; + } else { + $trigger_jquery_raw .= qq~\$("#inputYear_1_$_$suffix").change(function() { + calcAnnual$field() ; + }); + ~; + $trigger_jquery_raw .= qq~function calcAnnual$field() + { + var annual_ttl = getNum(parseFloat(\$("#inputYear_1_$_$suffix").val())) + getNum(parseFloat(\$("#inputYear_2_$_$suffix").val())) + getNum(parseFloat(\$("#inputYear_3_$_$suffix").val())) ; + \$("#inputTotal_$_$suffix").val(annual_ttl.toFixed(2)); + }~; + } + $preferred_placeholder{$field} = "Year $year Total $_" ; + # my $val = &q_get_val($db{$table}{$id}{$field}) ; + $excl_on_change{$field} = 1 ; + $year_totals{"yearly_totals_$year"} += $db{$table}{$id}{$field} ; + + $fcol = 12 ; + $add_form_fields .= qq~
    ~ if $year <= 3 ; + $add_form_fields .= qq~~ ; + } + $fcol = 2 ; + #---------------------------------------------------------------------------------------------------- + + $field = "total_$_$suffix" ; $input_style{$field} = qq~style="text-align:right;"~; $readonly{$field} = 'READONLY' ; # $fcol=2 ; + $preferred_placeholder{$field} = "Total $_" ; + # my $val = &q_get_val($db{$table}{$id}{$field}) ; + $add_form_fields .= &common_min_form_input_col($field,$db{$table}{$id}{$field},1) ; + #---------------------------------------------------------------------------------------------------- + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + } + $add_form_fields .= qq~
    ~ ; + for my $y (1 .. 5) { + $grand_tot += $year_totals{"yearly_totals_$y"} ; + $field ="yearly_totals_$y" ; + $readonly{$field} = 'READONLY' ; + # $year_totals{"yearly_totals_$y"} = &common_commify($year_totals{"yearly_totals_$y"}) ; + $input_style{$field} = qq~style="text-align:right;"~ ; + $fcol = 12 ; + $add_form_fields .= qq~
    ~ if $y <= 3 ; + $add_form_fields .= qq~~ ; + } + + $trigger_jquery_raw .= qq~ + // console.log("suffix : "+$suffix) ;console.log("1") ; + + if (\$("#selectPeriod").val() == 60) { + + for (let ii = 1; ii <= 5; ii++) { + + if (ii <= 3) { + \$("#year_"+ii+"_sum").removeClass("col-md-2").addClass("col-md-1") ; + \$("#total_"+ii+"").removeClass("col-md-2").addClass("col-md-1") + } + else if (ii <= 5 && ii > 3) { + \$("#year_"+ii+"_sum").removeClass("col-md-0").addClass("col-md-1") ; + \$("#total_"+ii+"").removeClass("col-md-0").addClass("col-md-1") ; + \$("#year_"+ii+"_sum").show() ; + \$("#total_"+ii+"").show() ; + } + for (let jj = 1; jj <= 3; jj++) { + + if (ii <= 3) { + \$("#b_year_"+ii+"_"+jj+"").removeClass("col-md-2").addClass("col-md-1") ; + } + else if (ii <= 5 && ii > 3) { + \$("#b_year_"+ii+"_"+jj+"").removeClass("col-md-0").addClass("col-md-1") ; + \$("#b_year_"+ii+"_"+jj+"").show() ; + } + } + } + } + + \$("#selectPeriod").on("change", function() { + + for (let i = 1; i <= 5; i++) { + + if (i <= 3 && \$(this).val() == 36) { + \$("#year_"+i+"_sum").removeClass("col-md-1").addClass("col-md-2") ; + \$("#total_"+i+"").removeClass("col-md-1").addClass("col-md-2") ; + } + else if (i <= 3 && \$(this).val() == 60) { + \$("#year_"+i+"_sum").removeClass("col-md-2").addClass("col-md-1") ; + \$("#total_"+i+"").removeClass("col-md-2").addClass("col-md-1") + } + else if (i <= 5 && i > 3 && \$(this).val() == 36) { + \$("#year_"+i+"_sum").removeClass("col-md-1").addClass("col-md-0") ; + \$("#total_"+i+"").removeClass("col-md-1").addClass("col-md-0") ; + \$("#year_"+i+"_sum").hide() ; + \$("#total_"+i+"").hide() ; + } + else if (i <= 5 && i > 3 && \$(this).val() == 60) { + \$("#year_"+i+"_sum").removeClass("col-md-0").addClass("col-md-1") ; + \$("#total_"+i+"").removeClass("col-md-0").addClass("col-md-1") ; + \$("#year_"+i+"_sum").show() ; + \$("#total_"+i+"").show() ; + } + for (let j = 1; j <= 3; j++) { + + if (i <= 3 && \$(this).val() == 36) { + \$("#b_year_"+i+"_"+j+"").removeClass("col-md-1").addClass("col-md-2") ; + } + else if (i <= 5 && i > 3 && \$(this).val() == 36) { + \$("#b_year_"+i+"_"+j+"").removeClass("col-md-1").addClass("col-md-0") ; + \$("#b_year_"+i+"_"+j+"").hide() ; + } + + else if (i <= 3 && \$(this).val() == 60) { + \$("#b_year_"+i+"_"+j+"").removeClass("col-md-2").addClass("col-md-1") ; + } + else if (i <= 5 && i > 3 && \$(this).val() == 60) { + \$("#b_year_"+i+"_"+j+"").removeClass("col-md-0").addClass("col-md-1") ; + \$("#b_year_"+i+"_"+j+"").show() ; + // if (\$("#b_year_"+i+"_"+j+"").text().trim() === '') { + // \$("#b_year_"+i+"_"+j+"").text("0.00") ; + // } + } + } + } + }); + ~ ; + + $fcol = 2 ; + $field ="yearly_total" ; + $readonly{$field} = 'READONLY' ; + # $grand_tot = &common_commify($grand_tot) ; + $input_style{$field} = qq~style="text-align:right;"~ ; + $add_form_fields .= &common_min_form_input_col($field,$grand_tot,1) ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END PURCHASE SUMMARY ---------------------------------------------------------------------------------------------------------------- + } + +if ($tab==5) { # Notes + + # --------------- START NOTES ---------------------------------------------------------------------------------------------------------------- + + my $sec = '_notes' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $add_form_fields = '' ; + + # &set_check_boxes_checked($id,$sec_cnt,"excl",$sec); + + + &db_min_ro('quote_notes','*',"id='1'",'','') ; + + $add_form_fields .= qq~

    Notes:

    ~ ; + &tab_build_terms_headers; + + $cntnoteloop=1; for (1 .. 12) { &tab_build_terms_fields('note',$_,$id) ; } + + $add_form_fields .= qq~

    Payment Terms:

    ~ ; + &tab_build_terms_headers; + + $cntnoteloop=1; for (1 .. 6) { &tab_build_terms_fields('payment_term',$_,$id) ; } + + $add_form_fields .= qq~

    ROE:

    ~ ; + &tab_build_terms_headers; + + $cntnoteloop=1; for (1 .. 6) { &tab_build_terms_fields('roe',$_,$id) ; } + + $add_form_fields .= qq~

    Delivery Time:

    ~ ; + &tab_build_terms_headers; + + $cntnoteloop=1; for (1 .. 4) { &tab_build_terms_fields('delivery_time',$_,$id) ; } + + $add_form_fields .= qq~

    Terms and Conditions:

    ~ ; + &tab_build_terms_headers; + + $cntnoteloop=1; for (1 .. 1) { &tab_build_terms_fields_terms_and_conditions('terms',$_,$id) ; } + + $trigger_jquery .= qq~\$("#selectTerms_chosen").css( "width", "100%" );~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END NOTES ---------------------------------------------------------------------------------------------------------------- + } + +if ($tab==6) { # Camera Details + + # --------------- START CAMERA DETAILS ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + my $sec = '_camera_details' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $add_form_fields = '' ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + # my $suffix = $sec ; my $rcnt = 11 ; + # my $suffix = $sec ; my $rcnt = 20 ; + my $suffix = $sec ; my $rcnt = $max_cams ; # set in quotes.pl + # our %linked_vpu = () ; our %vpu_serial_nr = () ; our %vpu_camera_nr = () ; + &tab_camera_details_select_opts('cameras','camera_nr',"camera_nr NOT LIKE 'vpu%'",$suffix,$rcnt) ; + + $rcnt = $max_cams ; # reset in tab_camera_details_select_opts + + # &tab_camera_details_select_opts('cameras','camera_nr',"event_system_id < 1",$suffix,$rcnt) ; + + my $cam_qtys = '' ; + + # &common_debug("cam_qtys : quote_nr=$db{$table}{$id}{quote_nr}") ; + + foreach (keys %{$camera_system_count{$db{$table}{$id}{quote_nr}}}) { + # &common_debug("cam_qtys : cam=$_, qty=$camera_system_count{$db{$table}{$id}{quote_nr}}{$_}") ; + $cam_qtys .= qq~$_ : $camera_system_count{$db{$table}{$id}{quote_nr}}{$_}
    ~ ; + } + + # our $cam_box_icon = qq~ ~ if $cam_qtys ; + our $cam_box_icon = qq~ ~ if $cam_qtys ; + + # foreach (sort keys %sec_cnt) { + # $_k = substr($_,1) ; + # my @parts = split(/\-/,$sec_cnt{$_}) ; + # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + # &tab_build_qt_col_headers("$sec$_k"); + # &build_cost_form($id,$tab,$parts[0],"$sec$_k"); + # } + + # unless ($db{quote_notes}{1}{$inpfield}) { $checkit{$exfield} = 1 ; } + + # $add_form_fields .= qq~
    ~ ; + # if ($checkit{$exfield} == 1) { $checked = 'CHECKED'; } elsif (($excl_tick{$cnt}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } + + # &set_check_boxes_checked($id,$rcnt,"excl",$suffix); + + my $cntcamloop=1; + + for (1 .. $rcnt) { + + my $q_nr = $db{$table}{$id}{quote_nr} ; + + + # next if substr($sel_cam_nr{$camera_details{$q_nr}{$_}{"$_$suffix"}{id}},0,3) eq 'VPU' ; + my $a = "$_$suffix" ; + # &common_debug("rcnt : $_ , q_nr : $q_nr , camera_details : $camera_details{$q_nr}{$_}{$a}{id}") ; + + $cam_display_style = '' ; $cam_display_plus_btn = '' ; + # unless ($_==1 or $db{$table}{$id}{"camera_nr_$_$suffix"}) { + unless ($_==1 or $camera_details{$q_nr}{$_}{"$_$suffix"}{id}) { + $cam_display_style = qq~style='display:none;'~ ; + $trigger_jquery_raw .= qq~ \$("#btn_$_$suffix").click(function () { + \$("#$_$suffix").toggle(); + \$("#btn_$_$suffix").hide(); + var v = $_ + 1 ; + \$("#btn_"+v+"$suffix").show(); + });~ ; + if ($_>$cntcamloop) { $cam_display_butt = qq~display:none;~ ; } else { $cam_display_butt = '' ; } + $cam_display_plus_btn = qq~~; + } else { $cntcamloop++ ; } + + + + $add_form_fields .= qq~
    ~ ; + + # my $cam_id = $db{$table}{$id}{"camera_nr_$_$suffix"} ; + + # $add_form_fields .= qq~
    ~ ; + #---------------------------------------------------------------------------------------------------- + $field = "excl_$_$suffix" ; $fcol=1 ; + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_cam_excl} ; + # if ($checkit{$field} == 1) { $checked = 'CHECKED'; } elsif ($_!=1 and $iaction eq 'add') { $checked = 'CHECKED'; } else { $checked = ''; } + if ($val==1) { $checked = 'CHECKED'; } elsif ($iaction eq 'add') { $checked = 'CHECKED'; } elsif ($val eq '0') { $checked = ''; } else { $checked = 'CHECKED'; } + # &common_debug("$field : [$val] [$checked] [$_$suffix]") ; + $label{$field} = 1 ; + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_checkbox_col($field,$val,$checked) ; + #---------------------------------------------------------------------------------------------------- + my $field = "camera_nr_$_$suffix" ; $fcol=2 ; + $allow_deselect{$field} = 1 ; + $preferred_placeholder{$field} = "Camera Nr $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{id} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + # $add_form_fields .= &common_min_form_input_col($field,$val) ; + $excl_on_change{$field} = 1 ; + + $opts{$field} = $opts_on_edit{$field} if $opts_on_edit{$field} and $db{quotes}{$i{id}}{max_cams} > 50 ; #and $username eq 'rory' ; # overwrite if selected and max_cams exceeded + + $add_form_fields .= &common_min_form_select_col($field,$val) ; + + my $abrv_cam_system = substr($sel_cam_nr{$val},0,3); + # next if $abrv_cam_system eq 'VPU' ; + # &common_debug("abrv_cam_system=$abrv_cam_system, abrv_prev_cam_system=$abrv_prev_cam_system, prev_cam_nr=$prev_cam_nr, link to: c_excl_$_\_camera_details") ; + # if ($abrv_cam_system eq 'VPU' and ($abrv_prev_cam_system eq 'S1' or $abrv_prev_cam_system_other eq 'Prime' or $abrv_prev_cam_system_other eq 'Coach')) { + + # if ($abrv_cam_system eq 'VPU' and ($abrv_prev_cam_system eq 'S1' or $abrv_prev_cam_system eq 'S2' or $abrv_prev_cam_system_other eq 'Prime' or $abrv_prev_cam_system_other eq 'Coach')) { + + if ($linked_vpu{$val}) { + $trigger_jquery .= qq~\$("#c_excl_$_\_camera_details").append("");\$('[data-toggle="tooltip"]').tooltip({html:true}) ;~; + } + # } + $abrv_prev_cam_system = substr($abrv_cam_system,0,2); + $abrv_prev_cam_system_other = substr($abrv_cam_system,0,5); + $prev_cam_nr = $sel_cam_nr{$val} ; + #---------------------------------------------------------------------------------------------------- + # # my $field = "item_code_$_$suffix" ; $fcol=1 ; + # # $preferred_placeholder{$field} = "Item Code $_" ; + # # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + # # $add_form_fields .= &common_min_form_input_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + my $field = "description_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "Description $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_cam_desc} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + # my $field = "qty_$_$suffix" ; $fcol=1 ; + # $preferred_placeholder{$field} = "Qty $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + # $type = 'hidden' ; $add_form_fields .= &common_min_form_input_col($field,$val) ; $type = '' ; + #---------------------------------------------------------------------------------------------------- + my $field = "serial_nr_$_$suffix" ; $fcol=2 ; + $preferred_placeholder{$field} = "Serial Nr $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{serial_nr} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + my $field = "ref_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "Ref $_" ; + # my $val = $db{$table}{$id}{$field} ; + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ref} ; + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + # &common_debug("2. $field : [$q_nr] [$_] [$_$suffix] [$val]") if $val; + #---------------------------------------------------------------------------------------------------- + my $field = "delivery_date_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "Delivery Date $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_delivery_date} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_datepicker_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + my $field = "active_date_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "Active Date $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_active_date} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $add_form_fields .= &common_min_form_datepicker_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + my $field = "ew_date_from_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "E/W Date From $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_from} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_datepicker_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + my $field = "ew_date_to_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "E/W Date To $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_to} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_datepicker_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + # my $ew_pdf_butt = '' ; if ($username eq 'rory' or $username eq 'handre') { $ew_pdf_butt = qq~ ~; } + # my $ew_pdf_butt = '' ; if ($camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_from} and $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_to} and uc substr($camera_details{$q_nr}{$_}{"$_$suffix"}{camera_nr},0,3) ne 'VPU') { $ew_pdf_butt = qq~ ~; } + my $ew_pdf_butt = '' ; if ($camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_from} and $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_to} and (uc substr($camera_details{$q_nr}{$_}{"$_$suffix"}{camera_nr},0,2) eq 'S1' or uc substr($camera_details{$q_nr}{$_}{"$_$suffix"}{camera_nr},0,5) eq 'SCORE')) { $ew_pdf_butt = qq~ ~; } + #---------------------------------------------------------------------------------------------------- + $add_form_fields .= qq~
    $ew_pdf_butt
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    $cam_display_plus_btn
    ~ ; + $add_form_fields .= qq~
    ~ ; + } + + $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + $cam_box_icon = '' ; + + # --------------- END CAMERA DETAILS ---------------------------------------------------------------------------------------------------------------- +} + +if ($tab==7) { # Invoice Details + + # --------------- START INVOICE DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_invoice_details' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $lcol = 2 ; + $fcol = 5 ; + + $add_form_fields = '' ; + + $add_form_fields .= &common_min_form_input('invoice_nr',$db{$table}{$id}{invoice_nr},'') ; + my $checked = 'CHECKED' if $db{$table}{$id}{annual_invoice} ; + $add_form_fields .= &common_min_form_checkbox('annual_invoice',$db{$table}{$id}{annual_invoice},$checked) ; + # if ($db{$table}{$id}{invoice_date} eq '' or $db{$table}{$id}{invoice_date} eq '0000-00-00') { $db{$table}{$id}{invoice_date} = $now_ccyy_mm_dd ; } + $add_form_fields .= &common_min_form_datepicker('invoice_date',$db{$table}{$id}{invoice_date}) ; + $add_form_fields .= &common_min_form_input('annual_invoice_2',$db{$table}{$id}{annual_invoice_2},'') ; + $add_form_fields .= &common_min_form_input('annual_invoice_3',$db{$table}{$id}{annual_invoice_3},'') ; + # $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END INVOICE DETAILS ---------------------------------------------------------------------------------------------------------- + } + +# if ($tab==7) { # Extended Warranty + + # # --------------- START EXTENDED WARRANTY -------------------------------------------------------------------------------------------------------- + + # my $sec = '_extended_warranty' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # if ($ret) { return ; } + + # $lcol = 2 ; + # $fcol = 3 ; + + # $add_form_fields = '' ; + + # if (($db{$table}{$id}{date_from} eq '') or ($db{$table}{$id}{date_from} eq '0000-00-00')) { $db{$table}{$id}{date_from} = $now_ccyy_mm_dd ; } + # $add_form_fields .= &common_min_form_datepicker('date_from',$db{$table}{$id}{date_from}) ; + # if (($db{$table}{$id}{date_to} eq '') or ($db{$table}{$id}{date_to} eq '0000-00-00')) { $db{$table}{$id}{date_to} = $now_ccyy_mm_dd ; } + # $add_form_fields .= &common_min_form_datepicker('date_to',$db{$table}{$id}{date_to}) ; + + # &tab_content_box($sec_name,$sec_col); + + # # --------------- END EXTENDED WARRANTY ---------------------------------------------------------------------------------------------------------- + # } + +# if ($tab==8) { # Rental + + # # --------------- START RENTAL -------------------------------------------------------------------------------------------------------- + + # my $sec = '_rental' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # if ($ret) { return ; } + + # $lcol = 2 ; + # $fcol = 3 ; + + # $add_form_fields = '' ; + + # # our %sec_cnt = ('_cost' => "1-Cost"); + + # # my $sec = '_rental' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + # # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # # if ($ret) { return ; } + + # # foreach (sort keys %sec_cnt) { + # # my @parts = split(/\-/,$sec_cnt{$_}) ; + # # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + # # &tab_build_qt_col_headers("$sec$_"); + # # &build_cost_form($id,$tab,$parts[0],"$sec$_"); + # # } + + # &tab_content_box($sec_name,$sec_col); + + # # --------------- END RENTAL ---------------------------------------------------------------------------------------------------------- + # } + +if ($tab==8) { # Document Uploads + + # --------------- START DOCUMENT UPLOADS ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + my $sec = '_document_uploads' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $add_form_fields = '' ; + + my @docs = ('Signed Quote','PO','Other 1','SLA','T&Cs','Other 2','Photos','Delivery Note','Other 3'); + + $add_form_fields .= qq~
    ~ ; + + foreach (@docs) { + my $doc = lc $_ ; $doc =~ s/ /\_/ ; $doc =~ s/&/\_/ ; + $costing_uploads = &common_get_field_uploads($id,"costing_$doc",'id') ; + if ($costing_uploads) { + $add_form_fields .= qq~
    $costing_uploads
    ~; + } else { + $add_form_fields .= qq~ +
    +
    + + +

    Upload file from PC.

    +
    +
    + ~; + } + } + + $add_form_fields .= qq~
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END DOCUMENT UPLOADS ---------------------------------------------------------------------------------------------------------------- + } + +} #------------------------------------------------------------------------------------ + +sub tab_costing_select_opts { + +my ($table,$dispfield,$where,$sec_) = @_ ; + +&db_min_ro($table,'*',$where,'','') ; +my @b = ( +"_costing_additional_services", +"_costing_game_breakdown_analytics", +"_costing_hardware_add_ons", +"_costing_installation_kits", +"_costing_match_credits", +"_costing_other", +"_costing_rental", +"_costing_software_licence", +"_costing_systems" ) ; + +foreach my $suf (@b){ + $col_name = "item" . "$suf" ; + $cnt = 0 ; + if($db{quotes_min}{$i{id}}{$col_name}){ + foreach my $col_input (split(";", $db{quotes_min}{$i{id}}{$col_name})){ + $cnt++ ; + $saved_field{"item"}{$suf}{$cnt} = $col_input ; + # &common_debug("$aa/$suffix : $cc") ; + } + } +} + +foreach my $id (keys %{$db{$table}}) { + foreach (sort keys %sec_cnt) { + $_k = substr($_,1) ; $k = substr($_,2) ; + # &common_debug("tab_select_opts : $db{$table}{$id}{type} ne $k") ; + unless ($db{$table}{$id}{type} eq $k) { next ; } + my @parts = split(/\-/,$sec_cnt{$_}) ; + for my $p_ (1 .. $parts[0]) { # item_1_costing_systems + my $field = "$p_$sec_$_k" ; #my $ucf_field = ucfirst $field ; my $chosen_field = ucfirst $field . '_chosen' ; + # $opts{"item_$p_$sec_$_k"} .= qq~~ ; + my $field_2 = "$sec_$_k" ; + # my $saved_val = $db{quotes}{$i{id}}{"item_$field"} ; + my $saved_val = $saved_field{"item"}{$field_2}{$p_} ; + + if ($saved_val) { my @valarr = split(/\:/,$saved_val) ; $saved_val = $valarr[0] ; } + + if ($saved_val eq $id) { $selected = 'SELECTED' ; } else { $selected = '' ; } + + # $opts{"item_$field"} .= qq~~ ; + $opts{"item_$field"} .= qq~~ ; + + # if ($field eq '3_costing_software_licence' or $field eq '2_costing_game_breakdown_analytics') { + if ($field eq '2_costing_systems' or $field eq '3_costing_systems' or $field eq '3_costing_software_licence' or $field eq '2_costing_game_breakdown_analytics') { + $item_type = 'input' ; + } else { + $item_type = 'select' ; + } + + unless ($got{$field}) { + $preferred_title{"item_$field"} = &common_min_print_field("item_$p_$_k") ; + if ($item_type eq 'select') { $trigger_jquery .= qq~\$("#selectItem_$field\_chosen").css( "width", "96%" ) +~ ; } $got{$field} = 1 ; + $trigger_jquery_raw .= qq~\$("#$item_type\Item_$field, #selectDiscount").change(function() { + calcCosting$field(1) ; + }); + ~; + $trigger_jquery_raw .= qq~\$("#inputQty_$field, #inputUsd_amnt_$field").change(function() { + calcCosting$field(0) ; + }); + ~;$trigger_jquery_raw .= qq~function calcCosting$field(b) + { + if (b==1) { \$("#inputUsd_amnt_$field").val(''); } + + var excl = \$("#checkboxExcl_$field"); + var item = \$("#$item_type\Item_$field"); + var usd = \$("#inputUsd_amnt_$field"); + var conv = \$("#inputCurr_amnt_$field"); + var qty = \$("#inputQty_$field"); + var ttl = \$("#inputItem_ttl_$field"); + var vat = \$("#checkboxVat_$field"); + + // console.log('DISCOUNT - item: '+item.val()+', usd: '+usd.val()) ; + + if (!item.val()) { + excl.prop("checked", true); + usd.val(""); + conv.val(""); + qty.val(""); + ttl.val(""); + vat.val(""); + // return ; + } + + calcCosting(excl,item,qty,usd,conv,vat,ttl) ; + }~; + + } + } + } + } +} #------------------------------------------------------------------------------------------ + +sub tab_camera_details_select_opts { + +my ($table,$dispfield,$where,$suffix,$rcnt) = @_ ; + +&db_min_ro('customers','id,name','','','') ; +foreach my $id (keys %{$db{customers}}) { $customers_name{$id} = $db{customers}{$id}{name} ; } + +&db_min_ro('camera_systems','id,name','','','') ; +foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + +# my $add_quote_fields = '' ; my $sql_or_where = '' ; my @sqlorwhere = () ; +# for (1 .. $rcnt) { + # $add_quote_fields .= ",quotes.camera_nr_$_$suffix" ; + # push @sqlorwhere, "quotes.camera_nr_$_$suffix>0" ; +# } +# $sql_or_where = join(" OR ",@sqlorwhere) ; + +# &db_min_ro("$table,quotes","quotes.id,$table.id$add_quote_fields",$sql_or_where,'','') ; + +# foreach my $id (keys %{$db{"$table,quotes"}}) { + # # $db{quotes}{$i{id}}{"camera_nr_$field"} + # for (1 .. 10) { + # my $field = $db{"$table,quotes"}{$id}{"camera_nr_$_$suffix"} ; + # if ($field) { + # # $camera_exists_on_quote{$field} = $id ; + # $exclude_camera_from_list{$field} = 1 ; + # # &common_debug("exclude_camera_from_list : $field") ; + # } + # } + +# } + +our %linked_vpu = () ; our %vpu_serial_nr = () ; our %vpu_camera_nr = () ; my $cnt_sel=0; my %done_quote_cam_num = () ; my %done_field = () ; +&db_min_ro($table,'id,camera_nr,serial_nr,quote_nr',"camera_nr LIKE 'vpu%'",'','') ; +foreach (keys %{$db{$table}}) { + $vpu_serial_nr{$_} = $db{$table}{$_}{serial_nr} ; + $vpu_camera_nr{$_} = $db{$table}{$_}{camera_nr} ; + + my $qnr = $db{$table}{$_}{quote_nr} ; + + if ($qnr eq $db{quotes}{$i{id}}{quote_nr}) { + $cnt_cams{$qnr}++; + # &common_debug("$cnt_cams{$qnr}. $qnr eq $db{quotes}{$i{id}}{quote_nr} ") if $qnr == 1261 ; + } + +} +&db_min_ro($table,'*',$where,'','') ; + +LOOP1: foreach my $id (sort keys %{$db{$table}}) { + + # &common_debug("1. LOOP1 $db{$table}{$id}{quote_nr} and $db{$table}{$id}{quote_nr} ne $db{quotes}{$i{id}}{quote_nr}") if $db{$table}{$id}{quote_nr} == 1261 ; + if ($db{$table}{$id}{quote_nr} and $db{$table}{$id}{quote_nr} ne $db{quotes}{$i{id}}{quote_nr}) { next ; } + + # &common_debug("2. LOOP1 event_system_id=$db{$table}{$id}{event_system_id} ") if $db{$table}{$id}{quote_nr} == 1261 ; + if ($db{$table}{$id}{event_system_id}) { $skip_event_linked_vpu{$db{$table}{$id}{event_linked_vpu}} = 1 ; next ; } # skip as it's being used for events + + # &common_debug("3. LOOP1 skip_event_linked_vpu=$skip_event_linked_vpu{$db{$table}{$id}{serial_nr}}") if $db{$table}{$id}{quote_nr} == 1261 ; + if ($skip_event_linked_vpu{$db{$table}{$id}{serial_nr}}) { next ; } # skip as it's being used for events + + # &common_debug("LOOP1 rcnt=$rcnt") if $db{$table}{$id}{quote_nr} == 1261 ; + + my $qnr = $db{$table}{$id}{quote_nr} ; + + if ($qnr eq $db{quotes}{$i{id}}{quote_nr}) { + $cnt_cams{$qnr}++; + # &common_debug("$cnt_cams{$qnr}. $qnr eq $db{quotes}{$i{id}}{quote_nr} ") if $qnr == 1261 ; + } + + # LOOP2: for (1 .. $rcnt) { + + # if ($qnr eq $db{quotes}{$i{id}}{quote_nr} and $db{$table}{$id}{quote_cam_num} eq $_) { + # $cnt_sel++ ; + # # &common_debug("$cnt_sel. $qnr eq $db{quotes}{$i{id}}{quote_nr} and $db{$table}{$id}{quote_cam_num} eq $_") if $qnr == 1261 ; + # } + # } +} + +$max_cams = $cnt_cams{$db{quotes}{$i{id}}{quote_nr}} if $cnt_cams{$db{quotes}{$i{id}}{quote_nr}} > $max_cams && $db{quotes}{$i{id}}{quote_nr} ; + +&common_debug("$cnt_cams{$db{quotes}{$i{id}}{quote_nr}} [max_cams = $max_cams]") ; + +# print "\n cnt_sel : $cnt_sel \n" ; +LOOP1: foreach my $id (sort keys %{$db{$table}}) { + + # &common_debug("exclude_camera_from_list [$exclude_camera_from_list{$id}] : [$table] : $id") ; + + if ($db{$table}{$id}{quote_nr} and $db{$table}{$id}{quote_nr} ne $db{quotes}{$i{id}}{quote_nr}) { next ; } + + if ($db{$table}{$id}{event_system_id}) { $skip_event_linked_vpu{$db{$table}{$id}{event_linked_vpu}} = 1 ; next ; } # skip as it's being used for events + if ($skip_event_linked_vpu{$db{$table}{$id}{serial_nr}}) { next ; } # skip as it's being used for events + + my ($camtype,$camcnt) = split(/\-/,$db{$table}{$id}{$dispfield}) ; + $camera_system_count{$db{$table}{$id}{quote_nr}}{$camtype}++ if $db{$table}{$id}{quote_nr} and $camtype ; + $linked_vpu{$id} = $db{$table}{$id}{linked_vpu_id} ; + + # &common_debug("[cam_qtys] quote_nr : [$db{$table}{$id}{quote_nr}] [$db{$table}{$id}{$dispfield}] [$camera_system_count{$db{$table}{$id}{quote_nr}}{$db{$table}{$id}{$dispfield}}]") if $db{$table}{$id}{quote_nr} ; + + my $qnr = $db{$table}{$id}{quote_nr} ; + + # LOOP2: for (1 .. $rcnt) { + LOOP2: for (1 .. $max_cams) { + my $field = "$_$suffix" ; + + # if ($exclude_camera_from_list{$id} and $db{quotes}{$i{id}}{"camera_nr_$_$suffix"} ne $id) { next LOOP2; ; } + # if ($exclude_camera_from_list{$id} and $db{quotes}{$i{id}}{"camera_nr_$_$suffix"} ne $id) { next LOOP1; ; } + + # my $quote_camera_id = $db{quotes}{$i{id}}{"camera_nr_$field"} ; if ($quote_camera_id) { my @valarr = split(/\:/,$quote_camera_id) ; $quote_camera_id = $valarr[0] ; } + + # # my $abrv_cam_system = substr($db{$table}{$id}{camera_nr},0,3); + # next if $seen_cnt{$_} ; + # $seen_cnt{$_} = 1 ; + + # next unless $qnr ; + my $selected = '' ; + + # if ($saved_val eq $id) { $selected = 'SELECTED' ; $sel_cam_nr{$id} = $db{$table}{$id}{camera_nr}; } else { $selected = '' ; } + # if ($db{$table}{$id}{quote_nr} eq $db{quotes}{$i{id}}{quote_nr} and $quote_camera_id eq $id) { + + # if ($qnr == 1261) { + # &common_debug("if ($qnr eq $db{quotes}{$i{id}}{quote_nr} and $_ <= $cnt_sel and not $done_quote_cam_num{$db{$table}{$id}{quote_cam_num}} and not $done_field{$field}) { ") ; + # } + + # if ($qnr eq $db{quotes}{$i{id}}{quote_nr} and $_ <= $cnt_sel and not $done_quote_cam_num{$db{$table}{$id}{quote_cam_num}} and not $done_field{$field}) { + if ($qnr eq $db{quotes}{$i{id}}{quote_nr} and $_ <= $max_cams and not $done_quote_cam_num{$db{$table}{$id}{quote_cam_num}} and not $done_field{$field}) { + $done_quote_cam_num{$db{$table}{$id}{quote_cam_num}} = 1 ; $done_field{$field} = 1 ; + $selected = 'SELECTED' ; $sel_cam_nr{$id} = $db{$table}{$id}{camera_nr}; + # &common_debug("1. quote_ref : [$db{$table}{$id}{quote_cam_num}] [$field] [$db{$table}{$id}{quote_ref}] [$_. max_cams=$max_cams]"); + $camera_details{$qnr}{$_}{$field}{quote_delivery_date} = $db{$table}{$id}{quote_delivery_date} ; + $camera_details{$qnr}{$_}{$field}{quote_active_date} = $db{$table}{$id}{quote_active_date} ; + $camera_details{$qnr}{$_}{$field}{quote_ew_date_from} = $db{$table}{$id}{quote_ew_date_from} ; + $camera_details{$qnr}{$_}{$field}{quote_ew_date_to} = $db{$table}{$id}{quote_ew_date_to} ; + $camera_details{$qnr}{$_}{$field}{quote_cam_desc} = $db{$table}{$id}{quote_cam_desc} ; + $camera_details{$qnr}{$_}{$field}{quote_cam_excl} = $db{$table}{$id}{quote_cam_excl} ; + $camera_details{$qnr}{$_}{$field}{quote_cam_num} = $db{$table}{$id}{quote_cam_num} ; + $camera_details{$qnr}{$_}{$field}{quote_nr} = $qnr ; + $camera_details{$qnr}{$_}{$field}{quote_ref} = $db{$table}{$id}{quote_ref} ; + $camera_details{$qnr}{$_}{$field}{serial_nr} = $db{$table}{$id}{serial_nr} ; + $camera_details{$qnr}{$_}{$field}{camera_nr} = $db{$table}{$id}{camera_nr} ; + $camera_details{$qnr}{$_}{$field}{id} = $id ; + } elsif ($qnr and $db{$table}{$id}{quote_cam_num}) { # camera alread linked to a quote + next ; + } + + # print "\n $qnr eq $db{quotes}{$i{id}}{quote_nr} and $db{$table}{$id}{quote_cam_num} and $_ <= $cnt_sel , field : $field" ; + # &common_debug("tab_camera_details_select_opts [$field] : [$saved_val eq $id] : $selected") ; + + my $display_field = $db{$table}{$id}{$dispfield} ; my ($system,$camcnt) = split(/\-/,$display_field) ; $camcnt+=0; $display_field .= " [$camcnt] [$db{$table}{$id}{serial_nr}]" ; # $display_field =~ s/-//g ; + + # my $opts = qq~~ ; + my $opts = qq~~ ; + + $opts_on_edit{"camera_nr_$field"} = $opts if $selected ; + + $opts{"camera_nr_$field"} .= $opts ; + + # $debugcnt++ ; &common_debug("$debugcnt. camera_nr_$field [$display_field] : [$iaction eq 'edit' and $camera_details{$q_nr}{$_}{$field}{id}] : $selected : cam camera_nr=$db{$table}{$id}{camera_nr} [max_cams=$db{quotes}{$i{id}}{max_cams}]") ; + + # # if ($username eq 'rory' and $iaction eq 'edit' and $db{quotes}{$i{id}}{quote_nr} and $db{quotes}{$i{id}}{max_cams} > 25) { + # if ($username eq 'rory' and $iaction eq 'edit' and $camera_details{$q_nr}{$_}{$field}{id} and $db{quotes}{$i{id}}{max_cams} > 25) { + # $opts_single{"camera_nr_$field"} = $opts if $selected ; + # $debugcnt++ ; &common_debug("$debugcnt. camera_nr_$field [$display_field] : [$username eq 'rory' and $iaction eq 'edit' and $camera_details{$q_nr}{$_}{$field}{id}] : $selected : cam camera_nr=$db{$table}{$id}{camera_nr} [max_cams=$db{quotes}{$i{id}}{max_cams}]") if $selected ; + # } else { + # $opts{"camera_nr_$field"} .= $opts ; + # $debugcnt++ ; &common_debug("NO *** $debugcnt. *** camera_nr_$field [$display_field] : [$username eq 'rory' and $iaction eq 'edit' and $camera_details{$q_nr}{$_}{$field}{id}] : $selected : cam camera_nr=$db{$table}{$id}{camera_nr} [max_cams=$db{quotes}{$i{id}}{max_cams}]") ; + # } + + unless ($got{$field}) { + # $preferred_title{"item_$field"} = &common_min_print_field("item_$p_$_k") ; + $trigger_jquery .= qq~\$("#selectCamera_nr_$field\_chosen").css( "width", "96%" ); +~ ; $got{$field} = 1 ; + + $trigger_jquery_raw .= qq~\$("#selectCamera_nr_$field").change(function() { + dispCamDetails$field('$_') ; + }); + ~; + + $trigger_jquery_raw .= qq~function dispCamDetails$field(f) + { + var excl = \$("#checkboxExcl_$field"); + var camnr = \$("#selectCamera_nr_$field"); + var itcode = '' ; // var itcode = \$("#inputItem_code_$field"); + var desc = \$("#inputDescription_$field"); + var qty = \$("#inputQty_$field"); + var snr = \$("#inputSerial_nr_$field"); + var ddate = \$("#datepickDelivery_date_$field"); + var adate = \$("#datepickActive_date_$field"); + + dispCamDetails(excl,camnr,qty,itcode,desc,snr,ddate,adate,f) ; + }~; + } + } +} + +} #------------------------------------------------------------------------------------------ + +sub tab_customer_select_opts { + +my ($table,$dispfield,$where,$field) = @_ ; + +&db_min_ro($table,'*',$where,'','') ; + +foreach my $id (keys %{$db{$table}}) { + + my $saved_val = $db{quotes}{$i{id}}{$field} ; + + if ($saved_val) { my @valarr = split(/\:/,$saved_val) ; $saved_val = $valarr[0] ; } + + if ($saved_val eq $id) { $selected = 'SELECTED' ; } else { $selected = '' ; } + + $opts{$field} .= qq~~ ; + unless ($got{$field}) { + # $trigger_jquery .= qq~\$("#selectQuote_to_chosen").css( "width", "96%" ); + $trigger_jquery .= qq~\$("#selectQuote_to_chosen").css( "width", "100%" ); +~ ; $got{$field} = 1 ; + + $trigger_jquery_raw .= qq~\$("#selectQuote_to").change(function() { + dispCustomer() ; + }); + ~; + + $trigger_jquery_raw .= qq~function dispCustomer() + { + var custval = \$("#selectQuote_to").val(); + var arrP = custval.split(":"); + \$("#inputContact_name").val(arrP[1]); + \$("#inputAddress").val(arrP[4]); + \$("#inputEmail").val(arrP[2]); + \$("#inputTel").val(arrP[3]); + }~; + } +} + +} #------------------------------------------------------------------------------------------ + +sub tab_build_terms_headers { + +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; + +} #------------------------------------------------------------------------------------ + +sub tab_build_terms_fields { + +my ($sec,$cnt,$id) = @_ ; + +my $exfield = "excl_$cnt\_$sec\s" ; +my $inpfield = "$sec\_$cnt" ; + +unless ($db{quote_notes}{1}{$inpfield}) { $checkit{$exfield} = 1 ; } + +my $val = ($db{$table}{$id}{$inpfield} && $db{$table}{$id}{$inpfield} ne "-1") ? $db{$table}{$id}{$inpfield} : (($db{$table}{$id}{$inpfield} && $db{$table}{$id}{$inpfield} eq "-1")) ? "" : $db{quote_notes}{1}{$inpfield} ; + +$note_display_style = '' ; $note_display_plus_btn = '' ; +# unless ($cnt==1 or $db{quote_notes}{1}{$inpfield}) { +unless ($cnt==1 || $val) { + $note_display_style = qq~style='display:none;'~ ; + $trigger_jquery_raw .= qq~ \$("#btn_$cnt\_$sec").click(function () { + \$("#$cnt\_$sec").toggle(); + \$("#btn_$cnt\_$sec").hide(); + var v = $cnt + 1 ; + \$("#btn_"+v+"\_$sec").show(); + });~ ; + if ($cnt>$cntnoteloop) { $note_display_butt = qq~display:none;~ ; } else { $note_display_butt = '' ; } + $note_display_plus_btn = qq~~; +} else { $cntnoteloop++ ; } + +$add_form_fields .= qq~
    ~ ; + +# $add_form_fields .= qq~
    ~ ; +# if ($checkit{$exfield} == 1) { $checked = 'CHECKED'; } elsif (($excl_tick{$cnt}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } + +# if ($db{$table}{$id}{$exfield} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } +$sec = "_" . $sec . "s" ; +$col_name = "excl" . "$sec" ; +$counter = 0 ; +# &db_min_ro('quotes_min', "id, excl$sec", "id = $id", '', '') ; + +foreach my $col_input (split(/\;/,$db{quotes_min}{$id}{$col_name})) { + $counter++ ; + $saved_field{"excl"}{$sec}{$counter} = $col_input ; +} + +if ($saved_field{"excl"}{$sec}{$cnt}) { $checked = 'CHECKED'; } else { $checked = '' ; } + +$label{$exfield} = 1 ; +$fcol=1 ; +$add_form_fields .= &common_min_form_checkbox_col($exfield,$checkit{$exfield},$checked) ; +$fcol=6 ; +$input_style{$inpfield} = qq~style='margin-bottom:4px;margin-top:-2px;'~ ; # add spaces between boxes +$add_form_fields .= &common_min_form_input_col($inpfield,$val,'') ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    $note_display_plus_btn
    ~ ; + +} #------------------------------------------------------------------------------------ + +sub tab_build_terms_fields_terms_and_conditions { + + my ($sec,$cnt,$id) = @_ ; + + my $exfield = "excl_$cnt\_$sec" ; + my $inpfield = "$sec" ; + my $quote_notes_field = "$sec\_$cnt" ; + + unless ($db{$table}{$id}{$inpfield}) { $checkit{$exfield} = 1 ; } + + if ($db{$table}{$id}{$inpfield}) { $selected{$db{$table}{$id}{$inpfield}} = 'SELECTED';} + + $note_display_style = '' ; + unless ($cnt==1 or $db{$table}{$id}{$inpfield}) { + $note_display_style = qq~style='display:none;'~ ; + $trigger_jquery_raw .= qq~ \$("#btn_$cnt\_$sec").click(function () { + \$("#$cnt\_$sec").toggle(); + \$("#btn_$cnt\_$sec").hide(); + var v = $cnt + 1 ; + \$("#btn_"+v+"\_$sec").show(); + });~ ; + if ($cnt>$cntnoteloop) { $note_display_butt = qq~display:none;~ ; } else { $note_display_butt = '' ; } + } else { $cntnoteloop++ ; } + + $add_form_fields .= qq~
    ~ ; + + + + # $add_form_fields .= qq~
    ~ ; + # if ($checkit{$exfield} == 1) { $checked = 'CHECKED'; } elsif (($excl_tick{$cnt}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } + $sec_2 = "_" . $sec ; + $col_name = "excl" . "$sec_2" ; + $counter = 0 ; + # &db_min_ro('quotes_min', "id, excl$sec", "id = $id", '', '') ; + + foreach my $col_input (split(";", $db{quotes_min}{$id}{$col_name})){ + $counter++ ; + $saved_field{"excl"}{$sec_2}{$counter} = $col_input ; + } + + if ($saved_field{"excl"}{$sec_2}{$cnt}) { $checked = 'CHECKED'; } else { $checked = ''; } + + # if ($db{$table}{$id}{$exfield} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + + $label{$exfield} = 1 ; + $fcol=1 ; + $add_form_fields .= &common_min_form_checkbox_col($exfield,$checkit{$exfield},$checked) ; + $fcol=6 ; + $input_style{$inpfield} = qq~style='margin-bottom:4px;margin-top:-2px;'~ ; # add spaces between boxes + $opts{$inpfield} = "" ; + for (1 .. 5){ + $quote_notes_field = "$sec\_$_" ; + next unless $db{quote_notes}{1}{$quote_notes_field} ; + $opts{$inpfield} .= qq() ; + } + $allow_deselect{$inpfield} = 1; + $add_form_fields .= &common_min_form_select_col($inpfield,$db{$table}{$id}{$inpfield},'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    $note_display_plus_btn
    ~ ; + +} #------------------------------------------------------------------------------------ + +sub tab_build_qt_right { + +my ($id,$tab,$ret) = @_ ; + +if ($tab==1) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_office_details' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $lcol = 2 ; + + $add_form_fields = '' ; + + $fcol = 9 ; + $textarea_height{notes} = 80 ; + $add_form_fields .= &common_min_form_textarea('notes',$db{$table}{$id}{notes},'') ; + $add_form_fields .= qq~
     
    ~ ; + $textarea_height{office_notes} = 80 ; + $add_form_fields .= &common_min_form_textarea('office_notes',$db{$table}{$id}{office_notes},'') ; + $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + +if ($tab==7) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_invoice_notes' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $lcol = 2 ; + + $add_form_fields = '' ; + + $fcol = 9 ; + # $add_form_fields .= qq~
     
    ~ ; + $add_form_fields .= &common_min_form_input('po_nr',$db{$table}{$id}{po_nr},'') ; + $add_form_fields .= &common_min_form_textarea('invoice_notes',$db{$table}{$id}{invoice_notes},'') ; + $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + +} #------------------------------------------------------------------------------------ + +sub tab_curr_symbols { + +$curr_symb{ZAR} = 'R'; +$curr_symb{USD} = '$'; +# $curr_symb{GBP} = '£'; +$curr_symb{GBP} = 'GBP'; +# $curr_symb{EUR} = '€'; +$curr_symb{EUR} = 'EUR'; + +our $js_curr_arr = '' ; + +foreach (keys %curr_symb) { + $js_curr_arr .= qq(currArr['$_'] = "$curr_symb{$_}";) ; + } + +} #------------------------------------------------------------------------------------ + +sub tab_build_qt_col_headers { + +my ($sec) = @_ ; + +my $style_vat = '' ; if ($no_vat{$sec}) { $style_vat = 'style="display:none;"' ; } + +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +# $add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; + +%cost_desc = () ; %def_qty = () ; %def_zar = () ; %min_zar = () ; %vat_tick = () ; %excl_tick = () ; + +} #---------------------------------------------------------------------------------------- + +sub tab_content_box { + +my ($sec_name,$sec_col) = @_ ; + +$fcol=9 ; +$print_box_content_rows .= &common_min_box_top('indent-left',$sec_name,$sec_col,$cam_box_icon); +# $print_box_content_rows .= qq~
    ~ ; +$print_box_content_rows .= qq~$add_form_fields~; +$print_box_content_rows .= &common_min_box_foot; + +} #---------------------------------------------------------------------------------------- + +sub tab_cnt { + +our %cntxt = () ; + +$cntxt{1} = 'one' ; +$cntxt{2} = 'two' ; +$cntxt{3} = 'three' ; +$cntxt{4} = 'four' ; +$cntxt{5} = 'five' ; +$cntxt{6} = 'six' ; +$cntxt{7} = 'seven' ; +$cntxt{8} = 'eight' ; +# $cntxt{9} = 'nine' ; + +} #---------------------------------------------------------------------------------------- + +sub tab_names { + +my ($tab) = @_ ; + +my $tabname = '' ; + + if ($tab==1) { $tabname = 'Quote Details' ; } +elsif ($tab==2) { $tabname = 'Costing' ; } +elsif ($tab==3) { $tabname = 'Costing Other' ; } +elsif ($tab==4) { $tabname = 'Purchase Summary' ; } +elsif ($tab==5) { $tabname = 'Notes' ; } +elsif ($tab==6) { $tabname = 'Camera Details' ; } +elsif ($tab==7) { $tabname = 'Invoice Details' ; } +# elsif ($tab==7) { $tabname = 'Extended Warranty' ; } +# elsif ($tab==8) { $tabname = 'Rental' ; } +elsif ($tab==8) { $tabname = 'Document Uploads' ; } + +return ($tabname) ; + +} #------------------------------------------------------------------------------------ + +sub tab_hash { + +# &tabs_get_default_totals ; + +# for (1 .. 8) { + # my $tname = &tab_names($_) ; + + # our $ret_pdf_link_sec = '' ; # _sa_out+16|_cl_del+13|_sa_in+17|_des_sa+13| + + # &tab_build_qt_left('',$_,1) ; + # &tab_build_qt_right('',$_,1) ; + + # $tabcnt{$tname} = $_ ; + # $tabsec{$tname} = $ret_pdf_link_sec ; + # } + +} #------------------------------------------------------------------------------------ + +sub tab_sec_det { + +my ($sec) = @_ ; + +my ($sec_nam,$sec_cnt,$sec_col) ; + +$sec_col = '71919b' ; # '85acb8' ; +$sec_cnt = 20 ; +$sec_nam = substr($sec,1) ; +@array = split(/\_/,$sec_nam); my @sec_nam = map ucfirst, @array; +$sec_nam = join(" ", @sec_nam) ; + +if ($sec eq '_costing') { + $sec_nam = 'Camera System Costing' ; + for (1 .. 20) { $vat_tick{$_} = 1 ; } + } + +return ($sec_nam,$sec_cnt,$sec_col) ; + +} #------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/tabs_test.pm b/libs/modules/_FromProd/tabs_test.pm similarity index 100% rename from libs/modules/tabs_test.pm rename to libs/modules/_FromProd/tabs_test.pm diff --git a/libs/modules/_FromProd/today.pm b/libs/modules/_FromProd/today.pm new file mode 100644 index 0000000..44374f2 --- /dev/null +++ b/libs/modules/_FromProd/today.pm @@ -0,0 +1,42 @@ +sub today { + +our ($now_sec,$now_min,$now_hour,$now_dd,$now_mm,$now_year,$now_wday,$now_yday,$isdst)=localtime(); + +$now_sec = sprintf("%02d", $now_sec) ; +$now_min = sprintf("%02d", $now_min) ; +$now_hour = sprintf("%02d", $now_hour) ; + +$now_year += 1900; + +$now_dd = sprintf("%02s", $now_dd) ; +$now_mm = sprintf("%02s", $now_mm + 1) ; +$now_yy = sprintf("%02s", $now_year - 2000) ; + +use Date::Calc qw(:all); + +our ($sayear,$samonth,$saday,$sahour,$samin,$sasec) = Add_Delta_DHMS($now_year,$now_mm,$now_dd,$now_hour,$now_min,$now_sec,0,2,0,0); # add 2 hours for server time + +$samonth = sprintf("%02s", $samonth) ; +$saday = sprintf("%02s", $saday) ; +$sahour = sprintf("%02s", $sahour) ; +$samin = sprintf("%02s", $samin) ; +$sasec = sprintf("%02s", $sasec) ; + +$now_year = $sayear ; +$now_mm = $samonth ; +$now_dd = $saday ; +$now_sec = $sasec ; +$now_min = $samin ; +$now_hour = $sahour ; + +$now_hh_min_sec = $sahour . ':' . $samin . ':' . $sasec ; + +$now_ccyymmdd = $now_year . $now_mm . $now_dd ; +$now_ccyymmddhrmnsc = $now_year . $now_mm . $now_dd . $now_hour . $now_min . $now_sec ; +$now_dd_mm_ccyy = $now_dd . '-' . $now_mm . '-' . $now_year ; +$now_ccyy_mm_dd = $now_year . '-' . $now_mm . '-' . $now_dd ; +$nowsddsmmsccyy = $now_dd . '/' . $now_mm . '/' . $now_year ; + +} #------------------------------------------------------------------------------------------ + +1; \ No newline at end of file diff --git a/libs/modules/_FromProd/uploader.pm b/libs/modules/_FromProd/uploader.pm new file mode 100644 index 0000000..2dd2df9 --- /dev/null +++ b/libs/modules/_FromProd/uploader.pm @@ -0,0 +1,30 @@ + +sub uploader_filmfreight { + +my ($file_to_upload,$ftp_dir,$ftp_file_name,$delete_file_to_upload) = @_ ; + +use Net::FTP; + +my $host = "154.0.175.152"; # filmfreight.co.za +my $user = "filmfree"; +my $password = "h0lNH8fMzrrWUC"; + +my $ftp = Net::FTP->new($host) or die "Can't open $host : $!\n" ; +$ftp->login($user, $password) or die "Can't log $user in : $!\n" ; + +$ftp->cwd($ftp_dir) or die "Can't cwd to $ftp_dir\n"; + +$ftp->binary() or die "Can't change to binary mode"; # Unix and Windows switch $ftp->ascii(); + +$ftp->put($file_to_upload, "$ftp_dir/$ftp_file_name") or die "Can't put $file_to_upload into $ftp_dir\n" ; + +$ftp->quit; + +# if ($delete_file_to_upload eq 'y') { + # unlink ("$file_to_upload") ; + # } + +} #------------------------------------------------------------------------------------------------------------- + +1; + diff --git a/libs/modules/_FromProd/users.pm b/libs/modules/_FromProd/users.pm new file mode 100644 index 0000000..ad80925 --- /dev/null +++ b/libs/modules/_FromProd/users.pm @@ -0,0 +1,426 @@ + +sub users_list_screen { + + &db_open_ro; + $db_ignore_open_close=1; + &users_list_vars ; + $db_ignore_open_close=0 ; + &db_close_conn ; + + foreach my $id (keys %{$db{$table}}) { + + $delete_button = ($seen_operator{$id}) ? qq~~ : qq~~ ; + + my $disp_blocked = qq~~; + if ($db{$table}{$id}{block} || $db{$table}{$id}{inactive} ) { $disp_blocked = qq~~; } + + # if (!$useropts{it}{$username} && (substr($db{$table}{$id}{username},0,4) eq 'rory' || substr($db{$table}{$id}{username},0,6) eq 'handre')) { next ; } + + my $it_username_subs_4 = substr($db{$table}{$id}{username},0,4) ; # rory / jean + my $it_username_subs_6 = substr($db{$table}{$id}{username},0,6) ; # handre + + if (($useropts{it}{$it_username_subs_4} || $useropts{it}{$it_username_subs_6}) && !$useropts{it}{$username} && $useremail =~ /re8it/g) { next ; } + + next if $glod_user_level < 4 && $level{$db{$table}{$id}{user_type}} > 1 && $user_type eq 'casual' ; + + $opts{$lcpage} .= qq~~ ; + $print_tbody .= qq~ + $id + $db{$table}{$id}{username} + $db{$table}{$id}{name} + $db{$table}{$id}{email} + $disp_blocked + $db{$table}{$id}{based_in}~ ; + + $print_tbody .= qq~ + $level{$db{$table}{$id}{user_type}}~ if $user_type eq 'casual' ; + + $print_tbody .= qq~ + $db{$table}{$id}{lastupdate} + $db{$table}{$id}{lastvisitdate} + +   +  $delete_button + + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub users_list_vars { + + our %seen = () ; our %seen_operator = () ; our $delete_button = '' ; + + &db_min_ro('events','id, user_id','','','') ; + + foreach my $id (keys %{$db{'events'}}) { + next if $seen{$db{'events'}{$id}{user_id}} ; + $seen{$db{'events'}{$id}{user_id}} = 1 ; + } + + &db_min_ro('event_quotes','id,user_id,operator_ids,daily_operator_ids','','','') ; + + foreach my $id (keys %{$db{event_quotes}}) { + # next if $seen{$db{event_quotes}{$id}{user_id}} ; + $seen{$db{event_quotes}{$id}{user_id}} = 1 ; + my $op_ids = $db{event_quotes}{$id}{operator_ids} ; + next unless $op_ids ; + my @op_ids = ($op_ids =~ /;/) ? split(/;/,$op_ids) : split(/,/,$op_ids) ; + for my $op_id (@op_ids) { + next if $seen_operator{$op_id} || !$op_id ; + $seen_operator{$op_id} = 1 ; + } + foreach my $op_ids_list (split(/\|/,$db{event_quotes}{$id}{daily_operator_ids})) { + next unless $op_ids_list ; + foreach my $op_id (split(/\;/,$op_ids_list)) { + next if $seen_operator{$op_id} || !$op_id ; + $seen_operator{$op_id} = 1 if $op_id ; + } + } + } + + &db_min_ro('quotes','id,user_id','','','') ; + + foreach my $id (keys %{$db{quotes}}) { + next if $seen{$db{quotes}{$id}{user_id}} ; + $seen{$db{quotes}{$id}{user_id}} = 1 ; + } + + $level{casual_a} = 1 ; + $level{casual_b} = 2 ; + $level{casual_c} = 3 ; + + if ($user_type eq 'coding_provider') { + &db_min_ro('analytics_event_bookings','id,fixtures_saved_values','','','') ; + foreach my $id (keys %{$db{analytics_event_bookings}}) { + my @split1 = split(/\|/,$db{analytics_event_bookings}{$id}{fixtures_saved_values}) ; + foreach my $row (@split1) { + my @split2 = split(/\;/,$row) ; + $seen{$split2[-2]} = 1 ; + } + } + } + + if ($user_type eq 'analytics_client') { + &db_min_ro('analytics_event_bookings','id,client_id','','','') ; + foreach (keys %{$db{analytics_event_bookings}}) { + $seen{$db{analytics_event_bookings}{$_}{client_id}} = 1 ; + } + } + + # my $cust_sql_where = "user_type = '$user_type'" if $user_type ; + my $cust_sql_where = ($user_type) ? "user_type LIKE '$user_type%'" : "user_type NOT LIKE 'casual%' AND user_type <> 'schools_manager' AND user_type <> 'installation_partner'" ; + + &db_min_ro($table,'*',$cust_sql_where,'username','') ; + +} #------------------------------------------------------------------------------------------ + +sub users_sort_fields { + + my $fcnt = 1 ; + + $sort_field{$fcnt} = 'name' ; $fcnt++ ; + $sort_field{$fcnt} = 'email' ; $fcnt++ ; + $sort_field{$fcnt} = 'phone' ; $fcnt++ ; + + if ($user_type eq 'casual') { + $sort_field{$fcnt} = 'bank' ; $fcnt++ ; + $sort_field{$fcnt} = 'bank_acc_no' ; $fcnt++ ; + } + + $sort_field{$fcnt} = 'based_in' ; $fcnt++ ; + $sort_field{$fcnt} = 'user_type' ; $fcnt++ ; + # $sort_field{$fcnt} = 'organisation_ids' ; $fcnt++ ; + + if ($user_type eq 'schools_manager' || $user_type eq 'installation_partner' || $user_type eq 'casual') { + $sort_field{$fcnt} = 'region_ids' ; + $fcnt++ ; + } + + if ($user_type eq 'installation_partner') { + $sort_field{$fcnt} = 'customer_ids' ; + $fcnt++ ; + } + + $sort_field{$fcnt} = 'block' ; $fcnt++ ; + $sort_field{$fcnt} = 'inactive' ; $fcnt++ ; + + # if ($dialog) { + # $sort_field{$fcnt} = 'sel_field' ; $fcnt++ ; + # } + + $sort_field{$fcnt} = 'username' ; $fcnt++ ; + $sort_field{$fcnt} = 'password' if $iaction eq 'add' ; + +} #------------------------------------------------------------------------------- + +sub users_add_db_fields { + + $ignore{lastvisitdate} = 1 ; + $ignore{iaction} = 1 ; + $ignore{block} = 1 ; + $ignore{inactive} = 1 ; + # $ignore{id} = 1 ; + $hidden{lastupdate} = 2 ; + $required{email} = 1 ; + $required{username} = 1 ; + $required{name} = 1 ; + $required{password} = 1 ; + + &sort_fields ; + +} #------------------------------------------------------------------------------------------ + +sub users_edit_db_fields { + + $ignore{lastvisitdate} = 1 ; + $ignore{password} = 1 ; + $ignore{iaction} = 1 ; + $hidden{id} = 1 ; # 1 = bypass for db update + $hidden{username} = 1 ; # 1 = bypass for db update + $hidden{lastupdate} = 2 ; # 2 = update db + # $readonly{username} = 'READONLY' ; + $checkbox{block} = 1 ; + $checkbox{inactive} = 1 ; + # $required{username} = 1 ; + $required{email} = 1 ; + + &sort_fields ; + +} #------------------------------------------------------------------------------------------ + +sub users_add_screen { + + # called from common_add_screen + + $selected{user_type}{$user_type} = "SELECTED" if $user_type ; + + &users_select_opts ; + + our $savjqy = 1 if $user_type ; # incorporate jquery into the save event to accommodate the multiple chosen options + +} #------------------------------------------------------------------------------------------ + +sub users_edit_screen { + + our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + + $selected{based_in}{$db{$table}{$i{id}}{based_in}} = "SELECTED" ; + $selected{user_type}{$db{$table}{$i{id}}{user_type}} = "SELECTED" ; + + $extra_form_fields .= &common_min_form_input('new_password','','password') ; + + &users_select_opts ; + + our $savjqy = 1 if $user_type ; # incorporate jquery into the save event to accommodate the multiple chosen options + +} #------------------------------------------------------------------------------------------ + +sub users_thead { + + $print_thead = qq~IDUSERNAMENAMEEMAILACTIVEBASE~; + + $print_thead .= qq~LEVEL~ if $user_type eq 'casual' ; + + $print_thead .= qq~LASTUPDATELASTVISITDATE ~ ; + +} #------------------------------------------------------------------------------- + +sub users_process_multi_select { + + # local @organisationids = split(/\,/,$i{organisationids}) ; + # my $organisationids = join(",",@organisationids) ; + # $organisationids =~ s/\s//g; # remove white space + # $ignore{organisationids} = 1 ; + # $i{organisation_ids} = $organisationids ; + + $i{organisation_ids} = '0' ; + + local @regionids = split(/\,/,$i{regionids}) ; + my $regionids = join(",",@regionids) ; + $regionids =~ s/\s//g; # remove white space + $ignore{regionids} = 1 ; + $i{region_ids} = $regionids || '0' ; + + if ($user_type eq 'installation_partner' || $user_type eq 'coding_provider' || $user_type eq 'analytics_client') { + local @customerids = split(/\,/,$i{customerids}) ; + my $customerids = join(",",@customerids) ; + $customerids =~ s/\s//g; # remove white space + $ignore{customerids} = 1 ; + $i{customer_ids} = $customerids ; + } else { + $i{customer_ids} = '0' ; + } + +} #------------------------------------------------------------------------------------------ + +sub users_select_opts { + + # $multiple{organisation_ids} = 1; + # my @organisation_ids = split(/\,/,$db{$table}{$i{id}}{organisation_ids}); + # foreach (@organisation_ids) { $selected_multi{$_} = 'SELECTED' ; } + # $preferred_title{organisation_ids} = "Venue" ; + # &common_min_select_opts('organisation_ids','organisations','name',$db{$table}{$i{id}}{organisation_ids},'') ; + # $extra_form_fields .= qq~~; + + # $trigger_jquery_raw .= qq~ + # \$("#savebutt").click(function() { + # let st_val = \$("#selectOrganisation_ids").chosen().val() ; + # \$('#organisation-ids').val(st_val); + # \$('#users-form').submit(); + # });~; + + if ($user_type eq 'installation_partner' || $user_type eq 'coding_provider' || $user_type eq 'analytics_client') { + $multiple{customer_ids} = 1; + my @customer_ids = split(/\,/,$db{$table}{$i{id}}{customer_ids}); + foreach (@customer_ids) { $selected_multi{$_} = 'SELECTED' ; } + $preferred_title{customer_ids} = "Customers" ; + &common_min_select_opts('customer_ids','customers','name','','') ; + $extra_form_fields .= qq~~; + $add_to_trigger_jquery_raw = qq~ + let cust_val = \$("#selectCustomer_ids").chosen().val() ; + \$('#customer-ids').val(cust_val); + ~; + } + + if ($user_type eq 'schools_manager' || $user_type eq 'installation_partner' || $user_type eq 'casual' || $user_type eq 'coding_provider' || $user_type eq 'analytics_client') { + $multiple{region_ids} = 1; + my @region_ids = split(/\,/,$db{$table}{$i{id}}{region_ids}); + foreach (@region_ids) { $selected_multi{$_} = 'SELECTED' ; } + $preferred_title{region_ids} = "Regions" ; + &common_min_select_opts('region_ids','regions','name','','') ; + $extra_form_fields .= qq~~; + + $trigger_jquery_raw .= qq~ + \$("#savebutt").click(function() { + let st_val = \$("#selectRegion_ids").chosen().val() ; + \$('#region-ids').val(st_val); + $add_to_trigger_jquery_raw + \$('#users-form').submit(); + });~; + } + + # &common_min_select_opts('organisation_ids','organisations','name',$db{$table}{$i{id}}{organisation_ids},1,'',''); + + &common_min_select_opts('based_in','regions','name',$db{$table}{$i{id}}{based_in},1,'','','code') ; + + # $required{based_in} = 1 ; + # $select{based_in} = 1 ; + # # $opts{based_in} = qq~~ ; + # $opts{based_in} = qq~~ ; + + $required{user_type} = 1 ; + $select{user_type} = 1 ; + if ($user_type eq 'casual') { + if ($glod_user_level > 2) { + $opts{user_type} = qq~~; + } + if ($glod_user_level > 3) { + $opts{user_type} .= qq~~; + } + $opts{user_type} .= qq~~; + } elsif ($user_type) { + my $user_type_name = join(" ", map { ucfirst lc } split /_/, $user_type); + $opts{user_type} = qq~ + + ~ ; + } else { + $opts{user_type} = qq~ + + + + + + + + + + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub users_insert { + + &add_db_fields ; + + my $crypted_password = apache_md5_crypt($i{password},$useropts{salt}) ; + $i{password} = $crypted_password ; + $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{email} = lc $i{email} ; + + $i{id} = &db_min_get_max($table,'id') ; + + &process_multi_select if $user_type ; + + &db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub users_update { + + unless ($i{id}) { $error = qq(NO ID) ; return ; } + + &edit_db_fields ; + + unless ($i{block}) { $i{block} = '0' ; } + unless ($i{inactive}) { $i{inactive} = '0' ; } + + if ($i{new_password}) { + my $crypted_password = apache_md5_crypt($i{new_password},$useropts{salt}) ; + $i{password} = $crypted_password ; + $ignore{password} = 0 ; + $hidden{password} = 2 ; + } + + $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + + &process_multi_select if $user_type ; + + &db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub users_validate { + + my $user_exists = '' ; my $email_exists = '' ; + + $i{username} = lc $i{username} ; + $i{username} =~ s/ //gi ; + + $i{email} = lc $i{email} ; + $i{email} =~ s/ //gi ; + + &db_min_ro($table,'*',"username='$i{username}' OR email='$i{email}'",'username','') ; + + foreach my $id (keys %{$db{$table}}) { + if ($db{$table}{$id}{username} eq $i{username}) { + $user_exists = 1 ; + last; + } + + if ($i{email} && $db{$table}{$id}{email} eq $i{email}) { + $email_exists = 1 ; + last; + } + } + + if ($user_exists) { + $alert = &common_min_alert('warning',"USERNAME ALREADY EXISTS!",'ok') ; + %col_name = (); + &common_min_add_screen; + &common_min_screen1 unless $dialog ; + &screen1 if $dialog ; + } + + if ($email_exists) { + $alert = &common_min_alert('warning',"EMAIL ALREADY EXISTS!",'ok') ; + %col_name = (); + &common_min_add_screen; + &common_min_screen1 unless $dialog ; + &screen1 if $dialog ; + } + +} #------------------------------------------------------------------------------------------ + +1 ; \ No newline at end of file diff --git a/libs/modules/_FromProd/v1.0/analytics_event_booking_tabs.pm b/libs/modules/_FromProd/v1.0/analytics_event_booking_tabs.pm new file mode 100644 index 0000000..05ca4b2 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/analytics_event_booking_tabs.pm @@ -0,0 +1,2029 @@ +sub analytics_event_bookings_tabs_build_qt_left { + + my ($id,$tab,$ret) = @_ ; + + if ($tab == 1) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_customer_details' ; + + my ($sec_name,$sec_cnt,$sec_col) = &analytics_event_bookings_tabs_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + $lcol = 2 ; $fcol = 1 ; $add_form_fields = '' ; + + # $add_form_fields .= qq~
    ~ if $is_schools_manager ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + + my $checked = ($db{$table}{$id}{event_completed}) ? 'CHECKED' : '' ; + $preferred_title{event_completed} = "Event Completed" ; + $add_form_fields .= &common_min_form_checkbox('event_completed',$db{$table}{$id}{event_completed},$checked) ; + + # my $checked = 'CHECKED' if $db{$table}{$id}{event_accepted} ; + my $checked = ($db{$table}{$id}{event_accepted}) ? 'CHECKED' : '' ; + $preferred_title{event_accepted} = "Event Accepted" ; + $add_form_fields .= &common_min_form_checkbox('event_accepted',$db{$table}{$id}{event_accepted},$checked) ; + + my $checked = ($db{$table}{$id}{event_rejected}) ? 'CHECKED' : '' ; + $preferred_title{event_rejected} = "Event Rejected" ; + $add_form_fields .= &common_min_form_checkbox('event_rejected',$db{$table}{$id}{event_rejected},$checked) ; + + # my $checked = 'CHECKED' if $db{$table}{$id}{event_pending} or $iaction eq 'add' ; + my $checked = ($db{$table}{$id}{event_pending} || $iaction eq 'add') ? 'CHECKED' : '' ; + $preferred_title{event_pending} = "Event Pending" ; + $add_form_fields .= &common_min_form_checkbox('event_pending',$db{$table}{$id}{event_pending},$checked) ; + + # my $checked = 'CHECKED' if $db{$table}{$id}{event_cancelled} ; + my $checked = ($db{$table}{$id}{event_cancelled}) ? 'CHECKED' : '' ; + $preferred_title{event_cancelled} = "Event Cancelled" ; + $add_form_fields .= &common_min_form_checkbox('event_cancelled',$db{$table}{$id}{event_cancelled},$checked) ; + + # $add_form_fields .= qq~
    ~ if $is_schools_manager ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + + # $add_form_fields .= qq~
    ~ if $is_schools_manager ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + + $fcol = 4 ; + $add_form_fields .= &common_min_form_input('contact_name',$db{$table}{$id}{contact_name},'') ; + $add_form_fields .= &common_min_form_input('address',$db{$table}{$id}{address},'') ; + $add_form_fields .= &common_min_form_input('email',$db{$table}{$id}{email},'') ; + $add_form_fields .= &common_min_form_input('tel',$db{$table}{$id}{tel},'') ; + # $fcol = 5 ; + + $add_form_fields .= qq~
     
    ~ ; + + &analytics_event_bookings_tabs_content_box($sec_name,$sec_col); + + $trigger_jquery_raw .= qq~ + + if (!\$("#checkboxEvent_accepted").is(":checked") && !\$("#checkboxEvent_rejected").is(":checked") && !\$("#checkboxEvent_pending").is(":checked") && !\$("#checkboxEvent_cancelled").is(":checked") && !\$("#checkboxEvent_completed").is(":checked")) { + \$("#checkboxEvent_pending").prop("checked","true") ; + } + + \$("#checkboxEvent_completed,#checkboxEvent_accepted,#checkboxEvent_rejected,#checkboxEvent_pending,#checkboxEvent_cancelled").click( function () { + + if (this.id != 'checkboxEvent_completed' && \$("#checkboxEvent_completed").is(":checked")) { + \$("#checkboxEvent_completed").prop("checked",false) ; + } + + if (this.id != 'checkboxEvent_accepted' && \$("#checkboxEvent_accepted").is(":checked")) { + \$("#checkboxEvent_accepted").prop("checked",false) ; + } + + if (this.id != 'checkboxEvent_rejected' && \$("#checkboxEvent_rejected").is(":checked")) { + \$("#checkboxEvent_rejected").prop("checked",false) ; + } + + if (this.id != 'checkboxEvent_pending' && \$("#checkboxEvent_pending").is(":checked")) { + \$("#checkboxEvent_pending").prop("checked",false) ; + } + + if (this.id != 'checkboxEvent_cancelled' && \$("#checkboxEvent_cancelled").is(":checked")) { + \$("#checkboxEvent_cancelled").prop("checked",false) ; + } + + if (this.id == 'checkboxEvent_completed' && !\$("#checkboxEvent_accepted").is(":checked")) { + \$("#checkboxEvent_accepted").prop("checked",true) ; + } + + if (!\$("#checkboxEvent_accepted").is(":checked") && !\$("#checkboxEvent_rejected").is(":checked") && !\$("#checkboxEvent_pending").is(":checked") && !\$("#checkboxEvent_cancelled").is(":checked") && !\$("#checkboxEvent_completed").is(":checked")) { + \$("#checkboxEvent_pending").prop("checked","true") ; + } + + }); + + ~ ; + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + + if ($tab == 2) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + return if $ret ; + + my $sec = '_event_details' ; + + my ($sec_name,$sec_cnt,$sec_col) = &analytics_event_bookings_tabs_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + $preferred_title{sport_type_ids} = "Sport Type(s)" ; + $preferred_title{start_date_time} = "Event Date/Time From" ; + $preferred_title{end_date_time} = "Event Date/Time To" ; + $add_form_fields = "" ; + + + foreach (keys %service_types) { + $opts{service_type_id} .= qq~~ ; + } + + foreach (split(/\,/,$db{$table}{$id}{sport_type_ids})) { + $opts{sport_type_ids} =~ s/value="$_"/value="$_" SELECTED/g ; + } + + $db{$table}{$id}{service_type_id} = 3 unless $db{$table}{$id}{service_type_id}; + + $opts{service_type_id} =~ s/value="$db{$table}{$id}{service_type_id}"/value="$db{$table}{$id}{service_type_id}" SELECTED/g ; + + for (1 .. 100) { + $opts{total_fixtures} .= qq~~ ; + } + + $db{$table}{$id}{total_fixtures} = 1 unless $db{$table}{$id}{total_fixtures} ; + + $opts{total_fixtures} =~ s/value="$db{$table}{$id}{total_fixtures}"/value="$db{$table}{$id}{total_fixtures}" SELECTED/g ; + + $db{$table}{$id}{start_date_time} = "$now_year-$now_mm-$now_dd 08:00:00" unless $db{$table}{$id}{start_date_time} ; + $db{$table}{$id}{end_date_time} = "$now_year-$now_mm-$now_dd 17:00:00" unless $db{$table}{$id}{end_date_time} ; + + $allow_deselect{client_id} = 1 ; + # $allow_deselect{total_fixtures} = 1 ; + # $allow_deselect{service_type_id} = 1 ; + + $lcol = 2 ; $fcol = 4 ; + + # if ($usertype eq 'analytics_client') { + # &db_min_ro('users','id,name',"id='$userid'") ; + # $opts{client_id} = qq~~ ; + # } else { + # &common_min_select_opts('client_id','customers','name','','','',"analytics='1'") ; + # # $db{$table}{$id}{client_id} = $userid if !$db{$table}{$id}{client_id} && $usertype eq 'analytics_client' ; + # $opts{client_id} =~ s/value="$db{$table}{$id}{client_id}"/value="$db{$table}{$id}{client_id}" SELECTED/g if $db{$table}{$id}{client_id} ; + # } + + $dlg{client_id} .= qq~
    ~ ; + + $dlg{sport_type_ids} .= qq~
    ~ ; + + # $onload = qq~onload=dispCustomer();~ if $iaction eq 'add' ; # SuperSport Schools (Pty) Ltd + + if ($sql_limit_user_regions) { + $sql_limit_user_regions =~ s/id/region_id/g ; + $sql_limit_user_regions .= "region_id='0' OR ($sql_limit_user_regions)" ; + } + + &analytics_event_bookings_tabs_customer_select_opts('customers','name',$sql_limit_user_regions,'client_id'); + + # $allow_deselect{client_id} = 1 ; + + # $required{client_id} = 1 ; + + $add_form_fields .= &common_min_form_select('client_id',$db{$table}{$id}{client_id}) ; + $add_form_fields .= &common_min_form_input('event_name',$db{$table}{$id}{event_name}) ; + $add_form_fields .= &common_min_form_datetimepicker('start_date_time',$db{$table}{$id}{start_date_time}) ; + $add_form_fields .= &common_min_form_datetimepicker('end_date_time',$db{$table}{$id}{end_date_time}) ; + $add_form_fields .= &common_min_form_select('sport_type_ids',$db{$table}{$id}{sport_type_ids}) ; + $add_form_fields .= &common_min_form_select('total_fixtures',$db{$table}{$id}{total_fixtures}) ; + $add_form_fields .= &common_min_form_select('service_type_id',$db{$table}{$id}{service_type_id}) ; + + $db{$table}{$id}{tournament_festival_id} = 1 if !$db{$table}{$id}{derby_day_weekly_fixture_id} && !$db{$table}{$id}{tournament_festival_id} ; + + $add_form_fields .= &common_min_form_checkbox('derby_day_weekly_fixture_id',$db{$table}{$id}{derby_day_weekly_fixture_id}) ; + $add_form_fields .= &common_min_form_checkbox('tournament_festival_id',$db{$table}{$id}{tournament_festival_id}) ; + + $trigger_jquery .= qq~ + // \$('.iPhoneCheckContainer').css("width","76px") ; + // \$('.iPhoneCheckHandle').css("width","32px") ; + // \$('.iPhoneCheckHandle').css("left","0px") ; + // \$('.iPhoneCheckLabelOff').css("width","71px") ; + // \$('.iPhoneCheckLabelOff').css("top","-5px") ; + // \$('.iPhoneCheckLabelOn').css("top","-5px") ; + // \$('.iPhoneCheckLabelOn').css("width","45px") ; + // \$('.iPhoneCheckLabelOff span').css("font-size","14px"); + // \$('.iPhoneCheckLabelOn span').css("font-size","14px"); + ~ ; + + $trigger_jquery_raw .= qq~\$("#checkboxTournament_festival_id").prop("checked",true) ;~ if $db{$table}{$id}{tournament_festival_id} ; + $trigger_jquery_raw .= qq~\$("#checkboxDerby_day_weekly_fixture_id").prop("checked",true) ;~ if $db{$table}{$id}{derby_day_weekly_fixture_id} ; + + &common_shared_build_select_primary_jquery ; + + $trigger_jquery_raw .= qq~ + + const getClientId = () => { + const val = \$clientSelect.val(); + return val ? val.toString().split(":")[0] : null; + }; + + const fillTeamSelect = (\$el, teams) => { + clearSelect(\$el); + teams.forEach(({ id, name }) => { + \$el.append(``); + }); + updateChosen(\$el); + }; + + \$("#checkboxDerby_day_weekly_fixture_id").on("change",function () { + if (\$(this).is(":checked")) { + \$("#checkboxTournament_festival_id").prop("checked",false) ; + \$("#add_existing_home_team").css("display","none") ; + build_teams_from_client() ; + } else { + \$("#checkboxTournament_festival_id").prop("checked",true) ; + \$("#add_existing_home_team").css("display","") ; + } + }) ; + \$("#checkboxTournament_festival_id").change( function () { + if (\$(this).is(":checked")) { + \$("#add_existing_home_team").css("display","") ; + \$("#checkboxDerby_day_weekly_fixture_id").prop("checked",false) ; + } else { + \$("#add_existing_home_team").css("display","none") ; + \$("#checkboxDerby_day_weekly_fixture_id").prop("checked",true) ; + build_teams_from_client() ; + } + }) ; + + + async function build_teams_from_client () { + + const clientId = getClientId() ; + + let teams_ = "[]" ; + + if (clientId) { + let url_teams2 = `$useropts{scripts}/get/get_sss_teams_from_client.pl?client_id=\${clientId}` ; + teams_ = await fetchJSON(url_teams2); + } + + \$("#fixtures_table select[id^='selectHome_team_']").each( function () { + let selected_val = (\$(this).val()) ? \$(this).val() : "" ; + clearSelect(\$(this)); + fillTeamSelect(\$(this),teams_) ; + if (teams_.length === 1) { + \$(this).val(teams_[0].id).trigger("chosen:updated") ; + } else { + \$(this).val(selected_val).trigger("chosen:updated") ; + } + + }) ; + + } + + ~ ; + + $add_form_fields .= &common_min_form_textarea('additional_notes',$db{$table}{$id}{additional_notes}) ; + + $trigger_jquery_raw .= qq~ + // let end_time = new Date("$db{$table}{$id}{end_date_time}") ; + // let start_time = new Date("$db{$table}{$id}{start_date_time}") ; + // \$("#datetimepickerStart_date_time").datetimepicker("setEndDate",end_time) ; + // \$("#datetimepickerEnd_date_time").datetimepicker("setStartDate",start_time) ; + + // let picker = \$("#datetimepickerStart_date_time").data("datetimepicker").endDate.toISOString().slice(0,19).replace('T',' ') ; + // console.log("endDate : "+picker); + + ~ ; + + &analytics_event_bookings_tabs_content_box($sec_name,$sec_col); + + # custom_selected_region" + # custom_selected_country + + $trigger_jquery_raw .= qq~ + + let map_client_to_country = {} ; + let map_region_to_country = {} ; + let map_client_to_region = {} ; + + const \$clientSelect = \$("#selectClient_id") ; + const \$countrySelect = \$("#selectCountry_id") ; + const \$regionSelect = \$("#selectRegion_id") ; + const \$fixturesTable = \$("#fixtures_table"); + + let regionId = \$regionSelect.val() ; + let countryId = \$("#selectCountry_id").val() ; + + // const populateSelect = (\$el, dataList, labelFn) => { + // let lastId = null ; + // for (const data of dataList) { + // \$el.append(``); + // lastId = data.id; + // } + // updateChosen(\$el) ; + // return { count: dataList.length, lastId } ; + // } ; + // const populateSelect = (\$el, list, getLabel) => { + // list.forEach(data => { \$el.append(``); }) ; + // updateChosen(\$el); + // return list.length; + // }; + + // const fillTeamSelect = (\$el, teams) => { + // \$el.empty().append(""); + // teams.forEach(team => { + // \$el.append(``); + // }); + // \$el.val("").trigger("chosen:updated"); + // }; + + + + const getInputValue = name => \$(`input[name='\${name}']`).val(); + const setInputValue = (name, val = "") => \$(`input[name='\${name}']`).val(val); + + + let prev_country_id = \$countrySelect.val() ; + let prev_region_id = \$regionSelect.val() ; + + \$clientSelect.on("change", async function () { + + dispCustomer() ; + + const hasCustomRegion = !!getInputValue('custom_selected_region') ; + const clientId = getClientId() ; + const hasCustomCountry = !!getInputValue('custom_selected_country') ; + + if (clientId && !hasCustomRegion) { + let url1 = `$useropts{scripts}/get/get_region_country_from_client.pl?client_id=\${clientId}` ; + if (!hasCustomRegion || !hasCustomCountry) { + const data = await fetchJSON(url1) ; + data.forEach(({region_id,country_id}) => { + if (region_id == '0') region_id = '' ; + if (country_id == '0') country_id = '' ; + if (\$regionSelect.val() == '13' && (!region_id || hasCustomCountry)) region_id = '13' ; + if (!hasCustomRegion && region_id != \$regionSelect.val()) \$regionSelect.val(region_id).trigger("chosen:updated") ; + if (!hasCustomCountry && country_id != \$countrySelect.val()) \$countrySelect.val(country_id).trigger("chosen:updated") ; + }) ; + } + + } else if (!clientId) { + + if (!hasCustomCountry) \$countrySelect.val("").trigger("chosen:updated") ; + if (!hasCustomRegion && \$regionSelect.val() != '13') \$regionSelect.val("").trigger("chosen:updated") ; + } + + let cnt = 0 ; let teams = "[]" ; + + if (clientId) { + let url_teams2 = `$useropts{scripts}/get/get_sss_teams_from_client.pl?client_id=\${clientId}` ; + teams = await fetchJSON(url_teams2); + } + + if (teams.length > 0 && teams != "[]") { + \$("input[name='home_teams_built_on_regions']").val("") ; + \$("#fixtures_table select[id^='selectHome_team_']").each( function () { + let selected_val = (\$(this).val()) ? \$(this).val() : "" ; + const \$teamSelect = \$(this) ; + clearSelect(\$teamSelect); + fillTeamSelect(\$teamSelect,teams) ; + if (teams.length === 1) { + \$teamSelect.val(teams[0].id).trigger("chosen:updated") ; + } else { + \$teamSelect.val(selected_val).trigger("chosen:updated") ; + } + + }) ; + } else if (\$regionSelect.val() && \$regionSelect.val() != prev_region_id) { + \$("input[name='home_teams_built_on_regions']").val("1") ; + await build_teams_from_region(\$regionSelect.val()) ; + } else if (\$countrySelect.val() && \$countrySelect.val() != prev_country_id) { + \$("input[name='home_teams_built_on_regions']").val("1") ; + await build_teams_from_region("",\$countrySelect.val()) ; + } else if (!\$regionSelect.val() && !\$countrySelect.val() && (\$("input[name='home_teams_built_on_regions']").val() || (!\$("input[name='home_teams_built_on_regions']").val() && !clientId))) { + \$("#fixtures_table select[id^='selectHome_team_']").each(function () { + clearSelect(\$(this)) ; + }) ; + } else if (!\$("input[name='home_teams_built_on_regions']").val() && \$regionSelect.val()) { + \$("input[name='home_teams_built_on_regions']").val("1") ; + await build_teams_from_region(\$regionSelect.val()) ; + } else if (!\$("input[name='home_teams_built_on_regions']").val() && \$countrySelect.val()) { + \$("input[name='home_teams_built_on_regions']").val("1") ; + await build_teams_from_region("",\$countrySelect.val()) ; + } + + prev_country_id = \$countrySelect.val() ; + prev_region_id = \$regionSelect.val() ; + + // else { + // \$("input[name='home_teams_built_on_regions']").val("1") ; + // const away_team_options = \$("#selectAway_team_fixtures_1").children().clone(); + // \$("#fixtures_table select[id^='selectHome_team_']").each( function () { + // let \$teamSelect = \$(this) ; + // clearSelect(\$teamSelect); + // \$teamSelect.append(away_team_options).trigger("chosen:updated") ; + // }) ; + // } + + hide_or_display_buttom_to_add_hometeam_from_existing() ; + + }) ; + + \$countrySelect.on("change", async function () { + + \$("input[name='custom_selected_country']").val("1") ; + await update_region_drop_down(\$countrySelect.val()) ; + if (\$regionSelect.val() && prev_region_id != \$regionSelect.val()) { + await build_teams_from_region(\$regionSelect.val()) ; + } else if (!\$regionSelect.val() && \$countrySelect.val() && prev_country_id != \$countrySelect.val()) { + await build_teams_from_region("",\$countrySelect.val()) ; + } + prev_country_id = \$countrySelect.val() ; + prev_region_id = \$regionSelect.val() ; + + }) ; + + \$regionSelect.on("change", async function () { + + \$("input[name='custom_selected_country']").val("") ; + \$("input[name='custom_selected_region']").val(\$(this).val()) ; + // await build_teams_from_region(\$regionSelect.val()) ; + await select_country_from_region(\$regionSelect.val(),1) ; + \$("input[name='custom_selected_country']").val("1") ; + prev_country_id = \$countrySelect.val() ; + prev_region_id = \$regionSelect.val() ; + // hide_or_display_buttom_to_add_hometeam_from_existing() ; + + }) ; + + function hide_or_display_buttom_to_add_hometeam_from_existing () { + + // // // if ((\$clientSelect.val()) && \$("#selectHome_team_fixtures_1 option").length > 0) { + // // // \$("#add_existing_home_team").css("display","none") ; + // // // } else { + // // // \$("#add_existing_home_team").css("display","") ; + // // // } + } + + async function update_region_drop_down (countryId) { + + if (typeof countryId === 'undefined') { + countryId = "" ; + } + + let region_id = \$regionSelect.val() ; + + clearSelect(\$regionSelect) ; + + const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}`; + + console.log("regionUrl : "+regionUrl) ; + + const regions = await fetchJSON(regionUrl); + + for (const data of regions) { + map_region_to_country[data.id] = countryId; + } + + const regionCount = populateSelect(\$regionSelect, regions, r => r.code ? `\${r.name} [\${r.code}]` : r.name ) ; + + let selectedRegionId = 0 ; + + if (regionCount["count"] === 1) { + selectedRegionId = regions[0].id ; + \$regionSelect.val(regions[0].id) ; + } else if (regionCount["count"] === 0 && \$countrySelect.val()) { + selectedRegionId = 13 ; + \$regionSelect.append(``) ; + } + if (selectedRegionId == 0) \$regionSelect.val(region_id) ; + updateChosen(\$regionSelect) ; + } + + async function select_country_from_region (regionId,update_country=0) { + + if (map_region_to_country[regionId]) { + \$countrySelect.val(map_region_to_country[regionId]).trigger("chosen:updated") ; + } else if (!\$("input[name='custom_selected_country']").val() || update_country) { + // let url_teams1 = "$useropts{scripts}/get/get_country_from_region.pl?region_id="+regionId ; + const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=®ion_id=\${regionId}`; + const regionMeta = await fetchJSON(lookupUrl); + const { country_id } = regionMeta[0] ?? {}; + + if (country_id) { + map_region_to_country[regionId] = country_id; + \$countrySelect.val(country_id).trigger("chosen:updated"); + } + } + } + + async function build_teams_from_region (regionId="",countryId="") { + + let url_teams1 = `$useropts{scripts}/get/get_sss_teams_from_region.pl?region_id=\${regionId}&country_id=\${countryId}` ; + // let tabs = (\$("input[name='home_teams_built_on_regions']").val() == "1") ? "#fixtures_table select[id^='selectHome_team_'],#fixtures_table select[id^='selectAway_team_']" : "#fixtures_table select[id^='selectAway_team_']" ; + + console.log("build_teams_from_region URL : "+url_teams1) ; + + let tabs = (\$("input[name='home_teams_built_on_regions']").val() == "1") ? "#fixtures_table select[id^='selectHome_team_']" : "" ; + const teams = await fetchJSON(url_teams1); + if (tabs != "") { + \$(tabs).each(function () { + const \$teamSelect = \$(this); + clearSelect(\$teamSelect); + fillTeamSelect(\$teamSelect, teams); + }); + } + + } + + ~ ; + + } + + if ($tab == 3) { + + return if $ret; + + my $sec = '_fixtures' ; + + my ($sec_name,$sec_cnt,$sec_col) = &analytics_event_bookings_tabs_sec_det($sec) ; + + $sec = 'fixtures' ; + + $add_form_fields = '' ; + + $lcol = 1; + $fcol = 2; + + our @headers = @fixture_headers ; + our %custom_header = () ; + + push @headers, "Stream Forwarding" ; + push @headers, "Stream Key" ; + push @headers, "Stream URL" ; + + &report_xlsx_export_header("Analytics-Fixtures-$i{id}",'analytics_fixtures') ; + + our $csvpath = "$htmlpath/csv/analytics_fixtures" ; + our $csvname = "Analytics-Fixtures-$i{id}-" . $now_ccyymmdd . $now_hour . $now_min . $now_sec . '.csv' ; ; + + &csv_clear_folder($csvpath,"Analytics-Fixtures-$i{id}") ; + &csv_create_new_file($csvpath,$csvname) ; + + &analytics_event_bookings_tabs_build_fixtures_table_headers(3) ; + &analytics_event_bookings_tabs_build_fixtures_table($id,"$sec") ; + + my $add_box_icon = $box_icon ; + $box_icon = "" ; + + $worksheet{$ws}->set_column(0,0,20) ; + $worksheet{$ws}->set_column(1,3,10) ; + $worksheet{$ws}->set_column(4,4,30) ; + $worksheet{$ws}->set_column(5,5,10) ; + $worksheet{$ws}->set_column(6,6,30) ; + $worksheet{$ws}->set_column(7,8,10) ; + + $box_icon .= qq~ +
    + + + +
    + ~ ; + + &csv_close_file("$csvpath/$csvname") ; + + &report_xlsx_export_footer('L',15,'analytics_fixtures') ; + + if (-f "$csvpath/$csvname") { + # $box_icon .= qq(
    ) ; + } + + $add_form_fields .= qq~
     
    ~ ; + + &analytics_event_bookings_tabs_content_box($sec_name,$sec_col,$box_icon); + + $box_icon = $add_box_icon ; + + $trigger_jquery_raw .= qq~ + function importDoc(t,b) { + dlgMdl("$useropts{'scripts'}/dialog/import_analytics_fixtures.pl?"+t+"&"+b,"Import EXCEL",'height:210px','min-dialog') ; + } + ~; + + $trigger_jquery_raw .= qq~ + \$('[data-toggle="tooltip"]').tooltip({ container: 'body' }); + // \$(' + + + + +
    + + $useropts{short} +

    + $email_msg + $br + + $thead + + $table_msg + +
    +
    +

    $display_notif_msg + Best regards, +
    +
    + The $useropts{short} Team. +

    +
    + + +END_OF_BODY + + return ($mail_body) ; + +} #---------------------------------------------------------------------------------------- + +sub common_email_with_attachments { + + my ($from,$to,$cc,$bcc,$subj,$text_msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication) = @_ ; + + use MIME::Lite; + use Net::SMTP_auth; + + return if $env eq 'DEV' ; + + # # SMTP configuration + # my $smtp_host = $afrihost_smtp ; + # my $smtp_port = $afrihost_port ; + # my $smtp_user = $afrihost_from ; + # my $smtp_pass = $afrihost_psw ; + $from = $afrihost_from ; + + # HTML body part + my $mail_body = &common_get_mail_body($text_msg,$table_msg) ; + + my $fullattachpath = "$attachpath/$attachname"; + die "Attachment file not found: $fullattachpath" unless -e $fullattachpath; + + # === build the MulitPart MIME Message === + + # Create the Message + my $msg = MIME::Lite::->new( + 'From' => "$useropts{short} Events <$from>", + 'Reply-To' => $email_reply_to, + 'To' => $to, + 'Cc' => $cc, + 'Bcc' => $bcc, + 'Subject' => $subj, + 'Type' => 'multipart/mixed', + ); + + # Create the HTML part + my $html_part = MIME::Lite::->new( + 'Type' => 'multipart/related', + ); + + $html_part->attach( + 'Type' => 'text/html', + 'Data' => $mail_body, + ) ; + + # === Attachments === + + my $attachtype = ($attachapplication) ? "application/$attachapplication" : 'AUTO' ; # application/pdf or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet + my $attach_part = MIME::Lite::->new( + 'Type' => 'multipart/mixed', + ); + $attach_part->attach ( + Type => "$attachtype", + Encoding => 'base64', + Path => "$fullattachpath", + Filename => $attachname, + Disposition => 'attachement' + ) ; + + $msg->attach($attach_part); + $msg->attach($html_part); + + my $email = $msg->as_string(); + + my $smtp_msg = Net::SMTP_auth->new('localhost') or die "Can't connect"; + + # my $smtp_msg = Net::SMTP_auth->new($smtp_host, Port=>587) or die "Can't connect"; + # $smtp_msg->auth('PLAIN', $smtp_user, $smtp_pass) or die "Can't authenticate:" . $smtp_msg->message(); + + $smtp_msg->mail($from) or die "Error:" . $smtp_msg->message(); + + $smtp_msg->to($_) for split(/\s*,\s*/, join(',', $to, $cc, $bcc)); + + # $smtp_msg->recipient($to) or die "Error:".$smtp_msg->message(); + $smtp_msg->data() or die "Error:".$smtp_msg->message(); + $smtp_msg->datasend($email) or die "Error:".$smtp_msg->message(); + $smtp_msg->dataend() or die "Error:".$smtp_msg->message(); + $smtp_msg->quit or die "Error:".$smtp_msg->message(); + +} #---------------------------------------------------------------------------------------- + +# sub common_send_mail { + + # my ($to,$cc,$bcc,$html,$thead,$msg,$subj) = @_ ; + + # return unless $msg ; + # return unless $subj ; + + # # my $res = &common_mailsend_sendgrid('html',$to,$subject,$emailmsg,'','','Film Freight','pod@ffwaybill.co.za'); + + # # return if $res eq 'success' ; # carry on if mailsend_sendgrid failed + + # use Mail::Sendmail; + + # my $main_email = 'tickets@interactivetvafrica.com' ; + + # $to = $main_email unless $to ; + + # my %mail = () ; + + # %mail = ( + # smtp => 'localhost', + # From => $main_email, + # To => $to, + # Cc => $cc, + # Bcc => $bcc, + # Subject => $subj + # ); + + # $mail{smtp} = "smtp.interactivetvafrica.com"; + # # $mail{Debug} = 6; + # $mail{port} = 587; + # # $mail{port} = 465; + # $mail{Auth} = {user => $main_email, pass => $send_mail_psw, method => "LOGIN", required => 1}; + + # $mail{body} = < + # + # + # + # $useropts{short} + # + # + # + #
    + # $useropts{short} + #

    + # + # $thead + # + # $msg + # + #
    + #
    + #

    + # Best regards, + #
    + #
    + # The $useropts{short} Team. + #

    + #
    + # + # + + # $boundary-- + +# END_OF_BODY + + # } + + # sendmail(%mail) ; + +# } #------------------------------------------------------------------------------------------ + +# sub common_send_smtp_mail { + + # my ($from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication,$uploaded_doc,$operator_email) = @_ ; + + # &common_debug("common_send_smtp_mail [$from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication,$uploaded_doc,$operator_email]") ; + + # return unless $msg ; + # return unless $subj ; + + # # my $htype = (-f "$attachpath/$attachname" || $uploaded_doc || $operator_email) ? 'htmlattach' : ($html eq 'html') ? $html : 'text' ; + + # # my $res = &common_mailsend_sendgrid($htype,$to,$subj,$msg,$attachpath,$attachname,"$useropts{short} Events",'events@itvadmin.co.za',$cc,$bcc,$uploaded_doc,$operator_email); + + # # return if $res eq 'success' ; # carry on if mailsend_sendgrid failed + + # my $main_email = $email_add{'events'} ; + + # $to = $main_email unless $to ; + # $from = $main_email unless $from ; + + # my $mail_body = ($html) ? &common_get_mail_body($msg,$table_msg,$thead) : $msg ; + + # if ($html) { + + # if (($attachname && -f "$attachpath/$attachname") or $uploaded_doc) { + + # use MIME::Lite; + # use Net::SMTP_auth; + + + # # ################################################################# + # # Lets build the MulitPart MIME Message + # # ################################################################# + # # Create the Message + # my $msg = MIME::Lite::->new( + # 'From' => "$useropts{short} Events <$from>", + # 'Reply-To' => $email_reply_to, + # 'To' => $to, + # 'Cc' => $cc, + # 'Bcc' => $bcc, + # 'Subject' => $subj, + # 'Type' => 'multipart/mixed', + # ); + + # # Create the text part + # # my $text_part = MIME::Lite::->new( + # # 'Type' => 'text/plain', + # # 'Data' => 'Hi\nThis is a test message', + # # ); + + # # Create the HTML part + # my $html_part = MIME::Lite::->new( + # 'Type' => 'multipart/related', + # ); + + # $html_part->attach( + # 'Type' => 'text/html', + # 'Data' => $mail_body, + # ) ; + + # if ($attachname && -f "$attachpath/$attachname") { + # my $attachtype = ($attachapplication) ? "application/$attachapplication" : 'AUTO' ; + # my $attach_part = MIME::Lite::->new( + # 'Type' => 'multipart/mixed', + # ); + # $attach_part->attach ( + # Type => "$attachtype", + # Encoding => 'base64', + # Path => "$attachpath/$attachname", + # Filename => $attachname, + # Disposition => 'attachement' + # ) or &common_send_mail('rory@kre8it.co.za','','','',"$useropts{short} ERROR : common.pm","common_send_smtp_mail cant attach $attachpath/$attachname : $!") ; + # $msg->attach($attach_part); + # } + + # if ($uploaded_doc) { + # my $upload_part = MIME::Lite::->new( + # 'Type' => 'multipart/mixed', + # ); + # $upload_part->attach ( + # Type => 'AUTO', + # FH => $uploaded_doc, + # Filename => $uploaded_doc, + # Disposition => 'attachment' + # ) or die "Error adding : $uploaded_doc $!\n"; + # $msg->attach($upload_part); + # } + + # if ($operator_email) { + # my $attach_flyer = MIME::Lite::->new( + # 'Type' => 'multipart/mixed', + # ); + # $attach_flyer->attach ( + # Type => "application/$attachapplication", + # Encoding => 'base64', + # Path => "$htmlpath/pdf/operator_flyer", + # Filename => "operator_email_attach.pdf", + # Disposition => 'attachement' + # ) or &common_send_mail('handre@kre8it.co.za','','','',"$useropts{short} ERROR : common.pm","common_send_smtp_mail cant attach $attachpath/$attachname : $!") ; + # $msg->attach($attach_flyer); + # } + + # # Now lets attach the text and html parts to the message + # # $msg->attach($text_part); + # $msg->attach($html_part); + + # my $email = $msg->as_string(); + + # # ################################################################# + # # Lets sent the Message + # # ################################################################# + + # my $smtp_msg = Net::SMTP_auth->new($smtp_server, Port=>587) or die "Can't connect"; + # # my $smtp_msg = Net::SMTP_auth->new($smtp_server, Port=>465) or die "Can't connect"; + # $smtp_msg->auth('PLAIN', $main_email, $send_mail_psw_events) or die "Can't authenticate:".$smtp_msg->message(); + + # $smtp_msg->mail($from) or die "Error:".$smtp_msg->message(); + # $smtp_msg->recipient($to) or die "Error:".$smtp_msg->message(); + + # $smtp_msg->data() or die "Error:".$smtp_msg->message(); + # $smtp_msg->datasend($email) or die "Error:".$smtp_msg->message(); + # $smtp_msg->dataend() or die "Error:".$smtp_msg->message(); + # $smtp_msg->quit or die "Error:".$smtp_msg->message(); + + # } else { + # &common_send_mail($to,$cc,$bcc,$html,$thead,$msg,$subj,$table_msg) ; + # } + + # } else { + # &common_send_mail($to,$cc,$bcc,$html,$thead,$msg,$subj,$table_msg) ; + # } + +# } #------------------------------------------------------------------------------------------ + +# sub common_mailsend_sendgrid { + + # local ($qtype,$qemail,$qsubject,$qbody,$qattachfilepath,$qattachfilename,$qfromname,$qfromemail,$qccemail,$qbccemail,$uploaded_doc,$operator_email) = @_; + + # $qccemail =~ s/\;/\,/g ; + # $qbccemail =~ s/\;/\,/g ; + + # use Email::SendGrid::V3; + + # &common_debug("common_mailsend_sendgrid [$qtype,$qemail,$qsubject,$qbody,$qattachfilepath,$qattachfilename,$qfromname,$qfromemail,$qccemail,$qbccemail,$uploaded_doc,$operator_email]") ; + + # #======================= + # #REF1: https://docs.sendgrid.com/for-developers/sending-email/curl-examples + # #REF2: https://github.com/GrantStreetGroup/Email-SendGrid-V3 + # #To Install: + # #cpan -i Email::SendGrid::V3 + # #cd /root/perl5/lib/perl5 + # #cp -R Email /usr/local/lib64/perl5 + # #======================= + + # my $sg = Email::SendGrid::V3->new(api_key => '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'); + + # $qbody =~ s/'/`/gi; + # $qbody =~ s/\r//gi; + # $qbody =~ s/\n//gi; + + # #------------------------------------------------ + # #SEND TEXT ONLY MAIL + # if ($qtype eq "text") { + + # # , cc => [ $qccemail ], bcc => [ $qbccemail ] + + # my %cc_args = ($qccemail) ? (cc => [ "$qccemail" ]) : () ; + # my %bcc_args = ($qbccemail) ? (bcc => [ "$qbccemail" ]) : () ; + + # my $result = $sg->from($qfromemail,$qfromname) + # ->reply_to($email_reply_to, "$useropts{short} Events") + # ->subject($qsubject) + # ->add_content('text/plain', $qbody) + # ->add_envelope( to => [ "$qemail" ], %cc_args, %bcc_args) + # ->send; + + # $qres = $result->{success} ? "success" : "error: " . $result->{reason}; + + # } + + # #------------------------------------------------ + # #SEND HTML ONLY MAIL + # if ($qtype eq "html") { + + # my $logo_domain = ($useropts{web}) ? $useropts{web} : $ENV{SERVER_NAME} ; + + # $qbody = qq~ +# +# +# +# $useropts{short} +# +# +# +#

    +# +#

    +#

    +# $qbody +#

    +#
    +#
    +# +# +# ~; + # my %cc_args = ($qccemail) ? (cc => [ "$qccemail" ]) : () ; + # my %bcc_args = ($qbccemail) ? (bcc => [ "$qbccemail" ]) : () ; + + # my $result = $sg->from($qfromemail,$qfromname) + # ->reply_to($email_reply_to, "$useropts{short} Events") + # ->subject($qsubject) + # ->add_content('text/html', $qbody) + # ->add_envelope( to => [ "$qemail" ], %cc_args, %bcc_args) + # ->send; + + # $qres = $result->{success} ? "success" : "error: " . $result->{reason}; + + # } + + # #------------------------------------------------ + # #SEND HTML WITH ATTACHMENT MAIL + # if ($qtype eq "htmlattach") { + + # my $encodedcontent = &encode_attachment("$qattachfilepath/$qattachfilename"); + + # my %args = ( + # type => 'AUTO', + # disposition => 'attachment' + # ); + + # my $logo_domain = ($useropts{web}) ? $useropts{web} : $ENV{SERVER_NAME} ; + + # $qbody = qq~ +# +# +# +# $useropts{short} +# +# +# +#

    +# +#

    +#

    +# $qbody +#

    +#
    +#
    +# +# +# ~; + + # my @attachments = ($qattachfilename, $encodedcontent, %args) ; + + # if ($uploaded_doc) { + # my $encodedcontent = &encode_attachment("$uploaded_doc") ; + # push @attachments, ($uploaded_doc, $encodedcontent, %args) ; + # } + + # if ($operator_email) { + # my $encodedcontent = &encode_attachment("$htmlpath/pdf/operator_flyer") ; + # push @attachments, ("operator_email_attach.pdf", $encodedcontent, %args) ; + # } + + + # my %cc_args = ($qccemail) ? (cc => [ "$qccemail" ]) : () ; + # my %bcc_args = ($qbccemail) ? (bcc => [ "$qbccemail" ]) : () ; + + # my $result = $sg->from($qfromemail,$qfromname) + # ->reply_to($email_reply_to, "$useropts{short} Events") + # ->subject($qsubject) + # ->add_content('text/html', $qbody) + # ->add_attachment(@attachments) + # ->add_envelope( to => [ "$qemail" ], %cc_args, %bcc_args) + # ->send; + + # $qres = $result->{success} ? "success" : "error: " . $result->{reason}; + + # #NOTE: Cannot use command line cURL here as the body (base64 pdf) is too large - below works for smaller content + # #$qres = `/usr/bin/curl --request POST --url https://api.sendgrid.com/v3/mail/send --header 'authorization: Bearer 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' --header 'Content-Type: application/json' --data '{"personalizations": [{"to": [{"email": "$qemail"}]}],"from": {"email": "no-reply\@myappointment.co.za"},"subject":"$qsubject","content": [{"type": "text/html","value": "$qbody"}], "attachments": [{"content": "$encodedcontent", "type": "text/plain", "filename": "$qattachfilename"}]}'`; + # } + # #------------------------------------------------ + + # &common_debug("common_mailsend_sendgrid [$qres]") ; + + # return "$qres"; + +# } #------------------------------------------------------------------------------------------ + +sub encode_attachment { + + my ($fh) = @_ ; + + use MIME::Base64 qw(encode_base64); + + my $myfilecontents = '' ; + + open (infile, "$fh"); + binmode infile; + while () { + $myfilecontents .= "$_"; + } + close(infile); + + my $encodedcontent = encode_base64($myfilecontents); + + $encodedcontent =~ s/'/`/gi; + $encodedcontent =~ s/\r//gi; + $encodedcontent =~ s/\n//gi; + + return($encodedcontent) ; + +} #------------------------------------------------------------------------------------------ + +sub common_fix_str { + + my ($txt) = @_ ; + + $txt = lc $txt ; + $txt =~ s/\'//iog ; + $txt =~ s/^\s+|\s+$//g; # remove whitespace before and after + local $txt_new = '' ; + foreach (split(/ /,$txt)) { + if ($_ ne 'and' and $_ ne 'or' and $_ ne 'of' and $_ ne 'in') { + $txt_new .= ucfirst $_ ; + } else { + $txt_new .= "$_" ; + } + $txt_new .= ' ' ; + } + chop $txt_new if $txt_new ; + + return ($txt_new) ; + +} #------------------------------------------------------------------------------- + +sub common_date_array { + + my ($from_date, $to_date) = @_ ; + + my $date_array_date = $from_date ; + + @common_date_array = () ; + + # &common_debug ("common_date_array : $from_date, $to_date") ; + + while ($date_array_date <= $to_date) { + + # &common_debug ("common_date_array : push \@common_date_array, $date_array_date") ; + push @common_date_array, $date_array_date ; + + my $array_date_dd = substr($date_array_date,6,2) ; + my $array_date_mm = substr($date_array_date,4,2) ; + my $array_date_ccyy = substr($date_array_date,0,4) ; + + $day_of_week{$date_array_date} = Day_of_Week($array_date_ccyy,$array_date_mm,$array_date_dd) unless $day_of_week{$date_array_date} ; # 1 is Monday + # $day_of_week{"$array_date_ccyy-$array_date_mm-$array_date_dd"} = Day_of_Week($array_date_ccyy,$array_date_mm,$array_date_dd) unless $day_of_week{"$array_date_ccyy-$array_date_mm-$array_date_dd"} ; # 1 is Monday + # $date_hash{$date_array_date} = 1 ; + + my ($ccyy,$month,$day) = Add_Delta_Days($array_date_ccyy,$array_date_mm,$array_date_dd,1) ; + $month = sprintf("%02s", $month) ; + $day = sprintf("%02s", $day) ; + + $date_array_date = "$ccyy$month$day" ; + } + + &common_debug ("common_date_array : @common_date_array") ; + +} #------------------------------------------------------------------------------- + +sub common_clean_json_one { + + my ($txt) = @_ ; + + # $txt =~ s/ //g; + $txt =~ s/\s+//g; # remove all spaces + $txt =~ s/\r\n|\n//g; + $txt =~ s/\t//g; + + $txt = &common_clean_json_two($txt) ; + + return ($txt) ; + +} #---------------------------------------------------------------------------------------- + +sub common_clean_json_two { + + my ($txt) = @_ ; + + $txt =~ s/\r\n|\n/ /g; + $txt =~ s/\t/ /g; + $txt =~ s/\"//g; + $txt =~ s/\'//g; + $txt =~ s/\’//g; + $txt =~ s/\/>/g; + $txt =~ s/\&/&/g; + $txt =~ s/\Ë/E/g; + $txt =~ s/ +/ /g; # remove excess spaces + + return ($txt) ; + +} #---------------------------------------------------------------------------------------- + +sub common_reverse_geocode_osm_address { + + my ($lat,$lng,$typ) = @_ ; + + my $address = '' ; my $decoded_json = '' ; + + my $url = "http://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=$lat&lon=$lng" ; # http://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=-32.851705&lon=24.727521&zoom=18&addressdetails=1&extratags=1 # https://wiki.openstreetmap.org/wiki/Key:highway # Google Roads API : https://roads.googleapis.com/v1/speedLimits?path=-32.851705,24.727521|-32.856349,24.730925|-32.89585,24.693126|-32.923483,24.675421&key=AIzaSyBVeP-dp1VpeceSo-80pukUBFaPsN_mcRw (https://developers.google.com/maps/documentation/roads/speed-limits) + my $json = get ($url) ; # or die "Couldn't get $url : $!"; + + if ($json) { + $decoded_json = decode_json $json ; + } + + if ($typ eq 'min') { + my @add = () ; %gotpart = () ; + push @add, $decoded_json->{'address'}->{'road'} if $decoded_json->{'address'}->{'road'} ; + + my ($suburb,$junk) = split / Ward /, $decoded_json->{'address'}->{'suburb'} ; + my ($suburb,$junk) = split / Industria /, $suburb ; $suburb =~ s/ Industrial//g ; + push @add, $suburb if $suburb ; + + $gotpart{$suburb} = 1 ; + + my $city = $decoded_json->{'address'}->{'city'} ; $city =~ s/ Local Municipality//g ; + + if ($gotpart{$city}) { + push @add, $decoded_json->{'address'}->{'state'} if $decoded_json->{'address'}->{'state'} ; + } else { + push @add, $city if $city ; + } + + my $country = $decoded_json->{'address'}->{'country'} ; + push @add, $country if $country and $country ne 'South Africa' ; + + $address = join ", ", @add ; + } elsif ($json) { + $address = $decoded_json->{'display_name'} ; + &common_debug("[API] common_get_osm_address : [$url] [$address] ") ; + } + + return ($address) ; + +} #---------------------------------------------------------------------------------------- + +sub common_location_osm_address { + + my ($loc) = @_ ; + + my $address = '' ; my $postcode = '' ; my $suburb = '' ; my $city = '' ; my $decoded_json = '' ; + + my $url = "https://nominatim.openstreetmap.org/search?q=$loc&format=json&addressdetails=1" ; + my $json = get ($url) ; # or die "Couldn't get $url : $!"; + + if ($json) { + $decoded_json = decode_json $json ; + } + + &common_debug("[API] common_location_osm_address : [$url] [$decoded_json] ") ; + + if (ref $decoded_json eq 'ARRAY' && @$decoded_json) { + + my $amenity = $decoded_json->[0]->{'address'}->{'amenity'} ; # "Rondebosch Boys' High School" + my $road = $decoded_json->[0]->{'address'}->{'road'} ; # "Canigou Avenue" + $postcode = $decoded_json->[0]->{'address'}->{'postcode'} ; # "7700" + + my @add = () ; %gotpart = () ; + push @add, $amenity if $amenity ; + push @add, $road if $road ; + + ($suburb,$junk) = split / Ward /, $decoded_json->[0]->{'address'}->{'suburb'} ; + ($suburb,$junk) = split / Industria /, $suburb ; $suburb =~ s/ Industrial//g ; + push @add, $suburb if $suburb ; + + $gotpart{$suburb} = 1 ; + + $city = $decoded_json->[0]->{'address'}->{'city'} ; $city =~ s/ Local Municipality//g ; # "Cape Town" + + if ($gotpart{$city}) { + push @add, $decoded_json->[0]->{'address'}->{'state'} if $decoded_json->[0]->{'address'}->{'state'} ; + } else { + push @add, $city if $city ; + } + + my $country = $decoded_json->[0]->{'address'}->{'country'} ; + push @add, $country if $country and $country ne 'South Africa' ; + + $address = join ", ", @add ; + } else { + return ('', '', ''); + } + + &common_debug("[API] common_location_osm_address : [suburb=$suburb] [postcode=$postcode] [address=$address]") ; + + # 0 + # place_id 60085165 + # licence "Data © OpenStreetMap contributors, ODbL 1.0. http://osm.org/copyright" + # osm_type "relation" + # osm_id 3068903 + # lat "-33.9696668" + # lon "18.477931506136713" + # class "amenity" + # type "school" + # place_rank 30 + # importance 0.3041234681398241 + # addresstype "amenity" + # name "Rondebosch Boys' High School" + # display_name "Rondebosch Boys' High School, Canigou Avenue, Cape Town Ward 59, Cape Town, City of Cape Town, Western Cape, 7700, South Africa" + # address + # amenity "Rondebosch Boys' High School" + # road "Canigou Avenue" + # suburb "Cape Town Ward 59" + # city "Cape Town" + # county "City of Cape Town" + # state "Western Cape" + # ISO3166-2-lvl4 "ZA-WC" + # postcode "7700" + # country "South Africa" + # country_code "za" + # boundingbox + # 0 "-33.9728789" + # 1 "-33.9664854" + # 2 "18.4755388" + # 3 "18.4820403" + + return ($suburb,$city,$postcode,$address) ; + +} #---------------------------------------------------------------------------------------- + +sub common_log_changes { + +my ($log,$nline) = @_ ; + +unless ($log) { return ; } + +$nline =~ s/[ ]+/ /g ; # Replaces all occurances of two spaces with one space +$nline =~ s/\n/ /g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc +$nline =~ s/\t/ /g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc +$nline =~ s/\r/ /g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc + +my $logfile = "/home/libs/data/logs/$log"; + +open (LFILE, "+>>$logfile") or die "can't open $logfile : $!" ; +flock (LFILE, LOCK_EX) or die "can't lock $logfile : $!" ; +seek (LFILE, 0, 0) or die "can't rewind $logfile : $!" ; +@lines = ; +seek (LFILE, 0, 0) or die "can't rewind $logfile : $!" ; +truncate (LFILE, 0) or die "can't truncate $logfile : $!" ; + +my @sort_lines = reverse sort @lines ; # put newest ones first + +my $log_cnt = 0 ; + +print LFILE $nline . "\n" ; + +foreach my $line (@sort_lines) { # 20181109104451|||| + + next unless $line ; + + chomp $line; + + @linex = split(/\|/,$line); + + my $data_col = ($linex[4] eq 'changed_from' || $linex[4] =~/action='Add'/ || $linex[4] =~/action='Edit'/) ? 5 : 4 ; + + my $num_of_data_splits = scalar @linex ; + + for ($data_col+1 .. $num_of_data_splits) { + $linex[$data_col] .= qq~|$linex[$_]~ ; + } + + my @changes = split(",","$linex[$data_col]") ; + + my $num_of_changes = scalar @changes ; + + next if $num_of_changes == 1 && ($changes[0] =~ /last_update/) ; + + my $hashkey = $linex[2] . $linex[3] . $linex[$data_col] ; + # my $hashkey = $linex[2] . $linex[3] . $linex[5] . substr($linex[0],0,8) ; + + if ($done_log_line{$hashkey}) { next ; } + + if ($log_cnt > 10000) { last ; } # only retain 10000 lines + + print LFILE "$line\n"; + + $done_log_line{$hashkey} = 1 ; + + $log_cnt++; +} + +close (LFILE) ; + +} #---------------------------------------------------------------------------------------- + +sub common_fix_cell { + +my ($cell) = @_ ; + + $cell =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; + $cell =~ s/amp;//g; + $cell =~ s/\(//g; + $cell =~ s/\)//g; + $cell =~ s/ //g; + + if ($cell == 0) { + return ; + } elsif ((substr($cell,0,1) == 0) and (length($cell) == 10)) { # e.g. 0825564120 + $cell = 27 . substr($cell,1) ; # 27825564120 + } elsif (substr($cell,0,1) eq '+') { + $cell = substr($cell,1) ; # 27825564120 + } + + return ($cell) ; + +} #------------------------------------------------------------------------------------------ + +sub add_extra_region_filter { + + my ($regions_sql) = @_ ; + + my $sql_limit_user_regions = ($is_schools_manager || $is_operator) ? join(' OR ', map { "id = '$_'" } keys %{$glob_regids{$userid}}) : '' ; + + if ($regions_sql && $sql_limit_user_regions) { + $regions_sql = "$regions_sql AND ($sql_limit_user_regions)" ; + } elsif (!$regions_sql && $sql_limit_user_regions) { + $regions_sql = $sql_limit_user_regions ; + } + + return $regions_sql ; + +}#------------------------------------------------------------------------------- + +1; diff --git a/libs/modules/_FromProd/v1.0/common_min.pm b/libs/modules/_FromProd/v1.0/common_min.pm new file mode 100644 index 0000000..6be46bc --- /dev/null +++ b/libs/modules/_FromProd/v1.0/common_min.pm @@ -0,0 +1,3123 @@ +sub common_min_load_params { + +for my $p ($q->param) { + my $val = $q->param($p) ; + $val =~ s/\"//g ; + $i{$p} = $val ; + # &common_min_debug("$p - $val") ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_alert_type { + +if ($error) { + $alert = &common_min_alert('danger',"$error",'remove-sign') ; + } +elsif ($warning) { + $alert = &common_min_alert('warning',"$warning") ; + } +elsif ($success) { + $alert = &common_min_alert('success',"$success",'ok') ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_alert { + +my ($type,$msg,$glyphicon,$id) = @_ ; + +unless ($id) { $id = 'alertmsg'; } +unless ($glyphicon) { $glyphicon = 'exclamation-sign'; } + +my $alert = qq() ; + +return ($alert) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_add_form { + +my ($table,$action,$label_col,$field_col,$ignore_colpart,$skip) = @_ ; + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +my $form = '' ; + +$form .= &common_min_forms_start($table,$skip) ; + +if (%sort_field) { + foreach my $cnt (sort {$a <=> $b} keys %sort_field) { + $col = $sort_field{$cnt} ; + &common_debug("common_min_add_form [sort_field] = $col [$cnt]") ; + $form .= &common_min_forms_loop('',$table,$ignore_colpart) ; + } + } +else + { + foreach (sort { $col_name{$a} cmp $col_name{$b} } keys %col_name) { + $col = $col_name{$_} ; + &common_debug("common_min_add_form = $col [$_]") ; + $form .= &common_min_forms_loop('',$table,$ignore_colpart) ; + } + } + + +$form .= &common_min_forms_end('',$table,$action,$skip) ; + +return ($form) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_edit_form { + +my ($iid,$table,$action,$label_col,$field_col,$ignore_colpart,$skip) = @_ ; + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +my $form = '' ; + +$form .= &common_min_forms_start($table,$skip) ; + +if (%sort_field) { + foreach my $cnt (sort {$a <=> $b} keys %sort_field) { + $col = $sort_field{$cnt} ; + $form .= &common_min_forms_loop($iid,$table,$ignore_colpart) ; + } + } +else + { + foreach $col (sort keys %{$db{$table}{$iid}}) { + $form .= &common_min_forms_loop($iid,$table,$ignore_colpart) ; + } + } + +$form .= &common_min_forms_end($iid,$table,$action,$skip) ; + +return ($form) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_forms_start { + +my ($table,$skip) = @_ ; + +if ($skip) { return ; } + +my $form = qq(
    ) ; + +$form .= $extra_form_fields_start ; + +return ($form) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_forms_loop { + + my ($iid,$table,$ignore_colpart) = @_ ; + + unless ($col) { return('') ; } + + if ($hidden{$col}) { return('') ; } + if ($ignore{$col}) { return('') ; } + + my ($colpart) = split(/\_/,$col) ; + if (($ignore_colpart) and ($ignore{$colpart})) { return('') ; } + + $ucfirst_col = ucfirst $col ; + + my $val = $db{$table}{$iid}{$col} ; + + # $tindex++ ; + + my $form = '' ; + + if ($checkbox{$col}) { + if ($val) { $checked = 'CHECKED'; } else { $checked = ''; } + $form .= &common_min_form_checkbox($col,$val,$checked) ; + return ($form) ; + } + + if ($radio{$col}) { + $form .= &common_min_form_radio($col,$val) ; + return ($form) ; + } + + &common_min_forms_required ; + + # $req_glyph = '' ; + + # if ($required{$col}) { + # if ($required{$col} == 1){ $required{$col} = 'data-validation="required"' ; } + # elsif ($required{$col} == 2){ $required{$col} = 'data-validation="length alphanumeric" data-validation-length="6-6"' ; } + # elsif ($required{$col} == 3){ $required{$col} = 'data-validation="alphanumeric"' ; } + # elsif ($required{$col} == 4){ $required{$col} = 'data-validation="number"' ; } + # elsif ($required{$col} == 5){ $required{$col} = 'data-validation="number" data-validation-allowing="range[0;1]"' ; } + # elsif ($required{$col} == 6){ $required{$col} = 'data-validation="email"' ; } + # elsif ($required{$col} == 7){ $required{$col} = 'data-validation="url"' ; } + + # $req_glyph = qq() ; + # } + + if ($datetimepicker{$col}) { + unless ($val) { $val = $now_ccyy_mm_dd . " $now_hour:$now_min:$now_sec" ; } + $form .= &common_min_form_datetimepicker($col,$val) ; + return ($form) ; + } + + if ($datepicker{$col}) { + unless ($val) { $val = $now_ccyy_mm_dd ; } + $form .= &common_min_form_datepicker($col,$val) ; + return ($form) ; + } + + if ($select{$col}) { + $form .= &common_min_form_select($col,$val) ; + return ($form) ; + } + + if ($textarea{$col}) { + $form .= &common_min_form_textarea($col,$val) ; + return ($form) ; + } + + if ($label{$col}) { + $form .= &common_min_form_label($col,$val) ; + return ($form) ; + } + + if ($add_col{$col}) { + $form .= &common_min_form_input_col($col,$val) ; + } else { + $form .= &common_min_form_input($col,$val) ; + } + + return ($form) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_forms_required { + +$req_glyph{$col} = '' ; + +if ($required{$col}) { + if ($required{$col} == 1){ $required{$col} = 'data-validation="required"' ; } + elsif ($required{$col} == 2){ $required{$col} = 'data-validation="length alphanumeric" data-validation-length="6-6"' ; } + elsif ($required{$col} == 3){ $required{$col} = 'data-validation="alphanumeric"' ; } + elsif ($required{$col} == 4){ $required{$col} = 'data-validation="number"' ; } + elsif ($required{$col} == 5){ $required{$col} = 'data-validation="number" data-validation-allowing="range[0;1]"' ; } + elsif ($required{$col} == 6){ $required{$col} = 'data-validation="email"' ; } + elsif ($required{$col} == 7){ $required{$col} = 'data-validation="url"' ; } + elsif ($required{$col} == 8){ $required{$col} = 'data-validation="" data-validation-allowing="" data-validation-decimal-separator=""' ; } + elsif ($required{$col} == 9){ $required{$col} = 'data-validation="custom" data-validation-regexp="^\d+(\.\d{1,2})?$"' ; } # New condition + elsif ($required{$col} == 10) { $required{$col} = 'data-validation="length number" data-validation-length="10-20"' ; } # 0846758345 or 27846758345 + + $req_glyph{$col} = qq() ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_forms_end { + +my ($iid,$table,$action,$skip) = @_ ; + +if ($skip) { return ; } + +my $form = '' ; + +$form .= $extra_form_fields ; + +foreach (keys %hidden) { + $form .= qq~~ ; +} + +if ($dialog) { + $varbtn = qq~ ~ ; +} else { + $varbtn = qq~ ~ ; +} +# if ($savjqy) { $savbtn = qq() ;} else { $savbtn = qq() ; } + +if ($savjqy) { + my $custom_class = ($invoice_exists && !$useropts{super}{$username} && !$useropts{it}{$username}) ? "custom" : "primary" ; + my $custom_tooltip = ($invoice_exists) ? qq~title data-toggle="tooltip" data-placement="top" data-original-title="Invoice Nr Exists!!!"~ : qq~~ ; + $savbtn = qq~  ~ ; +} elsif ($srchjqy) { + $savbtn = qq~ ~ ; +} elsif ($srchscr) { + $savbtn = qq~ ~ ; +} else { + $savbtn = qq~ ~ ; +} + +if ($addbkb) { + $bakbtn = qq~ ~; +} else { + $bakbtn = qq~~ ; +} + +if ($addcpb) { + $cpybtn = qq~ ~; + &common_min_footer('id',"$lcpage\s"); +} else { + $cpybtn = qq~~ ; +} + +my $custom_class = ($cancel_butt & $invoice_exists && !$useropts{super}{$username} && !$useropts{it}{$username}) ? "custom" : "danger" ; +my $custom_tooltip = ($invoice_exists) ? qq~title data-toggle="tooltip" data-placement="top" data-original-title="Invoice Nr Exists!!!"~ : qq~~ ; +$canxbtn = ($cancel_butt) ? qq~  ~ : '' ; + +$varbtn = $custom_back_button if $custom_back_button ; + +$savbtn = qq~~ if $skip_save_btn ; + +$form .= qq~ +
     
    +
    $savbtn$canxbtn$cpybtn$varbtn$bakbtn
     
    +
    ~ ; + +return ($form) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_columns { + +my ($label_col,$field_col) = @_ ; + +unless ($label_col) { $lcol = 2 ; } else { $lcol = $label_col ; } +unless ($field_col) { $fcol = 4 ; } else { $fcol = $field_col ; } + +return ($lcol,$fcol) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_status { + +my ($closed,$deleted) = @_ ; + +my ($class,$txt) ; + +if ($deleted == 1) { $class = 'danger' ; $txt = 'DELETED' ; $del{$iaction} = 1 ; } +elsif ($closed == 1) { $class = 'success' ; $txt = 'CLOSED' ; $clo{$iaction} = 1 ; } +elsif ($closed == 0) { $class = 'warning' ; $txt = 'ACTIVE' ; $act{$iaction} = 1 ; } + +return ($class,$txt) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_view { + +my ($field,$val,$type,$addclass,$dont_end_row) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +# $vrowcnt++; if ($vrowcnt % 2 == 0) { $bgcolor = '#cecbcb' ; } else { $bgcolor = '#eeeeee' ; } + +$bgcolor = '#eeeeee' ; + +unless ($val) { $val = ' ' ; } + +my $row = qq(
    +
    + +
    +
    +
    +
    + + $val +
    +
    +
    ) ; + +unless ($dont_end_row) { $row .= qq(
    ) ; } + +$row = qq~$row

    ~ if $val =~ /
    / ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_view_col { + +my ($val) = @_ ; + +# my $ucfirst_field = ucfirst $field ; +# my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +# $vrowcnt++; if ($vrowcnt % 2 == 0) { $bgcolor = '#cecbcb' ; } else { $bgcolor = '#eeeeee' ; }
    + +unless ($val) { $val = ' ' ; } + +my $row = qq~ +
    +
    +
    + $val +
    +
    +
    ~ ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_input { + +my ($field,$val,$type,$addclass,$dont_end_row) = @_ ; + +if ($field eq 'password') { $type = 'password' ; } unless ($type) { $type = 'text' ; } if ($cust_class{$field}) { $addclass = $cust_class{$field} ; } + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +if ($type eq 'hidden') { return ("") ; } + +my $labelid = '' ; if ($label_id{$field}) { $labelid = $label_id{$field} ; } + +$tindex++ ; + +$fcol = $fcol{$field} if $fcol{$field} ; + +my $row = '' ; + +if ($add_finish_div{$field}) { $row .= qq~
    ~ ; } + +$row .= qq~
    +
    + +
    +
    +
    +
    + +
    +
    +
    $dlg{$field}~ ; + +if (not $dont_end_row and not $dont_end_row{$field}) { $row .= qq~
    ~ ; } + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_input_col { + +my ($field,$val) = @_ ; + +unless ($type) { $type = 'text' ; } + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } +my $placeholder = $print_field ; if ($preferred_placeholder{$field}) { $placeholder = $preferred_placeholder{$field} ; } +my $field_id = "input$ucfirst_field" ; + +# unless ($excl_on_change{$field}) { push @jquery_workings_trigger_fields, $field_id ; } +unless ($excl_on_change{$field}) { push @jquery_trigger_fields, $field_id ; } + +if ($type eq 'hidden') { return ("") ; } + +$tindex++ ; + +$fcol = $fcol{$field} if $fcol{$field} ; + +my $row = qq~ +
    +
    +
    + +
    +
    +
    + $dlg{$field}~ ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_label { + +my ($field,$val) = @_ ; + +$hidden{$field} = 1 ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } +my $field_id = "label$ucfirst_field" ; + +my $row .= qq~
    +
    + +
    +
    +
    $val
    +
    $dlg{$field}~ ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_label_col { + +my ($field) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } +my $field_id = "label$ucfirst_field" ; + +my $row = qq~
    + +
    ~; + +unless ($excl_on_change{$field}) { push @jquery_trigger_fields, $field_id ; } +# unless ($excl_on_change{$field}) { push @jquery_workings_trigger_fields, $field_id ; } + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_textarea { + +my ($field,$val,$height) = @_ ; + +if ($textarea_height{$field}) { $height = $textarea_height{$field}; } + +unless ($height) { $height = 100; } + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +$tindex++ ; + +my $row = qq~
    +
    + +
    +
    +
    + +
    +
    +
    ~ ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_textarea_col { + +my ($field,$val,$height,$hide) = @_ ; + +if ($textarea_height{$field}) { $height = $textarea_height{$field}; } + +unless ($height) { $height = 100; } + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +$tindex++ ; + +my $hide = ($hide) ? "none" : "" ; + +my $row = qq~ +
    +
    + +
    +
    ~ ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_checkbox { + +my ($field,$val,$checked,$classic) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } +my $check_class = ($classic) ? 'class="iphone-toggle"' : '' ; +# + +$tindex++ ; + +my $row = qq(
    +
    +
    + +
    +
    ) ; + +# + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_checkbox_col { + +my ($field,$val,$checked,$classic) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } +my $field_id = "checkbox$ucfirst_field" ; +my $check_class = ($classic) ? 'class="iphone-toggle"' : '' ; + +my $label = '' ; if ($label{$field}) { $label = "" ; } + +$tindex++ ; + +my $row = qq(
    + + $label +
    ) ; + +unless ($excl_on_change{$field}) { push @jquery_trigger_fields, $field_id ; } +# unless ($excl_on_change{$field}) { push @jquery_workings_trigger_fields, $field_id ; } + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_radio { + +my ($field,$val,$opts) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +my @opts = split(/\+/,$radio_opts{$field}); + +foreach (@opts) { + if ($_ eq $val) { $checked = 'CHECKED'; } else { $checked = ''; } + $print_radios .= qq( $_) ; + } + +my $row = qq(
    +
    +
    + +
    +
    ) ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_select { + +my ($field,$val,$dont_end_row) = @_ ; + +if ($multiple{$field}) { $setmultiple = 'multiple' ; } else { $setmultiple = '' ; } + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +$tindex++ ; + +my $row = qq~
    +
    +
    +
    +
    + +
    +
    +
    + $dlg{$field}~ ; + +unless ($dont_end_row) { $row .= qq~
    ~ ; } + +if ($allow_deselect{$field}) { + if ($minify_jquery) { + push @all_select_ids,"#select$ucfirst_field" if $ucfirst_field ; + } else { + $trigger_jquery_raw .= qq~\$("#select$ucfirst_field").chosen({ allow_single_deselect:true,search_contains:true });~ ; + } +} + +# if ($val) { + # $trigger_jquery_raw .= qq~\$("#select$ucfirst_field").val($val) ; \$("#select$ucfirst_field").trigger("chosen:updated"); ~ ; +# } + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_select_col { + +my ($field,$val) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +if ($multiple{$field}) { $setmultiple = 'multiple' ; } else { $setmultiple = '' ; } + +$tindex++ ; + +my $row = qq~
    +
    +
    + + $dlg_operator{$field} +
    +
    +
    + $dlg{$field}~ ; + +if ($allow_deselect{$field}) { + if ($minify_jquery) { + push @all_select_ids,"#select$ucfirst_field" if $ucfirst_field ; + } else { + $trigger_jquery_raw .= qq~\$("#select$ucfirst_field").chosen({ allow_single_deselect:true });~ ; + } +} + +# if ($val) { + # $trigger_jquery_raw .= qq~\$("#select$ucfirst_field").val($val) ; \$("#select$ucfirst_field").trigger("chosen:updated"); ~ ; +# } + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_datetimepicker { + +my ($field,$val,$diff) = @_ ; + + $diff = 10 unless $diff ; +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +$tindex++ ; + +# if ($field eq 'date_from') { $val = "$now_ccyy_mm_dd $now_hour:00:00" unless $val ; } +if ($field eq 'date_from') { $val = "$now_ccyy_mm_dd 08:00:00" unless $val ; } +if ($field eq 'date_to') { my $hr = sprintf("%02s", $now_hour + 2) ; $val = "$now_ccyy_mm_dd $hr:00:00" unless $val ; } + +my $row = qq(
    +
    +
    +
    +
    + + + + + +
    +
    +
    +
    ) ; + +$trigger_jquery_raw .= qq(\$('#datetimepicker$ucfirst_field').datetimepicker({language: 'pt-BR'}); ) ; + +my @field_name_parts = split(/\_/,$field) ; + +if ($field_name_parts[-1] eq 'from' && !($ENV{'SCRIPT_NAME'} =~ /event_quotes/ && ($ENV{'QUERY_STRING'} =~ /edit/ || $ENV{'QUERY_STRING'} =~ /add/))) { + pop @field_name_parts ; my $field_prefix = join("_",@field_name_parts) ; my $ucfirst_field_prefix = ucfirst $field_prefix ; + if ($ENV{'QUERY_STRING'} =~ /filter/ || $ENV{'QUERY_STRING'} =~ /search/ || $ENV{'SCRIPT_NAME'} =~ /report/) { + $trigger_jquery_raw .= qq~ + \$('#datetimepicker$ucfirst_field_prefix\_from').on('changeDate', function(e) { + var datetimepickerDate_from = \$("input[name='$field_prefix\_from']").val(); + var datetimepickerDate_to = \$("input[name='$field_prefix\_to']").val(); + var newDatetimepickerDate_from = new Date(datetimepickerDate_from); + var newDatetimepickerDate_to = new Date(datetimepickerDate_to); + + if (newDatetimepickerDate_from > newDatetimepickerDate_to) { + newDatetimepickerDate_to = new Date(datetimepickerDate_from); + } + + console.log("datetimepickerDate_from="+datetimepickerDate_from) ; + newDatetimepickerDate_from.setHours(+2); + newDatetimepickerDate_from.setMinutes(0); + newDatetimepickerDate_from.setSeconds(0); + newDatetimepickerDate_from.setMilliseconds(0); + console.log("newDatetimepickerDate_from="+newDatetimepickerDate_from) ; + \$("#datetimepicker$ucfirst_field_prefix\_from").datetimepicker("setDate", newDatetimepickerDate_from); + + + console.log("datetimepickerDate_to="+newDatetimepickerDate_to) ; + newDatetimepickerDate_to.setHours(23+2); + newDatetimepickerDate_to.setMinutes(59); + newDatetimepickerDate_to.setSeconds(59); + newDatetimepickerDate_to.setMilliseconds(59); + console.log("newDatetimepickerDate_to="+newDatetimepickerDate_to) ; + \$("#datetimepicker$ucfirst_field_prefix\_to").datetimepicker("setDate", newDatetimepickerDate_to); + }) ; + \$('#datetimepicker$ucfirst_field_prefix\_to').on('changeDate', function(e) { + var datetimepickerDate_to = \$("input[name='$field_prefix\_to']").val(); + var newDatetimepickerDate_to = new Date(datetimepickerDate_to); + console.log("datetimepickerDate_to="+datetimepickerDate_to) ; + newDatetimepickerDate_to.setHours(23+2); + newDatetimepickerDate_to.setMinutes(59); + newDatetimepickerDate_to.setSeconds(59); + newDatetimepickerDate_to.setMilliseconds(59); + console.log("newDatetimepickerDate_to="+newDatetimepickerDate_to) ; + \$("#datetimepicker$ucfirst_field_prefix\_to").datetimepicker("setDate", newDatetimepickerDate_to); + }) ; + ~; + } else { + $trigger_jquery_raw .= qq~ + if (\$("#datetimepicker$ucfirst_field_prefix\_to").length) { + \$('#datetimepicker$ucfirst_field_prefix\_from').on('changeDate', function(e) { + var datetimepickerDate_from = \$("input[name='$field_prefix\_from']").val(); + console.log("datetimepickerDate_from="+datetimepickerDate_from) ; + + if (datetimepickerDate_from) { + // Parse datetimepickerDate_from value to a Date object + var datetimepickerDate_to = new Date(datetimepickerDate_from); + console.log("datetimepickerDate_to="+datetimepickerDate_to) ; + + // Add 2 hours to datetimepickerDate_from value + // datetimepickerDate_to.setHours(datetimepickerDate_to.getHours() + $diff); + datetimepickerDate_to.setHours(datetimepickerDate_to.getHours() + $diff); + console.log("datetimepickerDate_to="+datetimepickerDate_to) ; + \$("#datetimepicker$ucfirst_field_prefix\_to").datetimepicker("setDate", datetimepickerDate_to); + } + }) ; + } + ~; + } +} + +return ($row) ; + +# + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_datepicker { + +my ($field,$val,$label,$dont_end_row) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($label) { $print_field = $label ; } if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +if ($val eq '0000-00-00') { $val = '' ; } + +$tindex++ ; + +my $row = qq~
    +
    +
    +
    +
    + + + + +
    +
    +
    + ~ ; + +unless ($dont_end_row) { + $row .= qq~ +
    + ~ ; +} + +&common_min_form_datepicker_jquery($ucfirst_field); + +return ($row) ; + +# + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_datepicker_col { + +my ($field,$val,$end_row) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +$tindex++ ; + +if ($val eq '0000-00-00') { $val = '' ; } + +my $row = qq(
    +
    +
    + + + + +
    +
    +
    ) ; + +$row .= qq~
    ~ if $end_row ; + +&common_min_form_datepicker_jquery($ucfirst_field); + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_form_datepicker_jquery { + + my ($ucfirst_field) = @_ ; + + $trigger_jquery_raw .= qq~ + \$('#datepicker$ucfirst_field').datepicker({ + format: "yyyy-mm-dd"}).on('changeDate', function (ev) { + \$('.datepicker').hide(); + }) ; + ~ ; + + my $lc_field = lc $ucfirst_field ; + my @field_name_parts = split(/\_/,$lc_field) ; + + # if ($field_name_parts[-1] eq 'from') { + # pop @field_name_parts ; my $field_prefix = join("_",@field_name_parts) ; my $ucfirst_field_prefix = ucfirst $field_prefix ; + # $trigger_jquery_raw .= qq~ + # if (\$("#datepicker$ucfirst_field_prefix\_to").length) { + # // \$('#datepicker$ucfirst_field_prefix\_from').on('changeDate', function(e) { + # // var datepickerDate_from = \$("input[name='$field_prefix\_from']").val(); + # // console.log("datepickerDate_from [$field_prefix\_from]="+datepickerDate_from) ; + + # // if (datepickerDate_from) { + # // // Parse datepickerDate_from value to a Date object + # // var datepickerDate_to = new Date(datepickerDate_from); + # // console.log("datepickerDate_to="+datepickerDate_to) ; + # // // Add 1 month to datepickerDate_from value + # // datepickerDate_to.setMonth(datepickerDate_to.getMonth() + 1); + # // // var formattedDate = \$("#datepicker$ucfirst_field_prefix\_to").formatDate("yyyy-mm-dd", new Date(datepickerDate_to)); + # // // console.log("datepickerDate_to [datepicker$ucfirst_field_prefix\_to]="+datepickerDate_to+" ["+formattedDate+"]") ; + # // console.log("datepickerDate_to [datepicker$ucfirst_field_prefix\_to]="+datepickerDate_to) ; + # // // \$("#datepicker$ucfirst_field_prefix\_to").datepicker("setDate", new Date(datepickerDate_to)); + # // // \$("#datepicker$ucfirst_field_prefix\_to").setDate(datepickerDate_to); + # // } + # // }) ; + # var nowTemp = new Date(); + # var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0); + + # var from = \$('#datepicker$ucfirst_field_prefix\_from').datepicker({ + # format: "yyyy-mm-dd", + # onRender: function (date) { + # return date.valueOf() < now.valueOf() ? 'disabled' : ''; + # } + # }).on('changeDate', function (ev) { + # if (ev.date.valueOf() > to.date.valueOf()) { + # var newDate = new Date(ev.date) + # newDate.setDate(newDate.getDate() + 30); + # to.setValue(newDate); + # } + # // from.hide(); + # \$('#datepicker$ucfirst_field_prefix\_to')[0].focus(); + # }).data('datepicker'); + # var to = \$('#datepicker$ucfirst_field_prefix\_to').datepicker({ + # format: "yyyy-mm-dd", + # onRender: function (date) { + # return (date.valueOf() < now.valueOf()) && (date.valueOf() >= from.date.valueOf()) ? 'disabled' : ''; + # } + # }).on('changeDate', function (ev) { + # // to.hide(); + # }).data('datepicker'); + # } + # ~; + # } + +} #------------------------------------------------------------------------------------------ + +# sub common_min_form_datepicker { + +# my ($field,$val) = @_ ; + +# my $ucfirst_field = ucfirst $field ; +# my $print_field = &common_min_print_field($field) ; + +# my $row = qq(
    + #
    + #
    + #
    + #
    + # + # + # + # + # + #
    + #
    + #
    + #
    ) ; + +# $trigger_jquery_raw .= qq(\$('#datetimepicker$ucfirst_field').datetimepicker({language: 'pt-BR'}); ) ; + +# # $trigger_jquery_raw .= qq( +# # \$('#datepicker$ucfirst_field').datepicker({ + # # format: "yyyy-mm-dd"}).on('changeDate', function (ev) { + # # \$('.datepicker').hide(); + # # }) ; +# # ) ; + +# return ($row) ; + +# } #------------------------------------------------------------------------------------------ + +sub common_min_form_timepicker_col { + + my ($field,$val,$diff) = @_; + + $diff = 10 unless $diff; + my $ucfirst_field = ucfirst $field; + my $print_field = ($preferred_title{$field}) ? $preferred_title{$field} : &common_min_print_field($field) ; + + $tindex++; + + my $row = qq~ +
    +
    +
    + + + + +
    +
    +
    + ~ ; + + $trigger_jquery_raw .= qq(\$('#timepicker$ucfirst_field').datetimepicker({language:'pt-BR',pickDate:false});) ; + + return $row ; + +} #------------------------------------------------------------------------------------------ + +# # sub common_min_form_radio_col { + + # # my ($field,$val,$opts) = @_ ; + + # # my $ucfirst_field = ucfirst $field ; + # # my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + + # # my @opts = split(/\+/,$radio_opts{$field}); my $cnt = 0 ; + + # # foreach (@opts) { + # # my $value = $_ ; $value = lc $value ; $value =~ s/ /\_/g ; $cnt++ ; + # # if ($value eq $val) { $checked = 'CHECKED'; } else { $checked = ''; } + # # $print_radios .= qq~
     $_
    ~ ; #### WHY NOT class="radio col-md-$fcol" ????????????? + # # } + + # # my $row = qq~
    + # # + # # + # #
    + # # $print_radios~ ; + + # # for (1 .. $cnt) { + # # $trigger_jquery_raw .= qq~ + # # \$("#radio_$_").change(function () { + # # if(\$(this).is(":checked")) { + # # let sel_val = \$("#radio_$_").val() ; + # # console.log("sel_val : "+sel_val) ; + # # \$("#selected_$field").val(sel_val) ; + # # } + # # }) ; + # # ~ ; + # # } + + # # return ($row) ; + +# # } #------------------------------------------------------------------------------------------ + +sub common_min_form_radio_col { + + my ($field,$val,$opts,$columns,$nr_of_columns_to_display,$radio_row_id,$row_cnt,$display_horizontally) = @_ ; + + + # my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + + $nr_of_columns_to_display = $columns unless $nr_of_columns_to_display ; + + $row_cnt = 1 unless $row_cnt ; + + my %display = () ; + for ($nr_of_columns_to_display+1 .. 10) { + $display{$_} = qq~style="display:none;"~ ; + } + $display{row} = qq~style="display:none;"~ if $nr_of_columns_to_display < 0 ; ## HIDE SECOND ROW BY DEFAULT + + my @default_checked = split(/\;/,$val) ; my $print_radios = qq~~ ; my @opts = split(/\+/,$radio_opts{$field}); my $cnt = 0 ; my $ucfirst_field = ucfirst $field ; + + $print_radios .= qq~
    ~ if $display_horizontally ; + + foreach my $option (@opts) { + + $cnt++ ; + + my $row_id = ($radio_row_id) ? "$radio_row_id\_$cnt" : "" ; + + # my $print_field = ucfirst $option; + + $print_radios .= qq~
    ~ unless $display_horizontally ; + + my $align = qq~align='right'~ if $display_horizontally ; + + $print_radios .= qq~ +
    + +
    ~ ; + for (1 .. $columns) { + my $value = $option; $value = lc $value ; $value =~ s/ /\_/g ; + + my $radio_nr = ($display_horizontally) ? $display_horizontally : ($row_cnt*$columns - $columns) + $_ ; + + if ($value eq $default_checked[$radio_nr - 1]) { $checked = 'CHECKED'; } else { $checked = ''; } + + $print_radios .= qq~~ if $cnt == 1 ; + $print_radios .= qq~ +
    + +
    + ~ ; + } + + $print_radios .= qq~ +
    + ~ unless $display_horizontally ; #### WHY NOT class="radio col-md-$fcol" ????????????? + } + + $print_radios .= qq~ +
    + ~ if $display_horizontally ; + + my $row = qq~$print_radios~ ; + + my @radio_ids = () ; my $radio_to_selected = qq~~ ; + + for my $option_cnt (1 .. $cnt) { + for (1 .. $columns) { + push @radio_ids,"#radio_$_\_$option_cnt" ; + $radio_to_selected .= qq~"radio_$_\_$option_cnt":"selected_$_\_$option_cnt",~ ; + } + } + + chop $radio_to_selected if $radio_to_selected ; + my $radio_ids_string = join(",",@radio_ids) ; + $trigger_jquery_raw .= qq~ + \$("$radio_ids_string").change(function () { + if (\$(this).is(":checked")) { + const id = this.id ; + const radio_to_selected = {$radio_to_selected} ; + let sel_val = \$(this).val() ; + // console.log("sel_val : "+sel_val) ; + \$("#"+radio_to_selected[id]).val(sel_val) ; + } + }) ; + ~ ; + + return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_print_field { + +my ($txt) = @_ ; + +if (($testing == 1) and ($username eq 'rory')) { return($txt) ; } + +if ($addid{$txt}) { $addtxt = ' ID' ; } else { $addtxt = '' ; } + +$txt =~ s/\_id/ /gi ; + +@strings = split(/\_/,$txt) ; +@strings_ucf = map(ucfirst, map(lc,@strings)); +$txt = join(' ', @strings_ucf); +$txt .= $addtxt ; + +return ($txt) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table { + +my ($id,$page,$list,$sort_col,$do_not_auto_sort_table) = @_ ; + +unless ($sort_col) { $sort_col = 0 ; } if ($fnsortcol) { $sort_col = $fnsortcol ; } + +my $sort_order = ($do_not_auto_sort_table) ? '' : 'desc' ; if ($fnsortorder) { $sort_order = $fnsortorder; } + +$print_box_content_rows .= qq~ + + $print_thead + + $print_tbody + +
    ~ ; + +if ($list) { $trigger_jquery .= qq~var oTable = \$('#itv-table').dataTable(); oTable.fnSort( [ [$sort_col,'$sort_order'] ] );~ ; } + +&common_min_footer($id,$page); + +} #------------------------------------------------------------------------------------------ + +sub common_min_footer { + +my ($id,$page) = @_ ; + +if ($uniq_id) { $id = $uniq_id ; } + +$print_footer_jscript = qq( +) ; + +if ($page && $ENV{SCRIPT_NAME} =~ /\_test/) { $page .= '-test' ; } + +if ($page) { $action_delete = qq(delete-$page) ; $action_edit = qq(edit-$page) ; $action_view = qq(view-$page) ; $action_copy = qq(copy-$page) ; } else { $action_delete = '' ; $action_edit = '' ; $action_view = '' ; $action_copy = '' ; } + +if ($blank_action) { $action_delete = '' ; $action_edit = '' ; $action_view = '' ; $action_copy = '' ; } + +$print_footer_forms .= qq~ +
    + + +
    + +
    + + +$extra_edit_hidden_inputs +
    + +
    + + +
    + +
    + + +$extra_edit_hidden_inputs +
    +~ ; + +} #------------------------------------------------------------------------------------------ + +# sub common_min_select_opts { + +# my ($field,$table,$valfield,$fid,$required,$addfield,$where) = @_ ; + +# $select{$field} = 1 ; + +# if ($required) { $required{$field} = 1 ; } + +# &db_min_ro($table,'*',$where,'','') ; + +# foreach my $id (keys %{$db{$table}}) { + # if ($fid == $id) { $selected = 'selected="selected"'; } else { $selected = ''; } + + # # &common_min_debug("common_min_select_opts - $fid == $id [$valfield] [$table] [$db{$table}{$id}{$valfield}] [[$table][$id][$valfield]]") ; + + # if ($db{$table}{$id}{$addfield}) { $disp_addfield = " ($db{$table}{$id}{$addfield})" ; } else { $disp_addfield = '' ; } + # if ($extra{$table}{$id}{$addfield}) { $disp_addfield = " $extra{$table}{$id}{$addfield}" ; } else { $disp_addfield = '' ; } + # $opts{$field} .= qq() ; + # } + +# } #------------------------------------------------------------------------------------------ + +sub common_min_select_opts { + + my ($field,$table,$dispfield,$fid,$required,$addfield,$where,$valfield,$addmore,$select,$order_dropdown) = @_ ; + + $select{$field} = 1 ; + + my $val = '' ; + + # $select = '*' unless $select; + + unless ($select) { $select = '*' ; } + + # &common_min_debug("common_min_select_opts:$field,$table,$dispfield,$fid,$required,$addfield,$where,$valfield,$addmore,$select") ; + + if ($required) { $required{$field} = 1 ; } + + # if ($dispfield){ + # my $orderby = "' $dispfield '" ; + # } else { + # my $orderby = ' id DESC ' ; + # } + + my $orderby = ($dispfield) ? "' $dispfield '" : ' id DESC' ; + + &db_min_ro($table,$select,$where,$orderby,'') ; + + $order_dropdown = $dispfield if $dispfield and not $order_dropdown ; + + unless ($order_dropdown) { + foreach my $id (keys %{$db{$table}}) { + foreach (keys %{$db{$table}{$id}}) { + $order_dropdown = $_ ; + last ; + } + last ; + } + } + + foreach my $id (sort {$db{$table}{$a}{$order_dropdown} cmp $db{$table}{$b}{$order_dropdown}}keys %{$db{$table}}) { + + $selected = ($fid && ($fid eq $db{$table}{$id}{$valfield} || $fid == $id)) ? 'SELECTED' : '' ; + + # if ($table eq 'regions') { &common_debug("$selected = ($fid and ($fid eq $db{$table}{$id}{$valfield} || $fid == $id)) ? 'SELECTED' : '' ;") ; } + + if ($db{$table}{$id}{$addfield} && $db{$table}{$id}{$dispfield} ne $db{$table}{$id}{$addfield}) { $disp_addfield = " [$db{$table}{$id}{$addfield}]" ; } else { $disp_addfield = '' ; } + + my $disp_addmore = '' ; + + if ($display_addmore{$table}{$addmore}) { + my $glyph = '' ; + if ($db{$table}{$id}{$addmore} == 1) { + # $glyph = qq(); + $disp_addmore = " - $addmore" ; + } + } + + if ($valfield) { $val = $db{$table}{$id}{$valfield} ; } else { $val = $id ; } + + # if ($table eq 'regions') { &common_debug("filter_select_opts = $filter_select_opts{$table}, filter_val = $filter_val{$table}{$val} [$val] valfield=$valfield") ; } + + if ($filter_select_opts{$table} == 1) { + next unless $filter_val{$table}{$val} == 1 ; + } + + # if ($table eq 'countries') { &common_debug("$field : [$val] $db{$table}{$id}{$dispfield}$disp_addfield$disp_addmore") ; } + + # &common_debug("table=$table, id=$id, val=$val, dispfield=$dispfield [$db{$table}{$id}{$dispfield}]") ; + + $opts{$field} .= qq~~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_box_top { + +my ($glyphicon,$title,$bgcolor,$boxicon,$chevronid) = @_ ; + +# f5af19 +if ($bgcolor) { $box_header_style = qq~style="background:#$bgcolor;color:#ffffff;"~ ; } else { $box_header_style = '' ; } +if ($chevronid) { $box_chevron_id = qq~id="$chevronid"~ ; } else { $box_chevron_id = '' ; } + +my $box = qq~

    $title

    $boxicon
    ~ ; + +return($box) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_box_foot { + +my $box = qq(
    ) ; + +return ($box) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_extra_crumb { + +my ($crumb_url,$crumb_txt) = @_ ; + +$crumb_txt =~ s/\-/ /g; my @crumbs = split(/ /,$crumb_txt); my @crumbs_ucf = map ucfirst, @crumbs; $crumb_txt = join(' ',@crumbs_ucf) ; + +$insert_crumbs .= qq(
  • $crumb_txt
  • ) ; + +&config_set_breadcrumbs ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_dialog { + +$dialog{'common'}{'head'} = qq( + + + + $useropts{title} + + + + + + + + + + + + + $extra_dialog_js + + + + +) ; + +# table>thead>tr>th, .table>thead>tr>th, table>tbody>tr>th, .table>tbody>tr>th, table>tfoot>tr>th, .table>tfoot>tr>th, table>thead>tr>td, .table>thead>tr>td, table>tbody>tr>td, .table>tbody>tr>td, table>tfoot>tr>td, .table>tfoot>tr>td { border: 1px solid black; } +# .table>caption+thead>tr:first-child>th, .table>colgroup+thead>tr:first-child>th, .table>thead:first-child>tr:first-child>th, .table>caption+thead>tr:first-child>td, .table>colgroup+thead>tr:first-child>td, .table>thead:first-child>tr:first-child>td { border-top: 1px solid black; } + +$dialog{'common'}{'js'} = qq( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +) ; + +} #------------------------------------------------------------------------------------ + +sub common_min_commify { + +local($_) = shift; +1 while s/^(-?\d+)(\d{3})/$1,$2/; +return $_; + +} #------------------------------------------------------------------------------- + +sub common_min_debug { + +my ($msg) = @_ ; + +unless ($username eq 'rory') { return ; } +unless (($testing == 1) or ($debug == 1)) { return ; } + +print "\n" . $msg ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_action { + +if ($iaction eq 'add'){ + &common_min_add_screen; + &common_min_screen1; + } + +if ($iaction eq 'list' or $iaction eq 'detailed' or $iaction eq 'summary' or $iaction eq 'accepted' or $iaction eq 'pending' or $iaction eq 'closed' or $iaction eq 'all' or $iaction eq 'open' or $iaction eq 'active') { + &list_screen ; + &common_min_screen3; + } + +if ($iaction eq 'display'){ + &list_screen ; + &common_min_screen3; + } + +if ($iaction eq 'view'){ + &common_min_load_params ; + &common_min_view_screen ; + &common_min_screen1; + } + +if ($iaction eq 'edit'){ + &common_min_load_params ; + &common_min_edit_screen ; + &common_min_screen1; + } + +if ($iaction eq 'save'){ + &common_min_load_params ; + &validate ; + &insert ; + &common_min_screen2; + } + +if ($iaction eq 'update'){ + &common_min_load_params ; + &update ; + &common_min_screen2; + } + +if ($iaction eq 'delete'){ + &common_min_load_params ; + &common_min_delete ; + &common_min_screen2; + } + +if ($iaction eq 'copy'){ + &common_min_load_params ; + &duplicate ; ### Will cause error if using use File::Copy;, do not use sub copy { .. } ... + &common_min_edit_screen; + &common_min_screen1; + } + +if ($iaction eq 'search'){ + $srchscr = 1 ; + &report_screen ; + } + +if ($iaction eq 'filter'){ + $srchscr = 1 ; + &filter_screen ; + } + +if ($iaction eq 'report'){ + &common_min_load_params ; + &report_ifields; + &list_screen ; + &common_min_screen3; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_add_screen { + +&add_screen; + +%col_name = () ; + +my $dbid = 'id' ; if ($uniq_id) { $dbid = $uniq_id ; } + +&db_min_ro($table,'*',"$dbid > 0 AND $dbid < 10",'','') ; + +$page_title = 'Add' ; + +&add_db_fields ; + +unless ($double_box_layout) { $print_box_content_rows = &common_min_add_form($table,'save') ; } + +} #------------------------------------------------------------------------------------------ + +sub common_min_error_screen { + + $page_title = ($iaction eq 'save') ? 'Add' : "Edit $i{id}" ; + + foreach (keys %i) { $db{$table}{''}{$_} = $i{$_} ; } # reset other fields after &db_common_ro($table,'*','','id DESC',1) ; ## ALSO CHECK THAT THIS INCLUDES ALL THE FIELD IN ON SCREEN!!! + + &add_screen; # must occur before %col_name set to blank otherwise will include all previous columns + + %col_name = () ; + + &add_db_fields ; + + unless ($double_box_layout) { $print_box_content_rows = &common_min_add_form($table,'save') ; } + +} #------------------------------------------------------------------------------------------ + +sub common_min_edit_screen { + +my $dbid = 'id' ; if ($uniq_id) { $dbid = $uniq_id ; } + +unless ($i{$dbid}) { $warning = uc "NO $dbid" ; return ; } + +&db_min_ro($table,'*',"`$dbid`='$i{$dbid}'",'','') ; + +$page_title = 'Edit' ; +$page_title .= " : $i{$dbid}" ; + +&edit_db_fields ; + +&edit_screen; + +unless ($double_box_layout) { $print_box_content_rows = &common_min_edit_form($i{$dbid},$table,'update') ; } + +} #------------------------------------------------------------------------------------------ + +sub common_min_view_screen { + +my $dbid = 'id' ; if ($uniq_id) { $dbid = $uniq_id ; } + +unless ($i{$dbid}) { $warning = uc "NO $dbid" ; return ; } + +&db_min_ro($table,'*',"`$dbid`='$i{$dbid}'",'','') ; + +$page_title = 'View' ; +$page_title .= " : $i{$dbid}" ; + +&view_db_fields ; + +&view_screen($i{$dbid}); + +} #------------------------------------------------------------------------------------------ + +sub common_min_delete { + +my $dbid = 'id' ; if ($uniq_id) { $dbid = $uniq_id ; } + +unless ($i{$dbid}) { $error = uc "NO $dbid" ; return ; } + +&db_min_delete($table,"$dbid='$i{$dbid}'") ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_search_screen { + +&thead; + +&common_min_alert_type ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_thead { + +$print_thead = qq() ; + +foreach (@sql_col_display) { + my $coltitle = $_ ; $coltitle =~ s/\_id//g ; $coltitle =~ s/\_/ /g ; $coltitle = uc $coltitle ; $coltitle = $replace_blank_table_top_right if $coltitle eq '' and $replace_blank_table_top_right ; + # $custom_column_styles{$_} = qq~style="min-width:120px;"~ unless $custom_column_styles{$_} ; + $print_thead .= qq($coltitle); +} + +if ($add_th_row) { $print_thead .= $add_th_row ; } # used in agent_commission_report.pl and cruiseline_commission_report.pl + +$print_thead .= qq() ; + +} #------------------------------------------------------------------------------- + +sub common_min_split_sql_date_time { + +my ($datetime) = @_ ; + +my ($date,$time) = split(/ /,$datetime) ; + +my $dy = substr($date,0,4) ; +my $dm = substr($date,5,2) ; +my $dd = substr($date,8,2) ; + +my ($th,$tm,$ts) = split(/:/,$time) ; + +return($dy,$dm,$dd,$th,$tm,$ts) ; + +} #------------------------------------------------------------------------------- + +sub common_min_convert_sql_date_time { + +my ($datetime) = @_ ; + +my ($date,$time) = split(/ /,$datetime) ; + +my $dy = substr($date,0,4) ; +my $dm = substr($date,5,2) ; +my $dd = substr($date,8,2) ; + +my ($th,$tm,$ts) = split(/:/,$time) ; + +my $return = "$dy$dm$dd" ; if ($time) { $return .= "$th$tm$ts" ; } + +return($return) ; + +} #------------------------------------------------------------------------------- + +sub common_min_restriction_super { + +unless ($useropts{super}{lc $username}){ print "This page is restricted!" ; exit ; } + +} #------------------------------------------------------------------------------- + +sub common_min_add_extras { + +my $page = "$lcpage\s" ; if ($s{no}) { $page = $lcpage ; } + +$box_icon = qq(
    ) ; + +$useropts{'common'}{'css'} .= qq(.box-icon a i { top:1px; } .iPhoneCheckContainer { margin:2px 0 2px 0; } .iPhoneCheckContainer label { font-size: 14px; line-height: 14px; padding-top:7px; } .iPhoneCheckLabelOff { padding-right:5px; } ) ; + +# $extra_css .= qq~~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_add_box_icon { + +my $page = "$lcpage\s" ; if ($s{no}) { $page = $lcpage ; } + +$box_icon = qq(
    ) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_screen1 { + +&thead; + +&common_min_alert_type ; + +my $page = "$lcpage\s" ; if ($s{no}) { $page = $lcpage ; } +my $ucfpage = "$ucfirstpage\s" ; if ($s{no}) { $ucfpage = $ucfirstpage ; } + +unless ($redirtype) { $redirtype = 'list' ; } my $pname = ucfirst $redirtype ; + +&common_min_extra_crumb("$redirtype-$page","$pname $ucfpage") ; + +# &common_min_extra_crumb("list-$page","List $ucfpage") ; + +if ($cust_cols or $double_box_layout) { + require _blank_3 ; + } +else + { + require _blank ; + } + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_screen2 { + +my $page = "$lcpage\s" ; if ($s{no}) { $page = $lcpage ; } + +unless ($redirsave) { $redirsave = 'list' ; } +# unless ($redirsave) { $redirsave = 'edit' ; } + +if ($i{id} and $iaction ne 'delete') { + &common_min_edit_screen ; + &common_min_screen1; + # $input_hidden_id = qq~~ ; +} + +# # if ($i{id} && $redirsave eq 'edit') { +# if ($redirsave eq 'edit') { + # $input_hidden_id = qq~~ ; +# } + +# my $doc_ready_jquery = qq~\$(document).ready(function(){ \$('#$redirsave-form').submit(); })~ unless $username eq 'rory' ; + +my $form_name = $redirsave . 'form' ; + +&common_min_alert_type ; + +print < + + + + $useropts{title} + + + + + + +
    + + +$input_hidden_id +
    + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +my $page = "$lcpage\s" ; if ($s{no}) { $page = $lcpage ; } + +&common_min_table('id',$page,'list') ; + +# &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_opts { + +my ($whichone,$field,$deselect) = @_ ; + +if ($whichone eq 'leave_type') { + $required{$field} = 1 ; + $select{$field} = 1 ; + $opts{$field} = qq( + + + + ) ; + } + +my $ucfirst_field = ucfirst $field ; + +if ($deselect){ + $trigger_jquery_raw .= qq(\$("#select$ucfirst_field").chosen({ allow_single_deselect:true });) ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_dialog_load_screen { + +&dialog_common ; + +print < + + + $alert + +
    +
    +
    +
    + $print_box_content_rows +
    +
    +
    +
    + +
    + +
    + + + + + + + + + + + +ENDOFTEXT +# + +exit; + +} #------------------------------------------------------------------------------------------ + +sub common_min_dialog_save_screen { + +print < + + + + ITV Admin + + + + + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_validate_date_inputs_jquery { + + my $date_value_ids_str = join(",",@date_value_ids) ; + + return unless $date_value_ids_str ; + + $trigger_jquery_raw .= qq~ + + function isLeapYear(year) { + return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0); + } + + function isValidDate(dateString) { + + let count_comp = 0 ; let found_non_int = 0 ; + + for (let key in dateString.split('-').map(Number)) { + count_comp++ ; + if (dateString.split('-').map(Number)[key] != parseInt(dateString.split('-').map(Number)[key])) { + found_non_int = 1 ; + } + } + + if (count_comp != 3 || found_non_int) { + return false + } else { + return true ; + } + + } + + \$("$date_value_ids_str").change( function () { + + // console.log("date_value_ids_str : $date_value_ids_str") ; + + const dateInput = \$(this).val() ; + + if (!dateInput) { + return ; + } + + let result = "" ; + + if (!isValidDate(dateInput)) { + result = "Invalid Date Format!!!"; + } + + let [inputYear,inputMonth,inputDay] = dateInput.split("-").map(Number); + + if (inputYear > 2100 || inputYear < 2000) { + if (result) { + result = result + "
    "; + } + result = result + "Invalid Year!!!"; + } + + if (inputMonth < 1 || inputMonth > 12) { + if (result) { + result = result + "
    "; + } + result = result + "Invalid Month!!!"; + } + + const daysInMonth = [31, (isLeapYear(inputYear) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + + if (inputDay < 1 || inputDay > daysInMonth[inputMonth - 1]) { + if (result) { + result = result + "
    "; + } + result = result + "Invalid Day!!!"; + } + + if (result) { + + noty({text:result,layout:"center",type:"error",timeout:3000}) ; + + } else { + + let correct_day_or_month_format = 0 ; + + if (inputMonth > 0 && inputMonth < 10) { + inputMonth = inputMonth.toString() ; + inputMonth = inputMonth.padStart(2,'0'); + correct_day_or_month_format = 1 ; + } + if (inputDay > 0 && inputDay < 10) { + inputDay = inputDay.toString() ; + inputDay = inputDay.padStart(2,'0'); + correct_day_or_month_format = 1 ; + } + if (correct_day_or_month_format) { + \$("#"+this.id).val(inputYear+"-"+inputMonth+"-"+inputDay) ; + } + } + + }) ; + + ~ ; +} #------------------------------------------------------------------------------------------ + +sub common_min_table_update_checkbox_col_default { + + my $default_javascript_by_id_str = join ",", @default_javascript_by_id ; + + if ($default_javascript_by_id_str) { + $trigger_jquery_raw .= qq~ + let all_def_vals = {$default_javascript_by_id_str} ; + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_update_checkbox_col_jquery { + + my ($nr_of_characters_in_id_to_determine_row,$content_id,$update_fields_short_1,$update_fields_short_2) = @_ ; + + $content_id = "content" unless $content_id ; + + $nr_of_characters_in_id_to_determine_row = 1 unless $nr_of_characters_in_id_to_determine_row ; + + my $jquery_on_change_1 = "" ; + my $jquery_on_change_2 = "" ; + + if ($update_fields_short_1 || $update_fields_short_2) { + + ## NEW WAY + + $jquery_on_change_1 = qq~\$("#$content_id").on("change","$update_fields_short_1", function (event) {~ if $update_fields_short_1 ; # EXAMPLE: [id^='selectFixture_check_'],[id^='selectStatus_'] + $jquery_on_change_2 = qq~\$("#$content_id").on("changeDate","$update_fields_short_2", function (event) {~ if $update_fields_short_2 ; + + } else { + + ## OLD WAY + + my @all_update_field_ids_1 = () ; my @all_update_field_ids_2 = () ; + + foreach my $fields (@all_update_field_ids) { + foreach (split(/\,/,$fields)) { + if ($_ =~ /#datepicker/ || $_ =~ /#datetimepicker/ || $_ =~ /#timepicker/) { + push @all_update_field_ids_2,$_ ; + } else { + push @all_update_field_ids_1,$_ ; + } + } + } + + # my $all_update_field_ids_str = join "," , @all_update_field_ids ; + my $all_update_field_ids_str_1 = join "," , @all_update_field_ids_1 ; + my $all_update_field_ids_str_2 = join "," , @all_update_field_ids_2 ; + + $jquery_on_change_1 = qq~\$("$all_update_field_ids_str_1").change( function (event) {~ if $all_update_field_ids_str_1 ; + $jquery_on_change_2 = qq~\$("$all_update_field_ids_str_2").on('changeDate',function() {~ if $all_update_field_ids_str_2 ; + + } + + chop $multi_select_ids if $multi_select_ids ; + + if ($jquery_on_change_1 || $jquery_on_change_2) { + + $trigger_jquery_raw .= qq~ + + function get_row_nr (id,nr_of_characters_in_id_to_determine_row) { + + // console.log("get_row_nr : "+id) ; + // console.log("nr_of_characters_in_id_to_determine_row : "+nr_of_characters_in_id_to_determine_row) ; + + let lastIndex = id.lastIndexOf('_'); + lastIndex = parseInt(lastIndex) ; + let row_nr_1 = id.substring(1+lastIndex); + + if (!nr_of_characters_in_id_to_determine_row || nr_of_characters_in_id_to_determine_row == 1) { + return row_nr_1 ; + } + + let id_2 = id.substring(0,lastIndex); + lastIndex = id_2.lastIndexOf('_'); + lastIndex = parseInt(lastIndex) ; + let row_nr_2 = id_2.substring(1+lastIndex); + + if (nr_of_characters_in_id_to_determine_row == 2) { + return row_nr_2+"_"+row_nr_1 ; + } + + let id_3 = id_2.substring(0,lastIndex); + lastIndex = id_3.lastIndexOf('_'); + lastIndex = parseInt(lastIndex) ; + let row_nr_3 = id_3.substring(1+lastIndex); + + if (nr_of_characters_in_id_to_determine_row == 3) { + // console.log("return : "+row_nr_3+"_"+row_nr_2+"_"+row_nr_1) ; + return row_nr_3+"_"+row_nr_2+"_"+row_nr_1 ; + } + + } + + function check_whether_to_update (changed_id) { + + let row_nr = get_row_nr(changed_id) ; + + $trigger_jquery_raw_default_alt + + let nr_of_characters_in_id_to_determine_row = "$nr_of_characters_in_id_to_determine_row" ; + + if (row_nr == "row") { + row_nr = "add_row" ; + } else if (nr_of_characters_in_id_to_determine_row == "2") { + // Nothing Yet + row_nr = get_row_nr(changed_id,2) ; + } else if (nr_of_characters_in_id_to_determine_row == "3") { + row_nr = get_row_nr(changed_id,3) ; + } + + let def_vals = all_def_vals[row_nr] ; + + + console.log("changed_id val : "+\$("#"+changed_id).val()) ; + + let tick_update = 0 ; + + let multi_select_ids = {$multi_select_ids} ; + + for (const id in def_vals) { + + console.log("def_vals : "+\$("#"+id).val()) ; + + if ((\$("#"+id).attr('type') == 'radio' && (\$("#"+id).is(":checked") !== (def_vals[id] === "true"))) || (id.includes('input[name') && def_vals[id] != \$(id).val())) { + tick_update = 1 ; + } else if (id.includes('datepicker') || id.includes('timepicker')) { + console.log("1 tick_update : "+tick_update) ; + console.log("11 def_vals : "+def_vals[id]) ; + console.log("22 def_vals : "+\$("#"+id).data("date")) ; + if (def_vals[id] != \$("#"+id).data("date")) { + tick_update = 1 ; + } + console.log("2 tick_update : "+tick_update) ; + } else if (\$("#"+id).attr('type') == 'checkbox') { + if ((\$("#"+id).is(":checked") !== (def_vals[id] === "true")) || (!\$("#"+id).is(":checked") !== (def_vals[id] === "false"))) { + tick_update = 1 ; + } + } else if (!multi_select_ids[id] && !id.includes('input[name') && \$("#"+id).attr('type') != 'radio') { + + let sel_val = \$("#"+id).val() ; + if (sel_val == null) { + sel_val = '' ; + } + if (sel_val != def_vals[id]) { + tick_update = 1 ; + } + + } else if (multi_select_ids[id]) { + + let select_multi = \$("#"+id).chosen().val() ; + if (select_multi == null) { select_multi = "" ; } + if (select_multi != def_vals[id]) { + tick_update = 1 ; + } + } + + + + } + + if (tick_update && !\$("#checkboxUpdate_"+row_nr).is(":checked")) { + \$("#checkboxUpdate_"+row_nr).prop("checked",true) ; + } else if (!tick_update && \$("#checkboxUpdate_"+row_nr).is(":checked")) { + \$("#checkboxUpdate_"+row_nr).prop("checked",false) ; + } + } + ~ ; + + # $trigger_jquery_raw .= ($ids_short) ? qq~ + # \$("#$content_id").on("change","$update_fields_short_1", function (event) { // EXAMPLE: [id^='selectFixture_check_'],[id^='selectStatus_'] + # event.preventDefault(); + # check_whether_to_update(this.id); + # }); + # ~ : qq~ + # // \$("$all_update_field_ids_str_1").change( function (event) { + # $jquery_on_change_1 + # event.preventDefault(); + # $trigger_jquery_raw_on_change_1 + # check_whether_to_update(this.id) ; + # }) ; + + # ~ ; + + $trigger_jquery_raw .= qq~ + $jquery_on_change_1 + event.preventDefault(); + check_whether_to_update(this.id); + }); + ~ if $jquery_on_change_1 ; + + $trigger_jquery_raw .= qq~ + $jquery_on_change_2 + $trigger_jquery_raw_on_change_2 + check_whether_to_update(this.id) ; + }) ; + + ~ if $jquery_on_change_2 && !$no_dates_in_table ; + # unless $no_dates_in_table ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_update_checkbox_col { + + my ($nr_of_characters_in_id_to_determine_row,$content_id,$ids_short_1,$ids_short_2) = @_ ; + + &common_min_table_update_checkbox_col_default ; + + &common_min_table_update_checkbox_col_jquery($nr_of_characters_in_id_to_determine_row,$content_id,$ids_short_1,$ids_short_2) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_checkbox { + + my ($field_id,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved) = @_ ; + + if (!$only_display_val) { + my $ucfirstfield = ($ucfirstfield{$field_id}) ? $ucfirstfield{$field_id} : "checkbox" . ucfirst $field_id ; + $val = qq~~ ; + } else { + $val = qq~~ ; + } + $val_min = '' ; + return $val ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_textarea { + + my ($field_id,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved,$col_name,$table_id,$hide_textarea) = @_ ; + + $val = '' ; $val_min = 'MUSTBEBLANK' ; + + $table_id = "itv-table" unless $table_id ; + + if (!$only_display_val && $table_col) { + $found_editable = 1 ; + # my $print_field = ($preferred_placeholder{$field_id}) ? $preferred_placeholder{$field_id} : &common_min_print_field($field_id) ; + my $print_field = ($preferred_placeholder{$field_id}) ? $preferred_placeholder{$field_id} : ($preferred_title{$field_id}) ? $preferred_title{$field_id} : &common_min_print_field($field_id) ; + + $tindex++ ; + + $val_min = $default_val if $default_val ; + + my $ucfirstfield = ($ucfirstfield{$field_id}) ? $ucfirstfield{$field_id} : "textarea" . ucfirst $field_id ; + + # my $style = ($default_val && $default_val =~ /\n/) ? qq~style="height:100%;"~ : qq~~ ; + + # $default_val =~ s/\\n/\n/g ; + + $hide_textarea = ($hide_textarea) ? qq~display:none;~ : qq~~ ; + + $val = qq~ +
    +
    + +
    +
    + ~ ; + + # $default_val =~ s/\n/\\n/g ; + $default_val =~ s/[\n\r]+/\\n/g ; + + if ($default_val && $default_val_is_saved) { + $background_color = "#424949" unless $background_color ; + $table_with_default_ids{$background_color} .= "#$table_id tr:eq($table_row) td:nth-last-child($table_col)," ; + # $trigger_jquery .= qq~ \$("#$ucfirstfield").css("width","100%") ;~ ; + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ ; + } elsif ($default_val && !$default_val_is_saved) { + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ ; + } else { + $default_javascript .= qq~"$ucfirstfield":"",~ ; + } + + # box-sizing:border-box;overflow:hidden; + # box-sizing:border-box;overflow: hidden; + # oninput="adjustHeight(this)" row="1" + + # $trigger_jquery .= qq~ + # window.onload = function() { + # var textarea = document.getElementById('$ucfirstfield'); + # adjustHeight(textarea,'$ucfirstfield'); + # }; + # ~ ; + + # $trigger_jquery .= qq~ + # \$("#$ucfirstfield").css("width","100%") ; + # ~ ; + + #$trigger_jquery_raw .= qq~ + # \$('#$ucfirstfield').on('input', function() { + # // this.style.height = 'auto' ; + # // this.style.height = (this.clientHeight) + 'px'; + # }) ; + # \$('#$ucfirstfield').trigger('input'); + # ~ ; + + } elsif ($default_val) { + $val = $default_val ; + $val_min = $val ; + $val =~ s/\n/\
    /g ; + } + + $val_min =~ s/\\n/ /g ; + + return $val ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_input { + + my ($field_id,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved,$col_name,$table_id,$hide_input_field) = @_ ; + + $val = '' ; $val_min = 'MUSTBEBLANK' ; + + if (!$only_display_val) { + $found_editable = 1 ; + # my $print_field = ($preferred_placeholder{$field_id}) ? $preferred_placeholder{$field_id} : &common_min_print_field($field_id) ; + my $print_field = ($preferred_placeholder{$field_id}) ? $preferred_placeholder{$field_id} : ($preferred_title{$field_id}) ? $preferred_title{$field_id} : &common_min_print_field($field_id) ; + $tindex++ ; + + my $ucfirstfield = ($ucfirstfield{$field_id}) ? $ucfirstfield{$field_id} : "input" . ucfirst $field_id ; + + $hide_input_field = qq~display:none;~ if $hide_input_field ; + + $val = qq~
    +
    ~ ; + + # $trigger_jquery .= qq~ \$("#$ucfirstfield").css("width","100%") ;~ ; + if ($default_val && $default_val_is_saved) { + $background_color = "#424949" unless $background_color ; + $table_with_default_ids{$background_color} .= "#itv-table tr:eq($table_row) td:nth-last-child($table_col)," ; + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ ; + $val_min = $default_val ; + } else { + $val_min = '' ; + $default_javascript .= qq~"$ucfirstfield":"",~ ; + } + } else { + $val = $default_val ; + $val_min = $val ; + } + + return $val ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_select { + + my ($field_id,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved,$col_name,$table_id,$tooltip_1_text) = @_ ; + + if ($multiple{$field_id}) { $setmultiple = 'multiple' ; } else { $setmultiple = '' ; } + + $table_id = "itv-table" unless $table_id ; + + $val = '' ; + # $val_min = 'MUSTBEBLANK' ; + + # if (!$only_display_val && $table_col) { + if (!$only_display_val) { + + $found_editable = 1 ; + + my $ucfirstfield = ($ucfirstfield{$field_id}) ? $ucfirstfield{$field_id} : "select" . ucfirst $field_id ; + + my $print_field = ($preferred_placeholder{$field_id}) ? $preferred_placeholder{$field_id} : ($preferred_title{$field_id}) ? "Select $preferred_title{$field_id}" : "Select " . &common_min_print_field($field_id) ; + + push @all_select_ids,"#$ucfirstfield" if $ucfirstfield ; + if ($multiple{$field_id}) { + push @all_multi_select_ids,"#$ucfirstfield" if $ucfirstfield ; + $multi_select_ids .= qq~"$ucfirstfield":"1",~ if $ucfirstfield ; + push @dropdown_multi_chosen_ids,"#$ucfirstfield\_chosen" if $ucfirstfield ; + + } + + # $table_select_rows{$table_row} .= qq~#itv-table tr:eq($table_row) td:nth-last-child($table_col),~ ; + + # $trigger_jquery_raw .= qq~ + # \$("#$ucfirstfield").chosen({ allow_single_deselect:true }) ; \$("#itv-table tr:eq($table_row) td:nth-last-child($table_col)").css("z-index","$table_row") ; + # ~ ; + + # my $tooltip_1 = qq~~ ; + # if ($tooltip_1_text) { + # $tooltip_1 = qq~title data-toggle='tooltip' data-placement='top' data-original-title='$tooltip_1_text'~ ; + # } + + if ($tooltip_1_text) { + $add_tooltip{$tooltip_1_text} .= "#$ucfirstfield\_chosen," ; + } + + if (!$col_name) { + + $val = qq~ + + ~ ; + + } else { + $val = qq~ + + ~ ; + $opts{$col_name} = $opts{$field_id} unless $opts{$col_name} ; + $col_name_select_ids{$col_name} .= "#$ucfirstfield," ; + + } + + if ($default_val) { + unless ($val_min) { + $val_min = $default_val ; + $val_min =~ s/\_/ \[/g ; + $val_min .= qq~]~ if $val_min =~ /\[/; + } + + push @selects_with_default_ids,"#$ucfirstfield" if $ucfirstfield ; + + # foreach (split(/\,/,$default_val)) { + $selects_by_def_val{$default_val} .= "#$ucfirstfield," if $ucfirstfield ; + # } + + + # $trigger_jquery_raw .= qq~ + # \$("#$ucfirstfield").val("$default_val") ; + # ~ ; + + # if ($default_val_is_saved) { + if ($default_val_is_saved && $table_col) { + $background_color = "#424949" unless $background_color ; + $table_with_default_ids{$background_color} .= "#$table_id tr:eq($table_row) td:nth-last-child($table_col)," ; + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ ; + } elsif ($default_val_is_saved && !$table_col) { + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ ; + } else { + $default_javascript .= qq~"$ucfirstfield":"",~ ; + } + + } else { + $default_javascript .= qq~"$ucfirstfield":"",~ ; + } + if ($ucfirstfield) { push @dropdown_chosen_ids,"#$ucfirstfield\_chosen" unless $multiple{$field_id} ; } + + } elsif ($default_val) { + $val = $default_val ; + $val_min = $default_val ; + $val_min =~ s/\_/ \[/g ; + $val_min .= qq~]~ if $val_min =~ /\[/; + + # $val =~ s/\_/\[/g ; + $val =~ s/\_//g ; + # $val .= qq~]~ ; + # $val_min = $val unless $val_min ; + $table_with_default_ids{$background_color} .= "#$table_id tr:eq($table_row) td:nth-last-child($table_col)," if $background_color && $background_color ne "#424949" ; + } + + return $val ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_textarea_jquery { + + # $trigger_jquery .= qq~ + # function adjustHeight(textarea,id) { + + # textarea.style.height = 'auto'; // Reset height to auto to get the scroll height + # // textarea.style.height = textarea.scrollHeight + 'px'; // Set the height to the scroll height + + # \$("#"+id).css("height",textarea.scrollHeight+"px") ; + + # console.log("scrollHeight : "+textarea.scrollHeight) ; + # console.log("textarea : "+textarea) ; + # console.log("id : "+id) ; + + # } + # ~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_select_jquery { + + my ($columns_with_selects,$table_id) = @_ ; + + &common_min_table_select_fixed_width_jquery($columns_with_selects) ; + + &common_min_table_select_prevent_dropdown_overlap_jquery($table_id) ; + + &common_min_table_select_default_values_jquery ; + + &common_min_table_multi_select_jquery ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_select_fixed_width_jquery { + + my ($columns_with_selects) = @_ ; + + return unless $columns_with_selects ; + + $trigger_jquery_raw .= qq~ + \$("$columns_with_selects").css("position","relative") ; + \$("$columns_with_selects").css("text-align","center") ; + ~ ; + + my $dropdown_chosen_ids_str = join(',',@dropdown_chosen_ids) ; + my $dropdown_multi_chosen_ids_str = join(',',@dropdown_multi_chosen_ids) ; + + $trigger_jquery .= qq~ + \$("$dropdown_multi_chosen_ids_str").css("width","100%") ;~ if $dropdown_multi_chosen_ids_str ; + + return unless $dropdown_chosen_ids_str ; + + $trigger_jquery .= qq~ + \$("$dropdown_chosen_ids_str").css("position","absolute") ;~ ; + $trigger_jquery .= qq~ + \$("$dropdown_chosen_ids_str").css("width","90%") ;~ ; + $trigger_jquery .= qq~ + \$("$dropdown_chosen_ids_str").css("left","5%") ;~ ; + $trigger_jquery .= qq~ + \$("$dropdown_chosen_ids_str").css("top","50%") ;~ ; + $trigger_jquery .= qq~ + \$("$dropdown_chosen_ids_str").css("transform","translateY(-50%)") ;~ ; + + foreach (keys %add_tooltip) { + chop $add_tooltip{$_} ; + + $trigger_jquery .= qq~ + \$("$add_tooltip{$_}").attr({ + title : '', + 'data-original-title': '$_', + 'data-toggle': 'tooltip', + 'data-placement': 'top' + }); + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_select_prevent_dropdown_overlap_jquery_1 { + + my ($table_id) = @_ ; + + $table_id = "$useropts{table_id}" unless $table_id ; + + $trigger_jquery .= qq~ + + function prevent_drop_down_overlap (loading_page) { + + const table_ = \$('#$table_id').DataTable()._('tr') ; + // var table_ =\$("#$table_id").find('tr') ; + let row_nr = 1 ; + let z_index = 1 ; + + for (let i = table_.length; i >= 1 ; i--) { + + if (loading_page) { + $hide_other_column_for_logistics_report + $hide_columns_by_default + } + + if (!\$("#$table_id tr:eq("+i+") td:nth-last-child(1)").find('input').length && !\$("#$table_id tr:eq("+i+") td:nth-last-child(2)").find('input').length) { + continue ; + } + + let columns = table_[row_nr - 1]; + + for (let col_nr = 1; col_nr <= columns.length ; col_nr++) { + + if (!\$("#$table_id tr:eq("+i+") td:nth-last-child("+col_nr+")").find('select').length) { + continue ; + } + \$("#$table_id tr:eq("+i+") td:nth-last-child("+col_nr+")").css("z-index",z_index) ; + z_index++ ; + } + row_nr++ ; + } + // table_ = "" ; + } + + \$('#$table_id th').on('click', function() { + prevent_drop_down_overlap(0) ; + }); + + // \$("#select_temp_calibrators_2_length").css("display","none"); + // \$("#select_temp_calibrators_2_filter").css("display","none"); + // \$("#select_temp_calibrators_2_info").css("display","none"); + // \$("#select_temp_calibrators_2_paginate").css("display","none"); + + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_select_prevent_dropdown_overlap_jquery_2 { + + $trigger_jquery .= qq~ + prevent_drop_down_overlap(1) ; + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_select_prevent_dropdown_overlap_jquery { + + my ($table_id) = @_ ; + + &common_min_table_select_prevent_dropdown_overlap_jquery_1($table_id) ; + &common_min_table_select_prevent_dropdown_overlap_jquery_2 ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_select_default_values_jquery { + + foreach my $col_name (keys %col_name_select_ids) { + chop $col_name_select_ids{$col_name} if $col_name_select_ids{$col_name} ; + $opts{$col_name} =~ s/\"/\'/g ; + $opts{$col_name} =~ s/\' >/\'>/g ; + $opts{$col_name} =~ s/\' >/\'>/g ; + $trigger_jquery_raw .= qq~ + \$("$col_name_select_ids{$col_name}").html("$opts{$col_name}").trigger("chosen:updated") ; + ~ ; + } + + my $all_select_ids_str = join(",",@all_select_ids) ; + + $trigger_jquery_raw .= qq~\$("$all_select_ids_str").chosen({ allow_single_deselect:true }) ;~ ; + + # $trigger_jquery_raw .= qq~ + # \$("$all_select_ids_str").on("change", function () { + # console.log("FOCUS!!!!") ; + # event.preventDefault() ; + # }) ; + # ~ ; + + # $trigger_jquery_raw .= qq~ + # // \$("$all_select_ids_str").change( function () { + # // console.log("preventDefault") ; + # // event.preventDefault() ; + # // let scrollContainer = \$('#itv-table_wrapper') ; + # // let scrollPosition = scrollContainer.scrollLeft() ; + # // console.log("scrollPosition : "+scrollPosition) ; + # // scrollContainer.scrollLeft(scrollPosition) ; + + # // }) ; + # ~ ; + + foreach (keys %table_with_default_ids) { + chop $table_with_default_ids{$_} if $table_with_default_ids{$_} ; + $trigger_jquery_raw .= qq~ + \$("$table_with_default_ids{$_}").css("background-color","$_") ; + ~ ; + } + + foreach my $def_val (keys %selects_by_def_val) { + chop $selects_by_def_val{$def_val} if $selects_by_def_val{$def_val} ; + my $def_val2 = $def_val ; + if ($def_val2 =~ /,/) { + $def_val2 =~ s/\,/\','/g ; + $def_val2 = qq~['$def_val2']~ ; + $trigger_jquery_raw .= qq~ + \$("$selects_by_def_val{$def_val}").val($def_val2).trigger("chosen:updated") ; + ~ ; + } else { + + # foreach (split(/\,/,$selects_by_def_val{$def_val})) { + # $trigger_jquery_raw .= qq~ + # \$("$_").val("$def_val2").trigger("chosen:updated") ; + # ~ ; + # } + $trigger_jquery_raw .= qq~ + \$("$selects_by_def_val{$def_val}").val("$def_val2").trigger("chosen:updated") ; + ~ ; + } + + } + + # my $selects_with_default_ids_str = join(',',@selects_with_default_ids) ; + # $trigger_jquery_raw .= qq~ + # \$("$selects_with_default_ids_str").trigger("chosen:updated") ; + # ~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_multi_select_jquery { + + # my $all_multi_select_ids_str = join(",",@all_multi_select_ids) ; + + # foreach (@all_multi_select_ids) { + # $trigger_jquery_raw .= qq~set_row_height("$_") ; ~ ; + # } + + # $trigger_jquery_raw .= qq~ + + # function set_row_height (multi_id) { + + # let row_nr = get_row_nr(multi_id) ; + # let numOptions = \$(multi_id).find('option:selected').length; + # var optionHeight = 25; + # var padding = 40 ; + # let numOptions2 = Math.floor(numOptions/3) ; + + # var newHeight = numOptions * optionHeight + padding; + # console.log("set_row_height : "+multi_id) ; + + # if (numOptions == '3' || numOptions2 == '0') { + # newHeight = 0 ; + # } + # \$("#"+row_nr).height(newHeight); + # } + + # \$("$all_multi_select_ids_str").change( function() { + # set_row_height("#"+this.id) ; + # }); + + # ~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_datepicker { + + my ($field_id,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved,$col_name,$table_id,$icon_color,$tooltip_text,$tooltip_1_text,$tooltip_2_text) = @_ ; + + if ($default_val eq '0000-00-00') { $default_val = '' ; } + + if (!$only_display_val) { + + my $ucfirstfield = ($ucfirstfield{$field_id}) ? $ucfirstfield{$field_id} : "datepicker" . ucfirst $field_id ; + + $tindex++ ; + + my $tooltip_1 = qq~~ ; my $tooltip_2 = qq~~ ; + + if ($tooltip_1_text) { + $tooltip_1 = qq~title data-toggle='tooltip' data-placement='top' data-original-title='$tooltip_1_text'~ ; + } + + if ($default_val && $add_datepicker_tooltip{$field_id}) { + $tooltip_2 = qq~title data-toggle='tooltip' data-placement='top' data-original-title='$default_val'~ ; + } elsif ($tooltip_2_text) { + $tooltip_2 = qq~title data-toggle='tooltip' data-placement='top' data-original-title='$tooltip_2_text'~ ; + } + + if (!$default_val) { $default_val = "$now_year-$now_mm-$now_dd" ; } ; + + $icon_color = (!$icon_color) ? 'black' : $icon_color ; + + $val = qq~ +
    + + + + +
    + ~ ; + + if ($default_val_is_saved) { + $background_color = "#424949" unless $background_color ; + $table_with_default_ids{$background_color} .= "#itv-table tr:eq($table_row) td:nth-last-child($table_col)," if $table_row && $table_col ; + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ if $ucfirstfield ; + $val_min = $default_val ; + } else { + $default_javascript .= qq~"$ucfirstfield":"",~ if $ucfirstfield ; + $val_min = '' ; + } + push @all_datepicker_ids,"#$ucfirstfield" if $ucfirstfield ; + push @all_datepicker_names,"input[name='$field_id']" if $field_id ; + + } else { + $val = $default_val ; + $val_min = $val ; + } + +# &common_min_form_datepicker_jquery($ucfirst_field); + + return ($val) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_datepicker_jquery { + + our $all_datepicker_ids_str = join(",",@all_datepicker_ids) ; + + $trigger_jquery_raw .= qq~ + \$('$all_datepicker_ids_str').datepicker({format: "yyyy-mm-dd"}).on('changeDate', function (ev) { + \$('.datepicker').hide(); + \$("input[name='"+this.id.substring(10).toLowerCase()+"']").val(\$("#"+this.id).data("date")) ; + }) ; + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_timepicker { + + my ($field_id,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved,$col_name,$table_id,$icon_color,$tooltip_1_text,$tooltip_2_text) = @_ ; + + $tindex++; + $val = '' ; $val_min = '' ; + + if (!$only_display_val) { + + my $ucfirstfield = ($ucfirstfield{$field_id}) ? $ucfirstfield{$field_id} : "timepicker" . ucfirst $field_id ; + + if (!$default_val) { $default_val = "$now_hour:$now_min:$now_sec" ; } ; + + my $tooltip_1 = qq~~ ; my $tooltip_2 = qq~~ ; + + if ($tooltip_1_text) { + $tooltip_1 = qq~title data-toggle='tooltip' data-placement='top' data-original-title='$tooltip_1_text'~ ; + } + + if ($default_val && $add_timepicker_tooltip{$field_id}) { + $tooltip_2 = qq~title data-toggle='tooltip' data-placement='top' data-original-title='$default_val'~ ; + } elsif ($tooltip_2_text) { + $tooltip_2 = qq~title data-toggle='tooltip' data-placement='top' data-original-title='$tooltip_2_text'~ ; + } + + $icon_color = (!$icon_color) ? 'black' : $icon_color ; + + # + # + # + + # + + $val = qq~ +
    + + + + +
    + ~ ; + + if ($default_val && $default_val_is_saved) { + $background_color = "#424949" unless $background_color ; + $table_with_default_ids{$background_color} .= "#itv-table tr:eq($table_row) td:nth-last-child($table_col)," if $table_row && $table_col ; + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ if $ucfirstfield && $default_val ; + $val_min = $default_val ; + } else { + $default_javascript .= qq~"$ucfirstfield":"$default_val",~ if $ucfirstfield ; + $val_min = '' ; + } + push @all_timepicker_ids,"#$ucfirstfield" if $ucfirstfield ; + push @all_timepicker_names,"input[name='$field_id']" if $field_id ; + # $trigger_jquery_raw .= qq(\$('#timepicker$ucfirst_field').datetimepicker({language:'pt-BR',pickDate:false});) ; + } else { + $val = $default_val ; + $val_min = $val ; + } + return $val ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_table_timepicker_jquery { + + my ($ids_short) = @_ ; + + if ($ids_short) { + $trigger_jquery_raw .= qq~\$("$ids_short").datetimepicker({language:'pt-BR',pickDate:false});~ ; + return ; + } + + our $all_timepicker_ids = join(",",@all_timepicker_ids) ; + + $trigger_jquery_raw .= qq~\$('$all_timepicker_ids').datetimepicker({language:'pt-BR',pickDate:false});~ ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_get_event_quote_button { + + my ($event_id,$table,$page_url_part) = @_ ; + + $table = "event_quotes" unless $table ; + + return unless $event_id ; + + my $class = 'info' ; my $style = '' ; my $does_not_exist = 0 ; + if ($db{$table}{$event_id}{demo_id}) { + $style = 'style="background-color:rgb(255,64,255);border-color:rgb(255,64,255);"'; # pink + $tt_txt = 'Demo' ; + if ($db{$table}{$event_id}{quote_completed}) { + $tt_txt = 'Completed ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_accepted}) { + $tt_txt = 'Accepted ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_rejected}) { + $tt_txt = 'Rejected ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_cancelled}) { + $tt_txt = 'Cancelled ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_created}) { + $tt_txt = 'Pending, Created by School Manager ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_pending}) { + $tt_txt = 'Pending ' . $tt_txt ; + } + } elsif ($analytics_events{$event_id}) { + $style = 'style="background-color:rgb(255,129,0);border-color:rgb(255,129,0);"'; # pink + $tt_txt = 'Analytics Event' ; + if ($db{$table}{$event_id}{quote_completed}) { + $tt_txt = 'Completed ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_accepted}) { + $tt_txt = 'Accepted ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_rejected}) { + $tt_txt = 'Rejected ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_cancelled}) { + $tt_txt = 'Cancelled ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_created}) { + $tt_txt = 'Pending, Created by School Manager ' . $tt_txt ; + } elsif ($db{$table}{$event_id}{quote_pending}) { + $tt_txt = 'Pending ' . $tt_txt ; + } + } elsif ($db{$table}{$event_id}{quote_completed} || $db{$table}{$event_id}{event_completed} || $quote_completed) { + $class = 'success' ; # green + $tt_txt = 'Completed' ; + } elsif ($db{$table}{$event_id}{quote_accepted} || $db{$table}{$event_id}{event_completed} || $quote_accepted) { + $class = 'info' ; # blue + $tt_txt = 'Accepted' ; + my @fixed_system_overall_statuses = split(/\;/,$db{$table}{$event_id}{fixed_system_overall_status}) ; + my @event_system_ids = split(/\;/,$db{$table}{$event_id}{event_system_id_multiple}) ; + my $event_sys_cnt = 0 ; my $event_sys_test_status = 0 ; my $got_some_fixed = 0 ; my $fixed_status_color = '164473' ; # Dark Blue + foreach my $event_id (@event_system_ids) { + if ($db{event_systems}{$event_id}{system_type} eq 'fixed') { + $tt_txt = 'Accepted and tests show All Clear for the Fixed Systems' if $tt_txt eq 'Accepted' ; + $got_some_fixed = 1 ; + if ($fixed_system_overall_statuses[$event_sys_cnt] == 3) { # Not Clear + $fixed_status_color = '5d09d3' ; # Dark Purple + $tt_txt = 'Accepted but Not Clear on some Fixed Systems' ; + } elsif ($fixed_system_overall_statuses[$event_sys_cnt] == 2) { # Sound Issue + $fixed_status_color = '5d092c' ; + $tt_txt = 'Accepted but Sound Issue found on some Fixed Systems' ; + } + } + $event_sys_cnt++ ; + } + if ($got_some_fixed) { $style = "style='background-color:#$fixed_status_color;border-color:#$fixed_status_color'"; } + } elsif ($db{$table}{$event_id}{quote_rejected} || $db{$table}{$event_id}{event_rejected} || $quote_rejected) { + $style = 'style="background-color:#ca0ad3;border-color:#ca0ad3"'; # purple + $tt_txt = 'Rejected' ; + } elsif ($db{$table}{$event_id}{quote_cancelled} || $db{$table}{$event_id}{event_cancelled} || $quote_cancelled) { + $class = 'danger' ; # red + $tt_txt = 'Cancelled' ; + } elsif ($db{$table}{$event_id}{quote_created} || $db{$table}{$event_id}{event_created} || $quote_created) { # create by schools_manager + $style = 'style="background-color:#f6e305;border-color:#f6e305"'; # yellow + $tt_txt = 'Pending, Created by School Manager' ; + } elsif ($db{$table}{$event_id}{quote_pending} || $db{$table}{$event_id}{event_pending} || $quote_pending) { + $class = 'warning' ; # orange + $tt_txt = ($db{$table}{$event_id}{sssadmin_quote_nr}) ? 'Pending [Created by SSS platform]' : 'Pending' ; + } elsif (!$db{$table}{$event_id}{id}) { + $style = 'style="background-color:black;border-color:black"'; + $tt_txt = 'Does not Exist!!!' ; + $does_not_exist = 1 ; + } + + my $tt = qq~data-toggle="tooltip" data-placement="right" data-title="$tt_txt"~; + # ($glod_user_level < 3 && !$is_operator) + + my $glod_user_level_eff = ($glod_user_level == 2 && $is_operator) ? 3 : $glod_user_level ; + + my $href = ($page_url_part) ? qq~javascript:editMinItem('$event_id','$page_url_part');~ : qq~javascript:editMinItem('$event_id');~ ; + + my $event_quote_btn = ($glod_user_level_eff < 3 || $db{$table}{$event_id}{quote_cancelled} || $does_not_exist) ? qq~$event_id~ : qq~$event_id~ ; + + # || ($db{$table}{$event_id}{quote_completed} && $glod_user_level <= 3) + + return ($event_quote_btn) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_get_quote_button { + + my ($quote_id,$table) = @_ ; + + $table = "quotes" unless $table ; + + return unless $quote_id ; + + my $class = 'info' ; my $style = '' ; my $tt_txt = '' ; + + if ($db{$table}{$quote_id}{quote_cancelled}) { + $class = 'danger' ; + $tt_txt = 'Cancelled' ; + } elsif ($db{$table}{$quote_id}{quote_accepted}) { + $class = 'success' ; + $tt_txt = 'Accepted' ; + } elsif ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd") { ### $quote_expiry must be defined + $class = 'danger' ; + $tt_txt = 'Expired' ; + } elsif ($db{$table}{$quote_id}{quote_pending}) { + $class = 'warning' ; + $tt_txt = 'Pending' ; + } + + my $tt = qq~data-toggle="tooltip" data-placement="right" data-title="$tt_txt"~; + + my $quote_btn = qq~$db{$table}{$quote_id}{quote_nr}~ ; + + return ($quote_btn) ; + +} #------------------------------------------------------------------------------------------ + +# sub common_min_date_as_string { + + # my ($date) = @_ ; + + # my ($yr,$mon,$day) = split("-",$date) ; ## our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + # return ("$day-$months[$mon]-$yr") ; + +# } #------------------------------------------------------------------------------------------ + +sub common_min_date_as_string { + + my ($date) = @_ ; + + return if $date !~ /(\d+)/g ; + + my ($yr,$mon,$day) = split("-",substr($date,0,10)) ; ## our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + if (substr($date,11,5)) { + return ("$day-$months[$mon]-$yr \@ " . substr($date,11,5)) ; + } else { + return ("$day-$months[$mon]-$yr") ; + } + +} #------------------------------------------------------------------------------------------ + +sub greater_date_time { + + local ($date_time_1,$date_time_2) = @_ ; + + return Time::Piece->strptime($date_time_1,'%Y-%m-%d %H:%M:%S') <= Time::Piece->strptime($date_time_2,'%Y-%m-%d %H:%M:%S') ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_greater_date_time { + + local ($date_time_1,$date_time_2) = @_ ; + + return Time::Piece->strptime($date_time_1,'%Y-%m-%d %H:%M:%S') <= Time::Piece->strptime($date_time_2,'%Y-%m-%d %H:%M:%S') ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_greater_date { + + local ($date_1,$date_2) = @_ ; + + return Time::Piece->strptime($date_1,'%Y-%m-%d') <= Time::Piece->strptime($date_2,'%Y-%m-%d') ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_calc_time_diff { + + local ($date_time_1,$date_time_2) = @_ ; + + return "blank_date" if !$date_time_1 || !$date_time_2 ; + + return (Time::Piece->strptime($date_time_2,'%Y-%m-%d %H:%M:%S') - Time::Piece->strptime($date_time_1,'%Y-%m-%d %H:%M:%S')) ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_calc_day_diff { + + local ($date_1,$date_2) = @_ ; + + return 1 + abs(Time::Piece->strptime(substr($date_2,0,10),'%Y-%m-%d') - Time::Piece->strptime(substr($date_1,0,10),'%Y-%m-%d'))->days ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_delete_files { + + my ($dir,$file_name) = @_ ; + + return if !$dir || ($dir && not -d $dir) || ($file_name && not -f "$dir/$file_name") ; + + my @files = () ; my $dh ; + if ($file_name) { + push @files,$file_name ; + } else { + opendir($dh, $dir) or die "Cannot open directory: $!"; + @files = grep { !/^\.\.?$/ } readdir($dh); + } + foreach my $file (@files) { + my $file_path = "$dir/$file" ; + if (-f $file_path) { + unlink ("$file_path") or print "\n unable to unlink - $file_path : $!"; + } + } + if (!$file_name) { + closedir($dh); + } + +} #------------------------------------------------------------------------------------------ + +sub common_min_copy_files { + + # # # # use File::Copy; Make Sure THis is called ; + + my ($dir_from,$dir_to,$file_name) = @_ ; + + return if !$dir_from || !$dir_to || not -d $dir_from || ($file_name && not -f "$dir_from/$file_name"); + + mkdir $dir_to if not -d $dir_to; + + my @files = () ; my $dh ; + + if ($file_name) { + push @files,$file_name ; + } else { + opendir($dh,$dir_from) or die "Can't open $dir_from: $!"; + my $file_counter = 0 ; + @files = readdir($dh); + } + + foreach my $file (@files) { + next if $file =~ /^\.\.?$/ ; + my $src_file = "$dir_from/$file"; + my $dst_file = "$dir_to/$file"; + if (-f $src_file) { + copy("$src_file","$dst_file") or die "File cannot be copied." ; + } + } + + if (!$file_name) { + closedir($dh); + } + +} #------------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/_FromProd/v1.0/common_test.pm b/libs/modules/_FromProd/v1.0/common_test.pm new file mode 100644 index 0000000..ff0364d --- /dev/null +++ b/libs/modules/_FromProd/v1.0/common_test.pm @@ -0,0 +1,1428 @@ +use common_min_test ; + +sub common_upload_files { + +my ($folder) = @_ ; + +for my $p ($q->param) { + if (substr($p,0,7) eq 'iattach') { + my $val = $q->param($p) ; + my $fol = substr($p,7) ; + &common_upload_file($val,$p,$fol,$folder) ; + } + } + +} #------------------------------------------------------------------------------------------ + +sub common_append_log { + +my ($log,$nline) = @_ ; + +unless ($log) { return ; } + +if (substr($now_min,0,1)==3) { &common_large_log($log,$nline) ; return ; } # run on 30 min for 10 min + +$nline =~ s/[ ]+/ /g ; # Replaces all occurances of two spaces with one space + +# my $serverpath = (substr($ENV{SERVER_NAME},0,6) eq 'client') ? 'gwtruckassist' : 'gatewaytruckassa' ; + +my $logfile = "/home/libs/data/logs/$log"; + +open (LFILE, ">>$logfile") or die "can't open $logfile : $!" ; +flock (LFILE, LOCK_EX) or die "can't lock $logfile : $!" ; +print LFILE $nline . "\n" ; +close (LFILE) ; + +} #---------------------------------------------------------------------------------------- + +sub common_large_log { + +my ($log,$nline) = @_ ; + +unless ($log) { return ; } + +$nline =~ s/[ ]+/ /g ; # Replaces all occurances of two spaces with one space +$nline =~ s/\n/ /g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc +$nline =~ s/\t/ /g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc +$nline =~ s/\r/ /g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc + +my $logfile = "/home/libs/data/logs/$log"; + +open (LFILE, "+>>$logfile") or die "can't open $logfile : $!" ; +flock (LFILE, LOCK_EX) or die "can't lock $logfile : $!" ; +seek (LFILE, 0, 0) or die "can't rewind $logfile : $!" ; +@lines = ; +seek (LFILE, 0, 0) or die "can't rewind $logfile : $!" ; +truncate (LFILE, 0) or die "can't truncate $logfile : $!" ; + +my @sort_lines = reverse sort @lines ; # put newest ones first + +my $log_cnt = 0 ; + +print LFILE $nline . "\n" ; + +foreach my $line (@sort_lines) { # 20181109104451|||| + chomp $line; + @linex = split(/\|/,$line); + + # my $hashkey = $linex[2] . $linex[3] . $linex[4] . substr($linex[5],0,12) ; + my $hashkey = $linex[2] . $linex[3] . $linex[4] . substr($linex[0],0,8) ; + + if ($done_log_line{$hashkey}) { next ; } + + if ($log_cnt > 10000) { last ; } # only retain 10000 lines + + print LFILE "$line\n"; + + $done_log_line{$hashkey} = 1 ; + + $log_cnt++; + } + +close (LFILE) ; + +} #---------------------------------------------------------------------------------------- + +sub common_write_log { + +my ($log,$nline) = @_ ; + +unless ($log) { return ; } + +$nline =~ s/\n//g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc +$nline =~ s/\t//g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc +$nline =~ s/\r//g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc +$nline =~ s/\f//g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc +$nline =~ s/[ ]+/ /g ; # Replaces all occurances of two spaces with one space +$nline =~ s/> <' with '><' + +# my $serverpath = (substr($ENV{SERVER_NAME},0,6) eq 'client') ? 'gwtruckassist' : 'gatewaytruckassa' ; + +my $logfile = "/home/libs/data/logs/$log"; + +open (LFILE, "+>>$logfile") or die "can't open $logfile : $!" ; +flock (LFILE, LOCK_EX) or die "can't lock $logfile : $!" ; +seek (LFILE, 0, 0) or die "can't rewind $logfile : $!" ; +@lines = ; +seek (LFILE, 0, 0) or die "can't rewind $logfile : $!" ; +truncate (LFILE, 0) or die "can't truncate $logfile : $!" ; + +my @sort_lines = reverse sort @lines ; # put newest ones first + +my $log_cnt = 0 ; + +print LFILE $nline . "\n" ; + +foreach my $line (@sort_lines) { # 20181109104451|||| + chomp $line; + @linex = split(/\|/,$line); + + if ($log_cnt > 5000) { last ; } # only retain 5000 lines + + print LFILE "$line\n"; + + $log_cnt++; + } + +close (LFILE) ; + +} #---------------------------------------------------------------------------------------- + +sub common_upload_file { + +my ($filename,$param,$type,$folder) = @_ ; + +unless ($filename) { return ; } + +$CGI::POST_MAX = 1024 * 5000; +my $safe_filename_characters = "a-zA-Z0-9_.-"; + +my $upload_dir = "$htmlpath/uploads/$folder"; +mkdir $upload_dir unless -d $upload_dir ; + +my ($name,$path,$extension) = fileparse ($filename, '..*') ; +$filename = $name . $extension; +$filename =~ tr/ /_/; +$filename =~ s/[^$safe_filename_characters]//g; + +if ( $filename =~ /^([$safe_filename_characters]+)$/ ) { $filename = "$type-$1" ; } else { die "Filename contains invalid characters" ; } + +$uploads_hash{$type}{$filename} = 1 ; +$uploads_file{$type} = $filename ; + +if (($testing == 1) and ($username eq 'rory')) { &common_debug("Upload $type - $filename") ; return; } + +my $upload_filehandle = $q->upload($param) ; + +open ( UPLOADFILE, ">$upload_dir/$filename" ) or die "can't open $upload_dir/$filename: $!" ; +flock (UPLOADFILE, LOCK_EX) or die "can't lock $upload_dir/$filename: $!" ; +binmode UPLOADFILE or die "$!" ; + +while ( <$upload_filehandle> ) { + print UPLOADFILE ; + } + +close UPLOADFILE; + +# my ($filename,$param,$type,$folder) = @_ ; + +# unless ($filename) { return ; } + +# $CGI::POST_MAX = 1024 * 5000; +# my $safe_filename_characters = "a-zA-Z0-9_.-"; +# my $upload_dir = "$htmlpath/uploads/$folder"; + +# mkdir $upload_dir unless -d $upload_dir ; + +# my ($name,$path,$extension) = fileparse ($filename, '..*') ; +# $filename = $name . $extension; +# $filename =~ tr/ /_/; +# $filename =~ s/[^$safe_filename_characters]//g; + +# if ( $filename =~ /^([$safe_filename_characters]+)$/ ) { + # $filename = $type . '_' . $now_ccyymmdd . $now_hour . $now_min . $now_sec . '_' . $1 ; + # } +# else + # { + # die "Filename contains invalid characters" ; + # } + +# my $upload_filehandle = $q->upload($param) ; + +# open ( UPLOADFILE, ">$upload_dir/$filename" ) or die "can't open $upload_dir/$filename $!" ; +# flock (UPLOADFILE, LOCK_EX) or die "can't lock $upload_dir/$filename: $!" ; +# binmode UPLOADFILE or die "$!" ; + +# while ( <$upload_filehandle> ) { + # print UPLOADFILE ; + # } + +# close UPLOADFILE; + +} #------------------------------------------------------------------------------------------ + +sub common_get_field_uploads { + +my ($id,$type,$folder) = @_ ; + +unless ($id and $type) { return() ; } + +my $uploads = '' ; my %uploads = () ; + +my $field = $type ; my ($doctype,$num) = split(/\_/,$field) ; $doctype .= 's' ; + +$table = $doctype unless $table ; + +my $doc = $db{$table}{$id}{$field} ; + +&common_debug("$doc") ; + +if ($doc){ + my $tooltip = qq~data-toggle="tooltip" data-placement="top" data-title="$doc"~ ; + my @docarr = split(/\./,$doc); my $ext = pop @docarr ; my $file = pop @docarr ; + my $dlg_title = uc substr($doc,0,4) . ' ' . $ext ; + $file_cnt++; + + my $test_icon_loc = qq~$htmlpath/img/icons/doc/$ext.png~; + my $icon_loc = qq~/img/icons/doc/$ext.png~; $icon_loc = qq~/img/icons/doc/def.png~ unless -f $test_icon_loc ; + + # $uploads{$type} .= qq~~ ; + $uploads{$type} .= qq~~ ; + + $trigger_jquery_raw .= qq(\$('#delete-attach-$id-$file_cnt').click(function (e) { + BootstrapDialog.confirm({ + title: 'Confirm Delete', + message: 'Are you sure you want to delete $doc?', + type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + callback: function(result) { + if(result) { + var url = "$useropts{scripts}/get/get_delete_attach.pl?$doctype/$db{$table}{$id}{$folder}&$doc&$table&$id&$field" ; + \$.get(url); + \$('#attach-$id-$file_cnt').hide() ; + \$('#delete-attach-$id-$file_cnt').hide() ; + }else { + // alert('Nope.'); + } + } + }); + });) ; + + # $uploads .= qq~~; + } + +if ($uploads{$type}) { $uploads = $uploads{$type} ; } + +return ($uploads) ; + +} #------------------------------------------------------------------------------------------ + +sub common_get_uploads { + +my ($id,$type) = @_ ; + +unless ($id and $type) { return() ; } + +my $upload_dir = "$htmlpath/uploads/$id"; + +&common_debug("$upload_dir") ; + +unless (-e $upload_dir) { return ; } + +my $uploads = '' ; + +opendir(DIR, "$upload_dir") or die "cant open directory $upload_dir: $!\n"; + +while(defined($folder = readdir(DIR))) { + if ($type ne 'all') { unless ((substr($folder,0,4) eq $type) or (substr($folder,0,5) eq $type)) { next ; } } + if (length($folder) > 2) { + my @docarr = split(/\./,$folder); my $ext = pop @docarr ; my $file = pop @docarr ; + my $dlg_title = uc substr($folder,0,4) . ' ' . $ext ; if (substr($folder,0,5) eq $type) { $dlg_title = uc substr($folder,0,5) . ' ' . $ext ; } # leave + $file_cnt++; + + my $tag_id = $id ; $tag_id =~ s/\//\-/gi ; + + if ($type eq 'all'){ + $uploads .= qq( ) ; + } + elsif ($type eq 'canx'){ + $uploads .= qq(); + } + else + { + $uploads .= qq(); + } + + $trigger_jquery_raw .= qq(\$('#delete-attach-$tag_id-$file_cnt').click(function (e) { + BootstrapDialog.confirm({ + title: 'Confirm Delete', + message: 'Are you sure you want to delete $folder?', + type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + callback: function(result) { + if(result) { + var url = "$useropts{scripts}/get/get_delete_attach.pl?$id&$folder" ; + \$.get(url); + \$('#attach-$tag_id-$file_cnt').hide() ; + \$('#delete-attach-$tag_id-$file_cnt').hide() ; + }else { + // alert('Nope.'); + } + } + }); + });) ; + } + } + +return ($uploads) ; + +} #------------------------------------------------------------------------------- + +# sub common_load_params { + +# for my $p ($q->param) { + # my $val = $q->param($p) ; + # $val =~ s/\"//g ; + # $i{$p} = $val ; + # # &common_debug("$p -> $p1 -> $p1cnt -> $val") ; + # if ($p =~ /\_/g){ + # my ($p1,$p1cnt) = split(/\_/,$p) ; + # $i{$p1}{$p1cnt} = $val ; + # # print "
    $p -> $p1 -> $p1cnt -> $val" ; + # } + # } + +# } #------------------------------------------------------------------------------------------ + +sub common_time_opts { + +for (1 .. 24) { + my $hh = sprintf("%02s",$_) ; + $hour_opts .= qq() ; + } + +for (1 .. 60) { + my $mm = sprintf("%02s",$_) ; + $min_opts .= qq() ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_curr_opts { + +$curr_opts = qq() ; +$curr_opts_2 = qq() ; + +} #------------------------------------------------------------------------------------------ + +# sub common_select_opts { + +# my ($field,$table,$dispfield,$fid,$required,$addfield,$where,$valfield,$addmore) = @_ ; + +# $select{$field} = 1 ; + +# my $val = '' ; + +# if ($required) { $required{$field} = 1 ; } + +# &db_min_ro($table,'*',$where,'','') ; + +# foreach my $id (keys %{$db{$table}}) { + # # &common_debug("$table : $fid == $id") ; + + # if ($fid == $id) { $selected = 'SELECTED'; } else { $selected = ''; } + # if (($db{$table}{$id}{$addfield}) and ($db{$table}{$id}{$dispfield} ne $db{$table}{$id}{$addfield})) { $disp_addfield = " ($db{$table}{$id}{$addfield})" ; } else { $disp_addfield = '' ; } + + # my $disp_addmore = '' ; + + # if ($display_addmore{$table}{$addmore}) { + # my $glyph = '' ; + # if ($db{$table}{$id}{$addmore} == 1) { + # # $glyph = qq(); + # $disp_addmore = " - $addmore" ; + # } + # } + + # if ($valfield) { $val = $db{$table}{$id}{$valfield} ; } else { $val = $id ; } + # $opts{$field} .= qq() ; + # } + +# } #------------------------------------------------------------------------------------------ + +sub common_curr_symbols { + +$common{'symbol'}{'GBP'} = '£' ; +$common{'symbol'}{'ZAR'} = 'R' ; +$common{'symbol'}{'USD'} = '$' ; +$common{'symbol'}{'EUR'} = '€' ; + +$common{'pdfsymbol'}{'GBP'} = qq(£) ; +$common{'pdfsymbol'}{'ZAR'} = 'R' ; +$common{'pdfsymbol'}{'USD'} = '$' ; +$common{'pdfsymbol'}{'EUR'} = '€' ; + +} #------------------------------------------------------------------------------------------ + +sub common_exchange_rates { + +my $exchgfile = "/usr/lib/cgi-bin/scripts/cron/feed.dat"; + +open (IFILE, "$exchgfile") or print "Unable to open $exchgfile: $!" ; +flock (IFILE, LOCK_SH) or print "Can't lock $exchgfile: $!"; +@exchng = ; +close (IFILE); + +@exchng = sort @exchng ; + +foreach $line (@exchng) { + chomp $line; + @linex = split(/\|/,$line); + + my $from = $linex[0] ; + my $to = $linex[1] ; + my $rate = $linex[2] ; + my $prate = $linex[3] ; + my $ccapirate = $linex[4] ; + + my $glyphicon = 'minus' ; if ($prate > $rate){ $glyphicon = 'arrow-down' ; } elsif ($rate > $prate) { $glyphicon = 'arrow-up' ; } + + $x++ ; + + # my $cushion = 10 ; # % cushion on exchange rate + # my $sell_rate = sprintf("%.2f", ( $rate / ((100+$cushion) / 100) )) ; + + my $buy_rate = $ccapirate ; + my $sell_rate = sprintf("%.2f", ( $ccapirate / 0.975) ) ; # add 2.5% + + $roe{$to} = $sell_rate ; + $roe_buy{$to} = $buy_rate ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_customer_hidden_db_fields { + +&common_customer_sort_fields; + +$ignore{iaction} = 1 ; +$ignore{logo} = 1 ; +$ignore{customer_nr} = 1 ; + +$required{name} = 1 ; # alphanumeric +# $required{contact_email} = 6 ; # email +# $required{phone} = 1 ; +# $required{customer_nr} = 1 ; + +$checkbox{active} = 1 ; +$hidden{last_updated} = 2 ; + +$hidden{last_edited_by} = 2 ; +$hidden{date_time} = 2 ; +$hidden{user_id} = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub common_customer_sort_fields { + +%sort_field = () ; + +$sort_field{1} = 'active' ; +$sort_field{2} = 'name' ; # $preferred_title{name} = 'Customer Name' ; +$sort_field{3} = 'customer_nr' ; +$sort_field{4} = 'phone' ; $preferred_title{phone} = 'Tel' ; +$sort_field{5} = 'company_email' ; +$sort_field{6} = 'contact_name' ; +$sort_field{7} = 'contact_email' ; +$sort_field{8} = 'physical_address' ; +$sort_field{9} = 'postal_address' ; +$sort_field{10} = 'city' ; +$sort_field{11} = 'province' ; +$sort_field{12} = 'country' ; +$sort_field{13} = 'vat_nr' ; + +} #------------------------------------------------------------------------------- + +sub common_load_quote_vars { + + my ($sql_where) = @_ ; + my $t1 = 'cameras' ; + my $t2 = 'quotes' ; + my $tables = "$t1,$t2" ; + + # my $sql_match_credits = '' ; + # if ($cnt_match_credits) { # match_credits_report.pl + # for (1 .. $cnt_match_credits) { + # $sql_match_credits .= qq~,$t2.item_$_\_costing_match_credits~ ; + # } + # } + + my $sel_fields = qq~$t1.id AS 'cam_id',$t1.camera_nr,$t1.serial_nr,$t1.quote_linked_vpu,$t1.quote_delivery_date,$t1.quote_active_date,$t1.quote_cam_num,$t2.quote_nr AS 'q_nr',$t2.id AS 'quote_id',$t2.ref,$t2.camera_system_id,$t2.type,$t2.quote_to,$t2.quote_accepted,$t2.quote_cancelled,$t2.invoice_date,$t2.qty,$t2.total_1_purchase_summary,$t2.total_2_purchase_summary,$t2.total_3_purchase_summary$sql_match_credits~ ; + &db_min_ro($tables,"$sel_fields",$sql_where,'','') ; + + foreach my $id (keys %{$db{$tables}}) { + + my $quote_id = $db{$tables}{$id}{quote_id} ; + my $q_nr = $db{$tables}{$id}{q_nr} ; + my $cam_id = $db{$tables}{$id}{cam_id} ; + my $camera_nr = $db{$tables}{$id}{camera_nr} ; + my $serial_nr = $db{$tables}{$id}{serial_nr} ; + my $quote_linked_vpu = $db{$tables}{$id}{quote_linked_vpu} ; + my $quote_cam_num = $db{$tables}{$id}{quote_cam_num} ; + my $quote_delivery_date = $db{$tables}{$id}{quote_delivery_date} ; + my $quote_active_date = $db{$tables}{$id}{quote_active_date} ; + + $quote_id{$q_nr} = $quote_id ; + + $cnt_cams{$q_nr}++ ; + + $quote_cam_active_date{$q_nr}{$quote_cam_num} = $quote_active_date ; + $quote_cam_delivery_date{$q_nr}{$quote_cam_num} = $quote_delivery_date ; + + if (substr($camera_nr,0,3) eq 'VPU' and $quote_linked_vpu) { + $linked_sn{$quote_linked_vpu} = $serial_nr ; + $linked_cn{$quote_linked_vpu} = $camera_nr ; + } + + $quote_customer{$cam_id} = $customer{$db{$tables}{$id}{quote_to}} ; + $quote_ref{$cam_id} = $db{$tables}{$id}{ref} ; + $quote_type{$cam_id} = ucfirst $db{$tables}{$id}{type} ; + # $quote_date_from{$cam_id} = $db{$tables}{$id}{date_from} ; + # $quote_date_to{$cam_id} = $db{$tables}{$id}{date_to} ; + $quote_accepted{$cam_id} = $db{$tables}{$id}{quote_accepted} ; + $quote_cancelled{$cam_id} = $db{$tables}{$id}{quote_cancelled} ; + $invoice_date{$cam_id} = $db{$tables}{$id}{invoice_date} ; + $quote_qty{$cam_id} = $db{$tables}{$id}{qty} ; + $quote_camera_system_id{$cam_id} = $db{$tables}{$id}{camera_system_id} ; + $quote_amount{$cam_id} = &common_commify(sprintf("%0.2f",($db{$tables}{$id}{total_1_purchase_summary} + $db{$tables}{$id}{total_2_purchase_summary} + $db{$tables}{$id}{total_3_purchase_summary}))) ; + $quote_camera_serial_nr{$cam_id} = $serial_nr ; + $quote_camera_camera_nr{$cam_id} = $camera_nr ; + $quote_nr{$cam_id} = $q_nr ; + + # if ($cnt_match_credits) { + # for (1 .. $cnt_match_credits) { + # $quote_match_credits{$_}{$cam_id} = $db{$tables}{$id}{"item_$_\_costing_match_credits"} ; + # } + # } + + } + +} #------------------------------------------------------------------------------------------ + +sub common_status_txt { + + my ($completed,$accepted,$pending,$cancelled,$rejected) = @_ ; + + my $txt = ($completed) ? 'Completed' : ($accepted) ? 'Accepted' : ($pending) ? 'Pending' : ($cancelled) ? 'Cancelled' : ($rejected) ? 'Rejected' : 'Changed' ; + + return ($txt) ; + +} #------------------------------------------------------------------------------------------ + +# sub common_load_quote_vars { + +# my ($sql_camera_nr_where) = @_ ; + +# my $suffix = '_camera_details' ; + +# # my $add_quote_fields = '' ; my $sql_or_where = '' ; my @sqlorwhere = () ; +# # for (1 .. 10) { + # # $add_quote_fields .= ",camera_nr_$_$suffix,delivery_date_$_$suffix,active_date_$_$suffix,ew_date_from_$_$suffix,ew_date_to_$_$suffix,ref_$_$suffix" ; + # # push @sqlorwhere, "camera_nr_$_$suffix $sql_camera_nr_where" ; +# # } +# # $sql_or_where = join(" OR ",@sqlorwhere) ; + +# my $sel_fields = qq~id,quote_nr,ref,camera_system_id,date_from,date_to,type,quote_to$add_quote_fields~ ; +# &db_min_ro('quotes',"$sel_fields",$sql_or_where,'','') ; +# foreach my $id (keys %{$db{quotes}}) { + + # my $quote_id = $id ; + # my $quote_nr = $db{quotes}{$id}{quote_nr} ; + + # $quote_customer{$quote_nr} = $customer{$db{quotes}{$id}{quote_to}} ; + # $quote_ref{$quote_nr} = $db{quotes}{$id}{ref} ; + # $quote_type{$quote_nr} = ucfirst $db{quotes}{$id}{type} ; + # $quote_date_from{$quote_nr} = $db{quotes}{$id}{date_from} ; + # $quote_date_to{$quote_nr} = $db{quotes}{$id}{date_to} ; + + # # for (1 .. 10) { + # # my $field = $db{quotes}{$id}{"camera_nr_$_$suffix"} ; + # # my $delivery_date = $db{quotes}{$id}{"delivery_date_$_$suffix"} ; + # # my $active_date = $db{quotes}{$id}{"active_date_$_$suffix"} ; + # # my $ew_date_from = $db{quotes}{$id}{"ew_date_from_$_$suffix"} ; + # # my $ew_date_to = $db{quotes}{$id}{"ew_date_to_$_$suffix"} ; + # # my $ref = $db{quotes}{$id}{"ref_$_$suffix"} ; + + # # if ($field) { + # # $camera_exists_on_quote{$field} = $id ; + # # $quote_nr{$field} = $db{quotes}{$id}{quote_nr} ; + # # $camera_on_quote_cnt{$quote_nr{$field}}{$_} = $field ; + # # $quote_ref{$field} = $db{quotes}{$id}{ref} ; + # # $quote_type{$field} = ucfirst $db{quotes}{$id}{type} ; + # # $quote_date_from{$field} = $db{quotes}{$id}{date_from} ; + # # $quote_date_to{$field} = $db{quotes}{$id}{date_to} ; + # # $quote_customer{$field} = $customer{$db{quotes}{$id}{quote_to}} ; + # # $quote_cam_ref{$field} = $ref ; + # # $quote_delivery_date{$field} = $delivery_date ; + # # $quote_active_date{$field} = $active_date ; + # # $quote_ew_date_from{$field} = $ew_date_from ; + # # $quote_ew_date_to{$field} = $ew_date_to ; + # # } + # } +# } + +# } #------------------------------------------------------------------------------------------ + +sub common_check_for_linked_vpu { + + my ($camera_nr,$quote_nr,$id,$req) = @_ ; + + # unless (substr($camera_nr,0,2) eq 'S1' or substr($camera_nr,0,5) eq 'Prime' or substr($camera_nr,0,5) eq 'Coach') { return('','') ; + + # &db_min_ro('cameras',"$sel_fields",$sql_or_where,'','') ; + # foreach my $id (keys %{$db{quotes}}) { + + # my $quote_id = $id ; + # my $quote_nr = $db{quotes}{$id}{quote_nr} ; + # } + # } + + + + $req = 'SN' unless $req ; + + my $val = '' ; + + # if (substr($camera_nr,0,2) eq 'S1' or substr($camera_nr,0,5) eq 'Prime' or substr($camera_nr,0,5) eq 'Coach') { + if (substr($camera_nr,0,2) eq 'S1' or substr($camera_nr,0,2) eq 'S2' or substr($camera_nr,0,5) eq 'Prime' or substr($camera_nr,0,5) eq 'Coach') { + # &common_debug("vpu_serial_nr : $camera_nr") ; + # foreach $camcnt (sort {$camera_on_quote_cnt{$quote_nr}{$a} cmp $camera_on_quote_cnt{$quote_nr}{$b}} keys %{$camera_on_quote_cnt{$quote_nr}}) { + foreach $camcnt (sort {$a <=> $b} keys %{$camera_on_quote_cnt{$quote_nr}}) { + my $camid = $camera_on_quote_cnt{$quote_nr}{$camcnt} ; + my $camnrabrv = substr($cam_nr{$camid},0,3) ; + # &common_debug("vpu_serial_nr [3] camnrabrv=$camnrabrv, getnext=$getnext") ; + if ($getnext and $camnrabrv eq 'VPU') { $val = $req eq 'CN' ? $cam_nr{$camid} : $serial_nr{$camid} ; } + $getnext=0; if ($camid eq $id) { $getnext=1; } + # &common_debug("vpu_serial_nr [$camcnt], camid=$camid, id=$id, camnrabrv=$camnrabrv, getnext=$getnext") ; + } + } + + return ($val) ; + +} #------------------------------------------------------------------------------------------ + +sub common_camera_system_filter { + + my ($table,$id) = @_ ; + + my $next = 0 ; + + if ($i{stock} eq 'stock') { if ($db{$table}{$id}{quote_nr} or $db{$table}{$id}{demo_recipient} or $db{$table}{$id}{replacement_date}) { $next = 1 ; } } + + if ($i{stock} eq 'purchased') { unless ($db{$table}{$id}{quote_nr}) { $next = 1 ; } } + if ($i{stock} eq 'purchase') { unless (lc $quote_type{$id} eq 'purchase' and $db{$table}{$id}{quote_nr}) { $next = 1 ; } } + if ($i{stock} eq 'demo') { unless ($db{$table}{$id}{demo_recipient} ) { $next = 1 ; } } + if ($i{stock} eq 'rental') { unless ($db{$table}{$id}{camera_system_id}<7 and lc $quote_type{$id} eq 'rental') { $next = 1 ; } } + if ($i{stock} eq 'event') { unless ($db{$table}{$id}{event_system_id} > 0) { $next = 1 ; } } + + if ($i{camera_system_id} eq 'main') { unless ($db{$table}{$id}{camera_system_id}<7) { $next = 1 ; } } + if ($i{camera_system_id} eq 'other') { unless ($db{$table}{$id}{camera_system_id}>7) { $next = 1 ; } } + + if ($db{$table}{$id}{event_system_id} > 0) { unless ($i{stock} eq 'event' or $i{stock} eq '') { $next = 1 ; } } + + # &common_debug("common_camera_system_filter : next [$next], stock=$i{stock}, event_system_id=$db{$table}{$id}{event_system_id}, quote_type=$quote_type{$id}, camera_system_id=$db{$table}{$id}{camera_system_id}, quote_nr=$db{$table}{$id}{quote_nr}, demo_recipient=$db{$table}{$id}{demo_recipient}") ; + + return ($next) ; + +} #------------------------------------------------------------------------------------------ + +sub common_camera_opts { + + $opts{camera_system_id} = qq~~ ; + $opts{stock} = qq~ + + + + + ~ ; + + # + +} #------------------------------------------------------------------------------------------ + +sub common_camera_links { + + my ($table,$id,$val) = @_ ; + + if ($_ eq 'camera_nr') { + my $class = 'info' ; $class = 'warning' if $db{$table}{$id}{quote_nr} ; + my $style = '' ; $style = "background-color:purple;border:purple;" if $db{$table}{$id}{demo_recipient} ; $style = "background-color:#ff00fb;border:#ff00fb;" if $db{$table}{$id}{event_system_id} ; + # &common_debug("event_system_id=$db{$table}{$id}{event_system_id}, camera_system_id=$db{$table}{$id}{camera_system_id}, camera_nr=$db{$table}{$id}{camera_nr} [style=$style]") ; + # my $tooltip = qq~data-toggle="tooltip" data-placement="top" data-title=""~ ; + $val = qq~$val~ ; + } + + if ($_ eq 'quote_nr' or $_ eq 'ref_nr' or $_ eq 'ref') { + my $class = 'info' ; $class = 'warning' if $val ; + my $style = '' ; $style = "style='background-color:purple;'" if $db{$table}{$id}{demo_recipient} ; $class = 'success' if $db{$table}{$id}{quote_accepted} or $quote_accepted{$id} ; $class = 'danger' if $db{$table}{$id}{quote_cancelled} or $quote_cancelled{$id} ; + my $quote_id = $quote_id{$val} ? $quote_id{$val} : $id ; + my $js_func = ($table eq 'event_quotes') ? 'editEventQuote' : 'editQuote' ; + $val = $val ? qq~$val~ : '' ; + } + + return ($val) ; + +} #------------------------------------------------------------------------------------------ + +sub common_write_date_interval { + + my ($date_from,$date_to) = @_ ; + + my @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + $date_from = substr($date_from,0,10) ; + + $date_to = substr($date_to,0,10) ; + + my ($start_year,$start_mon,$start_day) = split("-",$date_from) ; + + my ($end_year,$end_mon,$end_day) = split("-",$date_to) ; + + $start_mon = int($start_mon) ; $end_mon = int($end_mon) ; + + my $date = "" ; + + if ($start_year ne $end_year) { + $date = "$start_day $months[$start_mon] $start_year - $end_day $months[$end_mon] $end_year" ; + } elsif ($start_mon ne $end_mon) { + $date = "$start_day $months[$start_mon]- $end_day $months[$end_mon] $end_year" ; + } elsif ($start_day ne $end_day) { + $date = "$start_day - $end_day $months[$end_mon] $end_year" ; + } elsif ($start_day eq $end_day) { + $date = "$end_day $months[$end_mon] $end_year" ; + } + + return ($date) ; + +} #------------------------------------------------------------------------------- + +sub common_check_if_string_contains_an_integer { + my $string = shift; + return $string =~ /\d/ ; + +} #------------------------------------------------------------------------------- + +sub common_check_if_time_is_greater { + + local ($time1,$time2) = @_ ; + + local $epoch1 = Time::Piece->strptime($time1, '%Y-%m-%d %H:%M:%S'); + local $epoch2 = Time::Piece->strptime($time2, '%Y-%m-%d %H:%M:%S'); + + local $moving_forward = 0 ; + + if ($epoch1 <= $epoch2) { + $moving_forward = 1 ; + } + + return ($moving_forward) ; + +} #------------------------------------------------------------------------------------------ + +sub common_add_delta_days { + +my ($days) = @_ ; + +my ($year,$month,$day) = Add_Delta_Days($now_year,$now_mm,$now_dd,$days); # + +$month = sprintf("%02s", $month) ; +$day = sprintf("%02s", $day) ; + +return("$year-$month-$day"); + +} #------------------------------------------------------------------------------- + +sub common_add_delta_ymd { + +my ($nyear,$nmonth,$nday) = @_ ; + +my ($syear,$smonth,$sday) = Add_Delta_YMD($now_year,$now_mm,$now_dd, $nyear,$nmonth,$nday); + +$smonth = sprintf("%02s", $smonth) ; +$sday = sprintf("%02s", $sday) ; + +return ($syear,$smonth,$sday) ; + +} #------------------------------------------------------------------------------- + +sub common_add_delta_dhms { + +my ($year,$mm,$dd,$hour,$min,$sec,$days_diff,$hrs_diff,$min_diff,$sec_diff) = @_ ; + +my ($syear,$smonth,$sday,$shour,$smin,$ssec) = Add_Delta_DHMS($year,$mm,$dd,$hour,$min,$sec,$days_diff,$hrs_diff,$min_diff,$sec_diff) ; # + +$smonth = sprintf("%02s", $smonth) ; +$sday = sprintf("%02s", $sday) ; +$shour = sprintf("%02s", $shour) ; +$smin = sprintf("%02s", $smin) ; +$ssec = sprintf("%02s", $ssec) ; + +return("$syear-$smonth-$sday","$shour:$smin:$ssec","$syear$smonth$sday$shour$smin$ssec"); + +} #------------------------------------------------------------------------------- + +sub common_split_sql_time { + +my ($datetime) = @_ ; # 2015-10-06 17:35:39 + +my ($date,$time) = split(/ /,$datetime) ; + +my $dy = substr($date,0,4) ; +my $dm = substr($date,5,2) ; +my $dd = substr($date,8,2) ; + +my ($th,$tm,$ts) = split(/:/,$time) ; + +return ($dy,$dm,$dd,$th,$tm,$ts) ; + +} #------------------------------------------------------------------------------- + +sub common_page_name { + +my @splitlcpage = split(/\-/,$lcpage) ; +my @ucfirstpage = map(ucfirst, map(lc,@splitlcpage)); +our $ucfirstpage = join(' ', @ucfirstpage); +our $ucpage = uc $ucfirstpage ; + +} #------------------------------------------------------------------------------- + +sub common_commify { + +local($_) = shift; +1 while s/^(-?\d+)(\d{3})/$1,$2/; +return $_; + +} #------------------------------------------------------------------------------- + +sub common_debug { + +my ($msg) = @_ ; + +unless ((substr($username,0,4) eq 'rory' || $username eq 'handre') && ($testing || $debug)) { return ; } + +print $msg . "\n" ; + +} #------------------------------------------------------------------------------------------ + +sub common_send_mail { + +my ($to,$cc,$bcc,$html,$thead,$msg,$subj) = @_ ; + +return unless $msg ; +return unless $subj ; + +# my $res = &common_mailsend_sendgrid('html',$to,$subject,$emailmsg,'','','Film Freight','pod@ffwaybill.co.za'); + +# return if $res eq 'success' ; # carry on if mailsend_sendgrid failed + +use Mail::Sendmail; + +my $main_email = 'tickets@interactivetvafrica.com' ; + +$to = $main_email unless $to ; + +my %mail = () ; + +%mail = ( + smtp => 'localhost', + From => $main_email, + To => $to, + Cc => $cc, + Bcc => $bcc, + Subject => $subj + ); + +$mail{smtp} = "smtp.interactivetvafrica.com"; +# $mail{Debug} = 6; +$mail{port} = 587; +# $mail{port} = 465; +$mail{Auth} = {user => $main_email, pass => $send_mail_psw, method => "LOGIN", required => 1}; + +$mail{body} = < + + + +ITV + + + +
    +ITV +

    + + $thead + + $msg + +
    +
    +

    +Best regards, +
    +
    +The ITV Africa Team. +

    +
    + + + +$boundary-- + +END_OF_BODY + +} + +sendmail(%mail) ; + +} #------------------------------------------------------------------------------------------ + +sub common_send_smtp_mail { + + my ($from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication,$uploaded_doc,$operator_email) = @_ ; + + &common_debug("common_send_smtp_mail [$from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication,$uploaded_doc,$operator_email]") ; + + return unless $msg ; + return unless $subj ; + + my $htype = (-f "$attachpath/$attachname" || $uploaded_doc || $operator_email) ? 'htmlattach' : ($html eq 'html') ? $html : 'text' ; + + my $res = &common_mailsend_sendgrid($htype,$to,$subj,$msg,$attachpath,$attachname,'ITV Africa Events','events@itvadmin.co.za',$cc,$bcc,$uploaded_doc,$operator_email); + + return if $res eq 'success' ; # carry on if mailsend_sendgrid failed + + my $main_email = $email_add{'events'} ; + + $to = $main_email unless $to ; + $from = $main_email unless $from ; + + if ($html) { + my $mail_body = < + + + + + + + + + + +
    + + ITV +

    + $msg +

    + + $thead + + $table_msg + +
    + +
    +

    $display_notif_msg + Best regards, +
    +
    + The ITV Africa Team. +

    +
    + + +END_OF_BODY + + if (($attachname && -f "$attachpath/$attachname") or $uploaded_doc) { + + use MIME::Lite; + use Net::SMTP_auth; + + + # ################################################################# + # Lets build the MulitPart MIME Message + # ################################################################# + # Create the Message + my $msg = MIME::Lite::->new( + 'From' => "ITV Africa Events <$from>", + 'Reply-To' => 'marizen@itvafrica.net', + 'To' => $to, + 'Cc' => $cc, + 'Bcc' => $bcc, + 'Subject' => $subj, + 'Type' => 'multipart/mixed', + ); + + # Create the text part + # my $text_part = MIME::Lite::->new( + # 'Type' => 'text/plain', + # 'Data' => 'Hi\nThis is a test message', + # ); + + # Create the HTML part + my $html_part = MIME::Lite::->new( + 'Type' => 'multipart/related', + ); + + $html_part->attach( + 'Type' => 'text/html', + 'Data' => $mail_body, + ) ; + + if ($attachname && -f "$attachpath/$attachname") { + my $attach_part = MIME::Lite::->new( + 'Type' => 'multipart/mixed', + ); + $attach_part->attach ( + Type => "application/$attachapplication", + Encoding => 'base64', + Path => "$attachpath/$attachname", + Filename => $attachname, + Disposition => 'attachement' + ) or &common_send_mail('rory@kre8it.co.za','','','','ITV ERROR : common.pm',"common_send_smtp_mail cant attach $attachpath/$attachname : $!") ; + $msg->attach($attach_part); + } + + if ($uploaded_doc) { + my $upload_part = MIME::Lite::->new( + 'Type' => 'multipart/mixed', + ); + $upload_part->attach ( + Type => 'AUTO', + FH => $uploaded_doc, + Filename => $uploaded_doc, + Disposition => 'attachment' + ) or die "Error adding : $uploaded_doc $!\n"; + $msg->attach($upload_part); + } + + if ($operator_email) { + my $attach_flyer = MIME::Lite::->new( + 'Type' => 'multipart/mixed', + ); + $attach_flyer->attach ( + Type => "application/$attachapplication", + Encoding => 'base64', + Path => "$htmlpath/pdf/operator_flyer", + Filename => "operator_email_attach.pdf", + Disposition => 'attachement' + ) or &common_send_mail('handre@kre8it.co.za','','','','ITV ERROR : common.pm',"common_send_smtp_mail cant attach $attachpath/$attachname : $!") ; + $msg->attach($attach_flyer); + } + + # Now lets attach the text and html parts to the message + # $msg->attach($text_part); + $msg->attach($html_part); + + my $email = $msg->as_string(); + + # ################################################################# + # Lets sent the Message + # ################################################################# + + my $smtp_msg = Net::SMTP_auth->new($smtp_server, Port=>587) or die "Can't connect"; + # my $smtp_msg = Net::SMTP_auth->new($smtp_server, Port=>465) or die "Can't connect"; + $smtp_msg->auth('PLAIN', $main_email, $send_mail_psw_events) or die "Can't authenticate:".$smtp_msg->message(); + + $smtp_msg->mail($from) or die "Error:".$smtp_msg->message(); + $smtp_msg->recipient($to) or die "Error:".$smtp_msg->message(); + + $smtp_msg->data() or die "Error:".$smtp_msg->message(); + $smtp_msg->datasend($email) or die "Error:".$smtp_msg->message(); + $smtp_msg->dataend() or die "Error:".$smtp_msg->message(); + $smtp_msg->quit or die "Error:".$smtp_msg->message(); + + } else { + use Mail::Sendmail; + + my %mail = () ; + + %mail = ( + smtp => 'localhost', + From => $main_email, + To => $to, + Cc => $cc, + Bcc => $bcc, + Subject => $subj + ); + + $mail{smtp} = $smtp; + $mail{port} = 587; + $mail{Auth} = {user => $main_email, pass => $send_mail_psw{$main_email}, method => "LOGIN", required => 1}; + + my $boundary = "====" . time() . "===="; + + $mail{'content-type'} = "multipart/alternative; boundary=\"$boundary\""; + + $boundary = '--'.$boundary; + + $mail{body} = < 'localhost', + From => $main_email, + To => $to, + Cc => $cc, + Bcc => $bcc, + Subject => $subj + ); + + $mail{smtp} = $smtp; + # $mail{Debug} = 6; + $mail{port} = 587; + # $mail{port} = 465; + $mail{Auth} = {user => $from, pass => $send_mail_psw{$from}, method => "LOGIN", required => 1}; + $mail{body} = <new(api_key => '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'); + + $qbody =~ s/'/`/gi; + $qbody =~ s/\r//gi; + $qbody =~ s/\n//gi; + + #------------------------------------------------ + #SEND TEXT ONLY MAIL + if ($qtype eq "text") { + + # , cc => [ $qccemail ], bcc => [ $qbccemail ] + + my %cc_args = ($qccemail) ? (cc => [ "$qccemail" ]) : () ; + my %bcc_args = ($qbccemail) ? (bcc => [ "$qbccemail" ]) : () ; + + my $result = $sg->from($qfromemail,$qfromname) + ->reply_to('marizen@itvafrica.net', 'ITV Events') + ->subject($qsubject) + ->add_content('text/plain', $qbody) + ->add_envelope( to => [ "$qemail" ], %cc_args, %bcc_args) + ->send; + + $qres = $result->{success} ? "success" : "error: " . $result->{reason}; + + } + + #------------------------------------------------ + #SEND HTML ONLY MAIL + if ($qtype eq "html") { + + $qbody = qq~ + + + +Film Freight + + + +

    + +

    +

    +$qbody +

    +
    +
    + + +~; + my %cc_args = ($qccemail) ? (cc => [ "$qccemail" ]) : () ; + my %bcc_args = ($qbccemail) ? (bcc => [ "$qbccemail" ]) : () ; + + my $result = $sg->from($qfromemail,$qfromname) + ->reply_to('marizen@itvafrica.net', 'ITV Events') + ->subject($qsubject) + ->add_content('text/html', $qbody) + ->add_envelope( to => [ "$qemail" ], %cc_args, %bcc_args) + ->send; + + $qres = $result->{success} ? "success" : "error: " . $result->{reason}; + + } + + #------------------------------------------------ + #SEND HTML WITH ATTACHMENT MAIL + if ($qtype eq "htmlattach") { + + my $encodedcontent = &encode_attachment("$qattachfilepath/$qattachfilename"); + + my %args = ( + type => 'AUTO', + disposition => 'attachment' + ); + + $qbody = qq~ + + + +Film Freight + + + +

    + +

    +

    +$qbody +

    +
    +
    + + +~; + + my @attachments = ($qattachfilename, $encodedcontent, %args) ; + + if ($uploaded_doc) { + my $encodedcontent = &encode_attachment("$uploaded_doc") ; + push @attachments, ($uploaded_doc, $encodedcontent, %args) ; + } + + if ($operator_email) { + my $encodedcontent = &encode_attachment("$htmlpath/pdf/operator_flyer") ; + push @attachments, ("operator_email_attach.pdf", $encodedcontent, %args) ; + } + + + my %cc_args = ($qccemail) ? (cc => [ "$qccemail" ]) : () ; + my %bcc_args = ($qbccemail) ? (bcc => [ "$qbccemail" ]) : () ; + + my $result = $sg->from($qfromemail,$qfromname) + ->reply_to('marizen@itvafrica.net', 'ITV Events') + ->subject($qsubject) + ->add_content('text/html', $qbody) + ->add_attachment(@attachments) + ->add_envelope( to => [ "$qemail" ], %cc_args, %bcc_args) + ->send; + + $qres = $result->{success} ? "success" : "error: " . $result->{reason}; + + #NOTE: Cannot use command line cURL here as the body (base64 pdf) is too large - below works for smaller content + #$qres = `/usr/bin/curl --request POST --url https://api.sendgrid.com/v3/mail/send --header 'authorization: Bearer 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' --header 'Content-Type: application/json' --data '{"personalizations": [{"to": [{"email": "$qemail"}]}],"from": {"email": "no-reply\@myappointment.co.za"},"subject":"$qsubject","content": [{"type": "text/html","value": "$qbody"}], "attachments": [{"content": "$encodedcontent", "type": "text/plain", "filename": "$qattachfilename"}]}'`; + } + #------------------------------------------------ + + &common_debug("common_mailsend_sendgrid [$qres]") ; + + return "$qres"; + +} #------------------------------------------------------------------------------------------ + +sub encode_attachment { + + my ($fh) = @_ ; + + use MIME::Base64 qw(encode_base64); + + my $myfilecontents = '' ; + + open (infile, "$fh"); + binmode infile; + while () { + $myfilecontents .= "$_"; + } + close(infile); + + my $encodedcontent = encode_base64($myfilecontents); + + $encodedcontent =~ s/'/`/gi; + $encodedcontent =~ s/\r//gi; + $encodedcontent =~ s/\n//gi; + + return($encodedcontent) ; + +} #------------------------------------------------------------------------------------------ + +sub common_fix_str { + + my ($txt) = @_ ; + + $txt = lc $txt ; + $txt =~ s/\'//iog ; + $txt =~ s/^\s+|\s+$//g; # remove whitespace before and after + local $txt_new = '' ; + foreach (split(/ /,$txt)) { + if ($_ ne 'and' and $_ ne 'or' and $_ ne 'of' and $_ ne 'in') { + $txt_new .= ucfirst $_ ; + } else { + $txt_new .= "$_" ; + } + $txt_new .= ' ' ; + } + chop $txt_new if $txt_new ; + + return ($txt_new) ; + +} #------------------------------------------------------------------------------- + +sub common_date_array { + + my ($from_date, $to_date) = @_ ; + + my $date_array_date = $from_date ; + + @common_date_array = () ; + + &common_debug ("common_date_array : $from_date, $to_date") ; + + while ($date_array_date <= $to_date) { + + &common_debug ("common_date_array : push \@common_date_array, $date_array_date") ; + push @common_date_array, $date_array_date ; + + my $array_date_dd = substr($date_array_date,6,2) ; + my $array_date_mm = substr($date_array_date,4,2) ; + my $array_date_ccyy = substr($date_array_date,0,4) ; + + $day_of_week{$date_array_date} = Day_of_Week($array_date_ccyy,$array_date_mm,$array_date_dd) unless $day_of_week{$date_array_date} ; # 1 is Monday + # $day_of_week{"$array_date_ccyy-$array_date_mm-$array_date_dd"} = Day_of_Week($array_date_ccyy,$array_date_mm,$array_date_dd) unless $day_of_week{"$array_date_ccyy-$array_date_mm-$array_date_dd"} ; # 1 is Monday + # $date_hash{$date_array_date} = 1 ; + + my ($ccyy,$month,$day) = Add_Delta_Days($array_date_ccyy,$array_date_mm,$array_date_dd,1) ; + $month = sprintf("%02s", $month) ; + $day = sprintf("%02s", $day) ; + + $date_array_date = "$ccyy$month$day" ; + } + +} #------------------------------------------------------------------------------- + +1; diff --git a/libs/modules/_FromProd/v1.0/csv.pm b/libs/modules/_FromProd/v1.0/csv.pm new file mode 100644 index 0000000..c10e12f --- /dev/null +++ b/libs/modules/_FromProd/v1.0/csv.pm @@ -0,0 +1,54 @@ +sub csv_create_new_file { + + my ($filepath,$filename,$seperator) = @_ ; + + use Text::CSV; + + return if !$filepath || !$filename ; + + unlink "$filepath/$filename" or die "Cannot remove $filepath/$filename: $!" if -e "$filepath/$filename" ; + + $seperator = ';' unless $seperator ; + + our $csv = Text::CSV->new({ binary => 1, sep_char => $seperator, eol => "\n" }) or die "Cannot use CSV: " . Text::CSV->error_diag(); + + open(our $fh, ">", "$filepath/$filename") or die "Cannot open $filepath/$filename: $!"; + +} #------------------------------------------------------------------------------------------ + +sub csv_write_in_file { + + my ($row) = @_ ; + $csv->print($fh, $row); + +} #------------------------------------------------------------------------------------------ + +sub csv_close_file { + + my ($filepath) = @_ ; + close $fh or die "Cannot close $filepath: $!"; + +} #------------------------------------------------------------------------------------------ + +sub csv_clear_folder { + + my ($path,$name_to_look_for) = @_ ; + + return unless -d $path ; + + opendir(DIR, "$path") or die "cant open Directory $path: $!\n"; + + while(defined($folder = readdir(DIR))) { + if (length $folder > 2) { + my ($file,$type) = split(/\./,$folder) ; + if ((-e "$path/$file.csv" && !$name_to_look_for) || ($name_to_look_for && -e "$path/$file.csv" && $file =~ /$name_to_look_for/)) { + unlink ("$path/$file.csv") or print "unable to unlink - $path/$file.csv : $!"; + } + } + } + + closedir(DIR) ; + +} #------------------------------------------------------------------------------------ + +1; \ No newline at end of file diff --git a/libs/modules/_FromProd/v1.0/db.pm b/libs/modules/_FromProd/v1.0/db.pm new file mode 100644 index 0000000..8360829 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/db.pm @@ -0,0 +1,98 @@ +use db_min ; + +sub db_open_ro { + + my ($sys) = @_ ; + + if ($db_ignore_open_close) { return ; } + + my ($db,$dbhost,$dbuser,$dbpass) = &ops_db_credentials($sys) ; + + my $connstr = "DBI:mysql:database=$db;host=$dbhost;" ; + + $dbh = DBI->connect($connstr,$dbuser,$dbpass) or die $DBI::errstr; + + &common_debug("db_open_ro:$connstr") ; + +} #---------------------------------------------------------------------------------------------------------------------- + +sub db_open_upd { + + my ($sys) = @_ ; + + if ($db_ignore_open_close) { return ; } + + my ($db,$dbhost,$dbuser,$dbpass) = &ops_db_credentials($sys) ; + + my $connstr = "DBI:mysql:database=$db;host=$dbhost;" ; + + $dbh = DBI->connect($connstr,$dbuser,$dbpass, { RaiseError => 1, AutoCommit => 1 } ) or die "Unable to connect, $DBI::errstr"; + $dbh->{LongReadLen} = 1000 ; + + &common_debug("db_open_upd:$connstr") ; + +} #---------------------------------------------------------------------------------------------------------------------- + +sub db_close_conn { + + if ($db_ignore_open_close) { return ; } + + $dbh->disconnect(); + + &common_debug('db_close_conn:$dbh->disconnect();') ; + +} #------------------------------------------------------------------------------------------ + +sub db_switch_conn { + + my ($sys) = @_ ; + + $db_ignore_open_close = 0 ; + &db_close_conn ; + &db_open_upd($sys) ; + $db_ignore_open_close = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub ops_db_credentials { + + my ($sys) = @_ ; + + my $db = "itv_admin_db"; + my $dbhost = "localhost"; + my $dbuser = "itv_admin_user"; + my $dbpass = '!Ja16Q7P0X3SVTWr'; + + if ($env eq 'DEV') { + $db = 'dev_aisa' ; + $dbhost = 'localhost' ; + $dbuser = 'dev_aisa_user' ; + $dbpass = 'L0rdJ35u5R31gN51vQow*!' ; + } + + if ($sys eq 'sss') { + $db = "sss_admin_db"; + $dbhost = "localhost"; + $dbuser = "sss_admin_user"; + $dbpass = 'bVrC2kyGJ8ZO0oVe!'; + + if ($env eq 'DEV') { + $db = 'dev_sss' ; + $dbhost = 'localhost' ; + $dbuser = 'dev_sss_user' ; + $dbpass = 'L0rdJ35u5R31gN51vQow*!' ; + } + } + + return ($db,$dbhost,$dbuser,$dbpass) ; + +} #---------------------------------------------------------------------------------------------------------------------- + +sub db_uniq { + + my %seen; + grep !$seen{$_}++, @_; + +} #------------------------------------------------------------------------------------------ + +1; \ No newline at end of file diff --git a/libs/modules/_FromProd/v1.0/db_min.pm b/libs/modules/_FromProd/v1.0/db_min.pm new file mode 100644 index 0000000..497de06 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/db_min.pm @@ -0,0 +1,269 @@ +sub db_min_upd { + + my ($table,$where) = @_ ; + + our $set = '' ; + + foreach (keys %i) { + if (substr($_,0,3) eq 'new') { next ; } + if ($ignore{$_}) { next ; } + if ($hidden{$_} == 1) { next ; } + if ($i{$_} =~ /\"/) { $set .= qq(`$_`='$i{$_}',) ; } elsif ($i{$_} eq 'NULL') { $set .= qq(`$_`=$i{$_},) ; } else { $set .= qq(`$_`="$i{$_}",) ; } + } + + $set = substr($set,0,-1) ; + + unless ($set) { return ; } + + &db_open_upd ; + + my $sql = qq(UPDATE $table SET $set WHERE $where) ; + + &common_debug($sql) ; + + if ($testing == 1 && $useropts{it}{$username}) { &common_debug(">>>>>> *** TESTING, DB NOT UPDATED *** <<<<<<") ; return ; } + + $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + + &db_close_conn ; + + $success = qq($i{id} SUCCESSFULLY SAVED) ; + +} #------------------------------------------------------------------------------------------ + +sub db_min_insert { + + my ($table) = @_ ; + + my $columns = '' ; + my $values = '' ; + + foreach (keys %i) { + if ($ignore{$_}) { next ; } + if ($hidden{$_} == 1) { next ; } + $columns .= qq(`$_`,) ; + if ($i{$_} =~ /\"/) { $values .= qq('$i{$_}',) ; } elsif ($i{$_} eq 'NULL') { $values .= qq(`$_`=$i{$_},) ; } else { $values .= qq("$i{$_}",) ; } + } + + $columns = substr($columns,0,-1) ; + $values = substr($values,0,-1) ; + + &db_open_upd ; + + my $sql = qq(INSERT INTO $table ($columns) VALUES ($values) ;) ; + + &common_debug($sql) ; + + if ($testing == 1 && $useropts{it}{$username}) { &common_debug(">>>>>> *** TESTING, DB NOT UPDATED *** <<<<<<") ; return ; } + + $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + our $new_row_id = $dbh->last_insert_id(undef, undef, $table, 'id') ; # or die "no insert id?"; + + &db_close_conn ; + + $success = qq($i{id} SUCCESSFULLY SAVED) ; + +} #------------------------------------------------------------------------------------------ + +sub db_min_delete { + +my ($table,$where) = @_ ; + +&db_open_upd ; + +my $sql = qq(DELETE FROM $table WHERE $where) ; + +&common_debug($sql) ; + +if ($testing == 1 && $useropts{it}{$username}) { &common_debug(">>>>>> *** TESTING, DB NOT UPDATED *** <<<<<<") ; return ; } + +$sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +&db_close_conn ; + +$success = qq($i{id} SUCCESSFULLY DELETED) ; + +} #------------------------------------------------------------------------------------------ + +sub db_min_ro { + +my ($table,$select,$where,$orderby,$limit) = @_ ; + +if ($where) { $where = 'WHERE ' . $where ; } +if ($limit) { $limit = 'LIMIT ' . $limit ; } +if ($orderby) { $orderby = 'ORDER BY ' . $orderby ; } + +&db_open_ro ; + +my $sql = qq(SELECT $select FROM $table $where $orderby $limit) ; + +&common_debug($sql) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; + +$col_cnt=0; + +foreach $col (@{$sth->{NAME}}) { $col_name{$col_cnt}=$col; $col_cnt++; } # &common_debug($col); NB *** must be before fetchall_arrayref + +my $rows_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +$db{$table} = () ; $done_col_val{$table} = () ; + +foreach $row (@$rows_array_ref) { + for (0 .. $col_cnt){ + if ($done_col_val{$table}{@$row[0]}{$col_name{$_}}) { next; } + # &common_debug("db_common_ro - [$_] [$table] [@$row[0]] [$col_name{$_}] [@$row[$_]]") ; + $db{$table}{@$row[0]}{$col_name{$_}} = @$row[$_] ; + $done_col_val{$table}{@$row[0]}{$col_name{$_}} = 1 ; + } + } + +} #------------------------------------------------------------------------------------------ + +sub db_min_raw { + +my ($sql) = @_ ; + +&common_debug($sql) ; + +if ($testing == 1 && $useropts{it}{$username}) { &common_debug(">>>>>> *** TESTING, DB NOT UPDATED *** <<<<<<") ; return ; } + +my $sth = $dbh->prepare($sql) ; + +$sth->execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; + +our $col_cnt=0; + +foreach $col (@{$sth->{NAME}}) { $col_name{$col_cnt}=$col; $col_cnt++; } # &common_debug($col); NB *** must be before fetchall_arrayref + +our $rows_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +} #------------------------------------------------------------------------------------------ + +sub db_min_copy { + +my ($table,$id) = @_ ; + +&db_open_upd ; + + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + $i{id} = &db_min_get_max($table,'id') ; + + my $add_upd_sql = '' ; + if ($table eq 'quotes' or $table eq 'event_quotes'){ + $i{quote_nr} = &db_min_get_max($table,'quote_nr') ; + $add_upd_sql = qq~, `quote_nr`='$i{quote_nr}'~; + } + + if ($table eq 'cameras'){ + $i{camera_nr} = &db_min_get_max_camera_nr($table,'camera_nr',$id) ; + $add_upd_sql = qq~, `camera_nr`='$i{camera_nr}'~; + } + + my $sql = qq~CREATE TEMPORARY TABLE `#temp` SELECT * FROM $table WHERE `id`='$id';~ ; + + &common_debug($sql) ; + + $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + + $sql = qq~UPDATE `#temp` SET `id`='$i{id}'$add_upd_sql WHERE `id`='$id';~ ; + + &common_debug($sql) ; + + $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + + $sql = qq~INSERT INTO $table SELECT * FROM `#temp` WHERE `id`='$i{id}';~ ; + + &common_debug($sql) ; + + $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + + $sql = qq~DROP TEMPORARY TABLE IF EXISTS `#temp`;~ ; + + &common_debug($sql) ; + + $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + +&db_close_conn ; + +$success = qq($id SUCCESSFULLY COPIED TO $i{id}) ; + +} #------------------------------------------------------------------------------------------ + +sub db_min_get_max_camera_nr { + +my ($table,$orderby,$camera_id) = @_ ; + +&db_min_ro($table,'id,camera_system_id',"`id`='$camera_id'",'','') ; +# &db_min_ro($table,'id,camera_nr',"`camera_system_id`='$db{$table}{$camera_id}{camera_nr}'",'`id` DESC',1) ; +&db_min_ro($table,'id,camera_nr',"`camera_system_id`='$db{$table}{$camera_id}{camera_system_id}'",'`id` DESC',1) ; + +my $max_cam_cnt = 0 ; + +foreach my $id (keys %{$db{$table}}) { + ($cam_type,$cam_cnt) = split(/\-/,$db{$table}{$id}{camera_nr}); + $max_cam_cnt = $cam_cnt unless $max_cam_cnt > $cam_cnt; +} + +$max_cam_cnt++; + +my $camera_nr = $cam_type . '-' . sprintf("%04s", $max_cam_cnt) ; # e.g. S1-0001 + +return ($camera_nr) ; + +} #------------------------------------------------------------------------------------------ + +sub db_min_get_max { + +my ($table,$orderby,$where) = @_ ; + +&db_open_ro ; + +if ($where) { $where = 'WHERE ' . $where ; } + +my $sql = qq~SELECT * FROM $table $where ORDER BY $orderby DESC LIMIT 1~ ; + +&common_debug($sql) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; + +$col_cnt=0; + +foreach $col (@{$sth->{NAME}}) { $col_name{$col_cnt}=$col; $col_cnt++; } # &common_debug($col); NB *** must be before fetchall_arrayref + +my $rows_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +my $new_id = 1 ; + +$db{$table} = () ; + +foreach $row (@$rows_array_ref) { + for (0 .. $col_cnt){ + $db{$table}{@$row[0]}{$col_name{$_}} = @$row[$_] ; + } + $new_id = $db{$table}{@$row[0]}{$orderby} ; + $new_id++ ; + } + +return ($new_id) ; + +} #------------------------------------------------------------------------------------------ + +1; \ No newline at end of file diff --git a/libs/modules/_FromProd/v1.0/dcb.pm b/libs/modules/_FromProd/v1.0/dcb.pm new file mode 100644 index 0000000..6a7fda1 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/dcb.pm @@ -0,0 +1,525 @@ + +sub dcb_trackntrace { + + my ($waybillNumber) = @_ ; + + our $soapenvelope = qq~ + + + + + + + + $waybillNumber + + + + ~ ; + + &common_debug("[API] dcb_trackntrace : [soapenvelope=$soapenvelope]") ; + + &dcb_send_it('TracknTrace') ; + &dcb_parse_it ; + &dcb_read_it('TracknTrace') ; + + # $returnxml = qq~ + # + # + # + # + # Completed + # + # + # + # DEV + # DARREN + # Proof of delivery + # 08052023 + # 0.00 + # 1 + # 15 SIM ROAD + # . + # KEMPTON PARK + # DARREN + # 0834752596 + # ReceiverName TESTING + # 1619 + # POMONA + # + # . + # KEMPTON PARK + # DEV + # 0112302085 + # 1619 + # POMONA + # EC + # YES + # + # DCBDEVLP + # + # + # overrideDefaultSubcontractor + # no + # Dn230505 + # + # + # + # + # + # PODCRE + # 09052023 + # Waybill has been PODed + # JNB + # 0719 + # + # + # WBLCRE + # 05052023 + # Waybill Dn230505 created in import + # JNB + # 0718 + # + # + # 05052023 + # Dn230505 + # + # + # + # +# ~ ; + +} #------------------------------------------------------------------------------- + +sub dcb_postalcode { + + our $soapenvelope = qq~ + + + + + $postal_code + $suburb + + + + ~ ; + + &common_debug("[API] dcb_postalcode : [soapenvelope=$soapenvelope]") ; + + &dcb_send_it('PostalCode') ; + &dcb_parse_it ; + &dcb_read_it('PostalCode') ; + +} #------------------------------------------------------------------------------- + +sub dcb_savewabill { + + my ($venue,$ft,$ev_id) = @_ ; + + my $system_loc = $i{"system_location_$ft\_$ev_id"} ; + my $supplier = $i{"logistics_supplier_id_$ft\_$ev_id"} ; + my $status = $i{"status_$ft\_$ev_id"} ; + my $waybill_nr = $i{"waybill_nr_$ft\_$ev_id"} ; + my $items = $i{"item_$ft\_$ev_id"} ; + my $poc = $i{"poc_$ft\_$ev_id"} ; + my $special_instructions = $i{"special_instructions_$ft\_$ev_id"} ; + + # my $dest = ($ft eq 'to') ? $db{organisations}{$venue}{name} : $db{logistics_locations}{$system_loc}{location} ; + # my $orig = ($ft eq 'from') ? $db{organisations}{$venue}{name} : $db{logistics_locations}{$system_loc}{location} ; + + my $dest = ($ft eq 'from') ? $db{logistics_locations}{$system_loc}{location} : ($routeCode) ? substr($routeCode,0,3) : $db{organisations}{$venue}{region_code} ; + my $orig = ($ft eq 'to') ? $db{logistics_locations}{$system_loc}{location} : ($routeCode) ? substr($routeCode,0,3) : $db{organisations}{$venue}{region_code} ; + + my ($poc_name,$poc_nr) = split(/\_/,$poc) ; + + if ($dest =~ /ITV/) { $dest =~ s/\ITV//g ; $dest =~ s/ //g ; } + elsif ($orig =~ /ITV/) { $orig =~ s/\ITV//g ; $orig =~ s/ //g ; } + + # my $accountnumber = ($testdcd) ? 'DCBMAILBAG' : 'DI31F' ; + my $accountnumber = ($testdcd) ? 'DCBMAILBAG' : 'DI31' ; + + our $soapenvelope = qq~ + + + + + + $accountnumber + $address1 + $address2 + $address3 + $address4 + $poc_nr + $poc_name + + $dcbdate + $dest + $waybill_nr + $orig + $postal_code + $suburb + $db{organisations}{$venue}{name} + $routeCode + $special_instructions + 1 + + + + ~ ; + + &common_debug("[API] dcb_savewabill : [soapenvelope=$soapenvelope]") ; + + &dcb_send_it('savewabill') ; + &dcb_parse_it ; + &dcb_read_it('savewabill') ; + +} #------------------------------------------------------------------------------- + +sub dcb_upload_oms_waybill { + + my ($venue,$ft,$ev_id) = @_ ; + + my $tbl_log_loc = 'logistics_locations' ; + my $tbl_org = 'organisations' ; + my $system_loc = $i{"system_location_$ft\_$ev_id"} ; + my $supplier = $i{"logistics_supplier_id_$ft\_$ev_id"} ; + my $status = $i{"status_$ft\_$ev_id"} ; + my $waybill_nr = $i{"waybill_nr_$ft\_$ev_id"} ; + my $items = $i{"item_$ft\_$ev_id"} ; + my $poc = $i{"poc_$ft\_$ev_id"} ; my ($poc_name,$poc_nr) = split(/\_/,$poc) ; + # my $special_instructions = $i{"special_instructions_$ft\_$ev_id"} ; + + my $start_end = ($ft eq 'from') ? 'end' : 'start' ; + my $special_instructions = "Event $start_end : $dcbdate. " . $i{"special_instructions_$ft\_$ev_id"} ; + + $rec{address1} = $address1 ; + $rec{address1} .= ', ' if $address1 && $address2 ; + $rec{address1} .= $address2 if $address2 ; + $rec{address2} = $address3 ; + $rec{address2} .= ', ' if $address3 && $address4 ; + $rec{address2} .= $address4 if $address4 ; + $rec{city} = $city ; + $rec{suburb} = $suburb ; + $rec{postal_code} = $postal_code ; + $rec{poc_name} = $poc_name ; + $rec{poc_nr} = $poc_nr ; + $rec{name} = $db{$tbl_org}{$venue}{name} ; + $rec{routecode} = $routeCode ; + + $send{address1} = $db{$tbl_log_loc}{$system_loc}{address_line_1} ; + $send{address1} .= ', ' if $db{$tbl_log_loc}{$system_loc}{address_line_1} && $db{$tbl_log_loc}{$system_loc}{address_line_2} ; + $send{address1} .= $db{$tbl_log_loc}{$system_loc}{address_line_2} if $db{$tbl_log_loc}{$system_loc}{address_line_2} ; + $send{address2} = $db{$tbl_log_loc}{$system_loc}{address_line_3} ; + $send{address2} .= ', ' if $db{$tbl_log_loc}{$system_loc}{address_line_3} && $db{$tbl_log_loc}{$system_loc}{address_line_4} ; + $send{address2} .= $db{$tbl_log_loc}{$system_loc}{address_line_4} if $db{$tbl_log_loc}{$system_loc}{address_line_4} ; + $send{city} = $db{$tbl_log_loc}{$system_loc}{city} ; + $send{suburb} = $db{$tbl_log_loc}{$system_loc}{suburb} ; + $send{postal_code} = $db{$tbl_log_loc}{$system_loc}{postal_code} ; + $send{poc_name} = $db{$tbl_log_loc}{$system_loc}{poc_name} ; + $send{poc_nr} = $db{$tbl_log_loc}{$system_loc}{poc_nr} ; + $send{name} = $db{$tbl_log_loc}{$system_loc}{location} ; + $send{routecode} = $db{$tbl_log_loc}{$system_loc}{dcb_route_code} ; + + # my $dest = ($ft eq 'from') ? $db{$tbl_log_loc}{$system_loc}{location} : ($routeCode) ? substr($routeCode,0,3) : $db{$tbl_log_loc}{$venue}{region_code} ; + # my $orig = ($ft eq 'to') ? $db{$tbl_log_loc}{$system_loc}{location} : ($routeCode) ? substr($routeCode,0,3) : $db{$tbl_log_loc}{$venue}{region_code} ; + + if ($ft eq 'from') { + foreach (keys %rec) { + my $rec = $rec{$_} ; + $rec{$_} = $send{$_} ; + $send{$_} = $rec ; + } + } + + # if ($dest =~ /ITV/) { $dest =~ s/\ITV//g ; $dest =~ s/ //g ; } + # elsif ($orig =~ /ITV/) { $orig =~ s/\ITV//g ; $orig =~ s/ //g ; } + + # our $soapenvelope = qq~ + # + # + # + # + # DCBMAILBAG + # $items_cnt~; + + # my $accountnumber = ($testdcd) ? 'DCBMAILBAG' : 'DI31F' ; + my $accountnumber = ($testdcd) ? 'DCBMAILBAG' : 'DI31' ; + + our $soapenvelope = qq~ + + + + + $accountnumber + + + + + + + 0 + + + $items_cnt~; + + for my $parcel_cnt (1 .. $items_cnt) { + my $parcel_qty = ($db{logistics_items}{$items[$parcel_cnt-1]}{qty}) ? $db{logistics_items}{$items[$parcel_cnt-1]}{qty} : 1 ; + my $parcel_desc = ($db{logistics_items}{$items[$parcel_cnt-1]}{name}) ? $db{logistics_items}{$items[$parcel_cnt-1]}{name} : 1 ; + $soapenvelope .= qq~ + + + STD + G + 0 + 1 + $parcel_desc + 1 + 1 + 1 + $parcel_cnt + $parcel_qty + + ~; + } + + $soapenvelope .= qq~ + $rec{address1} + $rec{address2} + $rec{city} + $rec{poc_name} + $rec{poc_nr} + $rec{name} + $rec{postal_code} + $rec{routecode} + $rec{suburb} + $send{address1} + $send{address2} + $send{city} + $send{poc_name} + $send{poc_nr} + $send{name} + $send{postal_code} + $send{routecode} + $send{suburb} + OE + $special_instructions + $waybill_nr + + + +~ ; + + &common_debug("[API] dcb_upload_oms_waybill : [soapenvelope=$soapenvelope]") ; + + &dcb_send_it('UploadOMSWaybill') ; + &dcb_parse_it ; + &dcb_read_it('UploadOMSWaybill') ; + +} #------------------------------------------------------------------------------- + +sub dcb_send_it { + + my ($soapaction) = @_ ; + + my $environment = ($testdcd) ? 'APIUAT' : 'API' ; + + my $header_soapaction = "http://tempuri.org/IOMSIntegrate/$soapaction" ; + my $host = "https://dcboms.co.za/$environment/OMSIntegrate.svc" ; + + &common_write_log("dcb/xml_send_$now_year\_$now_mm.log","$now_ccyymmddhrmnsc|$now_ccyy_mm_ddT$now_hh_min_sec|$soapaction|$host|$header_soapaction|$soapenvelope|"); + + &common_debug("[API] dcb_send_it : [host=$host]") ; + &common_debug("[API] dcb_send_it : [soapaction=$header_soapaction]") ; + + if ($testing == 1 && $useropts{it}{$username} && $soapaction ne 'PostalCode') { &common_debug(">>>>>> *** TESTING, $soapaction API call NOT SENT *** <<<<<<") ; return ; } + + my $userAgent = LWP::UserAgent->new(); + my $request = HTTP::Request->new(POST => $host); + $request->header(SOAPAction => "$header_soapaction"); + $request->content($soapenvelope); + $request->content_type("text/xml; charset=utf-8"); + my $response = $userAgent->request($request); + + # Check response + my $response_code = $response -> code ; + my $response_content = $response -> content ; + + &common_debug("[API] dcb_send_it : [response_code=$response_code]") ; + &common_debug("[API] response_content : [response_content=$response_content]") ; + + $returnxml = $response_content ; + + &common_write_log("dcb/xml_response_$now_year\_$now_mm.log","$now_ccyymmddhrmnsc|$now_ccyy_mm_ddT$now_hh_min_sec|$soapaction|$response_code|$returnxml|"); + +} #------------------------------------------------------------------------------- + +sub dcb_parse_it { + + # use Data::Dumper; + # print Dumper(\$returnxml); + # exit; + + $returnxml =~ s/[\x80-\xFF]/?/g ; + my $xml = new XML::Simple or die "Cant instantiate object XML::Simple $!" ; + # my $xmldata = $xml->XMLin($returnxml) or die "Cant open xmldata $!" ; + $xmldata = $xml->XMLin($returnxml, forcearray => 1) or die "Cant open xmldata $!"; + + if ($debug) { + use Data::Dumper; + print Dumper(\$xmldata); + # exit ; + } + +} #------------------------------------------------------------------------------- + +sub dcb_read_it { + + my ($soapaction) = @_ ; + + # my $result = '' ; + + if ($soapaction eq 'UploadOMSWaybill') { + our $uploadwaybillresult = $xmldata->{'s:Body'}->[0]->{'UploadOMSWaybillResponse'}->[0]->{'UploadOMSWaybillResult'}->[0] ; + } elsif ($soapaction eq 'savewabill') { + our $savewabillResult = $xmldata->{'s:Body'}->[0]->{'savewabillResponse'}->[0]->{'savewabillResult'}->[0] ; + } elsif ($soapaction eq 'PostalCode') { + our $routeCode = '' ; # our $routeCode = '' ; + foreach my $hashref (@{$xmldata->{'s:Body'}->[0]->{'PostalCodeResponse'}->[0]->{'PostalCodeResult'}->[0]->{'a:ArrayOfpostalCode'} } ) { + foreach $address (@{$hashref}{'a:postalCode'}) { + $routeCode = ${$hashref}{'a:postalCode'}->[0]->{'a:routeCode'}->[0] ; + } + } + # $routeCode = substr($routeCode,0,3) ; + } elsif ($soapaction eq 'TracknTrace') { + + + foreach my $hashref (@{$xmldata->{'s:Body'}->[0]->{'TracknTraceResponse'}->[0]->{'TracknTraceResult'}->[0]->{'a:Waybill'} } ) { + + $trackntrace{booking_date} = (ref(${$hashref}{'a:BookingDate'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:BookingDate'}->[0] ; + $trackntrace{comments} = ${$hashref}{'a:Comments'}->[0]->{'content'} ; + $trackntrace{consignee_name} = (ref(${$hashref}{'a:ConsigneeName'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ConsigneeName'}->[0] ; + $trackntrace{consignor_name} = (ref(${$hashref}{'a:ConsignorName'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ConsignorName'}->[0] ; + $trackntrace{current_status} = (ref(${$hashref}{'a:CurrentStatus'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:CurrentStatus'}->[0] ; + $trackntrace{delivery_date} = (ref(${$hashref}{'a:DeliveryDate'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:DeliveryDate'}->[0] ; + $trackntrace{insured_value} = (ref(${$hashref}{'a:InsuredValue'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:InsuredValue'}->[0] ; + $trackntrace{number_of_parcels} = (ref(${$hashref}{'a:NumberOfParcels'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:NumberOfParcels'}->[0] ; + $trackntrace{receiver_address_line_1} = (ref(${$hashref}{'a:ReceiverAddressLine1'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ReceiverAddressLine1'}->[0] ; + $trackntrace{receiver_address_line_2} = (ref(${$hashref}{'a:ReceiverAddressLine2'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ReceiverAddressLine2'}->[0] ; + $trackntrace{receiver_city} = (ref(${$hashref}{'a:ReceiverCity'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ReceiverCity'}->[0] ; + $trackntrace{receiver_contact_name} = (ref(${$hashref}{'a:ReceiverContactName'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ReceiverContactName'}->[0] ; + $trackntrace{receiver_contact_tel_1} = (ref(${$hashref}{'a:ReceiverContactTel1'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ReceiverContactTel1'}->[0] ; + $trackntrace{receiver_name} = ${$hashref}{'a:ReceiverName'}->[0]->{'content'} ; + $trackntrace{receiver_postal_code} = (ref(${$hashref}{'a:ReceiverPostalCode'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ReceiverPostalCode'}->[0] ; + $trackntrace{receiver_suburb} = (ref(${$hashref}{'a:ReceiverSuburb'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ReceiverSuburb'}->[0] ; + $trackntrace{sender_address_line_1} = (ref(${$hashref}{'a:SenderAddressLine1'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:SenderAddressLine1'}->[0] ; + $trackntrace{sender_address_line_2} = (ref(${$hashref}{'a:SenderAddressLine2'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:SenderAddressLine2'}->[0] ; + $trackntrace{sender_city} = (ref(${$hashref}{'a:SenderCity'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:SenderCity'}->[0] ; + $trackntrace{sender_contact_name} = (ref(${$hashref}{'a:SenderContactName'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:SenderContactName'}->[0] ; + $trackntrace{sender_contact_tel} = (ref(${$hashref}{'a:SenderContactTel'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:SenderContactTel'}->[0] ; + $trackntrace{sender_postal_code} = (ref(${$hashref}{'a:SenderPostalCode'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:SenderPostalCode'}->[0] ; + $trackntrace{sender_suburb} = (ref(${$hashref}{'a:SenderSuburb'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:SenderSuburb'}->[0] ; + $trackntrace{service_type_code} = (ref(${$hashref}{'a:ServiceTypeCode'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ServiceTypeCode'}->[0] ; + $trackntrace{shipment_is_insured} = (ref(${$hashref}{'a:ShipmentIsInsured'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ShipmentIsInsured'}->[0] ; + $trackntrace{shipper_reference} = (ref(${$hashref}{'a:ShipperReference'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:ShipperReference'}->[0]->{''} ; + $trackntrace{account_nr} = (ref(${$hashref}{'a:accNr'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:accNr'}->[0] ; + $trackntrace{pod} = ${$hashref}{'a:pod'}->[0]->{'xmlns:b'} ; + $trackntrace{waybill_date} = (ref(${$hashref}{'a:waybillDate'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:waybillDate'}->[0] ; + $trackntrace{waybill_number} = (ref(${$hashref}{'a:waybillNumber'}->[0]) eq 'HASH') ? '' : ${$hashref}{'a:waybillNumber'}->[0] ; + + my $additional_info = $hashref->{'a:additionalInformation'}->[0]->{'b:AdditionalInformation'}->[0]; + $trackntrace{additional_information}{additional_info_code} = (ref($additional_info->{'b:additionalInfoCode'}->[0]) eq 'HASH') ? '' : $additional_info->{'b:additionalInfoCode'}->[0]; + $trackntrace{additional_information}{additional_info_value} = (ref($additional_info->{'b:additionalInfoValue'}->[0]) eq 'HASH') ? '' : $additional_info->{'b:additionalInfoValue'}->[0]; + $trackntrace{additional_information}{waybill_number} = (ref($additional_info->{'b:waybillNumber'}->[0]) eq 'HASH') ? '' : $additional_info->{'b:waybillNumber'}->[0]; + + my $tracking_details = $hashref->{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}; + for my $i (0..$#$tracking_details) { + my $event_index = $i + 1; + $trackntrace{tracking_detail}{event_code}{$event_index} = (ref($tracking_details->[$i]->{'b:eventCode'}->[0]) eq 'HASH') ? '' : $tracking_details->[$i]->{'b:eventCode'}->[0]; + $trackntrace{tracking_detail}{event_date}{$event_index} = (ref($tracking_details->[$i]->{'b:eventDate'}->[0]) eq 'HASH') ? '' : $tracking_details->[$i]->{'b:eventDate'}->[0]; + $trackntrace{tracking_detail}{event_description}{$event_index} = (ref($tracking_details->[$i]->{'b:eventDescription'}->[0]) eq 'HASH') ? '' : $tracking_details->[$i]->{'b:eventDescription'}->[0]; + $trackntrace{tracking_detail}{event_hub_code}{$event_index} = (ref($tracking_details->[$i]->{'b:eventHubCode'}->[0]) eq 'HASH') ? '' : $tracking_details->[$i]->{'b:eventHubCode'}->[0]; + $trackntrace{tracking_detail}{event_time}{$event_index} = (ref($tracking_details->[$i]->{'b:eventTime'}->[0]) eq 'HASH') ? '' : $tracking_details->[$i]->{'b:eventTime'}->[0]; + } + + # $trackntrace{additional_information}{additional_info_code} = ${$hashref}{'a:additionalInformation'}->[0]->{'b:AdditionalInformation'}->[0]->{'b:additionalInfoCode'}->[0] ; + # $trackntrace{additional_information}{additional_info_value} = ${$hashref}{'a:additionalInformation'}->[0]->{'b:AdditionalInformation'}->[0]->{'b:additionalInfoValue'}->[0] ; + # $trackntrace{additional_information}{waybill_number} = ${$hashref}{'a:additionalInformation'}->[0]->{'b:AdditionalInformation'}->[0]->{'b:waybillNumber'}->[0] ; + + # $trackntrace{tracking_detail}{event_code}{1} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[0]->{'b:eventCode'}->[0] ; + # $trackntrace{tracking_detail}{event_date}{1} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[0]->{'b:eventDate'}->[0] ; + # $trackntrace{tracking_detail}{event_description}{1} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[0]->{'b:eventDescription'}->[0] ; + # $trackntrace{tracking_detail}{event_hub_code}{1} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[0]->{'b:eventHubCode'}->[0] ; + # $trackntrace{tracking_detail}{event_time}{1} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[0]->{'b:eventTime'}->[0] ; + + # $trackntrace{tracking_detail}{event_code}{2} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[1]->{'b:eventCode'}->[0] ; + # $trackntrace{tracking_detail}{event_date}{2} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[1]->{'b:eventDate'}->[0] ; + # $trackntrace{tracking_detail}{event_description}{2} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[1]->{'b:eventDescription'}->[0] ; + # $trackntrace{tracking_detail}{event_hub_code}{2} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[1]->{'b:eventHubCode'}->[0] ; + # $trackntrace{tracking_detail}{event_time}{2} = ${$hashref}{'a:trackingDetail'}->[0]->{'b:TrackingDetail'}->[1]->{'b:eventTime'}->[0] ; + + } + + } + + # return ($result) ; + + # print "\n" . $xmldata->{'s:Body'}->[0]->{'savewabillResponse'}->[0]->{'savewabillResult'}->[0] ; + + # return unless $event_id ; + # return unless $from_to ; + + # &db_min_ro("event_quotes","1,logistics_dcb_waybill","`id`='$event_id'","","") ; + + # my @waybill_nrs = split(/\-/,$db{event_quotes}{1}{logistics_waybill_nrs}) ; + # my @dcb_waybill = split(/\-/,$logistics_dcb_waybill) ; + + # my $dcb_waybill = ($from_to eq 'to') ? "$dcb_waybill[0]-1" : "1-$dcb_waybill[1]" ; + + # $ii{$event_id}{logistics_dcb_waybill} = $dcb_waybill ; + + # our $testing = 1 ; + + # &db_min_upd('event_quotes',"`id`='$event_id'") ; + # &db_min_upd('event_quotes',"`id`='5136'") ; + +} #------------------------------------------------------------------------------- + +# sub dcb_send_it_get_route_code { + + # my ($postal_code,$suburb) = @_ ; + + # my $message = qq~ + # + # + # + # + # $postal_code + # $suburb + # + # + # + # + # ~ ; + + # if ($debug) { + # print $message; + # } + + # my $userAgent = LWP::UserAgent->new(); + # my $request = HTTP::Request->new(POST => 'https://dcboms.co.za/APIUAT/OMSIntegrate.svc'); + # $request->header(SOAPAction => '"http://tempuri.org/IOMSIntegrate/savewabill"'); + # $request->content($message); + # $request->content_type("text/xml; charset=utf-8"); + # my $response = $userAgent->request($request); + + # # Check response + # my $response_code = $response -> code ; + # my $response_content = $response -> content ; + + # $returnxml = $response_content ; + +# } #------------------------------------------------------------------------------- + + +1 ; \ No newline at end of file diff --git a/libs/modules/_FromProd/v1.0/dialog.pm b/libs/modules/_FromProd/v1.0/dialog.pm new file mode 100644 index 0000000..1d8643b --- /dev/null +++ b/libs/modules/_FromProd/v1.0/dialog.pm @@ -0,0 +1,34 @@ +#--------------------------------------------------------------------------------- + +sub dialog_common { + +$dialog{'common'}{'head'} = qq( + + + + $useropts{short} Admin + + + + + + + + + + + + + + + + +) ; + +} #------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/_FromProd/v1.0/event_email.pm b/libs/modules/_FromProd/v1.0/event_email.pm new file mode 100644 index 0000000..6c175cc --- /dev/null +++ b/libs/modules/_FromProd/v1.0/event_email.pm @@ -0,0 +1,146 @@ + +sub create_event_email_table { + + my ($event_id) = @_ ; + + &db_min_ro('event_quotes','1,country_id,event_system_id_multiple,type_details_id,qty,club_name,operator_ids,ref,organisation_ids,date_from,date_to,poc_name,poc_contact_nr,type,sport_type_ids,region_id,city_id,quote_to,category_id_1,category_id_2,additional_notes,user_id,format_of_title',"`id`='$event_id'",'','') ; + + # &db_min_ro('user_type','id,name,email,user_type',"",'','') ; + &db_min_ro('users','id,name,email,user_type',"",'','') ; + + our %operator_email = () ; + foreach (keys %{$db{user_type}}) { + $operator_email{$db{user_type}{$_}{email}} = 1 if substr($db{user_type}{$_}{user_type},0,6) eq 'casual' and $db{user_type}{$_}{email} ; + } + + my $system_details = "" ; + + &db_min_ro('event_type_details','id,name','','','') ; + + foreach (split(",",$db{event_quotes}{1}{type_details_id})) { + $system_details .= qq~$db{event_type_details}{$_}{name},~ ; + } + chop $system_details if $system_details ; + + &db_min_ro('sport_types','id,name','','','') ; + + &db_min_ro('event_systems','id,name','','','') ; + + my $SystemName = qq~~ ; + + foreach (split(";",$db{$table}{$qt_id}{event_system_id_multiple})) { + $SystemName .= qq~$db{event_systems}{$_}{name},~ ; + } + chop $SystemName if $SystemName ; + + &db_min_ro('event_quotes_categories','id,category','','','') ; + + &db_min_ro('regions','id,name','','','') ; + + &db_min_ro('countries','1,name,country',"`id`='$db{event_quotes}{1}{country_id}'",'','') ; + + &db_min_ro('cities','id,city','','','') ; + + &db_min_ro('organisations','id,name','','','') ; + + &db_min_ro('customers','id,name','','','') ; + + &db_min_ro('event_types','1,name',"`id`='$db{event_quotes}{1}{type}'",'','') if $db{event_quotes}{1}{type} ; + + &db_min_ro('event_quotes_min','1,category_details',"`id`='$event_id'",'','') ; + + my @cat_details = split('\|;\|',$db{event_quotes_min}{1}{category_details}) ; + + our $sports = qq~~ ; + + foreach (split(",",$db{event_quotes}{1}{sport_type_ids})) { + + $sports .= qq~$db{sport_types}{$_}{name},~ ; + + } + + chop $sports if $sports ; + + my $venues = qq~~ ; + + foreach (split(",",$db{event_quotes}{1}{organisation_ids})) { + + $venues .= qq~$db{organisations}{$_}{name},~ ; + + } + + chop $venues if $venues ; + + my $op_cnt = qq~~ ; my $op_names = qq~~ ; + + foreach (split(",",$db{event_quotes}{1}{operator_ids})) { + $op_cnt++ ; + $op_names .= qq~$db{users}{$_}{name},~ ; + } + chop $op_names if $op_names ; + $op_names = qq~$op_cnt [$op_names]~ if $op_names; + + my %event_details = () ; + + my $city_name = qq~~ ; + $city_name .= qq~$db{cities}{$db{event_quotes}{1}{city_id}}{city},~ if $db{cities}{$db{event_quotes}{1}{city_id}}{city} ; + $city_name .= qq~$db{regions}{$db{event_quotes}{1}{region_id}}{name},~ if $db{regions}{$db{event_quotes}{1}{region_id}}{name} ; + $city_name .= qq~$db{countries}{1}{name} [$db{countries}{1}{country}]~ ; + + $event_details{Client} = qq~Client$db{customers}{$db{event_quotes}{1}{quote_to}}{name}~ ; + $event_details{EventName} = qq~Event Name$db{event_quotes}{1}{ref} [$event_id]~ ; + $event_details{DateFrom} = qq~Event Date/Time From $db{event_quotes}{1}{date_from}~ if $db{event_quotes}{1}{date_from} ; + $event_details{DateTo} = qq~Event Date/Time To $db{event_quotes}{1}{date_to}~ if $db{event_quotes}{1}{date_to} ; + $event_details{Type} = qq~Type of System $db{event_types}{1}{name}~ if $db{event_types}{1}{name} ; + $event_details{SystemDetails} = qq~System Details $system_details~ if $system_details ; + $event_details{SystemName} = qq~System Name $SystemName~ if $SystemName ; + $event_details{ClubName} = qq~Club Name $db{event_quotes}{1}{club_name}~ if $db{event_quotes}{1}{club_name} ; + $event_details{Days} = qq~Days $db{event_quotes}{1}{qty}~ if $db{event_quotes}{1}{qty} ; + $event_details{NrofOperators} = qq~Nr of Operators $op_names~ if $op_names ; + $event_details{SportTypes} = qq~Sport Types(s) $sports~ if $sports ; + $event_details{City} = qq~City $city_name~ ; + $event_details{Venue} = qq~Venue(s) $venues~ if $venues ; + $event_details{PocName} = qq~Poc Name $db{event_quotes}{1}{poc_name}~ if $db{event_quotes}{1}{poc_name} ; + $event_details{PocContactNr} = qq~Poc Contact Nr $db{event_quotes}{1}{poc_contact_nr}~ if $db{event_quotes}{1}{poc_contact_nr} ; + + $cat_details[0] =~ s/\n/,/g; $cat_details[1] =~ s/\n/,/g; $db{event_quotes}{1}{additional_notes} =~ s/\n/,/g; $db{event_quotes}{1}{format_of_title} =~ s/\n/,/g; + + $event_details{Category1} = qq~Category 1 $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_1}}{category}~ if $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_1}}{category} ; + $event_details{Category1Details} = qq~Category 1 Details $cat_details[0]~ if $cat_details[0] ; + $event_details{Category2} = qq~Category 2 $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_2}}{category}~ if $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_2}}{category} ; + $event_details{Category2Details} = qq~Category 2 Details $cat_details[1]~ if $cat_details[1] ; + $event_details{AdditionalNotes} = qq~Additional Notes $db{event_quotes}{1}{additional_notes}~ if $db{event_quotes}{1}{additional_notes} ; + $event_details{format_of_title} = qq~Format of TITLE to be followed 
    when scheduling events $db{event_quotes}{1}{format_of_title}~ if $db{event_quotes}{1}{format_of_title} ; + + our $table_message = qq~ + $event_details{Client} + $event_details{EventName} + $event_details{DateFrom} + $event_details{DateTo} + $event_details{Type} + $event_details{SystemDetails} + $event_details{SystemName} + $event_details{ClubName} + $event_details{Days} + $event_details{NrofOperators} + $event_details{SportTypes} + $event_details{City} + $event_details{Venue} + $event_details{PocName} + $event_details{PocContactNr} + $event_details{Category1} + $event_details{Category1Details} + $event_details{Category2} + $event_details{Category2Details} + $event_details{AdditionalNotes} + $event_details{format_of_title} + ~ ; + + $message = qq~Good day + +Please find attached event details.~ ; + + +} #------------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/_FromProd/v1.0/event_tabs.pm b/libs/modules/_FromProd/v1.0/event_tabs.pm new file mode 100644 index 0000000..779c63b --- /dev/null +++ b/libs/modules/_FromProd/v1.0/event_tabs.pm @@ -0,0 +1,5118 @@ +sub build_workings_costings_forms_jquery { + + my $description_options_costing = $opts{"description_costing_event_1"} ; + $description_options_costing =~ s/\SELECTED//g ; + $description_options_costing =~ s/\"/\'/g ; + + my $description_options_workings = $opts{"description_workings_event_1"} ; + $description_options_workings =~ s/\SELECTED//g ; + $description_options_workings =~ s/\"/\'/g ; + + our $operator_options = $opts{"operator_workings_event_1"} ; + $operator_options =~ s/\SELECTED//g ; + $operator_options =~ s/\"/\'/g ; + + my $btn_ids_string = join(",",@btn_ids) ; + + my $excl_field_ids_string = join(",",@excl_field_ids) ; + my $description_field_ids_string = join(",",@description_field_ids) ; + my $operator_field_ids_string = join(",",@operator_field_ids) ; + my $vat_field_ids_string = join(",",@vat_field_ids) ; + my $qty_field_ids_string = join(",",@qty_field_ids) ; + my $amount_usd_field_ids_string = join(",",@amount_usd_field_ids) ; + + $trigger_jquery_raw .= qq~ + // function update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days + function get_tab (id) { + let tab = "" ; + if (id.includes("workings_event")) { + tab = "workings_event" ; + } else if (id.includes("costing_event")) { + tab = "costing_event" ; + } + return tab ; + } + + function changed_vat (id) { + let tab = get_tab (id) ; + let row_nr = get_row_nr(id) ; + calc_totals(row_nr,tab) ; + } + + function changed_others (id) { + + let row_nr = get_row_nr(id) ; + let firstIndex = id.indexOf('_'); + let col = id.substring(0,firstIndex); + let tab = get_tab (id) ; + if (col == "inputAmount") { + let inp = parseFloat(\$("#"+id).val()) ; + inp = parseFloat(inp) ; + \$("#"+id).val(inp.toFixed(2)) ; + } else if (\$("#selectDescription_"+tab+"_"+row_nr).val() && \$("#selectDescription_"+tab+"_"+row_nr).val() != 14 && \$("#selectOperator_"+tab+"_"+row_nr).val()) { + // \$("#selectOperator_"+tab+"_"+row_nr).val("") ; + // \$("#selectOperator_"+tab+"_"+row_nr).trigger("chosen:updated") ; + } + // else if (col == "selectOperator" && \$("#selectDescription"+tab+"_"+row_nr).val() != 14) { + + // } + + if (col == "selectOperator") { // || (col == "selectDescription" && \$("#selectDescription_"+tab+"_"+row_nr).val( + return ; + } + + calc_totals(row_nr,tab) ; + } + + // \$("$vat_field_ids_string").change(function() { + \$("#content").on("change","[id^='checkboxVat_']", function () { + const id = this.id ; + changed_vat(id) ; + }); + + // \$("$excl_field_ids_string,$description_field_ids_string,$qty_field_ids_string,$amount_usd_field_ids_string,$operator_field_ids_string").change(function() { + \$("#content").on("change","[id^='checkboxExcl_'],[id^='selectDescription_'],[id^='inputQty_'],[id^='inputAmount_usd_'],[id^='selectOperator_workings_event_']", function () { + const id = this.id ; + + if ((id.includes("inputQty_") || id.includes("inputAmount_usd_")) && id.includes("costing_event")) { + + let row_nr = get_row_nr(id) ; + + let f_t = (\$("input[name='added_full_day_cost_item_"+row_nr+"']").val()) ? "full" : (\$("input[name='added_half_day_cost_item_"+row_nr+"']").val()) ? "half" : "" ; + + if (f_t) { + + let col = (id.includes("inputQty_")) ? "-2" : "-1" ; + + let full_half_add = \$("input[name='added_"+f_t+"_day_cost_item_"+row_nr+"']").val() ; + + let get_e_cost_id = (id.includes("inputAmount_usd_")) ? get_row_nr(\$("input[name='added_"+f_t+"_day_cost_item_"+row_nr+"']").val()) : "" ; + + if (((id.includes("inputQty_") && \$(this).val() == nr_days[f_t]) || (id.includes("inputAmount_usd_") && \$(this).val() == default_cost_item_rates[f_t+","+get_e_cost_id])) && full_half_add && full_half_add.includes(col)) { + full_half_add = full_half_add.replace(col+"_","") ; + \$("input[name='added_"+f_t+"_day_cost_item_"+row_nr+"']").val(full_half_add) ; + } else if (full_half_add && !full_half_add.includes(col)) { + \$("input[name='added_"+f_t+"_day_cost_item_"+row_nr+"']").val(col+"_"+full_half_add) ; + } + } + + } else if (id.includes("selectDescription_")) { + + let this_id = id ; + + let row_nr = get_row_nr(id) ; + + let tab = (this_id.includes("_costing_event_")) ? "costing_event" : (this_id.includes("_workings_event_")) ? "workings_event" : "" ; + + let full_day_exists = nr_days["full"] ; let half_day_exists = nr_days["half"] ; + + let already_loaded_full_day = (\$("#"+this_id).val()) ? \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val() : "" ; + let already_loaded_half_day = (\$("#"+this_id).val()) ? \$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val() : "" ; + + already_loaded_full_day = (typeof already_loaded_full_day == 'undefined') ? "" : 1 ; + already_loaded_half_day = (typeof already_loaded_half_day == 'undefined') ? "" : 1 ; + + if (already_loaded_full_day && already_loaded_half_day) { + return ; + } + + if (already_loaded_full_day == 1) { + full_day_exists = 0 ; + } + + if (already_loaded_half_day == 1) { + half_day_exists = 0 ; + } + + let date_from = \$("input[name='date_from']").val() ; + + date_from = date_from.substring(0,10) ; + + let full_half_day = 0 ; + + if (full_day_exists != 0) { + if ((typeof \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val() == 'undefined' || \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val()) && \$("#"+this_id).val()) { + \$("#content").append("") ; + } + full_half_day = 1 ; + // } else if (half_day_exists || (already_loaded_full_day && !half_day_exists && !already_loaded_half_day)) { + } else if (half_day_exists != 0) { + if ((typeof \$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val() == 'undefined' || !\$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val()) && \$("#"+this_id).val()) { + \$("#content").append("") ; + } + full_half_day = 2 ; + } + + let rate_ = "" ; + + if (default_cost_item_rates["full,"+\$("#"+this_id).val()] && full_half_day == 1) { + rate_ = default_cost_item_rates["full,"+\$("#"+this_id).val()] ; + } else if (default_cost_item_rates["half,"+\$("#"+this_id).val()] && full_half_day == 2) { + rate_ = default_cost_item_rates["half,"+\$("#"+this_id).val()] ; + } + if (rate_ == "") { + \$("input[name='added_full_day_cost_item_"+row_nr+"']").remove() ; + \$("input[name='added_half_day_cost_item_"+row_nr+"']").remove() ; + return ; + } + full_half_day = (full_half_day == 1) ? "full" : (full_half_day == 2) ? "half" : "" ; + + \$("input[name='qty_"+tab+"_"+row_nr+"']").val(nr_days[full_half_day]) ; + \$("input[name='amount_usd_"+tab+"_"+row_nr+"']").val(rate_) ; + \$("input[name='amount_ttl_"+tab+"_"+row_nr+"']").val((rate_*nr_days[full_half_day]).toFixed(2)) ; + if (!\$("input[name='added_"+full_half_day+"_day_cost_item_"+row_nr+"']").val()) { + \$("#"+tab+"_"+row_nr).append("") ; + } else { + \$("input[name='added_"+full_half_day+"_day_cost_item_"+row_nr+"']").val("-3_"+\$(this).val()) ; + } + + calc_totals(row_nr,tab) ; + + + } + + changed_others(id) ; + }); + ~ ; + + $trigger_jquery_raw .= qq~ + + \$("#content").on("click","[id^='btn_workings_event_'],[id^='btn_costing_event_']", function () { + // \$("$btn_ids_string").click(function () { + const id = this.id ; + let tab = get_tab (id) ; + + console.log("id : "+id) ; + console.log("tab : "+tab) ; + + add_quote_expenses_row_all(id,tab) ; + }); + + function add_quote_expenses_row_all (id,tab) { + + let row_nr = get_row_nr(id) ; + \$("#"+tab+"_"+row_nr).show(); + let row_html = "" ; + if (tab == "workings_event") { + row_html = add_quote_expenses_row(row_nr,tab,"$description_options_workings","$operator_options") ; + } else if (tab == "costing_event") { + row_html = add_quote_expenses_row(row_nr,tab,"$description_options_costing","") ; + } + \$("#"+tab+"_"+row_nr).html(row_html); + // \$("#$suffix\_"+row_nr).trigger("chosen:updated") ; + + \$("#selectDescription_"+tab+"_"+row_nr).chosen({ allow_single_deselect:true }) ; + + if (tab == "workings_event") { + \$("#selectOperator_workings_event_"+row_nr).chosen({ allow_single_deselect:true }); + \$("#inputRemarks_workings_event_"+row_nr).css("text-align","") ; + \$("#inputSupplier_workings_event_"+row_nr).css("text-align","") ; + \$("#inputRef_nr_workings_event_"+row_nr).css("text-align","") ; + } + + \$("#btn_"+tab+"_"+row_nr).hide(); + \$("#btn_row_"+tab+"_"+row_nr).hide(); + var v = row_nr + 1 ; + + // \$("#btn_$suffix\_"+v).css("padding-left","16px") ; + \$("#btn_"+tab+"_"+v).html("") ; + \$("#btn_"+tab+"_"+v).show(); + \$("#btn_row_"+tab+"_"+v).show() ; + \$("#2_"+tab+"_"+row_nr).show() ; + + \$("#checkboxExcl_"+tab+"_"+row_nr).prop('checked',false) ; + + // \$("#"+tab+"_"+row_nr).on("change","#checkboxVat_"+tab+"_"+row_nr+"", function() { + // const id = this.id ; + // changed_vat(id) ; + // }); + + // \$("#"+tab+"_"+row_nr).on("change","#checkboxExcl_"+tab+"_"+row_nr+",#selectDescription_"+tab+"_"+row_nr+",#selectOperator_"+tab+"_"+row_nr+",#inputQty_"+tab+"_"+row_nr+",#inputAmount_usd_"+tab+"_"+row_nr+"", function() { + // const id = this.id ; + // changed_others(id) ; + // }); + + } + + ~ if $btn_ids_string ; + + $trigger_jquery_raw .= qq~ + + \$("#selectCurrency").change(function () { + + }) ; + + \$("input[name='roe']").change(function () { + + let roe = \$(this).val() ; + if (roe < 0 || !roe) { + roe = 1 ; + } + \$(this).val(parseFloat(roe).toFixed(2)) ; + + var sub_total = 0 ; var vat_total = 0 ; var sub_total_quote = 0 ; var vat_total_quote = 0 ; + + [sub_total,vat_total] = add_up_totals("workings_event",50,roe,1) ; + [sub_total_quote,vat_total_quote] = add_up_totals("costing_event",30,roe,1) ; + + // // // \$("input[name='income']").val((sub_total_quote+vat_total_quote).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("input[name='income']").val((sub_total_quote+vat_total_quote).toFixed(2)) ; + \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + update_overall_totals(sub_total,vat_total,"workings_event") ; + update_overall_totals(sub_total_quote,vat_total_quote,"costing_event") ; + + }) ; + + function add_up_totals (tab,nr_of_rows,roe,recalc_totals) { + + let sub_total = 0 ; let vat_total = 0 ; + for (let i=1; i<=nr_of_rows; i++) { + if (!\$("#"+tab+"_"+i).html()) { break ; } + if (\$("#selectDescription_"+tab+"_"+i).val()) { + if (\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { continue ; } + let ttl = 0 ; + if (recalc_totals) { + ttl = parseFloat(\$("#inputAmount_usd_"+tab+"_"+i).val()) * parseFloat(\$("#inputQty_"+tab+"_"+i).val()) * parseFloat(roe) ; + } else { + ttl = parseFloat(\$("#inputAmount_ttl_"+tab+"_"+i).val().replace(/,/g, '')) + } + // // // // \$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toFixed(2)) ; + if (!\$("#inputAmount_ttl_"+tab+"_"+i).val() || \$("#inputAmount_ttl_"+tab+"_"+i).val() == "NaN") { + \$("#inputAmount_ttl_"+tab+"_"+i).val("0.00") ; + ttl = 0 ; + } + sub_total += ttl ; + if (\$("#checkboxVat_"+tab+"_"+i).is(":checked")) { + vat_total += ttl*0.15 ; + } + } else if (!\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { + \$("#checkboxExcl_"+tab+"_"+i).prop('checked',true) ; + } + } + return [sub_total,vat_total] ; + } + + // function getNum(val) { + + // if (isNaN(val)) { + // return 0; + // } + // return val; + // } + + function calc_totals (row_cnt,tab) { + + var qty = \$("#inputQty_"+tab+"_"+row_cnt) ; + var usd = \$("#inputAmount_usd_"+tab+"_"+row_cnt) ; + var conv = \$("#inputAmount_ttl_"+tab+"_"+row_cnt) ; + var excl = \$("#checkboxExcl_"+tab+"_"+row_cnt) ; + var item = \$("#selectDescription_"+tab+"_"+row_cnt) ; + + if (!usd.val() && !conv.val() && !usd.val()) { + // console.log("skip calc_totals_workings") ; + if (!item.val()) { + excl.prop("checked",true) ; + } + return ; + } + + var vat = \$("#checkboxVat_"+tab+"_"+row_cnt) ; + + if (!item.val()) { + + excl.prop("checked",true) ; + vat.prop("checked",true) ; + qty.val("") ; + usd.val("") ; + conv.val(""); + if (tab == "workings_event") { + var rem = \$("#inputRemarks_"+tab+"_"+row_cnt) ; + var sup = \$("#inputSupplier_"+tab+"_"+row_cnt) ; + var ref = \$("#inputRef_nr_"+tab+"_"+row_cnt) ; + var op = \$("#selectOperator_"+tab+"_"+row_cnt) ; + rem.val("") ; + sup.val("") ; + ref.val("") ; + op.val("") ; + op.trigger("chosen:updated") ; + } + // } else if (excl.is(":checked") && item.val() && conv.val() == "0.00") { + } else if (excl.is(":checked")) { + excl.prop("checked",false) ; + } + + if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) ; } + + let roe = parseFloat(\$("#inputRoe").val()) ; + + let ttl = usd.val() * qty.val() * roe ; + + // // // conv.val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + conv.val(ttl.toFixed(2)) ; + + let sub_total = 0 ; let vat_total = 0 ; + + let nr_of_rows = 50 ; + if (tab == "costing_event") { + nr_of_rows = 30 ; + } + + [sub_total,vat_total] = add_up_totals (tab,nr_of_rows,roe,0) ; + + if (tab == "workings_event") { + // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + update_overall_totals(sub_total,vat_total,tab) ; + } else { + // // // \$("input[name='income']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; + update_overall_totals(sub_total,vat_total,tab) ; + // update_overall_totals_costings(sub_total,vat_total) ; + } + } + + function update_overall_totals (sub_total,vat_total,tab) { + + let profit_loss = parseFloat(\$("input[name='income']").val().replace(/,/g, '')) - parseFloat(\$("input[name='expenses']").val().replace(/,/g, '')) ; + + // // // \$("input[name='profit_loss']").val(profit_loss.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='sub_total_"+tab+"']").val(sub_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='vat_total_"+tab+"']").val(vat_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + + \$("input[name='profit_loss']").val(profit_loss.toFixed(2)) ; + \$("input[name='sub_total_"+tab+"']").val(sub_total.toFixed(2)) ; + \$("input[name='vat_total_"+tab+"']").val(vat_total.toFixed(2)) ; + \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toFixed(2)) ; + } + + function add_quote_expenses_row (row_nr,tab,options1,options2) { + + let tindex = $tindex ; + tindex = parseInt(tindex) ; + row_nr = parseInt(row_nr) ; + tindex = tindex - 10*(1+50-row_nr) ; + + let row = add_checkbox(row_nr,"excl_"+tab+"_"+row_nr,"checkboxExcl_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + + // row = row+""+add_select(row_nr,"description_"+tab+"_"+row_nr,"selectDescription_"+tab+"_"+row_nr,"Select Description "+row_nr,options1,tindex,2,90,'','') ; tindex++ ; + row = row+add_select(row_nr,"description_"+tab+"_"+row_nr,"selectDescription_"+tab+"_"+row_nr,"Select Description "+row_nr,options1,tindex,2,90,'','') ; tindex++ ; + if (tab == "workings_event") { + row = row+add_select(row_nr,"operator_workings_event_"+row_nr,"selectOperator_workings_event_"+row_nr,"Select Operator "+row_nr,options2,tindex,2,90,'','') ; tindex++ ; + row = row+add_input(row_nr,"remarks_workings_event_"+row_nr,"inputRemarks_workings_event_"+row_nr,"Remarks "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"supplier_workings_event_"+row_nr,"inputSupplier_workings_event_"+row_nr,"Supplier "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"ref_nr_workings_event_"+row_nr,"inputRef_nr_workings_event_"+row_nr,"Ref Nr "+row_nr,tindex,'',1) ; tindex++ ; + } + row = row+add_input(row_nr,"qty_"+tab+"_"+row_nr,"inputQty_"+tab+"_"+row_nr,"Qty "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"amount_usd_"+tab+"_"+row_nr,"inputAmount_usd_"+tab+"_"+row_nr,"Amount "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"amount_ttl_"+tab+"_"+row_nr,"inputAmount_ttl_"+tab+"_"+row_nr,"Total Amount "+row_nr,tindex,"readonly",1) ; tindex++ ; + row = row+add_checkbox(row_nr,"vat_"+tab+"_"+row_nr,"checkboxVat_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + return row ; + } + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub event_tabs_build_qt_left { + + my ($id,$tab,$ret,$demo_page) = @_ ; + + if ($tab == 1) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $title_ = ($demo_page) ? "Demo" : "Event" ; + + my $sec = '_customer_details' ; + + my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + $lcol = 3 ; $fcol = 1 ; $add_form_fields = '' ; + + # $add_form_fields .= qq~
    ~ if $is_schools_manager ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + + my $checked = ($db{$table}{$id}{quote_completed}) ? 'CHECKED' : '' ; + $preferred_title{quote_completed} = "$title_ Completed" ; + $add_form_fields .= &common_min_form_checkbox('quote_completed',$db{$table}{$id}{quote_completed},$checked) ; + + # my $checked = 'CHECKED' if $db{$table}{$id}{quote_accepted} ; + my $checked = ($db{$table}{$id}{quote_accepted}) ? 'CHECKED' : '' ; + $preferred_title{quote_accepted} = "$title_ Accepted" ; + $add_form_fields .= &common_min_form_checkbox('quote_accepted',$db{$table}{$id}{quote_accepted},$checked) ; + + my $checked = ($db{$table}{$id}{quote_rejected}) ? 'CHECKED' : '' ; + $preferred_title{quote_rejected} = "$title_ Rejected" ; + $add_form_fields .= &common_min_form_checkbox('quote_rejected',$db{$table}{$id}{quote_rejected},$checked) ; + + # my $checked = 'CHECKED' if $db{$table}{$id}{quote_pending} or $iaction eq 'add' ; + my $checked = ($db{$table}{$id}{quote_pending} || $iaction eq 'add') ? 'CHECKED' : '' ; + $preferred_title{quote_pending} = "$title_ Pending" ; + $add_form_fields .= &common_min_form_checkbox('quote_pending',$db{$table}{$id}{quote_pending},$checked) ; + + # my $checked = 'CHECKED' if $db{$table}{$id}{quote_cancelled} ; + my $checked = ($db{$table}{$id}{quote_cancelled}) ? 'CHECKED' : '' ; + $preferred_title{quote_cancelled} = "$title_ Cancelled" ; + $add_form_fields .= &common_min_form_checkbox('quote_cancelled',$db{$table}{$id}{quote_cancelled},$checked) ; + + # $add_form_fields .= qq~
    ~ if $is_schools_manager ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + + $fcol = 8 ; + $add_form_fields .= &common_min_form_input('contact_name',$db{$table}{$id}{contact_name},'') ; + $add_form_fields .= &common_min_form_input('address',$db{$table}{$id}{address},'') ; + $add_form_fields .= &common_min_form_input('email',$db{$table}{$id}{email},'') ; + $add_form_fields .= &common_min_form_input('tel',$db{$table}{$id}{tel},'') ; + $fcol = 5 ; + + $add_form_fields .= qq~
     
    ~ ; + + &event_tabs_content_box($sec_name,$sec_col); + + $trigger_jquery_raw .= qq~ + + if (!\$("#checkboxQuote_accepted").is(":checked") && !\$("#checkboxQuote_rejected").is(":checked") && !\$("#checkboxQuote_pending").is(":checked") && !\$("#checkboxQuote_cancelled").is(":checked") && !\$("#checkboxQuote_completed").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked","true") ; + } + + \$("#checkboxQuote_completed,#checkboxQuote_accepted,#checkboxQuote_rejected,#checkboxQuote_pending,#checkboxQuote_cancelled").click( function () { + + if (this.id != 'checkboxQuote_completed' && \$("#checkboxQuote_completed").is(":checked")) { + \$("#checkboxQuote_completed").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_accepted' && \$("#checkboxQuote_accepted").is(":checked")) { + \$("#checkboxQuote_accepted").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_rejected' && \$("#checkboxQuote_rejected").is(":checked")) { + \$("#checkboxQuote_rejected").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_pending' && \$("#checkboxQuote_pending").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_cancelled' && \$("#checkboxQuote_cancelled").is(":checked")) { + \$("#checkboxQuote_cancelled").prop("checked",false) ; + } + + if (this.id == 'checkboxQuote_completed' && !\$("#checkboxQuote_accepted").is(":checked")) { + \$("#checkboxQuote_accepted").prop("checked",true) ; + } + + if (!\$("#checkboxQuote_accepted").is(":checked") && !\$("#checkboxQuote_rejected").is(":checked") && !\$("#checkboxQuote_pending").is(":checked") && !\$("#checkboxQuote_cancelled").is(":checked") && !\$("#checkboxQuote_completed").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked","true") ; + } + + }) ; + + ~ ; + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + + if ($tab == 2) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_event_details' ; + + my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + # my $op_change = qq~~ ; + + # for (1 .. $nr_of_system_names_and_clubs) { + # $op_change .= qq~,#selectOperator_id_calibration_$_~ ; + # } + # $op_change = substr($op_change,1) ; + + $lcol = 2 ; $fcol = 3 ; + + $add_form_fields = '' ; + + $add_form_fields .= qq~ +
    +
    ~ ; + + # $fcol = 6 ; + $preferred_title{ref} = 'Event Name' ; + $preferred_title{date_from} = 'Event Date/Time From' ; + $preferred_title{date_to} = 'Event Date/Time To' ; + + my $current_day_of_week = Day_of_Week($now_year,$now_mm,$now_dd) ; + + my $delta_days = 6 - $current_day_of_week ; + $delta_days = 7 unless $delta_days ; + $delta_days = 6 if $delta_days < 0 ; + + my ($def_year,$def_mon,$def_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,$delta_days) ; + $def_mon = sprintf("%02d",$def_mon) ; + $def_day = sprintf("%02d",$def_day) ; + + $db{$table}{$id}{date_from} = "$def_year-$def_mon-$def_day 08:00:00" unless $db{$table}{$id}{date_from} ; + $db{$table}{$id}{date_to} = "$def_year-$def_mon-$def_day 17:00:00" unless $db{$table}{$id}{date_to} ; + + my $hide_select_1 = '' ; my $readonly_select = '' ; my $sport_type_ids_readonly = '' ; my $organisation_ids_readonly = '' ; my $linear_id_readonly = '' ; my $readonlyform = 0 ; # my $hide_select_2 = qq~~ ; + + my $quote_accepted = $db{$table}{$id}{quote_accepted} ; + my $quote_rejected = $db{$table}{$id}{quote_rejected} ; + my $quote_cancelled = $db{$table}{$id}{quote_cancelled} ; + my $quote_completed = $db{$table}{$id}{quote_completed} ; +# $db{$table}{$event_id}{quote_completed} + # if (($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 4) { + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { + + for (1 .. 20) { + $readonly{"time_from_$_"} = "READONLY"; + $readonly{"time_to_$_"} = "READONLY"; + } + + $readonlyform = 1 ; + + $readonly{ref} = "READONLY" ; $readonly{date_from} = "READONLY" ; $readonly{date_to} = "READONLY" ; $readonly{qty} = "READONLY" ; $readonly{city_id} = "READONLY" ; + $add_form_fields .= &common_min_form_input('ref',$db{$table}{$id}{ref},'') ; + $add_form_fields .= &common_min_form_input('date_from',$db{$table}{$id}{date_from}) ; + $add_form_fields .= &common_min_form_input('date_to',$db{$table}{$id}{date_to}) ; + $hide_select_1 = qq~~ ; + + $readonly{sport_type_ids_readonly} = "READONLY" ; $readonly{region_id_readonly} = "READONLY" ; $readonly{city_id_readonly} = "READONLY" ; $readonly{organisation_ids_readonly} = "READONLY" ; $readonly{linear_id_readonly} = "READONLY" ; + + $preferred_title{sport_type_ids_readonly} = "Sport Type(s)" ; $preferred_title{region_id_readonly} = "Regions" ; $preferred_title{city_id_readonly} = "City" ; $preferred_title{organisation_ids_readonly} = "Venue(s)" ; $preferred_title{linear_id_readonly} = "Linear" ; + + foreach (split(",",$db{$table}{$id}{sport_type_ids})) { + $sport_type_ids_readonly .= qq~$db{sport_types}{$_}{name},~ ; + } + chop $sport_type_ids_readonly if $sport_type_ids_readonly ; + + foreach (split(",",$db{$table}{$id}{organisation_ids})) { + $organisation_ids_readonly .= qq~$db{organisations}{$_}{name},~ ; + } + chop $organisation_ids_readonly if $organisation_ids_readonly ; + + local %linear_vals = () ; $linear_vals{1} = "Yes" ; $linear_vals{2} = "No" ; $linear_vals{3} = "Delayed" ; + + # my $cities_readoly = qq~~ ; + # foreach my $city_id (split(",",$db{$table}{$id}{city_id})) { + # $cities_readoly .= qq~$db{cities}{$city_id}{city}, ~ ; + # } + # chop $cities_readoly if $cities_readoly ; chop $cities_readoly if $cities_readoly ; + + my $cities_readoly = join (", ", map { "$db{cities}{$city_id}{name}" } split(/\,/,$db{$table}{$id}{city_id})) ; + + # $readonly_select .= &common_min_form_input('sport_type_ids_readonly',$db{sport_types}{$db{$table}{$id}{sport_type_ids}}{name},'') ; + $readonly_select .= &common_min_form_input('sport_type_ids_readonly',$sport_type_ids_readonly ,'') ; + $readonly_select .= &common_min_form_input('region_id_readonly',$db{regions}{$db{$table}{$id}{region_id}}{name},'') ; + $readonly_select .= &common_min_form_input('city_id_readonly',$cities_readoly,'') ; + # $readonly_select .= &common_min_form_input('organisation_ids_readonly',$db{organisations}{$db{$table}{$id}{organisation_ids}}{name},'') ; + $readonly_select .= &common_min_form_input('organisation_ids_readonly',$organisation_ids_readonly,'') ; + $readonly_select .= &common_min_form_input('linear_id_readonly',$linear_vals{$db{$table}{$id}{linear_id}},'') ; + } else { + $add_form_fields .= &common_min_form_input('ref',$db{$table}{$id}{ref},'') ; + $readonly{date_from} = "READONLY" ; $readonly{date_to} = "READONLY" ; + $add_form_fields .= &common_min_form_datetimepicker('date_from',$db{$table}{$id}{date_from}) ; + $add_form_fields .= &common_min_form_datetimepicker('date_to',$db{$table}{$id}{date_to}) ; + + $dlg{sport_type_ids} = qq~   $db{$table}{$id}{sports_type}~ ; + $dlg{sport_type_ids} .= qq~
    ~ ; + $dlg{city_id} .= qq~   $db{$table}{$id}{city}~ ; + $dlg{city_id} .= qq~
    ~ ; + $dlg{organisation_ids} .= qq~   $db{$table}{$id}{location}~ ; + $dlg{organisation_ids} .= qq~
    ~ ; + $dlg{region_id} .= qq~   $db{$table}{$id}{location}~ ; + $dlg{region_id} .= qq~
    ~ ; + } + + # $fcol = 1 ; + $preferred_title{qty} = 'Actual Days' ; $dont_end_row{qty} = 1 ; + + # if (($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 4) { $readonly{qty} = "READONLY" ; } + # if (($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) { $readonly{qty} = "READONLY" ; } + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { $readonly{qty} = "READONLY" ; } + + my @times_from = split(/\;/,";$db{$table}{$id}{times_from}") ; + my @times_to = split(/\;/,$db{$table}{$id}{times_to}) ; + + my @default = () ; my $saved_time_from = qq~~ ; my $saved_time_to = qq~~ ; + + my $year = ($db{$table}{$id}{date_from}) ? substr($db{$table}{$id}{date_from},0,4) : $now_year ; + my $month = ($db{$table}{$id}{date_from}) ? substr($db{$table}{$id}{date_from},5,2) : $now_mm ; + my $day = ($db{$table}{$id}{date_from}) ? substr($db{$table}{$id}{date_from},8,2) : $now_dd ; + + $fcol = 1 ; + + $radio_opts{event_length} = "Full Day+Half Day" ; + + # my $cnt_radio_opts = 0 ; + + # foreach (split(/\+/,$radio_opts{event_length})) { + # $cnt_radio_opts++ ; + # } + + my @timepicker_ids = () ; my @day_ids = () ; + + my %default_days_selected = () ; our %default_active_event_dates = () ; + + # our $final_day_active = 0 ; local $cnt_days = 0 ; + + # foreach (@defaut_days_active) { + # $cnt_days++ ; + # $final_day_active = $cnt_days if $_ ; + # } + + my ($year1,$month1,$day1) = split(/\-/,substr($db{$table}{$id}{date_from},0,10)); + my ($year2,$month2,$day2) = split(/\-/,substr($db{$table}{$id}{date_to},0,10)); + + our $final_day = Delta_Days($year1,$month1,$day1,$year2,$month2,$day2) + 1 ; + + our @defaut_days_active = split(/\;/,$db{$table}{$id}{days_active}) ; + + my $event_without_saved_defaults = 0 ; + + if (!$db{$table}{$id}{days_active}) { + $event_without_saved_defaults = 1 ; + # my $def_qty = ($db{$table}{$id}{qty}) ? $db{$table}{$id}{qty} : 1 ; + + for (1 .. $final_day) { + # for (1 .. $def_qty) { + $db{$table}{$id}{days_active} .= "1;" ; + } + # $trigger_jquery .= qq~\$("#selectDay_1_chosen").css("width","100%" );~ if $def_qty== 1 ; + } + my @default_event_length = split(/\;/,$db{$table}{$id}{event_length}) ; my %calc_default_event_length = () ; + + my @days_active = split(/\;/,$db{$table}{$id}{days_active}) ; + + my $cnt = 0 ; + # my $final_day = 0 ; + my $no_event_days_cnt = 0 ; + + my $hide_rows_1 = (substr($db{$table}{$id}{date_from},0,10) eq substr($db{$table}{$id}{date_to},0,10)) ? "style='display:none;'" : "" ; + my $hide_rows_2 = ($final_day <= 10) ? "style='display:none;'" : "" ; + + my %time_label_header_row = () ; + + $time_label_header_row{1} = qq~
    ~ ; + $time_label_header_row{2} = qq~
    ~ ; + + # foreach (@days_active) { + # $cnt++ ; + # $final_day = $cnt if $_ ; + # } + + # $final_day = 1 unless $final_day ; + # $final_day = $db{$table}{$id}{qty} if $db{$table}{$id}{qty} && !$days_active[$db{$table}{$id}{qty}-1] ; + + my $def_nr_of_full_days = 0 ; my $def_nr_of_half_days = 0 ; + + for (1 .. 20) { + + my $cnt_row = ($_ <= 10) ? 1 : 2 ; + + $default_days_selected{blank}{$_} = "SELECTED" unless $days_active[$_ - 1] ; + $default_days_selected{1}{$_} = "SELECTED" if $days_active[$_ - 1] ; + + push @timepicker_ids,"#timepickerTime_from_$_" ; + push @timepicker_ids,"#timepickerTime_to_$_" ; + push @day_ids,"#day_$_" ; + + my ($new_year,$new_month,$new_day) = ($_ > 1) ? Add_Delta_Days($year,$month,$day,$_-1) : ($year,$month,$day) ; + $new_day = sprintf("%02s",$new_day) ; + $new_month = sprintf("%02s",$new_month) ; + + # $default_active_event_dates{$_} = "$new_year-$new_month-$new_day" if $days_active[$_ - 1] ; + $default_active_event_dates{$_} = "$new_year-$new_month-$new_day" if $_ <= $final_day ; + + my $field = "time_from_$_" ; + $default[$_ - 1] = $times_from[$_ - 1] ; + $default[$_ - 1] = substr($db{$table}{$id}{date_from},11) if $db{$table}{$id}{date_from} && (!$times_from[$_ - 1] || $_ == 1) ; + my $default1 = $default[$_ - 1] ; + + $custom_style{$field} = ((!$event_without_saved_defaults && !$defaut_days_active[$_ - 1]) || $_ == 1 || ($_ > $final_day)) ? qq~display:none;~ : '' ; + # $days_time_row .= ($glod_user_level > 2) ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} ne "READONLY" || ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~ ; + $days_time_row{$cnt_row} .= ($readonly{qty} ne "READONLY") ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} eq "READONLY" && ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~ ; + + $trigger_jquery_raw .= qq~\$("#timepickerTime_from_1").css("display","none");~ ; + + # $default_time_from .= qq~"$_":"$default[$_ - 1]",~ ; + $saved_time_from .= qq~"$_":"$times_from[$_ - 1]",~ if $times_from[$_ - 1] ; + # $final_day = $_ if $times_from[$_ - 1] ; + $field = "time_to_$_" ; + + + $custom_style{$field} = ((!$event_without_saved_defaults && !$defaut_days_active[$_ - 1]) || $_ >= $final_day) ? qq~display:none;~ : '' ; + $default[$_ - 1] = $times_to[$_ - 1] ; + $default[$_ - 1] = substr($db{$table}{$id}{date_to},11) if $db{$table}{$id}{date_to} && (!$times_to[$_ - 1] || $_ == 6) ; + #___ + # $days_time_row_2 .= ($readonly{qty} ne "READONLY") ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($final_day >= $_ && !$custom_style{$field}) ? &common_min_form_input_col($field,$default[$_ - 1],'',0) : qq~
    ~ ; + + # $days_time_row_2 .= ($glod_user_level > 2) ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} ne "READONLY" || ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~ ; + $days_time_row_2{$cnt_row} .= ($readonly{qty} ne "READONLY") ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} eq "READONLY" && ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~ ; + + # $trigger_jquery_raw .= qq~\$("#timepickerTime_from_$_").css("display","none");~ if $db{$table}{$id}{qty} < $_ ; + + # if (!$db{$table}{$id}{days_active} && ($db{$table}{$id}{qty} != 1 || !$db{$table}{$id}{event_length}) && $db{$table}{$id}{qty} >= $_) { + # if (!$db{$table}{$id}{days_active} || ($days_active[$_ - 1] && !$default_event_length[$_ - 1])) { + + # $trigger_jquery .= qq~ + # \$("#radio_1_1").prop('checked',true) ; + # ~ if $_ == 1 ; + + if ($default_event_length[$_ - 1] eq '1' && $days_active[$_ - 1]) { + $def_nr_of_full_days++ ; + } elsif ($default_event_length[$_ - 1] eq '2' && $days_active[$_ - 1]) { + $def_nr_of_half_days++ ; + } + + if (!$db{$table}{$id}{event_length}) { + + my ($h1,$m1,$s1) = ($_ == 1 || !$times_from[$_ - 1]) ? split(/\:/,substr($db{$table}{$id}{date_from},11)) : split(/\:/,$times_from[$_ - 1]) ; + my ($h2,$m2,$s2) = split(/\:/,substr($db{$table}{$id}{date_to},11)) ; + my $time_diff = 3600*($h2-$h1) + 60*($m2-$m1) + ($s2-$s1) ; + + if ($time_diff >= 18000) { + $calc_default_event_length{$_} = 1 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_1").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_full_days++ if $default_event_length[$_ - 1] ; + } elsif ($time_diff >= 0 && $time_diff < 18000) { + $calc_default_event_length{$_} = 2 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_2").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_half_days++ if $default_event_length[$_ - 1] ; + } + + $trigger_jquery .= qq~ + \$("#day_$_").val("1") ; + \$("#day_$_").trigger("chosen:updated") ; + ~ if $_ <= $final_day && $readonly{qty} ne "READONLY" ; + + } elsif ($_ <= $final_day) { + + # $days_active[$_ - 1 + + # my ($h1,$m1,$s1) = split(/\:/,$times_from[$_ - 1]) ; + # my ($h2,$m2,$s2) = split(/\:/,$times_to[$_ - 1]) ; + # my $time_diff = 3600*($h2-$h1) + 3600*($m2-$m1) + ($s2-$s1) ; + if ($default_event_length[$_ - 1]) { + if ($default_event_length[$_-1] eq "1") { + $trigger_jquery .= qq~ + // \$("input[name='selected_$_\_event_length']").val("1") ; + \$("#radio_$_\_1").prop('checked',true) ; + ~ ; + # $def_nr_of_full_days++ ; + } elsif ($default_event_length[$_-1] eq "2") { + $trigger_jquery .= qq~ + // \$("input[name='selected_$_\_event_length']").val("2") ; + \$("#radio_$_\_2").prop('checked',true) ; + ~ ; + # $def_nr_of_half_days++ ; + } + } else { + my ($h1,$m1,$s1) = split(/\:/,substr($db{$table}{$id}{date_from},11)) ; + my ($h2,$m2,$s2) = split(/\:/,substr($db{$table}{$id}{date_to},11)) ; + my $time_diff = 3600*($h2-$h1) + 60*($m2-$m1) + ($s2-$s1) ; + + if ($time_diff >= 18000) { + $calc_default_event_length{$_} = 1 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_1").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_full_days++ ; + } elsif ($time_diff >= 0 && $time_diff < 18000) { + $calc_default_event_length{$_} = 2 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_2").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_half_days++ ; + } + } + } + + if ((!$days_active[$_ - 1] && $_ > $final_day) || ($db{$table}{$id}{days_active} == ";;;;;") || (!$days_active[$_ - 1] && $_ <= $final_day)) { + $trigger_jquery .= qq~\$("#radio_$_\_1").css("display","none") ; ~ ; + $trigger_jquery .= qq~\$("#radio_$_\_2").css("display","none") ; ~ ; + } + + # $default_time_to .= qq~"$_":"$default[$_ - 1]",~ ; + $saved_time_to .= qq~"$_":"$times_to[$_ - 1]",~ if $times_to[$_ - 1] ; + + $field = "day_$_" ; + $custom_style{$field} = ($final_day < $_ || $final_day == 1) ? qq~display:none;~ : '' ; + + if ($readonly{qty} ne "READONLY") { + # if ($glod_user_level > 2) { + + $trigger_jquery .= qq~\$("#day_$_\_chosen").css("display","none");~ if $_ > $final_day || $final_day == 1 ; + + # $time_label_header_row .= qq~
    ~ ; + + $time_label_header_row{$cnt_row} .= qq~ +
    + +
    + ~ ; + + # $trigger_jquery .= qq~ console.log("Day $_ : ;$default_days_selected{blank}{$_};$default_days_selected{1}{$_}; "+\$("#day_$_").val()) ; ~ ; + + } else { + $time_label_header_row{$cnt_row} .= (!$default_days_selected{1}{$_}) ? qq~ +
    + ~ : qq~ +
    +
    + ~ ; + } + } + + $def_nr_of_full_days = 1 if !$def_nr_of_full_days && !$def_nr_of_half_days ; + + $trigger_jquery_raw .= qq~\$("#timepickerTime_to_$final_day").css("display","none");~ if $final_day ; + + my $day_ids_string = join(",",@day_ids) ; + + # chop $default_time_from if $default_time_from ; chop $default_time_to if $default_time_to ; + + $trigger_jquery_raw .= qq~ + + // let [nr_days["full"],nr_days["half"]] = count_nr_of_full_day_and_half_days() ; + + let nr_days = {} ; let prev_nr_days = {} ; + + nr_days["full"] = "$def_nr_of_full_days" ; + nr_days["half"] = "$def_nr_of_half_days" ; + + nr_days["full"] = parseInt(nr_days["full"]) ; + nr_days["half"] = parseInt(nr_days["half"]) ; + + prev_nr_days["full"] = nr_days["full"] ; prev_nr_days["half"] = nr_days["half"] ; + const default_cost_item_rates = {$default_cost_item_rates_javascript} ; + // const default_full_day_cost_item_rates = {$default_full_day_cost_item_rates_javascript} ; + // const default_half_day_cost_item_rates = {$default_half_day_cost_item_rates_javascript} ; + + let ij = 0 ; let orig_selected_system_names = {} ; + // const get_event_cost_id = {"63":"24","286":"25","285":"10"} ; // TESTING + const get_event_cost_id = {$get_event_cost_id_from_system_id_javascript} ; // TESTING + let cnt_systems_per_cost_item = {} ; + + let changed_radio_cnt = 0 ; let system_with_cost_item_rates_selected = 0 ; + + let saved_time_from = {$saved_time_from} ; + let saved_time_to = {$saved_time_to} ; + + // while (true) { + // ij++ ; + // if (!\$("#system_name_row_"+ij).html()) { + // break ; + // } + // orig_selected_system_names[ij] = (\$("#selectSystem_name_"+ij).val()) ? \$("#selectSystem_name_"+ij).val() : "" ; + // if (default_cost_item_rates[get_event_cost_id[\$("#selectSystem_name_"+ij).val()]]) { + // system_with_cost_item_rates_selected = 1 ; + // } + + // } + ~ ; + + $trigger_jquery_raw .= qq~ + cnt_selected_systems_per_cost_item() ; + ~ if $cntxt{4} ; + + $trigger_jquery_raw .= qq~ + + \$("#days_drop_downs_1 [id^='day_'],#days_drop_downs_2 [id^='day_']").on("change", function (e) { + // \$("$day_ids_string").change(function (e) { + + console.log("changed day "+this.id) ; + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + + const id = this.id ; + let col_nr = get_row_nr(id) ; + // const secondLastIndex = beforeLastUnderscore.lastIndexOf('_'); + // const changedInput = beforeLastUnderscore.substring(secondLastIndex + 1); + + let nr_days = \$("input[name='qty']").val() ; + + let nr_of_active_days = calc_nr_of_active_days() ; + + let datesBetween ; + + let date_counter = 0 ; let dates_map = {} ; + + // if ((\$\(this).val() && (nr_of_active_days == 7 || nr_of_active_days == 11)) || (!\$\(this).val() && (nr_of_active_days == 6 || nr_of_active_days == 10))) { + datesBetween = getDatesBetween(\$("input[name='date_from']").val(),\$("input[name='date_to']").val(),0) ; + for (const date of datesBetween) { + date_counter++ ; + dates_map[date_counter] = date ; + // console.log("date_counter : "+date_counter+" , dates_map[date_counter] : "+dates_map[date_counter]) ; + } + // } + + let all_added_dropdowns = "#1" ; + let all_added_dropdowns_chosen = "#1" ; + + // let select_chosen_ids_1 = '#3' ; + // let select_chosen_ids_2 = '#4' ; + + // let def_val = 0 ; + + // if (\$("#day_"+b).val()) { + + // def_val = \$("#selectCustom_operator_"+a+"_"+b).val() ; + // add_operator_dropdown("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,0) ; + // select_chosen_ids_1 = select_chosen_ids_1+",#selectCustom_operator_"+a+"_"+b ; + // select_chosen_ids_2 = select_chosen_ids_2+",#selectCustom_operator_"+a+"_"+b+"_chosen" ; + // names_to_display = names_to_display + ",#day_"+b+"_name_"+a+"_extra_1" ; + // } + + // delete_operator_dropdown ("day_"+b+"_name","day_"+a+"_"+b) ; + // delete_operator_dropdown ("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_2") ; + + // if (!\$("#selectCustom_operator_"+a+"_"+b).val() && def_val) { + // \$("#selectCustom_operator_"+a+"_"+b).val(def_val) ; + // \$("#selectCustom_operator_"+a+"_"+b).trigger("chosen:updated") ; + // } + // } + + let def_val = 0 ; + + let hide_this_1 = '' ; + let hide_this_2 = '' ; + + if (!\$\(this).val()) { + + \$("#timepickerTime_from_"+col_nr+"").css("display","none") ; + \$("#timepickerTime_to_"+col_nr+"").css("display","none") ; + \$("#radio_"+col_nr+"_1").css("display","none") ; + \$("#radio_"+col_nr+"_2").css("display","none") ; + nr_days=nr_days-1; + if (nr_of_active_days < 6) { + \$("#day_"+col_nr+"_name").css("display","none") ; + \$("#day_"+col_nr+"_name").removeClass('col-md-1').addClass('col-md-0') ; + } + for (let q=1;q<=15;q++) { + if (\$("input[name='clicked_button_"+q+"']").val()) { + + if (nr_of_active_days <= 6 && q > 1 && !\$("#extra_heading_"+q).is(":hidden")) { + \$("#extra_heading_"+q).hide() ; + console.log("Hide Heading") ; + } else if (nr_of_active_days > 6 && q > 1 && \$("#extra_heading_"+q).length && \$("#extra_heading_"+q).is(":hidden") && \$("input[name='clicked_button_"+q+"']").val()) { + \$("#extra_heading_"+q).show() ; + console.log("Display Heading") ; + } else if (nr_of_active_days > 6 && q > 1 && !\$("#extra_heading_"+q).length && \$("input[name='clicked_button_"+q+"']").val()) { + console.log("Add Heading") ; + \$("#system_name_row_"+q).before("
    ") ; + + } + + if (nr_of_active_days < 6) { + \$("#day_"+q+"_"+col_nr).css("display","none") ; + \$("#day_"+q+"_"+col_nr).removeClass('col-md-1').addClass('col-md-0') ; + } else if (nr_of_active_days == 6) { + + if (q > 1 && !\$("#extra_heading_"+q).is(":hidden")) { + \$("#extra_heading_"+q).hide() ; + } + + for (let col=1;col<=20;col++) { + if (\$("#day_"+col).val() && !\$("#day_"+q+"_"+col).html()) { + add_operator_dropdown ("day_"+col+"_name","day_"+q+"_"+col,"custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,0) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (!\$("#day_"+col).val() && dates_map[col] && !\$("#day_"+q+"_"+col).html()) { + add_operator_dropdown ("day_"+col+"_name","day_"+q+"_"+col,"custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,1) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (\$("#day_"+col).val() && \$("#day_"+q+"_"+col).html() && \$("#day_"+q+"_"+col).is(":hidden")) { + display_non_empty_operator_dropdown("day_"+col+"_name","day_"+q+"_"+col) ; + } + delete_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1") ; + // console.log("hide_operator_dropdown : ) ; + } + \$("#system_name_row_"+q+"_extra_1").hide() ; + \$("#day_names_"+q+"_extra_1").hide() ; + } else if (nr_of_active_days > 6 && nr_of_active_days < 10) { + // hide_non_empty_operator_dropdown("day_"+col_nr+"_name","day_"+q+"_"+col_nr) ; + hide_non_empty_operator_dropdown("day_"+col_nr+"_name_"+q+"_extra_1","day_"+q+"_"+col_nr+"_extra_1") ; + } else if (nr_of_active_days == 10) { + for (let col=1;col<=20;col++) { + if (\$("#day_"+col).val() && dates_map[col]) { + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,0) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (!\$("#day_"+col).val() && dates_map[col]) { + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,1) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (\$("#day_"+col).val() && \$("#day_"+q+"_"+col+"_extra_1").html() && \$("#day_"+q+"_"+col+"_extra_1").is(":hidden")) { + display_non_empty_operator_dropdown("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1") ; + } + delete_operator_dropdown ("day_"+col+"_name_"+q+"_extra_2","day_"+q+"_"+col+"_extra_2") ; + } + hide_non_empty_operator_dropdown("day_"+col_nr+"_name_"+q+"_extra_1","day_"+q+"_"+col_nr+"_extra_1") ; + \$("#system_name_row_"+q+"_extra_1").show() ; + \$("#day_names_"+q+"_extra_1").show() ; + \$("#system_name_row_"+q+"_extra_2").hide() ; + \$("#day_names_"+q+"_extra_2").hide() ; + } else if (nr_of_active_days > 10) { + + let nr_dates_used = 0 ; + + console.log("de select : #nr_of_active_days : "+nr_of_active_days) ; + + for (let col=1;col<=20;col++) { + + if (nr_dates_used == 10 && !dates_map[col]) { + break ; + } + if (\$("#day_"+col).val() && dates_map[col] && nr_dates_used < 10) { + nr_dates_used++ ; + if (\$("#day_"+q+"_"+col+"_extra_1").is(":hidden")) { + def_val = \$("#selectCustom_operator_"+q+"_"+col).val() ; + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,0) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + delete_operator_dropdown("day_"+col+"_name_"+q+"_extra_2","day_"+q+"_"+col+"_extra_2",0) ; + if (!\$("#selectCustom_operator_"+q+"_"+col).val() && def_val) { + \$("#selectCustom_operator_"+q+"_"+col).val(def_val) ; + \$("#selectCustom_operator_"+q+"_"+col).trigger("chosen:updated") ; + } + } + } else if (!\$("#day_"+col).val() && dates_map[col]) { + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,1) ; + if (!\$("#day_"+q+"_"+col+"_extra_1").is(":hidden")) { + hide_this_1 = "day_"+col+"_name_"+q+"_extra_1" ; + hide_this_2 = "day_"+q+"_"+col+"_extra_1" ; + } + if (!\$("#day_"+q+"_"+col+"_extra_2").is(":hidden") && col > 10) { + hide_this_1 = "day_"+col+"_name_"+q+"_extra_2" ; + hide_this_2 = "day_"+q+"_"+col+"_extra_2" ; + } + } + } + } + } + if (hide_this_1) { + console.log("hide this : "+hide_this_1+" , "+hide_this_2) ; + hide_non_empty_operator_dropdown (hide_this_1,hide_this_2) ; + } + } + } else { + if (col_nr != "1") { + \$("#timepickerTime_from_"+col_nr).css("display","") ; + } + \$("#timepickerTime_to_"+col_nr).css("display","") ; + \$("#radio_"+col_nr+"_1").css("display","") ; + \$("#radio_"+col_nr+"_2").css("display","") ; + nr_days=parseInt(nr_days)+1; + + for (let q=1;q<=15;q++) { + if (\$("input[name='clicked_button_"+q+"']").val()) { + \$("#day_"+q+"_"+col_nr).css("display","") ; + if (\$("#selectCustom_operator_"+q+"_"+col_nr+"_chosen").css("width") !== "100%"){ + \$("#selectCustom_operator_"+q+"_"+col_nr+"_chosen").css("width","100%") ; + } + } + } + + if (nr_of_active_days <= 6 && \$("#clicked_any_button").text() && \$("#day_"+col_nr+"_name").css("display") === "none") { + \$("#day_"+col_nr+"_name").show() ; + \$("#day_"+col_nr+"_name").removeClass('col-md-0').addClass('col-md-1') ; + } + for (let q=1;q<=15;q++) { + + if (\$("input[name='clicked_button_"+q+"']").val()) { + + if (nr_of_active_days <= 6 && q > 1 && !\$("#extra_heading_"+q).is(":hidden")) { + \$("#extra_heading_"+q).hide() ; + console.log("Hide Heading") ; + } else if (nr_of_active_days > 6 && q > 1 && \$("#extra_heading_"+q).length && \$("#extra_heading_"+q).is(":hidden") && \$("input[name='clicked_button_"+q+"']").val()) { + \$("#extra_heading_"+q).show() ; + console.log("Display Heading") ; + } else if (nr_of_active_days > 6 && q > 1 && !\$("#extra_heading_"+q).length && \$("input[name='clicked_button_"+q+"']").val()) { + console.log("Add Heading") ; + \$("#system_name_row_"+q).before("
    ") ; + + } + + if (q > 1 && \$("#extra_heading_"+q).is(":hidden")) { + \$("#extra_heading_"+q).show() ; + } + + if (nr_of_active_days <= 6) { + \$("#day_"+q+"_"+col_nr).show() ; + \$("#day_"+q+"_"+col_nr).removeClass('col-md-0').addClass('col-md-1') ; + console.log("#day_"+q+"_"+col_nr) ; + } else if (nr_of_active_days == 7) { + for (let col=1;col<=20;col++) { + def_val = \$("#selectCustom_operator_"+q+"_"+col).val() ; + if (\$("#day_"+col).val()) { + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,0) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (!\$("#day_"+col).val() && dates_map[col]) { + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,1) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (\$("#day_"+col).val() && \$("#day_"+q+"_"+col).html() && \$("#day_"+q+"_"+col).is(":hidden")) { + display_non_empty_operator_dropdown("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1") ; + } + delete_operator_dropdown ("day_"+col+"_name","day_"+q+"_"+col) ; + if (!\$("#selectCustom_operator_"+q+"_"+col).val() && def_val) { + \$("#selectCustom_operator_"+q+"_"+col).val(def_val) ; + \$("#selectCustom_operator_"+q+"_"+col).trigger("chosen:updated") ; + } + } + \$("#day_"+col_nr+"_name").hide() ; + \$("#system_name_row_"+q+"_extra_1").show() ; + \$("#day_names_"+q+"_extra_1").show() ; + } else if (nr_of_active_days > 7 && nr_of_active_days <= 10) { + display_non_empty_operator_dropdown("day_"+col_nr+"_name_"+q+"_extra_1","day_"+q+"_"+col_nr+"_extra_1") ; + hide_non_empty_operator_dropdown("day_"+col_nr+"_name","day_"+q+"_"+col_nr) ; + } else if (nr_of_active_days >= 11) { + let date_used = {} ; let date_used_hidden = {} ; let nr_dates_used = 0 ; + for (let col=1;col<=20;col++) { + + if (nr_dates_used == 10 && !dates_map[col]) { + break ; + } + if (\$("#day_"+col).val() && dates_map[col] && nr_dates_used < 10) { + date_used[col] = 1 ; + nr_dates_used++ ; + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,0) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (!\$("#day_"+col).val() && dates_map[col]) { + date_used_hidden[col] = 1 ; + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,1) ; + } + } + + for (let col=11;col<=20;col++) { + // if (col > 10) { + if (\$("#day_"+col).val() && !date_used[col]) { + def_val = \$("#selectCustom_operator_"+q+"_"+col).val() ; + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_2","day_"+q+"_"+col+"_extra_2","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + delete_operator_dropdown("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1",0) ; + if (!\$("#selectCustom_operator_"+q+"_"+col).val() && def_val) { + \$("#selectCustom_operator_"+q+"_"+col).val(def_val) ; + \$("#selectCustom_operator_"+q+"_"+col).trigger("chosen:updated") ; + } + } else { + delete_operator_dropdown ("day_"+col+"_name_"+q+"_extra_2","day_"+q+"_"+col+"_extra_2",0) ; + } + } + \$("#system_name_row_"+q+"_extra_2").show() ; + \$("#day_names_"+q+"_extra_2").show() ; + \$("#system_name_row_"+q+"_extra_1").show() ; + \$("#day_names_"+q+"_extra_1").show() ; + } + } + } + } + + // hide_non_empty_operator_dropdown (hide_this_1,hide_this_2) ; + + \$(all_added_dropdowns).chosen({allow_single_deselect:true}) ; + \$(all_added_dropdowns_chosen).css("width","100%") ; + + // \$(select_chosen_ids_1).chosen({allow_single_deselect:true}) ; + // \$(select_chosen_ids_2).css("width","100%") ; + \$("input[name='qty']").val(nr_days) ; + }) ; + ~ if $readonly{qty} ne "READONLY" ; + + my $timepicker_ids_string = join(",",@timepicker_ids) ; + + # $trigger_jquery_raw .= qq~ \$("$timepicker_ids_string").datetimepicker({language:'pt-BR',pickDate:false});~ ; + + if ($readonly{qty} ne "READONLY") { + + $trigger_jquery_raw .= qq~ + + function set_full_half_day (beforeUnderscore,afterUnderscore) { + + let start_time = \$("input[name='time_from_"+afterUnderscore+"']").val() ; + let end_time = \$("input[name='time_to_"+afterUnderscore+"']").val() ; + + let seconds1 = timeStringToSeconds(start_time) ; + let seconds2 = timeStringToSeconds(end_time) ; + + let diffSeconds = seconds2 - seconds1 ; + + // let nr_days = \$("#inputQty").val() ; + + let changed_a_full_half_day_toggle = 0 ; + if (diffSeconds >= 18000) { + if (\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + nr_days["half"]-- ; + } + if (!\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + \$("#radio_"+afterUnderscore+"_1").prop('checked',true) ; + changed_a_full_half_day_toggle = 1 ; + nr_days["full"]++ ; + } + } else if (diffSeconds >= 0 && diffSeconds < 18000) { + if (\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + nr_days["full"]-- ; + } + if (!\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + \$("#radio_"+afterUnderscore+"_2").prop('checked',true) ; + changed_a_full_half_day_toggle = 1 ; + nr_days["half"]++ ; + } + } else { + // nr_days = parseInt(nr_days) ; + // nr_days-- ; + // \$("#inputQty").val(nr_days) ; + + if (\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + \$("#radio_"+afterUnderscore+"_1").prop('checked',false) ; + changed_a_full_half_day_toggle = 1 ; + nr_days["full"]-- ; + } + if (\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + \$("#radio_"+afterUnderscore+"_2").prop('checked',false) ; + changed_a_full_half_day_toggle = 1 ; + nr_days["half"]-- ; + } + if (beforeUnderscore == 'timepickerTime_from') { + \$("input[name='time_from_"+afterUnderscore+"']").val(end_time) ; + } else if (beforeUnderscore == 'timepickerTime_to') { + \$("input[name='time_to_"+afterUnderscore+"']").val(start_time) ; + } + } + if (changed_a_full_half_day_toggle == 1) { + changed_radio_cnt++ ; + } + + } + + \$("$timepicker_ids_string").datetimepicker({language:'pt-BR',pickDate:false}); + + // \$("#timepickerTime_from_1").on('changeDate', function() { + // let dateString1 = \$("input[name='time_from").val() ; + // }) ; + + \$("$timepicker_ids_string").on('changeDate', function() { + + const id = this.id ; + const lastIndex = id.lastIndexOf('_'); + const beforeUnderscore = id.substring(0,lastIndex); + let afterUnderscore = id.substring(lastIndex+1); + afterUnderscore = parseInt(afterUnderscore) ; + // const from_to_toggle = {"timepickerTime_from":"time_to","timepickerTime_to":"time_from"} ; + // console.log("timepicker change id : "+id+" , beforeUnderscore : "+beforeUnderscore+" , afterUnderscore : "+afterUnderscore) ; + // let date_to = \$("input[name='date_to']").val() ; + // let datetimeValue = \$("#datetimepickerDate_to").data("date"); + // // // if (beforeUnderscore == 'from' && afterUnderscore == 1) { + + // // // let dateString = \$("input[name='time_from").val() ; + // // // let timePart = dateString.split(' ')[1]; + // // // \$("input[name='time_from_1']").val(timePart) ; + // // // return ; + // // // } + // // // if (beforeUnderscore == 'to') { + // // // let dateString1 = \$("input[name='time_from").val() ; + // // // let dateString2 = \$("input[name='time_to").val() ; + // // // const count_dates = getDatesBetween(dateFromInput,dateToInput,1) ; + // // // if (afterUnderscore == count_dates) { + // // // let timePart = dateString.split(' ')[1]; + // // // \$("input[name='time_to_"+count_dates+"']").val(timePart) ; + // // // return ; + // // // } + // // // } + + if (id.includes("timepickerTime_from_")) { + saved_time_from[afterUnderscore] = \$("input[name='time_from_"+afterUnderscore+"']").val() ; + } else if (id.includes("timepickerTime_to_")) { + saved_time_to[afterUnderscore] = \$("input[name='time_to_"+afterUnderscore+"']").val() ; + } + + // console.log("input[name='time_from_"+afterUnderscore+"']") ; + // console.log("input[name='time_to_"+afterUnderscore+"']") ; + + changed_radio_cnt = 0 ; + + set_full_half_day(beforeUnderscore,afterUnderscore) ; + + if (changed_radio_cnt) { + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + } + + // let start_time = \$("input[name='time_from_"+afterUnderscore+"']").val() ; + // let end_time = \$("input[name='time_to_"+afterUnderscore+"']").val() ; + // let seconds1 = timeStringToSeconds(start_time) ; + // let seconds2 = timeStringToSeconds(end_time) ; + + // let diffSeconds = seconds2 - seconds1 ; + // if (diffSeconds >= 18000) { + // if (!\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + // \$("#radio_"+afterUnderscore+"_1").prop('checked',true) ; + // } + // } else if (diffSeconds >= 0 && diffSeconds < 18000) { + // if (!\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + // \$("#radio_"+afterUnderscore+"_2").prop('checked',true) ; + // } + // } else { + // if (\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + // \$("#radio_"+afterUnderscore+"_1").prop('checked',false) ; + // } + // if (\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + // \$("#radio_"+afterUnderscore+"_2").prop('checked',false) ; + // } + // if (beforeUnderscore == 'timepickerTime_from') { + // \$("input[name='time_from_"+afterUnderscore+"']").val(end_time) ; + // } else { + // \$("input[name='time_to_"+afterUnderscore+"']").val(start_time) ; + // } + + // } + // console.log("start_time : "+start_time+" , end_time : "+end_time+" , seconds1 : "+seconds1+" , seconds2 : "+seconds2+" , diffSeconds : "+diffSeconds) ; + }) ; + ~ ; + } + + chop $default_time_from if $default_time_from ; chop $default_time_to if $default_time_to ; + + $fcol = 3 ; $lcol = 2 ; my $expenses_html_for_javascript = qq~~ ; my $vat_default_for_hidden_expenses = qq~~ ; my $cnt_hidden_rows = 0 ; my $changed_opid_as_level_3 = 0 ; + + # my $default_event_length_1 = qq~~ ; my $default_event_length_2 = qq~~ ; my $e_cnt = 0 ; + # foreach (split(/\;/,$db{$table}{$id}{event_length})) { + # $e_cnt++ ; + # $default_event_length_1 .= qq~$_;~ if $e_cnt <= 10 ; + # $default_event_length_2 .= qq~$_;~ if $e_cnt > 10 ; + # } + # chop $default_event_length_1 if $default_event_length_1 ; + # chop $default_event_length_2 if $default_event_length_2 ; + + my %event_length_rows = () ; + + if ($readonly{qty} eq "READONLY") { + + $readonly{nr_of_systems} = "READONLY" ; + + $event_length_rows{1} .= qq~ +
    ~ ; + + $event_length_rows{1} .= qq~ +
    + +
    + ~ ; + + # $event_length_rows{2} = $event_length_rows{1} ; + + if ($db{$table}{$id}{event_length}) { + + # my + my @words = split /\;/, $db{$table}{$id}{event_length} ; + my $output = join ' ', map { ucfirst lc $_ } @words; + # style="top:4px;left:-4px;" + + # my $time_label_header_row = qq~
    ~ ; +# + my $cnt = 0 ; + foreach (@words) { + $cnt++ ; + + $event_length_rows{2} = qq~
    ~ if $cnt >= 11 && $_ && !$event_length_rows{2} ; + + my $el_row_cnt = ($cnt <= 10) ? 1 : 2 ; + + $event_length_rows{$el_row_cnt} .= ($_ eq '1') ? qq~ +
    + +
    + ~ : ($_ eq '2') ? qq~ +
    + +
    ~ : qq~ +
    +
    ~ ; + + } + } else { + for (1 .. $final_day) { # + + my $el_row_cnt = ($cnt <= 10) ? 1 : 2 ; + $event_length_rows{$el_row_cnt} .= ($calc_default_event_length{$_} eq '1') ? qq~ +
    + +
    + ~ : ($calc_default_event_length{$_} eq '2') ? qq~ +
    + +
    + ~ : qq~ +
    +
    + ~ ; + } + } + + # $add_form_fields .= &common_min_form_label('event_length',$output) ; + # $add_form_fields .= qq~
    ~ ; + $event_length_rows{1} .= qq~ +
    ~ if $event_length_rows{1} ; + + $event_length_rows{2} .= qq~ +
    ~ if $event_length_rows{2} ; + # $add_form_fields .= &common_min_form_input('qty',$db{$table}{$id}{qty},'',1) ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + + } else { + + $fcol = 1 ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'',10,$final_day) ; + + $event_length_rows{1} .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'',10,$final_day,"",1) ; + my $final_day_second = $final_day - 10 ; + $final_day_second = -1 if $final_day_second <= 0 ; + $event_length_rows{2} .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'',10,$final_day_second,"radio_row_id_2",2) ; + + # my $sec = &common_min_form_radio_col('event_length',$default_event_length_2,'',10,$final_day_second) ; + + # $add_form_fields .= qq~
    ~ ; + $fcol = 3 ; + # $add_form_fields .= &common_min_form_input('qty',$db{$table}{$id}{qty},'',1) ; + # $add_form_fields .= qq~
    ~ ; + if ($glod_user_level < 4) { + + $changed_opid_as_level_3 = 1 ; + + my @excl_def = split(/\;/,$db{event_quotes_min}{$id}{excl_workings_event}) ; + my @saved_des = split(/\;/,$db{event_quotes_min}{$id}{description_workings_event}) ; + my @saved_op = split(/\;/,$db{event_quotes_min}{$id}{operator_workings_event}) ; + my @remarks_def = split(/\;/,$db{event_quotes_min}{$id}{remarks_workings_event}) ; + my @supp_def = split(/\;/,$db{event_quotes_min}{$id}{supplier_workings_event}) ; + my @ref_nr_def = split(/\;/,$db{event_quotes_min}{$id}{ref_nr_workings_event}) ; + my @qty_old = split(/\;/,$db{event_quotes_min}{$id}{qty_workings_event}); + my @amount_usd_old = split(/\;/,$db{event_quotes_min}{$id}{amount_usd_workings_event}); + my @amount_old = split(/\;/,$db{event_quotes_min}{$id}{amount_workings_event}); + my @vat_default = split(/\;/,$db{event_quotes_min}{$id}{vat_workings_event}) ; + + my %expenses_html = () ; + + &db_min_ro('users','id',"user_type LIKE 'casual%' AND block <> 1 AND inactive <> 1",'','') ; + + foreach (keys %{$db{users}}) { + $opts{users} .= qq~~ ; + } + $opts{description} = qq~~ ; + + $add_form_fields .= qq~
    ~ ; + $db{$table}{$id}{roe} = 1 unless $db{$table}{$id}{roe} ; + + my $custom_set_checked = ($db{$table}{$id}{custom_set} || $db{$table}{$id}{demo_id}) ? "CHECKED" : "" ; + + $add_form_fields .= qq~ + + + + + + + ~ ; + + for (1 .. 50) { + if ($qty_old[50-$_] || $amount_usd_old[50-$_] || $amount_old[50-$_] || $saved_des[50-$_] || $saved_op[50-$_]) { + $cnt_hidden_rows = 51-$_ ; + last ; + } + } + + my @ttlarr = ("sub_total_workings_event","vat_total_workings_event","grand_total_workings_event") ; + + if ($cnt_hidden_rows) { + + # &db_min_ro('event_cost_items','id','','','') ; + &db_min_ro('event_cost_items','id',"excl_from_expenses < 1",'','') ; + + for my $row_cnt (1 .. $cnt_hidden_rows) { + + foreach (keys %{$db{event_cost_items}}) { + my $sel = ($saved_des[$row_cnt-1] and $saved_des[$row_cnt-1] eq $_) ? "SELECTED" : "" ; + $opts{"description_$row_cnt"} .= qq~~ ; + } + foreach (keys %{$db{users}}) { + my $sel = ($saved_op[$row_cnt-1] and $saved_op[$row_cnt-1] eq $_) ? "SELECTED" : "" ; + $opts{"users_$row_cnt"} .= qq~~ ; + } + + $vat_default_for_hidden_expenses .= qq~$row_cnt:"$vat_default[$row_cnt-1],"~ ; + + $add_form_fields .= qq~
    ~ ; + my $excl_checked = ($excl_def[$row_cnt-1]) ? "CHECKED" : "" ; + my $vat_checked = ($vat_default[$row_cnt-1]) ? "CHECKED" : "" ; + + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + + $add_form_fields .= qq~
    ~ ; + + last if $cnt_hidden_rows == $row_cnt ; + } + + $add_form_fields .= qq~
    ~ ; + foreach (@ttlarr) { + my $inp_name = "input" . ucfirst $_ ; + $add_form_fields .= qq~~ ; + } + $add_form_fields .= qq~
    ~ ; + # chop $vat_default_for_hidden_expenses if $vat_default_for_hidden_expenses ; + } + + for ($cnt_hidden_rows+1 .. 50) { + # next if $cnt_hidden_rows && $_ <= $cnt_hidden_rows ; + $add_form_fields .= qq~
    ~ ; + # $expenses_html{$_} = qq~$_:""~ ; + } + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + foreach (@ttlarr) { + my $inp_name = "input" . ucfirst $_ ; + $expenses_html{1000} .= qq~~ ; + } + $expenses_html{1000} = qq~1000:"$expenses_html{1000}"~ ; + + foreach (sort keys %expenses_html) { + $expenses_html_for_javascript .= qq~$expenses_html{$_},~ ; + } + chop $expenses_html_for_javascript if $expenses_html_for_javascript ; + + } + } + + $add_form_fields .= qq~$time_label_header_row{1}
    ~ ; + $add_form_fields .= qq~
    $days_time_row{1}
    ~ ; + $add_form_fields .= qq~
    $days_time_row_2{1}
    ~ ; + $add_form_fields .= qq~$event_length_rows{1}~ ; + + $add_form_fields .= qq~$time_label_header_row{2}
    ~ ; + $add_form_fields .= qq~
    $days_time_row{2}
    ~ ; + $add_form_fields .= qq~
    $days_time_row_2{2}
    ~ ; + $add_form_fields .= qq~$event_length_rows{2}~ ; + + $add_form_fields .= &common_min_form_input('qty',$db{$table}{$id}{qty},'',1) ; + $add_form_fields .= qq~
    ~ ; + + $db{$table}{$id}{nr_of_systems} = 0 unless $db{$table}{$id}{nr_of_systems} ; + + $preferred_title{nr_of_systems} = "Number of Systems" ; + + # if ($glod_user_level > 3) { + # if ($glod_user_level > 2) { + + if ($glod_user_level > 3 || (!$quote_completed && $glod_user_level == 3)) { + $preferred_title{type} = "Type of System" ; + $add_form_fields .= &common_min_form_select('type',$db{$table}{$id}{type},'') ; + $trigger_jquery .= qq~\$("#selectType\_chosen").css( "width", "100%" );~ ; + $add_form_fields .= &common_min_form_input('nr_of_systems',$db{$table}{$id}{nr_of_systems},'') ; + $preferred_title{type_details_id} = "Type Details" ; + $add_form_fields .= &common_min_form_select('type_details_id',$db{$table}{$id}{type_details_id},'') ; + $trigger_jquery .= qq~\$("#selectType_details_id\_chosen").css("width","100%") ;~ ; + # } elsif ($glod_user_level < 4 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + } + # elsif ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + elsif ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { + &db_min_ro('event_types','id,name',"`id`='$db{$table}{$id}{type}'",'','') if $db{$table}{$id}{type} ; + $readonly{type_of_system} = "READONLY" ; $readonly{system_details} = "READONLY" ; $readonly{system_name} = "READONLY" ; $readonly{club_name} = "READONLY" ; + $preferred_title{type_of_system} = "Type of System" ; + $add_form_fields .= &common_min_form_input('type_of_system',$db{event_types}{$db{$table}{$id}{type}}{name},'') ; + $add_form_fields .= &common_min_form_input('nr_of_systems',$db{$table}{$id}{nr_of_systems},'') ; + + &db_min_ro('event_type_details','id,name',"`id`='$db{$table}{$id}{type_details_id}'",'','') unless $db{$table}{$id}{type_details_id} =~ /;/ ; + &db_min_ro('event_type_details','id,name',"",'','') if $db{$table}{$id}{type_details_id} =~ /;/ ; + my $input_val = qq~~ ; + foreach my $type_id (split(",",$db{$table}{$id}{type_details_id})) { + next unless $db{event_type_details}{$type_id}{name} ; + $input_val .= qq~$db{event_type_details}{$type_id}{name}, ~ ; + } + chop $input_val if $input_val ; chop $input_val if $input_val ; + $add_form_fields .= &common_min_form_input('system_details',$input_val,'') ; + } else { + $preferred_title{type} = "Type of System" ; + $add_form_fields .= &common_min_form_select('type',$db{$table}{$id}{type},'') ; + $trigger_jquery .= qq~\$("#selectType\_chosen").css("width","100%" );~ ; + $add_form_fields .= &common_min_form_input('nr_of_systems',$db{$table}{$id}{nr_of_systems},'') ; + } + + our $remaining_op_ids = qq~~ ; + + &build_system_name_form($db{$table}{$id}{event_system_id_multiple},$db{$table}{$id}{club_ids},$quote_accepted,$quote_rejected,$quote_cancelled,$db{$table}{$id}{daily_operator_ids},$db{$table}{$id}{days_active},$db{$table}{$id}{quote_completed}) ; + + my $hide_club_name1 = qq~~ ; my $hide_club_name2 = qq~~ ; my $required_fields_full = 0 ; + + $required_fields_full = 1 if $db{$table}{$id}{ref} and $db{$table}{$id}{type} and $db{$table}{$id}{event_system_id} + and $db{$table}{$id}{qty} and $db{$table}{$id}{region_id} and $db{$table}{$id}{city_id} ; + + $add_form_fields .= qq~
    ~ ; + + $fcol = 3 ; + + # # if ($glod_user_level > 3) { + # if ($glod_user_level > 2) { + # $dlg{operator_ids} .= qq~
    ~ ; + # $preferred_title{operator_ids} = "Operator(s)" ; + # $add_form_fields .= &common_min_form_select('operator_ids',$remaining_op_ids,'') ; + # $trigger_jquery .= qq~\$("#selectOperator_ids\_chosen").css( "width", "100%" );~ ; + # # } elsif ($glod_user_level < 4 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + # } + + # if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { + my @op_names = map { $db{users}{$_}{name} } @multi_select_op_ids; + $op_names = join(", ",@op_names) ; + $preferred_title{operators} = "Operator(s)" ; $readonly{operators} = "READONLY" ; + $add_form_fields .= &common_min_form_input('operators',$op_names,'') ; + } else { + + if ($glod_user_level > 2) { + $dlg{operator_ids} .= qq~
    ~ ; + $preferred_title{operator_ids} = "Operator(s)" ; + $trigger_jquery .= qq~\$("#selectOperator_ids\_chosen").css( "width", "100%" );~ ; + } + + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + $add_form_fields .= &common_min_form_select('operator_ids',$remaining_op_ids,'') ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + # } elsif ($glod_user_level < 4 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + } + + my @casuals = () ; + + foreach (keys %{$db{events}}) { + $qnr = $db{events}{$_}{event_quote_nr} ; + $uid = $db{events}{$_}{user_id} ; + next unless $db{events}{$_}{category} eq 'available' ; + push @casuals, "$casual_name{$uid} [$casual_type{$uid}]" ; + } + + $add_form_fields .= &common_min_form_input('casual_worker','A','hidden') ; + $add_form_fields .= &common_min_form_input('casual_worker_2','B','hidden') ; + + my $nr_of_casuals = 0 + $db{$table}{$id}{nr_of_casuals} + $db{$table}{$id}{nr_of_casuals_2} ; + + $add_form_fields .= &common_min_form_input('nr_of_casuals',$nr_of_casuals,'hidden') ; + $add_form_fields .= &common_min_form_input('nr_of_casuals_2',0,'hidden') ; + + $fcol = 3 ; + # $add_form_fields .= &common_min_form_input('sports_type',$db{$table}{$id}{sports_type},'') ; + + if ($hide_select_1) { + $add_form_fields .= qq~$readonly_select~ ; + } + + $preferred_title{sport_type_ids} = "Sport Type(s)" ; $preferred_title{organisation_ids} = "Venue(s)" ; + $add_form_fields .= qq~$hide_select_1~ ; + $add_form_fields .= &common_min_form_select('sport_type_ids',$db{$table}{$id}{sport_type_ids},'') ; + # $add_form_fields .= &common_min_form_input('ligr',$db{$table}{$id}{ligr},'') ; + # if ($db{$table}{$id}{ligr} eq 'Yes') { $checked = 'CHECKED'; } else { $checked = ''; } + # $add_form_fields .= &common_min_form_checkbox('ligr',$db{$table}{$id}{ligr},$checked) ; + # $add_form_fields .= &common_min_form_input('Location',$db{$table}{$id}{location},'') ; + $add_form_fields .= &common_min_form_select('region_id',$db{$table}{$id}{region_id},'') ; + + $add_form_fields .= &common_min_form_select('city_id',$db{$table}{$id}{city_id},'') ; + $add_form_fields .= &common_min_form_select('organisation_ids',$db{$table}{$id}{organisation_ids},'') ; + + $allow_deselect{linear_id} = 1 ; + my %linear_def = () ; $linear_def{$db{$table}{$id}{linear_id}} = 'SELECTED' ; + $opts{linear_id} .= qq~~ ; + $add_form_fields .= &common_min_form_select('linear_id',$db{$table}{$id}{linear_id},'') ; + + # $supplier_type_ids + + $preferred_title{supplier_type_ids} = "Supplier Type(s)" ; + $add_form_fields .= qq~~ . &common_min_form_select('supplier_type_ids',$db{$table}{$id}{supplier_type_ids},'') if $db{$table}{$id}{sss_quote_nr} ; + + if ($hide_select_1) { + $add_form_fields .= qq~
    ~ ; + } + + # $opts{event_length} = qq~~ ; + # $radio_opts{event_length} = "Full Day+Half Day" ; + # $fcol = 1 ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'') ; + # $add_form_fields .= qq~
    ~ ; + # $fcol = 6 ; + # $add_form_fields .= qq~$hide_select_2~ ; + + # $ignore{club} = 1 ; + # $add_form_fields .= &common_min_form_input('club','','') ; + # $add_form_fields .= &common_min_form_input('City',$db{$table}{$id}{city},'') ; + + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + + # $operator_options = qq~~ ; + + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + + $trigger_jquery_raw .= qq~ + + // // // \$("input[name='event_length']").change( function () { + + // // // let radio_sel = \$(this).val() ; + + // // // for (let i = 1; i<=50; i++) { + + // // // let usd = \$("#inputAmount_usd_workings_event_"+i) ; + // // // let item = \$("#selectDescription_workings_event_"+i) ; + + // // // let amnt = 0 ; + // // // if (\$('input[name="event_length"][value="full_day"]').is(":checked") && usd.val() == '500.00' && item.val() == 14) { + // // // amnt = 750 ; + // // // } else if (\$('input[name="event_length"][value="half_day"]').is(":checked") && usd.val() == '750.00' && item.val() == 14) { + // // // amnt = 500 ; + // // // } else { + // // // continue ; + // // // } + + // // // let qty = \$("#inputQty_workings_event_"+i) ; + // // // let conv = \$("#inputAmount_ttl_workings_event_"+i) ; + + // // // usd.val(amnt.toFixed(2)) ; + // // // let total_amnt = qty.val()*amnt ; + // // // conv.val(total_amnt.toFixed(2)) ; + // // // } + // // // if ($changed_opid_as_level_3) { + // // // calc_hidden_totals() ; + // // // } else { + // // // calcAllWorkings() ; + // // // } + // // // }) ; + + + + let map_region_to_country = {} ; + + const \$clientSelect = \$("#selectQuote_to") ; + const \$countrySelect = \$("#selectCountry_id") ; + const \$regionSelect = \$("#selectRegion_id") ; + const \$citySelect = \$("#selectCity_id") ; + const \$venuesSelect = \$("#selectOrganisation_ids") ; + + let prev_region = \$regionSelect.val() ; + let prev_country = \$countrySelect.val() ; + + const updateChosen = \$el => \$el.trigger("chosen:updated"); + + const getClientId = () => { + const val = \$clientSelect.val(); + return val ? val.toString().split(":")[0] : null; + } ; + + const fetchJSON = async url => { + try { + const res = await fetch(url); + if (!res.ok) throw new Error(`Request failed: \${res.status}`); + return await res.json(); + } catch (err) { + console.error("Fetch error:", err); + return []; + } + }; + + const populateSelect = (\$field,json_list,getLabel,defaultSelected = () => "") => { + let isSelected ; + if (typeof defaultSelected === "function") { + isSelected = defaultSelected; + } else if (Array.isArray(defaultSelected)) { + isSelected = data => defaultSelected.includes(data.id) ? "selected" : ""; + } else { + isSelected = data => data.id == defaultSelected ? "selected" : ""; + } + + json_list.forEach(data => { + \$field.append(``); + }); + + updateChosen(\$field); + return json_list.length; + }; + + const getInputValue = name => \$(`input[name='\${name}']`).val(); + + const getMultiSelectSplitNumbers = (\$field) => { + + let field_ = \$field.chosen().val() ; + field_ = String(field_); + return field_.split(',') ; + + } ; + + const clearSelect = (\$el) => { + \$el.empty(); + \$el.append(``).trigger("chosen:updated"); + }; + + // async function update_country_region_from_client (clientId) { + + + // } + + async function update_region_drop_down_from_country (countryId) { + + clearSelect(\$regionSelect) ; + + const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}` ; + + const regions = await fetchJSON(regionUrl); + + for (const data of regions) { + map_region_to_country[data.id] = countryId ; + } + + const regionCount = populateSelect(\$regionSelect, regions, r => r.code ? `\${r.name} [\${r.code}]` : r.name , "") ; + + // let selectedRegionId = 0 ; + + if (regionCount === 1) { + \$regionSelect.val(regions[0].id) + } else if (regionCount === 0 && \$countrySelect.val()) { + // selectedRegionId = 13 ; + \$regionSelect.append(``) ; + } + updateChosen(\$regionSelect) ; + + const regionId = \$regionSelect.val() ; + + if (regionId != prev_region) { + await update_cities_from_region_and_country(regionId,countryId) ; + await update_venues_from_region_and_country(regionId,countryId) ; + } + prev_region = regionId ; + + } + + async function update_cities_from_region_and_country (regionId,countryId="") { + + let splittedNumbers = getMultiSelectSplitNumbers(\$citySelect) ; + clearSelect(\$citySelect) ; + + let url = `$useropts{scripts}/get/get_cities_from_region.pl?region_id=\${regionId}&country_id=\${countryId}` ; + const cities = await fetchJSON(url); + const citiesCount = populateSelect(\$citySelect, cities, r => r.city_name ? r.city_name : "",r => splittedNumbers.includes(r.id) ? "selected" : "" ) ; + if (citiesCount == 1) \$citySelect.val(cities[0].id).trigger("chosen:updated") ; + + } + + async function update_venues_from_region_and_country (regionId,countryId="") { + + let splittedNumbers2 = getMultiSelectSplitNumbers(\$venuesSelect) ; + clearSelect(\$venuesSelect) ; + url = `$useropts{scripts}/get/get_venues_from_region.pl?region_id=\${regionId}&country_id=\${countryId}` ; + const venues = await fetchJSON(url); + const venuesCount = populateSelect(\$venuesSelect, venues, r => r.venue_name , r => splittedNumbers2.includes(r.id) ? "selected" : "" ) ; + // if (venuesCount == 1) \$venuesSelect.val(venues[0].id).trigger("chosen:updated") ; + + } + + \$clientSelect.change( async function() { + + dispCustomer() ; + let clientId = getClientId() ; + + // __________________________________________________________________ update_country_region_from_client + + const hasCustomRegion = !!getInputValue('custom_selected_region'); + const hasCustomCountry = !!getInputValue('custom_selected_country'); + + if (clientId) { + let url1 = `$useropts{scripts}/get/get_region_country_from_client.pl?client_id=\${clientId}` ; + console.log("1 clientId : "+clientId) ; + + if (!hasCustomRegion || !hasCustomCountry) { + + const data = await fetchJSON(url1); + data.forEach(async ({region_id,country_id}) => { + + if (!hasCustomCountry && country_id && country_id != '0') { + + \$countrySelect.val(country_id).trigger("chosen:updated") ; + if (!hasCustomRegion) await update_region_drop_down_from_country(country_id) ; + if (!region_id || region_id == '0') { + await update_cities_from_region_and_country(0,country_id) ; + await update_venues_from_region_and_country(0,country_id) ; + } + } + + if (!hasCustomRegion && region_id && region_id != '0') { + \$regionSelect.val(region_id).trigger("chosen:updated") ; + await update_cities_from_region_and_country(region_id) ; + await update_venues_from_region_and_country(region_id) ; + } + + // if (!hasCustomCountry && country_id && country_id != '0') + // if (!hasCustomRegion && region_id && region_id != '0') \$regionSelect.val(region_id).trigger("chosen:updated") ; + + }); + } + } else { + if (!hasCustomCountry) \$countrySelect.val("").trigger("chosen:updated") ; + if (!hasCustomRegion) { + \$regionSelect.val("").trigger("chosen:updated") ; + let region_option_count = \$regionSelect.find("option").length ; + if (region_option_count <= 2) { + await update_region_drop_down_from_country(clientId) ; + } + } + } + + // await update_country_region_from_client(clientId) ; + + // __________________________________________________________________ update_country_region_from_client + + }) ; + + \$countrySelect.change( async function() { + + \$("input[name='custom_selected_country']").val("1") ; + await update_region_drop_down_from_country(\$countrySelect.val()) ; + + }) ; + + \$regionSelect.change( async function() { + + \$("input[name='custom_selected_region']").val("1") ; + \$("input[name='custom_selected_country']").val("1") ; + const regionId = \$regionSelect.val() ; + await update_country_from_region(regionId,1) ; + await update_cities_from_region_and_country(regionId) ; + await update_venues_from_region_and_country(regionId) ; + + }); + + let prev_date_part_from = \$("input[name='date_from']").val() ; + prev_date_part_from = prev_date_part_from.split(' ')[0] ; + let prev_date_part_to = \$("input[name='date_to']").val() ; + prev_date_part_to = prev_date_part_to.split(' ')[0] ; + + \$('#datetimepickerDate_from,#datetimepickerDate_to').on('changeDate', function(e) { + let from_to = get_row_nr(this.id) ; + // saved_time_from["1"] = $("input[name='date_from']").val() ; + if (this.id == "datetimepickerDate_from") { + let date_new = \$("input[name='date_from']").val() ; + let time_part = date_new.split(' ')[1]; + \$("input[name='time_from_1']").val(time_part) ; + } + calc_date_diff_in_days(this.id) ; + // \$("#day_4_name_1_extra_1").css("display","none") ; + }) ; + + async function update_country_from_region (regionId,update_country=0) { + + if (map_region_to_country[regionId] || regionId == '13') { + \$countrySelect.val(map_region_to_country[regionId]).trigger("chosen:updated") ; + } else if (!\$("input[name='custom_selected_country']").val() || update_country) { + const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=®ion_id=\${regionId}`; + console.log("update_country_from_region lookupUrl : "+lookupUrl) ; + const regionMeta = await fetchJSON(lookupUrl); + const { country_id } = regionMeta[0] ?? {} ; + if (country_id) { + map_region_to_country[regionId] = country_id; + \$countrySelect.val(country_id).trigger("chosen:updated"); + } + } + + } + + // function javascript_sprintf_sort_off (num) { + // if (num < 10) { + // num = "0"+num.toString() ; + // } + // return num ; + // } + + + + // // function move_system_operators_drop_downs_between_short_to_long () { + + // // let cnt_active_days = 0 ; let cnt_dates_between = 0 ; + // // for (let col=1; col<=20; col++) { + // // if (\$("#day_"+col).val()) { + // // cnt_active_days++ ; cnt_dates_between = col ; + // // } + // // } + // // if ((cnt_active_days <= 6 && \$("#day_1_1").html()) || (cnt_active_days <= 20 && cnt_active_days > 6 && \$("#day_1_1_1").html())) { + // // return ; + // // } + + // // if (cnt_active_days && &cnt_active_days <= 6 && !\$("#day_1_1").html() && \$("#day_1_1_extra_1").html()) { + // // for (let row=1; row<=15; col++) { + // // if (!\$("input[name='clicked_button_"+row+"']").val()) { continue ; } + + // // \$("#system_name_row_"+row+"_extra_1").css("display","none") ; + // // \$("#system_name_row_"+row+"_extra_2").css("display","none") ; + // // \$("day_names_extra_1").css("display","none") ; + // // \$("day_names_extra_2").css("display","none") ; + + // // for (let col=1; col<=20; col++) { + // // if (\$("#day_"+col).val()) { + // // \$("#day_"+row+"_"+col).append(\$("#day_"+row+"_"+col+"_extra").contents()); + // // \$("#day_"+row+"_"+col).css("display","") ; + // // } + // // } + // // } + + // // // \$("#2").append(\$("#1").contents()); + // // } else if (cnt_active_days > 6 && \$("#day_1_1").html() && !\$("#day_1_1_1").html()) { + // // for (let row=1; row<=15; col++) { + // // if (!\$("input[name='clicked_button_"+row+"']").val()) { continue ; } + + // // if (\$("#system_name_row_"+row+"_1").is(":hidden")) { + // // (\$("#system_name_row_"+row+"_1").css("display","") ; + // // } + // // if (\$("#system_name_row_"+row+"_2").is(":hidden") && cnt_active_days > 10) { + // // (\$("#system_name_row_"+row+"_2").css("display","") ; + // // } + // // let active_day_counter = 0 ; + // // for (let col=1; col<=20; col++) { + // // if (\$("#day_"+col).val()) { + // // active_day_counter++ ; + // // \$("#day_"+row+"_"+active_day_counter+"_extra").append(\$("#day_"+row+"_"+col+"").contents()); + // // } + // // } + // // } + // // } + + // // } + + function calc_date_diff_in_days(from_to) { + + // console.log("from_to : "+from_to) ; + + let dateFromInput = \$("input[name='date_from']").val(); + // const dateToInput = \$("#datetimepickerDate_to").data("date"); + let dateToInput = \$("input[name='date_to']").val() ; + + let date_part_from = dateFromInput.split(' ')[0]; + let date_part_to = dateToInput.split(' ')[0]; + + let time_part_from = dateFromInput.split(' ')[1]; + let time_part_to = dateToInput.split(' ')[1]; + + if (prev_date_part_from == date_part_from && date_part_to == prev_date_part_to) { + + changed_radio_cnt = 0 ; + + const datesBetween = getDatesBetween(dateFromInput,dateToInput,0) ; let date_counter = 0 ; + + for (const date of datesBetween) { + + date_counter++ ; + + if (date_counter > 20) { date_counter = 20 ; break ; } + + if (((!saved_time_to[date_counter] || datesBetween.length == date_counter) && from_to.includes("Date_to")) || (date_counter > 1 && !saved_time_from[date_counter] && from_to.includes("Date_from"))) { + + if (from_to.includes("Date_from")) { + \$("input[name='time_from_"+date_counter+"']").val(time_part_from) ; + } else { + \$("input[name='time_to_"+date_counter+"']").val(time_part_to) ; + } + + set_full_half_day('',date_counter) ; + if ((nr_days["full"] && !prev_nr_days["full"]) || (nr_days["half"] && !prev_nr_days["half"]) || (!nr_days["full"] && prev_nr_days["full"]) || (!nr_days["half"] && prev_nr_days["half"])) { + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + changed_radio_cnt = 0 ; + } + prev_nr_days["full"] = nr_days["full"] ; + prev_nr_days["half"] = nr_days["half"] ; + + } + } + + // if (saved_time_to[date_counter] && from_to.includes("Date_to")) { + // \$("input[name='time_to_"+date_counter+"']").val(time_part_to) ; + // } + + if (from_to.includes("Date_to")) { + saved_time_to[date_counter] = time_part_to ; + } else { + saved_time_from["1"] = time_part_from ; + } + + // if (from_to.includes("Date_from")) { + // \$("input[name='time_from_1']").val(time_part_from) ; + // set_full_half_day('',1) ; + // } else { + // let diffInDays = 1 + (new Date(date_part_to) - new Date(date_part_from)) / (1000 * 60 * 60 * 24) ; + // \$("input[name='time_to_"+diffInDays+"']").val(time_part_to) ; + // set_full_half_day('',diffInDays) ; + // } + + if (changed_radio_cnt) { + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + } + return ; + } + + prev_date_part_from = date_part_from ; + prev_date_part_to = date_part_to ; + + const date1 = new Date(dateFromInput) ; + const date2 = new Date(dateToInput) ; + + let hide_date_names = "#1" ; + + let glod_user_level = parseInt("$glod_user_level") ; + + let y1 = date1.getFullYear() ; let m1 = date1.getMonth() ; let d1 = date1.getDate() ; let y2 = date2.getFullYear() ; let m2 = date2.getMonth() ; let d2 = date2.getDate() ; + + m1 = m1 + 1 ; + if (m1 < 10) { + m1 = "0"+m1.toString() ; + } + m2 = m2 + 1 ; + if (m2 < 10) { + m2 = "0"+m2.toString() ; + } + + if ((y1 == y2 && m1 == m2 && d1 == d2) || date1 > date2) { + + if (date1 > date2 && from_to == "datetimepickerDate_from") { + \$("#datetimepickerDate_to").datetimepicker("setDate",date_part_from+" "+time_part_to) ; + \$("#day_1_name label.control-label").text(date_part_from) ; + } else if (date1 > date2 && from_to == "datetimepickerDate_to") { + \$("#datetimepickerDate_from").datetimepicker("setDate",date_part_to+" "+time_part_from) ; + \$("#day_1_name label.control-label").text(date_part_to) ; + } + + \$("input[name='time_from_1']").val(time_part_from) ; + \$("input[name='time_to_1']").val(time_part_to) ; + + changed_radio_cnt = 0 ; + + set_full_half_day('',1) ; + + \$("#radio_1_1").css("display",""); + \$("#radio_1_2").css("display",""); + + \$("#radio_row_id_2_1").hide() ; + \$("#radio_row_id_2_2").hide() ; + + if (!\$("#days_drop_downs_1").is(":hidden")) { + \$("#start_times_row_1").hide() ; + \$("#end_times_row_1").hide() ; + \$("#days_drop_downs_1").hide() ; + } + + if (!\$("#days_drop_downs_2").is(":hidden")) { + \$("#start_times_row_2").hide() ; + \$("#end_times_row_2").hide() ; + \$("#days_drop_downs_2").hide() ; + } + + let reduced_nr_of_days = 0 ; + + for (let i=2; i<=20; i++) { + \$("#day_"+i+"_chosen").css("display","none") ; + + if (\$("#day_"+i).val()) { + \$("#day_"+i).val("") ; + \$("#day_"+i).trigger("chosen:updated") ; + \$("#radio_"+i+"_1").css("display","none") ; + \$("#radio_"+i+"_2").css("display","none") ; + reduced_nr_of_days = 1 ; + } + } + + if (changed_radio_cnt || reduced_nr_of_days) { + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + } + + if (!\$("#day_1").val()) { + \$("#day_1").val("1") ; + \$("#day_1").trigger("chosen:updated") ; + } + \$("#inputQty").val("1") ; + + if (\$("#clicked_any_button").text()) { + + // if (!\$("#days_drop_downs_1").is(":hidden")) { + // \$("#days_drop_downs_1").css("display","none") ; + // \$("#start_times_row_1").css("display","none") ; + // \$("#end_times_row_1").css("display","none") ; + // } + + // if (!\$("#days_drop_downs_2").is(":hidden")) { + // \$("#days_drop_downs_2").css("display","none") ; + // \$("#start_times_row_2").css("display","none") ; + // \$("#end_times_row_2").css("display","none") ; + // } + // if (\$("#day_1_1").is(":hidden")) { + // \$("#day_1_1").removeClass('col-md-0').addClass('col-md-1') ; + // \$("#day_1_1").css("display","") ; + // } + + // if (!\$("#day_1_1").html()) { + // let select_1_1_raw = add_select_raw (1,"custom_operator_1_1","selectCustom_operator_1_1","Select an Option","$operator_options",-1,100) ; + // \$("#day_1_1").html(select_1_1_raw) ; + // } + + add_operator_dropdown("day_1_name","day_1_1","custom_operator_1_1","selectCustom_operator_1_1",y1+"-"+m1+"-"+d1,1,0) ; + + for (let a=1;a<=15;a++) { + if (!\$("input[name='clicked_button_"+a+"']").val()) { continue ; } + + if (a > 1 && !\$("#extra_heading_"+a).is(":hidden")) { + \$("#extra_heading_"+a).hide() ; + } + + if (!\$("#day_names_"+a+"_extra_1").is(":hidden")) { + \$("#day_names_"+a+"_extra_1").css("display","none") ; + \$("#system_name_row_"+a+"_extra_1").css("display","none") ; + } + if (!\$("#day_names_"+a+"_extra_2").is(":hidden")) { + \$("#day_names_"+a+"_extra_2").css("display","none") ; + \$("#system_name_row_"+a+"_extra_2").css("display","none") ; + } + + // \$("#day_"+row+"_"+active_day_counter+"_extra").append(\$("#day_"+row+"_"+col+"").contents()); + + \$("#day_1_name").css("display","") ; + \$("#day_"+a+"_1").css("display","") ; + + for (let b=2;b<=20;b++) { + if (!\$("#day_"+b+"_name").is(":hidden")) { + \$("#day_"+b+"_name").css("display","none") ; + } + if (!\$("#day_"+a+"_"+b).is(":hidden")) { + \$("#day_"+a+"_"+b).css("display","none") ; + } + } + } + } + + return ; + } + + // if (\$("#clicked_any_button").text()) { + + // for (let a=1;a<=15;a++) { + + // if (!\$("input[name='clicked_button_"+a+"']").val()) { continue ; } + + // for (let b=1;b<=date_counter;b++) { + // if (!\$("#day_"+b+"_name").is(":hidden")) { + // \$("#day_"+a+"_"+b).css("display","") ; + // \$("#selectCustom_operator_"+a+"_"+b+"_chosen").css("width","100%") ; + // } else { + // \$("#day_"+a+"_"+b).css("display","none") ; + // } + // } + // } + // } + + + if (\$("#days_drop_downs_1").is(":hidden")) { + // if (glod_user_level > 3) { + \$("#days_drop_downs_1").css("display","") ; + \$("#start_times_row_1").css("display","") ; + \$("#end_times_row_1").css("display","") ; + } + + // if (date1 > date2 ) { + + // \$("#inputQty").val("0") ; + // for (let k=1;k<=6;k++) { + // \$("#day_"+k).val('') ; + // \$("#day_"+k).trigger("chosen:updated") ; + // \$("input[name='time_from_"+k+"']").val('') ; + // \$("input[name='time_to_"+k+"']").val('') ; + // \$("#timepickerTime_from_"+k).css("display","none") ; + // \$("#timepickerTime_to_"+k).css("display","none") ; + // \$("#radio_"+k+"_1").css("display","none") ; + // \$("#radio_"+k+"_2").css("display","none") ; + // \$("#day_"+k+"_chosen").css("display","none") ; + // } + + // return ; + + + // let date_part_from = dateFromInput.split(' ')[0]; + // \$("#datetimepickerDate_to").datetimepicker("setDate",date_part_from+" "+time_part_to) ; + + // \$("input[name='time_from_1']").val(time_part_from) ; + // \$("input[name='time_to_1']").val(time_part_to) ; + + // let time_1 = timeStringToSeconds(time_part_from) ; + // let time_2 = timeStringToSeconds(time_part_to) ; + + // if (time_2 < time_1 || !\$("#day_1").val()) { + // \$("#inputQty").val("0") ; + // } else { + // \$("#inputQty").val("1") ; + // let time_diff_ = time_2 - time_1 ; + // if (time_diff_ >= 18000) { + // \$("#radio_1_1").prop('checked',true) ; + // } else { + // \$("#radio_1_2").prop('checked',true) ; + // } + // } + + // \$("#days_drop_downs").css("display","none") ; + // \$("#start_times_row").css("display","none") ; + // \$("#end_times_row").css("display","none") ; + + // for (let k=2;k<=6;k++) { + // if (\$("#day_"+k).val()) { + // \$("#day_"+k).val('') ; + // \$("#day_"+k).trigger("chosen:updated") ; + // \$("#radio_"+k+"_1").css("display","none") ; + // \$("#radio_"+k+"_2").css("display","none") ; + // } + // } + + // return ; + // } + + \$("input[name='time_from_1']").val(time_part_from) ; + + const datesBetween = getDatesBetween(dateFromInput,dateToInput,0) ; + let date_counter = 0 ; let dates_count = 0 ; let count_days = 0 ; + + let count_days_after = 0 ; let nr_of_active_days = 0 ; + + // for (const date of datesBetween) { + // date_counter++ ; dates_count++ ; + // if (\$("#day_"+date_counter+"_chosen").is(":hidden")) { + + // \$("#radio_"+date_counter+"_1").css("display",""); + // \$("#radio_"+date_counter+"_2").css("display",""); + // \$("#day_"+date_counter).val("1") ; + // \$("#day_"+date_counter).trigger("chosen:updated") ; + // \$("#day_"+date_counter+"_chosen").css("display",""); + // \$("#day_"+date_counter+"_chosen").css("width","100%"); + // \$("#day_"+date_counter).val('1') ; + // \$("#day_"+date_counter).trigger("chosen:updated") ; + // if (date_counter > 1) { + // console.log("1 . display timepickerTime_from_"+date_counter) ; + // \$("#timepickerTime_from_"+date_counter).css("display",""); + // } + // } + // if (\$("#day_"+date_counter).val()) { + // nr_of_active_days++ ; + // } + // } + + // date_counter = 0 ; + + let dates_map = {} ; + + changed_radio_cnt = 0 ; let changed_nr_of_days = 0 ; + + for (const date of datesBetween) { + + date_counter++ ; + + dates_map[date_counter] = date ; + + // console.log("1 . date_counter : "+dates_map[date_counter]) ; + + // if (date_counter > 6) { date_counter = 6 ; count_days_after++ ; continue ; } + if (date_counter > 20) { date_counter = 20 ; break ; } + if (date_counter > 1 && !saved_time_from[date_counter]) { + \$("input[name='time_from_"+date_counter+"']").val(time_part_from) ; + } + if (!saved_time_to[date_counter]) { + \$("input[name='time_to_"+date_counter+"']").val(time_part_to) ; + } + + set_full_half_day('',date_counter) ; + + if (\$("#day_"+date_counter+"_chosen").is(":hidden")) { + + \$("#radio_"+date_counter+"_1").css("display",""); + \$("#radio_"+date_counter+"_2").css("display",""); + \$("#day_"+date_counter).val("1") ; + \$("#day_"+date_counter).trigger("chosen:updated") ; + \$("#day_"+date_counter+"_chosen").css("display",""); + \$("#day_"+date_counter+"_chosen").css("width","100%"); + \$("#day_"+date_counter).val('1') ; + \$("#day_"+date_counter).trigger("chosen:updated") ; + if (date_counter > 1) { + // console.log("1 . display timepickerTime_from_"+date_counter) ; + \$("#timepickerTime_from_"+date_counter).css("display",""); + } + changed_nr_of_days = 1 ; + } + + if (\$("#day_"+date_counter).val()) { + \$("#timepickerTime_to_"+date_counter).css("display","") ; + nr_of_active_days++ ; + } + + \$("#day_"+date_counter+" option[value='1']").text(date); + \$("#day_"+date_counter+" option[value='1']").trigger("chosen:updated") ; + + if (\$("#day_"+date_counter).val()) { + count_days++ ; + } + } + + if (\$("#days_drop_downs_2").is(":hidden") && date_counter > 10) { + // if (glod_user_level > 3) { + \$("#days_drop_downs_2").css("display","") ; + \$("#start_times_row_2").css("display","") ; + \$("#end_times_row_2").css("display","") ; + \$("#radio_row_id_2_1").css("display","") ; + \$("#radio_row_id_2_2").css("display","") ; + } else if (!\$("#days_drop_downs_2").is(":hidden") && date_counter <= 10) { + \$("#days_drop_downs_2").css("display","none") ; + \$("#start_times_row_2").css("display","none") ; + \$("#end_times_row_2").css("display","none") ; + \$("#radio_row_id_2_1").css("display","none") ; + \$("#radio_row_id_2_2").css("display","none") ; + } + + if (count_days_after) { + + date2.setDate(date2.getDate() - count_days_after); + \$("#datetimepickerDate_to").datetimepicker("setDate",date2) ; + + } + + let select_raw ; + + // console.log("nr_of_active_days : "+nr_of_active_days) ; + + let select_chosen_ids_1 = '#1' ; + let select_chosen_ids_2 = '#2' ; + let names_to_display = '#3' ; + + let def_val = 0 ; + + if (\$("#clicked_any_button").text()) { + + if (nr_of_active_days <= 6) { + for (let b=1;b<=date_counter;b++) { + + if (from_to == "datetimepickerDate_from") { + \$("#day_"+b+"_name label.control-label").text('') ; + } + + // if (!\$("#day_"+date_counter+"_name label.control-label").text()) { + if (\$("#day_"+b+"_name").is(":hidden")) { + \$("#day_"+b+"_name label.control-label").text(dates_map[b]) ; + \$("#day_"+b+"_name").css("display","") ; + \$("#day_"+b+"_name").removeClass('col-md-0').addClass('col-md-1') ; + } + + if (!\$("#day_"+b).val() || !\$("#clicked_any_button").text()) { + \$("#day_"+b+"_name").css("display","none") ; + } + } + } + + for (let a=1;a<=15;a++) { + + if (!\$("input[name='clicked_button_"+a+"']").val()) { + let prev_row_nr = a - 1 ; + if (!\$("extra_heading_"+a).html() && \$("input[name='clicked_button_"+a+"']").val() && prev_row_nr && nr_of_active_days > 6) { + + console.log("hello world Add Heading") ; + + \$("#system_name_row_"+a).before("
    ") ; + } else if (\$("extra_heading_"+a).is(":hidden") && \$("input[name='clicked_button_"+a+"']").val() && prev_row_nr && nr_of_active_days > 6) { + \$("#system_name_row_"+a).show() ; + } else if (!\$("extra_heading_"+a).is(":hidden") && \$("input[name='clicked_button_"+a+"']").val() && prev_row_nr && nr_of_active_days <= 6) { + \$("#extra_heading_"+a).hide() ; + } + continue ; + } + + // let prev_row = a - 1 ; + + if (nr_of_active_days <= 6 && a > 1 && !\$("#extra_heading_"+a).is(":hidden")) { + \$("#extra_heading_"+a).hide() ; + console.log("Hide Heading") ; + } else if (nr_of_active_days > 6 && a > 1 && \$("#extra_heading_"+a).length && \$("#extra_heading_"+a).is(":hidden") && \$("input[name='clicked_button_"+a+"']").val()) { + \$("#extra_heading_"+a).show() ; + console.log("Display Heading") ; + } else if (nr_of_active_days > 6 && a > 1 && !\$("#extra_heading_"+a).length && \$("input[name='clicked_button_"+a+"']").val()) { + console.log("123 Add Heading") ; + \$("#system_name_row_"+a).before("
    ") ; + + } + + if (nr_of_active_days <= 6) { + + + if (!\$("#day_names_"+a+"_extra_1").is(":hidden")) { + \$("#day_names_"+a+"_extra_1").css("display","none") ; + \$("#system_name_row_"+a+"_extra_1").css("display","none") ; + } + if (!\$("#day_names_"+a+"_extra_2").is(":hidden")) { + \$("#day_names_"+a+"_extra_2").css("display","none") ; + \$("#system_name_row_"+a+"_extra_2").css("display","none") ; + } + for (let b=1;b<=date_counter;b++) { + // if (!\$("#day_"+b+"_name").is(":hidden")) { + + def_val = \$("#selectCustom_operator_"+a+"_"+b).val() ; + + if (!\$("#day_"+a+"_"+b).html() && \$("#day_"+b).val()) { + \$("#day_"+a+"_"+b).show() ; + \$("#day_"+a+"_"+b).removeClass('col-md-0').addClass('col-md-1') ; + if (!\$("#day_"+a+"_"+b).html()) { + let select_raw = add_select_raw (a,"custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,"Select an Option","$operator_options",-1,100) ; + \$("#day_"+a+"_"+b).html(select_raw) ; + \$("#day_"+a+"_"+b).trigger("chosen:updated") ; + \$("#selectCustom_operator_"+a+"_"+b).chosen({allow_single_deselect:true}) ; + \$("#selectCustom_operator_"+a+"_"+b+"_chosen").css("width","100%") ; + } + + // \$("#selectCustom_operator_"+a+"_"+b+"_chosen").css("width","100%") ; + } + + if (!\$("#selectCustom_operator_"+a+"_"+b).val() && def_val) { + \$("#selectCustom_operator_"+a+"_"+b).val(def_val) ; + \$("#selectCustom_operator_"+a+"_"+b).trigger("chosen:updated") ; + } + + // else { + // \$("#day_"+a+"_"+b).css("display","none") ; + // } + } + } else if (nr_of_active_days > 6 && nr_of_active_days <= 10) { + + // console.log("EXTRA TAB 1 nr_of_active_days : "+nr_of_active_days) ; + + if (\$("#day_names_"+a+"_extra_1").is(":hidden")) { + \$("#day_names_"+a+"_extra_1").show() ; + } + \$("#system_name_row_"+a+"_extra_1").show() ; + if (!\$("#day_names_"+a+"_extra_2").is(":hidden")) { + \$("#day_names_"+a+"_extra_2").hide() ; + } + \$("#system_name_row_"+a+"_extra_2").hide() ; + + for (let b=1;b<=date_counter;b++) { + // for (let b=1;b<=20;b++) { + + // if (\$("#day_"+b).val()) { + + def_val = \$("#selectCustom_operator_"+a+"_"+b).val() ; + add_operator_dropdown("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,0) ; + select_chosen_ids_1 = select_chosen_ids_1+",#selectCustom_operator_"+a+"_"+b ; + select_chosen_ids_2 = select_chosen_ids_2+",#selectCustom_operator_"+a+"_"+b+"_chosen" ; + names_to_display = names_to_display + ",#day_"+b+"_name_"+a+"_extra_1" ; + \$("#day_"+b+"_name_"+a+"_extra_1 label.control-label").text(dates_map[b]) ; + // } + console.log("#day_"+b+"_name_"+a+"_extra_1") ; + if (!\$("#day_"+b).val()) { + + hide_non_empty_operator_dropdown("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1") ; + // \$("#day_"+b+"_name_"+a+"_extra_1").css("display","none") ; + hide_date_names = hide_date_names + ",#day_"+b+"_name_"+a+"_extra_1" ; + // \$("#day_4_name_1_extra_1").css("display","none") ; + } + + delete_operator_dropdown ("day_"+b+"_name","day_"+a+"_"+b) ; + delete_operator_dropdown ("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_2") ; + + if (!\$("#selectCustom_operator_"+a+"_"+b).val() && def_val) { + \$("#selectCustom_operator_"+a+"_"+b).val(def_val) ; + \$("#selectCustom_operator_"+a+"_"+b).trigger("chosen:updated") ; + } + } + } else if (nr_of_active_days > 10) { + + if (\$("#day_names_"+a+"_extra_1").is(":hidden")) { + \$("#day_names_"+a+"_extra_1").show() ; + } + if (\$("#day_names_"+a+"_extra_2").is(":hidden")) { + \$("#day_names_"+a+"_extra_2").show() ; + } + \$("#system_name_row_"+a+"_extra_1").show() ; + \$("#system_name_row_"+a+"_extra_2").show() ; + + let used_dates = 0 ; + + for (let b=1;b<=date_counter;b++) { + + // if (used_dates <= 10) { + + let def_val = 0 ; + def_val = \$("#selectCustom_operator_"+a+"_"+b).val() ; + + if (used_dates < 10 && \$("#day_"+b).val()) { + + used_dates++ ; + add_operator_dropdown("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,0) ; + select_chosen_ids_1 = select_chosen_ids_1+",#selectCustom_operator_"+a+"_"+b ; + select_chosen_ids_2 = select_chosen_ids_2+",#selectCustom_operator_"+a+"_"+b+"_chosen" ; + delete_operator_dropdown ("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_2") ; + \$("#day_"+b+"_name_"+a+"_extra_2 label.control-label").text(dates_map[b]) ; + + } else if (!\$("#day_"+b).val() && dates_map[b]) { + add_operator_dropdown("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,1) ; + select_chosen_ids_1 = select_chosen_ids_1+",#selectCustom_operator_"+a+"_"+b ; + select_chosen_ids_2 = select_chosen_ids_2+",#selectCustom_operator_"+a+"_"+b+"_chosen" ; + hide_non_empty_operator_dropdown("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_2") ; + } else if (\$("#day_"+b).val() && used_dates == 10) { + add_operator_dropdown("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_2","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,0) ; + delete_operator_dropdown ("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1") ; + select_chosen_ids_1 = select_chosen_ids_1+",#selectCustom_operator_"+a+"_"+b ; + select_chosen_ids_2 = select_chosen_ids_2+",#selectCustom_operator_"+a+"_"+b+"_chosen" ; + } + + delete_operator_dropdown ("day_"+b+"_name","day_"+a+"_"+b) ; + + if (!\$("#selectCustom_operator_"+a+"_"+b).val() && def_val) { + \$("#selectCustom_operator_"+a+"_"+b).val(def_val) ; + \$("#selectCustom_operator_"+a+"_"+b).trigger("chosen:updated") ; + } + + // if (\$("#day_"+a+"_"+b+"_extra_2").html()) { + // \$("#day_"+a+"_"+b+"_extra_2").html('') ; + // \$("#day_"+a+"_"+b+"_extra_2").removeClass('col-md-1').addClass('col-md-0') ; + // \$("#day_"+a+"_"+b+"_extra_2").css("display","none") ; + // } + + // } + + // else { + + // if (\$("#day_"+b).val()) { + + // add_operator_dropdown("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_1","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,0) ; + + // } else if (!\$("#day_"+b).val() && dates_map[b]) { + // hide_non_empty_operator_dropdown("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_2") ; + // } + + // } + } + } + } + + } + + \$("#inputQty").val(count_days) ; + + \$("#timepickerTime_to_"+date_counter).css("display","none"); + + // console.log("date_counter : "+date_counter) ; + + if (date_counter <= 20) { + for (let j=date_counter+1;j<=20;j++) { + for (let k=1; k<=15; k++) { + if (\$("input[name='clicked_button_"+k+"']").val()) { + if ( \$("#day_"+k+"_"+j).html()) { + \$("#day_"+k+"_"+j).html('') ; + \$("#day_"+k+"_"+j).removeClass('col-md-1').addClass('col-md-0') ; + \$("#day_"+k+"_"+j).hide() ; + } + // delete_operator_dropdown("day_"+j+"_name_"+k,"day_"+k+"_"+j) ; + delete_operator_dropdown("day_"+j+"_name_"+k+"_extra_1","day_"+k+"_"+j+"_extra_1") ; + delete_operator_dropdown("day_"+j+"_name_"+k+"_extra_2","day_"+k+"_"+j+"_extra_2") ; + } + } + if (\$("#day_"+j).val()) { + \$("#day_"+j).val("").trigger("chosen:updated") ; changed_nr_of_days = 1 ; + } + if (!\$("#day_"+j+"_chosen").is(":hidden")) { + \$("#day_"+j+"_name label.control-label").text('') ; + \$("#day_"+j+"_name").css("display","none") ; + \$("#radio_"+j+"_1").css("display","none") ; + \$("#radio_"+j+"_2").css("display","none") ; + \$("#day_"+j+"_chosen").css("display","none") ; + // console.log("col : "+j) ; + } + if (!\$("#timepickerTime_from_"+j).is(":hidden")) { + \$("#timepickerTime_from_"+j).css("display","none") ; + } + if (!\$("#timepickerTime_to_"+j).is(":hidden")) { + \$("#timepickerTime_to_"+j).css("display","none") ; + } + + } + } + + + if (changed_radio_cnt || changed_nr_of_days) { + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + } + + + \$(names_to_display).removeClass('col-md-0').addClass('col-md-1'); + \$(names_to_display).show() ; + \$(select_chosen_ids_1).chosen({allow_single_deselect:true}) ; + \$(select_chosen_ids_2).css("width","100%") ; + + // // // for (let k=1;k<=50;k++) { + // // // if (\$("#selectDescription_workings_event_"+k).val() == 14) { + // // // \$("#inputQty_workings_event"+k).val(0) ; + // // // let ttl_amnt = 0 ; + // // // \$("#inputAmount_workings_event"+k).val(ttl_amnt.toFixed(2)) ; + // // // } + // // // } + // // // calcAllWorkings() ; + + // // // for (let k=1;k<=50;k++) { + // // // if (\$("#selectDescription_workings_event"+k).val() == 14) { + // // // let inp_qty = differenceDays ; + // // // \$("#inputQty_workings_event"+k).val(inp_qty) ; + // // // let amnt = \$("#inputAmount_usd_workings_event"+k).val() ; + // // // let ttl_amnt = amnt*inp_qty ; + // // // \$("#inputAmount_workings_event"+k).val(ttl_amnt.toFixed(2)) ; + // // // } + // // // } + // // // if ($changed_opid_as_level_3) { + // // // calc_hidden_totals() ; + // // // } else { + // // // calcAllWorkings() ; + // // // } + + // \$("#day_4_name_1_extra_1").css("display","none") ; + + if (hide_date_names != "#1") { + \$(hide_date_names).css("display","none") ; + } + + } + + + + + function timeStringToSeconds(timeString) { + + const [hours, minutes, seconds] = timeString.split(':').map(Number); + return hours * 3600 + minutes * 60 + seconds; + } + + function getDatesBetween(startDateStr,endDateStr,count_dates) { + if (!startDateStr || !endDateStr) { + return ; + } + const dates = []; + let currentDate = new Date(startDateStr); + let endDate = new Date(endDateStr) ; + // currentDate.setHours(currentDate.getHours() + 2); + // endDate.setHours(endDate.getHours() + 2); + currentDate.setHours(+2); + currentDate.setMinutes(0); + currentDate.setSeconds(0); + endDate.setHours(+2); + endDate.setMinutes(59); + endDate.setSeconds(59); + + // console.log("2 . currentDate : "+currentDate.toISOString().split('T')[0]) ; + while (currentDate < endDate) { + // console.log("3 . currentDate : "+currentDate.toISOString().split('T')[0]) ; + dates.push(currentDate.toISOString().split('T')[0]); + currentDate.setDate(currentDate.getDate() + 1); + if (count_dates) { count_dates++ ; } + } + if (count_dates) { + count_dates-- ; + return count_dates; + } else { + return dates; + } + } + ~ ; + + &event_tabs_content_box($sec_name,$sec_col); + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + + if ($tab == 3) { # Event Specifics + + # --------------- START DOCUMENT UPLOADS ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + my $sec = '_event_specifics' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $add_form_fields = '' ; + + my %selected_1 = () ; my %selected_2 = () ; + + &db_min_ro('event_quotes_categories','*','','','') ; + + $selected_1{$db{$table}{$id}{category_id_1}} = 'SELECTED' ; + $selected_2{$db{$table}{$id}{category_id_2}} = 'SELECTED' ; + my $none_id = 0 ; + + foreach (sort {$db{event_quotes_categories}{$a}{category} cmp $db{event_quotes_categories}{$b}{category}} keys %{$db{event_quotes_categories}}) { + + if ($db{event_quotes_categories}{$_}{category} eq 'None') { + $none_id = $_ ; + next ; + } + $opts{category_id_2} .= qq~~ ; + $opts{category_id_1} .= qq~~ ; + } + $opts{category_id_2} .= qq~~ ; + $opts{category_id_1} .= qq~~ ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + $fcol = 8 ; $lcol = 3 ; + + my @cat_details = split('\|;\|',$db{event_quotes_min}{$id}{category_details}) ; + + $preferred_title{category_1_details} = "Category 1 Sub Categories" ; + $preferred_title{category_2_details} = "Category 2 Sub Categories" ; + + &common_shared_poc_recipient_select_code("poc",'',$id) ; + + $add_form_fields .= qq~ +
    +
    + +
    +
    +

    SPORT:_AGE GROUP_TEAM 1_VS_AGE GROUP_TEAM 2
    SPORT:_AGE GROUP_TEAM 1_VS_AGE GROUP_TEAM 2-FESTIVAL/LEAGUE

    +
    +
    + ~ ; + + $add_form_fields .= &common_min_form_select('category_id_1',$db{$table}{$id}{category_id_1},'') ; + $add_form_fields .= &common_min_form_textarea('category_1_details',$cat_details[0],'') ; + $add_form_fields .= &common_min_form_select('category_id_2',$db{$table}{$id}{category_id_2},'') ; + $add_form_fields .= &common_min_form_textarea('category_2_details',$cat_details[1],'') ; + + $trigger_jquery .= qq~\$("#selectCategory_id_1\_chosen").css("width","100%");~ ; + $trigger_jquery .= qq~\$("#selectCategory_id_2\_chosen").css("width","100%");~ ; + + $preferred_title{format_of_title} = "Format of TITLE to be followed when scheduling events" ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= &common_min_form_input('recipient_name',$db{$table}{$id}{recipient_name},'') ; + # $add_form_fields .= &common_min_form_input('recipient_nr',$db{$table}{$id}{recipient_nr},'') ; + &common_shared_poc_recipient_select_code("recipient",'',$id) ; + $add_form_fields .= &common_min_form_textarea('additional_notes',$db{$table}{$id}{additional_notes},'') ; + $add_form_fields .= &common_min_form_textarea('format_of_title',$db{$table}{$id}{format_of_title},'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + my @docs = ('1','2','3') ; + + $add_form_fields .= qq~ +
     
    +
    + ~ ; + + &common_shared_poc_recipient_select_shared_jquery ; + + foreach (@docs) { + my $doc = lc $_ ; $doc =~ s/ /\_/ ; $doc =~ s/&/\_/ ; + $working_uploads = &common_get_field_uploads($id,"upload_$doc",'id') ; + if ($working_uploads) { + $add_form_fields .= qq~ +
    + $working_uploads +
    ~; + } else { + $add_form_fields .= qq~ +
    +
    + + +

    Upload file from PC.

    +
    +
    + ~; + } + } + + $add_form_fields .= qq~ +
    + ~ ; + + &event_tabs_content_box($sec_name,$sec_col); + + # --------------- END DOCUMENT UPLOADS ---------------------------------------------------------------------------------------------------------------- + } + + if ($tab == 4) { # Costing + + # --------------- START COSTING ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + $lcol = 1; + $fcol = 2; + $preferred_title{currency} = 'Currency' ; + $add_form_fields .= &common_min_form_select('currency',$db{$table}{$id}{currency},1) ; # don't end row + $trigger_jquery .= qq~\$("#selectCurrency_chosen").css( "width", "96%" );~ ; + $preferred_title{roe} = ' ROE ' ; $fcol=1; # $fcol=2 ; + $add_form_fields .= &common_min_form_label_col('roe') ; + $db{$table}{$id}{roe} = 1 if not $db{$table}{$id}{roe} ; + $add_form_fields .= &common_min_form_input_col('roe',$db{$table}{$id}{roe},1) ; + # $preferred_title{roe} = ' Discount ' ; + # $add_form_fields .= &common_min_form_label_col('discount') ; + # $add_form_fields .= &common_min_form_select_col('discount',$db{$table}{$id}{discount}) ; + $trigger_jquery .= qq~\$("#selectDiscount_chosen").css( "width", "96%" );~ ; + $add_form_fields .= qq~
    ~ ; + + our %sec_cnt = ('a_event' => "30-List Event Costings"); + + our $display_hidden_input = ($username eq 'handre') ? "readonly" : "style='display:none;'" ; + + my $sec = 'costing' ; + my ($sec_name, $sec_cnt, $sec_col) = &tab_sec_det($sec) ; + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret; + + &event_tabs_build_sec($sec,$tab) ; + + foreach (sort keys %sec_cnt) { + $_k = substr($_, 1) ; + my @parts = split(/\-/, $sec_cnt{$_}) ; + $add_form_fields .= qq~ +
    +
    +

    + $parts[1] : +

    +
    +
    + ~ ; + &tab_build_qt_col_headers("$sec$_k"); + # # # &db_min_ro('event_quotes_min','id,excl_costing_event,item_costing_event,qty_costing_event,usd_amnt_costing_event,item_ttl_costing_event,vat_costing_event,curr_amnt_costing_event',"id=$id",'','') if $id ; + &event_tabs_build_costs_forms($id,$tab,$parts[0],"$sec$_k"); + } + + $add_form_fields .= qq~ +
    +
    +   +
    +
    ~ ; + $add_form_fields .= qq~ +
    +
    +   +
    + ~ ; + + my @ttlarr = ("sub_total","vat_total","grand_total") ; + $lcol = 1 ; + $fcol = 1 ; + foreach (@ttlarr) { + $lcol = 1 ; $add_form_fields .= &common_min_form_label_col($_) ; + } + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $lcol = 2 ; + $add_form_fields .= &common_min_form_label_col('Total') ; + $lcol = 1 ; $fcol = 1 ; + + foreach (@ttlarr) { + $readonly{"$_\_costing_event"} = "READONLY" ; + $input_style{"$_\_costing_event"} = qq~style="text-align:right;"~ ; + my $val = $db{$table}{$id}{$_} ? $db{$table}{$id}{$_} : '0.00' ; + $add_form_fields .= &common_min_form_input_col("$_\_costing_event",$val) ; + } + + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= qq~ +
    +
    +   +
    +
    + ~ ; + + &event_tabs_content_box($sec_name,$sec_col); + + $trigger_jquery_raw .= qq~ + + function count_nr_of_full_day_and_half_days () { + + let full_day_exists = 0 ; let half_day_exists = 0 ; + + console.log("count_nr_of_full_day_and_half_days") ; + + for (let i = 1; i<=20; i++) { + if (\$("#radio_"+i+"_1").is(":checked") && \$("#day_"+i).val()) { + full_day_exists++ ; + } else if (\$("#radio_"+i+"_2").is(":checked") && \$("#day_"+i).val()) { + half_day_exists++ ; + } + } + + console.log("full_day_exists : "+full_day_exists) ; + + return [full_day_exists,half_day_exists] ; + + } + + function cnt_selected_systems_per_cost_item () { + + let i = 0 ; + cnt_systems_per_cost_item = {} ; + while (true) { + i++ ; + + let system_id = \$("#selectSystem_name_"+i).val() ; + + if (!cnt_systems_per_cost_item[get_event_cost_id[system_id]]) { + cnt_systems_per_cost_item[get_event_cost_id[system_id]] = 0 ; + } + if (!\$("#system_name_row_"+i).html()) { + i-- ; + break ; + } + if (system_id && get_event_cost_id[system_id]) { + cnt_systems_per_cost_item[get_event_cost_id[system_id]]++ ; + } + } + } + + function auto_deselect_cost_items_in_quote_tab (row_nr) { + + let orig_system_id = orig_selected_system_names[row_nr] ; + let orig_cost_item = get_event_cost_id[orig_system_id] ; // Check whether get_event_cost_id exists + + if (!orig_system_id || (orig_system_id && !orig_cost_item)) { + return ; + } + let i = 0 ; + // Chech if the corresponding cost item exists for a diffent selected system + + while (true) { + i++ ; + if (!\$("#system_name_row_"+i).html()) { + break ; + } + if (i == row_nr) { + continue ; + } + if (orig_cost_item == get_event_cost_id[\$("#selectSystem_name_"+i).val()]) { + return ; + } + } + + i = 0 ; let j = 0 ; let select_new_values = {} ; let input_new_values = {} ; let checkbox_new_values = {} ; + + while (true) { + + i++ ; j++ ; + if (!\$("#costing_event_"+i).html()) { + i-- ; j-- ; + break ; + } + + let hidden_input = (\$("input[name='added_full_day_cost_item_"+i+"']").val()) ? \$("input[name='added_full_day_cost_item_"+i+"']").val() : (\$("input[name='added_half_day_cost_item_"+i+"']").val()) ? \$("input[name='added_full_day_cost_item_"+i+"']").val() : "" ; + + if (typeof hidden_input !== "undefined" && (hidden_input.includes("-1") || hidden_input.includes("-2"))) { + continue ; + } + + if (orig_cost_item == \$("#selectDescription_costing_event_"+i).val()) { + + j-- ; + \$("#selectDescription_costing_event_"+i).val("").trigger("chosen:updated") ; + \$("#inputQty_costing_event_"+i).val("") ; + \$("#inputAmount_usd_costing_event_"+i).val("") ; + + // calc_totals(i,"costing_event") ; + } else { + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = \$("input[name='qty_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; ; + input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = \$("input[name='amount_ttl_costing_event_"+i+"']").val() ; ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + } + + if (i != j) { + \$("input[name='added_full_day_cost_item_"+i+"']").remove() ; + \$("input[name='added_half_day_cost_item_"+i+"']").remove() ; + } + + } + + for (let key in select_new_values) { + console.log("select_new_values : "+key) ; + if (select_new_values[key] != \$(key).val()) { + \$(key).val(select_new_values[key]).trigger("chosen:updated") ; + } + } + + for (let key in input_new_values) { + if (typeof \$(key).val() == 'undefined' && input_new_values[key]) { + // let display = (hidden_input_name[key].includes("_day_cost_item_")) ? "" : "" ; + let display = (hidden_input_name[key].includes("_day_cost_item_") && "$username" == "handre") ? "" : "style='display:none;'" ; + \$(hidden_input_to_html_row[key]).append("") ; + } + + if (input_new_values[key] != \$(key).val()) { + \$(key).val(input_new_values[key]) ; + } + } + + for (let key in checkbox_new_values) { + if (\$(key).is(":checked") && !checkbox_new_values[key]) { + \$(key).prop("checked",false) ; + } else if (!\$(key).is(":checked") && checkbox_new_values[key]) { + \$(key).prop("checked",true) ; + } + } + + if (j < i) { + for (let k=j+1;k<=i+1;k++) { + if ((j == 0 && k > 1) || j > 0) { + \$("#costing_event_"+k).html("") ; + } + if ((k == j+1 && j > 0) || (j == 0 && k == 2)) { + console.log("SHOW : #btn_row_costing_event_"+k) ; + \$("#btn_row_costing_event_"+k).show() ; + \$("#btn_costing_event_"+k).show() ; + } else if (j > 0 || (j == 0 && k > 2)) { + console.log("HIDE : #btn_row_costing_event_"+k) ; + \$("#btn_row_costing_event_"+k).hide() ; + \$("#btn_costing_event_"+k).hide() ; + } + } + } + + } + + function auto_select_cost_items_in_quote_tab (id,row_number) { + + cnt_selected_systems_per_cost_item() ; + + let system_id = \$("#"+id).val() ; + + let row_nr = (row_number) ? row_number : get_row_nr(id) ; + + if (orig_selected_system_names[row_nr] && get_event_cost_id[orig_selected_system_names[row_nr]] != get_event_cost_id[system_id]) { + auto_deselect_cost_items_in_quote_tab(row_nr) ; + } + + let event_cost_id = get_event_cost_id[system_id] ; + + console.log("event_cost_id : "+event_cost_id) ; + + let i = 0 ; + + if (!event_cost_id) { + + while (true) { + i++ ; + if (!\$("#costing_event_"+i).html()) { + break ; + } + if (\$("#selectDescription_costing_event_"+i).val() && \$("#selectDescription_costing_event_"+i).val() == get_event_cost_id[orig_selected_system_names[row_nr]] && i != row_nr) { + event_cost_id = get_event_cost_id[orig_selected_system_names[row_nr]] ; + } + } + + if (!event_cost_id) { + orig_selected_system_names[row_nr] = \$("#selectSystem_name_"+row_nr).val() ; + return ; + } + + } else if (event_cost_id && get_event_cost_id[orig_selected_system_names[row_nr]] && get_event_cost_id[orig_selected_system_names[row_nr]] != event_cost_id) { + + while (true) { + i++ ; + if (!\$("#costing_event_"+i).html()) { + break ; + } + if (\$("#selectDescription_costing_event_"+i).val() && \$("#selectDescription_costing_event_"+i).val() == get_event_cost_id[orig_selected_system_names[row_nr]]) { + + let hidden_input_val = (\$("input[name='added_full_day_cost_item_"+i+"']").val()) ? \$("input[name='added_full_day_cost_item_"+i+"']").val() : (\$("input[name='added_half_day_cost_item_"+i+"']").val()) ? \$("input[name='added_half_day_cost_item_"+i+"']").val() : "" ; + if (hidden_input_val && !hidden_input_val.includes("-2")) { + let hidden_input_fh = (\$("input[name='added_full_day_cost_item_"+i+"']").val()) ? "full" : (\$("input[name='added_half_day_cost_item_"+i+"']").val()) ? "half" : "" ; + if (hidden_input_fh) { + \$("#inputQty_costing_event_"+i).val(nr_days[hidden_input_fh]*cnt_systems_per_cost_item[get_event_cost_id[orig_selected_system_names[row_nr]]]) ; + calc_totals(i,"costing_event") ; + } + } + + } + } + } + + orig_selected_system_names[row_nr] = \$("#selectSystem_name_"+row_nr).val() ; + + let default_full_day_cost_item_rate = default_cost_item_rates["full,"+event_cost_id] ; + let default_half_day_cost_item_rate = default_cost_item_rates["half,"+event_cost_id] ; + + if (!default_full_day_cost_item_rate && !default_half_day_cost_item_rate) { + return ; + } + + if (!nr_days["full"] && !nr_days["half"]) { + return ; + } + + if (nr_days["full"] && !default_full_day_cost_item_rate && !nr_days["half"] && default_half_day_cost_item_rate) { + return ; + } + + if (!nr_days["full"] && default_full_day_cost_item_rate && nr_days["half"] && !default_half_day_cost_item_rate) { + return ; + } + + let last_used_row = 0 ; i = 0 ; let cnt_systems = cnt_systems_per_cost_item[event_cost_id] ; + + if (\$("#costing_event_1").html() && !\$("#costing_event_2").html() && !\$("#selectDescription_costing_event_1").val()) { + last_used_row = 0 ; + } else { + + let nr_of_blank_rows_needed = (nr_days["full"] && nr_days["half"]) ? 2 : 1 ; + + while (true) { + i++ ; + let j = 1 + i ; + if (\$("#selectDescription_costing_event_"+i).val() && \$("#selectDescription_costing_event_"+i).val() != event_cost_id) { + last_used_row = i ; + // console.log(" 5.1 last_used_row : "+last_used_row) ; + } else if (\$("#costing_event_"+i).html() && \$("#selectDescription_costing_event_"+i).val() && \$("#selectDescription_costing_event_"+i).val() == event_cost_id) { + last_used_row = i - 1 ; + break ; + } else if ((!\$("#selectDescription_costing_event_"+i).val() && nr_of_blank_rows_needed == 1) || (nr_of_blank_rows_needed == 2 && !\$("#selectDescription_costing_event_"+i).val() && !\$("#selectDescription_costing_event_"+j).val())) { + i-- ; + break ; + } + } + } + + let full_half_loop = (nr_days["full"] && nr_days["half"]) ? ["full","half"] : (nr_days["full"]) ? ["full"] : (nr_days["half"]) ? ["half"] : [] ; + + let = f_t_h = {"full":"half","half":"full"} ; + + i = 0 ; let j = 0 ; last_used_row++ ; let need_to_shift_data_below_down = 0 ; let select_new_values = {} ; let input_new_values = {} ; let checkbox_new_values = {} ; let hidden_input_to_html_row = {} ;let hidden_input_name = {} ; let add_html_row = {} ; let already_moved_this_row = {} ; let break_loop = 0 ; let cals_totals_row = {} ; + + while (true) { + + i++ ; j++ ; + + if (last_used_row > i) { + continue ; + } + + let k = last_used_row ; + + if (j > i && \$("#selectDescription_costing_event_"+i).val() && !already_moved_this_row[i]) { + + need_to_shift_data_below_down = 1 ; + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = \$("input[name='qty_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = \$("input[name='amount_ttl_costing_event_"+i+"']").val() ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + let hidden_input_value = (\$("input[name='added_full_day_cost_item_"+i+"']").val()) ? "full" : (\$("input[name='added_half_day_cost_item_"+i+"']").val()) ? "half" : "" ; + if (hidden_input_value && hidden_input_value != "") { + input_new_values["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = \$("input[name='added_"+hidden_input_value+"_day_cost_item_"+i+"']").val() ; + hidden_input_to_html_row["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = "added_"+hidden_input_value+"_day_cost_item_"+j ; + \$("input[name='added_"+hidden_input_value+"_day_cost_item_"+i+"']").remove() ; + } + + if (!\$("#costing_event_"+j).html()) { + add_html_row[j] = 1 ; + } + cals_totals_row[j] = 1 ; + + } + + if (i == last_used_row) { + + for (let f_h in full_half_loop) { + + let default_rate = (full_half_loop[f_h] == "full") ? default_full_day_cost_item_rate : default_half_day_cost_item_rate ; + + if (nr_days[full_half_loop[f_h]] && default_rate) { + + i++ ; j++ ; + if (f_h == 0 && full_half_loop[1] && \$("#selectDescription_costing_event_"+i).val() && \$("#selectDescription_costing_event_"+i).val() != event_cost_id) { + + j++ ; + already_moved_this_row[i] = 1 ; + need_to_shift_data_below_down = 1 ; + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = \$("input[name='qty_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = \$("input[name='amount_ttl_costing_event_"+i+"']").val() ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + let hidden_input_value = (\$("input[name='added_full_day_cost_item_"+i+"']").val()) ? "full" : (\$("input[name='added_half_day_cost_item_"+i+"']").val()) ? "half" : "" ; + if (hidden_input_value && hidden_input_value != "") { + input_new_values["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = \$("input[name='added_"+hidden_input_value+"_day_cost_item_"+i+"']").val() ; + hidden_input_to_html_row["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = "added_"+hidden_input_value+"_day_cost_item_"+j ; + \$("input[name='added_"+hidden_input_value+"_day_cost_item_"+i+"']").remove() ; + } + cals_totals_row[j] = 1 ; + } + i-- ; j-- ; + + if (!\$("#costing_event_"+k).html()) { + add_quote_expenses_row_all("costing_event_"+k,"costing_event") ; + \$("#selectDescription_costing_event_"+k+"_chosen").css("width","90%") ; + \$("#costing_event_"+k).append("") ; + break_loop = 1 ; + } else if (\$("#costing_event_"+k).html() && typeof \$("input[name='added_"+full_half_loop[f_h]+"_day_cost_item_"+k+"']").val() == 'undefined') { + \$("#costing_event_"+k).append("") ; + \$("input[name='added_"+f_t_h[full_half_loop[f_h]]+"_day_cost_item_"+k+"']").remove() ; + } else { + \$("input[name='added_"+full_half_loop[f_h]+"_day_cost_item_"+k+"']").val(event_cost_id) ; + } + + \$("#selectDescription_costing_event_"+k).val(event_cost_id).trigger("chosen:updated") ; + \$("#inputQty_costing_event_"+k).val(nr_days[full_half_loop[f_h]]*cnt_systems) ; + \$("#inputAmount_usd_costing_event_"+k).val(default_rate) ; + calc_totals(k,"costing_event") ; + + k++ ; + + } + } + } + + if (!\$("#costing_event_"+i).html() || break_loop) { + i-- ; j-- ; + break ; + } + + } + + if (need_to_shift_data_below_down) { + + for (let row_nr in add_html_row) { + add_quote_expenses_row_all("costing_event_"+row_nr,"costing_event") ; + \$("#selectDescription_costing_event_"+row_nr+"_chosen").css("width","90%") ; + } + + for (let key in select_new_values) { + if (select_new_values[key] != \$(key).val()) { + \$(key).val(select_new_values[key]).trigger("chosen:updated") ; + } + } + + for (let key in input_new_values) { + if (typeof \$(key).val() == 'undefined' && input_new_values[key]) { + // let display = (hidden_input_name[key].includes("_day_cost_item_")) ? "" : "" ; + let display = (hidden_input_name[key].includes("_day_cost_item_") && "$username" == "handre") ? "" : "style='display:none;'" ; + \$(hidden_input_to_html_row[key]).append("") ; + } + if (input_new_values[key] != \$(key).val()) { + \$(key).val(input_new_values[key]) ; + } + } + + for (let key in checkbox_new_values) { + if (\$(key).is(":checked") && !checkbox_new_values[key]) { + \$(key).prop("checked",false) ; + } else if (!\$(key).is(":checked") && checkbox_new_values[key]) { + \$(key).prop("checked",true) ; + } + } + + for (let key in cals_totals_row) { + calc_totals(key,"costing_event") ; + } + + if (j > i) { + for (let k=i+1;k<=j;k++) { + \$("#costing_event_"+k).show() ; + \$("#btn_row_costing_event_"+k).hide() ; + \$("#btn_costing_event_"+k).hide() ; + } + let k = j+1 ; + \$("#btn_row_costing_event_"+k).show() ; + \$("#btn_costing_event_"+k).show() ; + } + + // let [sub_total,vat_total] = add_up_totals ("costing_event",j,\$("input[name='roe']").val(),0) ; + // \$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; + // update_overall_totals(sub_total,vat_total,"costing_event") ; + + } + } + + \$("#content").on("change","[id^='radio_']", function () { + + // [nr_days["full"],nr_days["half"]] = count_nr_of_full_day_and_half_days() ; + + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days () ; + + }) ; + + function update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days () { + + console.log("update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days") ; + + [nr_days["full"],nr_days["half"]] = count_nr_of_full_day_and_half_days() ; + + let opp_add = {"full":"half","half":"full"} ; + + let i = 0 ; let j = 0 ; let select_new_values = {} ; let input_new_values = {} ; let checkbox_new_values = {} ; + + if (!prev_nr_days["full"] && !prev_nr_days["half"] && (nr_days["full"] || nr_days["half"])) { + // return ; + } + + let add = + (!prev_nr_days["full"] && !prev_nr_days["half"] && nr_days["full"]) ? "blank_full" : + (!prev_nr_days["half"] && !prev_nr_days["full"] && nr_days["half"]) ? "blank_half" : + (!prev_nr_days["full"] && nr_days["full"]) ? "full" : + (!prev_nr_days["half"] && nr_days["half"]) ? "half" : + "" ; + + let remove = + (prev_nr_days["full"] && !nr_days["full"]) ? "full" : + (prev_nr_days["half"] && !nr_days["half"]) ? "half" : + "" ; + + let change = + (prev_nr_days["full"] != nr_days["full"] && prev_nr_days["half"] != nr_days["half"] && prev_nr_days["full"] && nr_days["full"] && prev_nr_days["half"] && nr_days["half"]) ? "both" : + (prev_nr_days["full"] && nr_days["full"] && prev_nr_days["full"] != nr_days["full"]) ? "full" : + (prev_nr_days["half"] != nr_days["half"] && prev_nr_days["half"] && nr_days["half"]) ? "half" : + "" ; + + let hidden_input_to_html_row = {} ; let hidden_input_name = {} ; let add_html_row = {} ; let remove_input = {} ; let cals_totals_row = {} ; + + while (true) { + + i++ ; j++ ; + + if (!\$("#costing_event_"+i).html()) { + i-- ; j-- ; + break ; + } + + let added_full_cost_item = \$("input[name='added_full_day_cost_item_"+i+"']").val() ; + let added_half_cost_item = \$("input[name='added_half_day_cost_item_"+i+"']").val() ; + + let event_cost_id = (added_full_cost_item) ? added_full_cost_item : (added_half_cost_item) ? added_half_cost_item : "" ; + + let event_cost_id_extract = (event_cost_id.includes("_")) ? get_row_nr(event_cost_id) : event_cost_id ; + + let added = (added_full_cost_item) ? "full" : (added_half_cost_item) ? "half" : "" ; + + if ((added && add && added == add) || (add == "blank_full" && add == "full") || (add == "blank_half" && add == "half")) { + continue ; + } + + let do_not_remove_this_row = (event_cost_id.includes("-1") || event_cost_id.includes("-2")) ? 1 : 0 ; + + if (event_cost_id && event_cost_id != "") { + + let change_row = (change && (change == added || change == "both")) ? added : 0 ; + + let rate = (event_cost_id.includes("-1")) ? \$("input[name='amount_usd_costing_event_"+i+"']").val() : default_cost_item_rates[added+","+event_cost_id_extract] ; + // let rate = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; + let qty = (event_cost_id.includes("-2")) ? \$("input[name='qty_costing_event_"+i+"']").val() : (!cnt_systems_per_cost_item[event_cost_id_extract]) ? nr_days[added] : nr_days[added]*cnt_systems_per_cost_item[event_cost_id_extract] ; + + if (!qty) { qty = 0 ; } + + if (change_row) { + input_new_values["input[name='qty_costing_event_"+j+"']"] = qty ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = rate ; + // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (qty*rate).toFixed(2) ; + if (i != j) { + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + input_new_values["input[name='added_"+change_row+"_day_cost_item_"+j+"']"] = event_cost_id ; + hidden_input_to_html_row["input[name='added_"+change_row+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+change_row+"_day_cost_item_"+j+"']"] = "added_"+change_row+"_day_cost_item_"+j ; + \$("input[name='added_"+change_row+"_day_cost_item_"+i+"']").remove() ; + } + cals_totals_row[j] = 1 ; + if (!add || event_cost_id.includes("-3")) { + continue ; + } + } + + if (add == "full") { + \$("input[name='added_"+added+"_day_cost_item_"+i+"']").remove() ; + j++ ; + } + + if (i != j && ((add && add != added && added != remove) || (!do_not_remove_this_row && remove && remove != added))) { + + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = qty ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = rate ; + // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (qty*rate).toFixed(2) ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + if (!\$("#costing_event_"+j).html()) { + add_html_row[j] = 1 ; + console.log("add_html_row : "+j) ; + input_new_values["input[name='added_"+added+"_day_cost_item_"+j+"']"] = event_cost_id ; + hidden_input_to_html_row["input[name='added_"+added+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+added+"_day_cost_item_"+j+"']"] = "added_"+added+"_day_cost_item_"+j ; + } + cals_totals_row[j] = 1 ; + + } + + if (add == "half") { + if (i != j) { + \$("input[name='added_full_day_cost_item_"+i+"']").remove() ; + input_new_values["input[name='added_"+added+"_day_cost_item_"+j+"']"] = event_cost_id ; + hidden_input_to_html_row["input[name='added_"+added+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+added+"_day_cost_item_"+j+"']"] = "added_"+added+"_day_cost_item_"+j ; + } + + j++ ; + } + + if (remove && remove == added && !add) { + if (do_not_remove_this_row) { + continue ; + } + j-- ; + \$("#selectDescription_costing_event_"+i).val("").trigger("chosen:updated") ; + \$("input[name='qty_costing_event_"+i+"']").val("") ; + \$("input[name='amount_usd_costing_event_"+i+"']").val("") ; + \$("input[name='amount_ttl_costing_event_"+i+"']").val("") ; + \$("input[name='added_"+remove+"_day_cost_item_"+i+"']").remove() ; + continue ; + } else if (!do_not_remove_this_row && remove && remove == added && add) { + if (add == "half") { + j-- ; + } + \$("input[name='added_"+remove+"_day_cost_item_"+i+"']").remove() ; + } + + let jj = (add == "full") ? j - 1 : (add == "half") ? j : j ; + + if (add) { + if (!\$("#costing_event_"+jj).html()) { + add_html_row[jj] = 1 ; + // console.log("add : "+add) ; + } + if (!do_not_remove_this_row && remove == "half") { + j-- ; + } + + rate = default_cost_item_rates[add+","+event_cost_id_extract] ; + qty = (!cnt_systems_per_cost_item[event_cost_id_extract]) ? nr_days[add] : nr_days[add]*cnt_systems_per_cost_item[event_cost_id_extract] ; + + // select_new_values["#selectDescription_costing_event_"+jj] = \$("#selectDescription_costing_event_"+i).val() ; + select_new_values["#selectDescription_costing_event_"+jj] = event_cost_id_extract ; + input_new_values["input[name='qty_costing_event_"+jj+"']"] = qty ; + input_new_values["input[name='amount_usd_costing_event_"+jj+"']"] = rate ; + // input_new_values["input[name='amount_ttl_costing_event_"+jj+"']"] = (rate*qty).toFixed(2) ; + input_new_values["input[name='added_"+add+"_day_cost_item_"+jj+"']"] = (event_cost_id.includes("-3")) ? "-3_"+event_cost_id_extract : event_cost_id_extract ; + hidden_input_to_html_row["input[name='added_"+add+"_day_cost_item_"+jj+"']"] = "#costing_event_"+jj ; + hidden_input_name["input[name='added_"+add+"_day_cost_item_"+jj+"']"] = "added_"+add+"_day_cost_item_"+jj ; + if (add != added && \$("input[name='added_"+added+"_day_cost_item_"+jj+"']").val()) { + // \$("input[name='added_"+added+"_day_cost_item_"+jj+"']").remove() ; + remove_input["input[name='added_"+added+"_day_cost_item_"+jj+"']"] = 1 ; + } + cals_totals_row[jj] = 1 ; + } + } else if (!event_cost_id && i != j) { + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = \$("input[name='qty_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = \$("input[name='amount_ttl_costing_event_"+i+"']").val() ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + if (!\$("#costing_event_"+j).html()) { + add_html_row[j] = 1 ; + } + // cals_totals_row[j] = 1 ; + + } else if (!event_cost_id && (add == "blank_full" || add == "blank_half")) { + + let k = j + 1 ; + + if (\$("#selectDescription_costing_event_"+j).val() && !\$("#costing_event_"+k).html()) { + j++ ; + } + + if (!\$("#selectDescription_costing_event_"+j).val()) { + + let ij = 0 ; let add_type = (add == "blank_full") ? "full" : "half" ; + + while (true) { + + ij++ ; + if (!\$("#system_name_row_"+ij).html()) { + break ; + } + + if (default_cost_item_rates[add_type+","+get_event_cost_id[\$("#selectSystem_name_"+ij).val()]]) { + + if (!\$("#costing_event_"+j).html()) { + add_html_row[j] = 1 ; + } else { + \$("#checkboxExcl_costing_event_"+j).prop("checked",false) ; + } + + select_new_values["#selectDescription_costing_event_"+j] = get_event_cost_id[\$("#selectSystem_name_"+ij).val()] ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = nr_days[add_type] ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = default_cost_item_rates[add_type+","+get_event_cost_id[\$("#selectSystem_name_"+ij).val()]] ; + // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (nr_days[add_type]*default_cost_item_rates[add_type+","+get_event_cost_id[\$("#selectSystem_name_"+ij).val()]]).toFixed(2) ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = 1 ; + input_new_values["input[name='added_"+add_type+"_day_cost_item_"+j+"']"] = get_event_cost_id[\$("#selectSystem_name_"+ij).val()] ; ; + hidden_input_to_html_row["input[name='added_"+add_type+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+add_type+"_day_cost_item_"+j+"']"] = "added_"+add_type+"_day_cost_item_"+j ; + cals_totals_row[j] = 1 ; + j++ ; + } + } + j-- ; + break ; + + } + } else if (event_cost_id.includes("-3")) { + + let rate = (event_cost_id.includes("-1")) ? \$("input[name='amount_usd_costing_event_"+i+"']").val() : default_cost_item_rates[added+","+event_cost_id_extract] ; + // let rate = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; + let qty = (event_cost_id.includes("-2")) ? \$("input[name='qty_costing_event_"+i+"']").val() : (!cnt_systems_per_cost_item[event_cost_id_extract]) ? nr_days[added] : nr_days[added]*cnt_systems_per_cost_item[event_cost_id_extract] ; + + if (!qty) { qty = 0 ; } + + input_new_values["input[name='qty_costing_event_"+j+"']"] = qty ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = rate ; + // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (qty*rate).toFixed(2) ; + cals_totals_row[j] = 1 ; + + } + } + + for (let key in remove_input) { + \$(key).remove() ; + } + + for (let row_nr in add_html_row) { + add_quote_expenses_row_all("costing_event_"+row_nr,"costing_event") ; + \$("#selectDescription_costing_event_"+row_nr+"_chosen").css("width","90%") ; + } + + for (let key in select_new_values) { + if (select_new_values[key] != \$(key).val()) { + \$(key).val(select_new_values[key]).trigger("chosen:updated") ; + } + } + + for (let key in input_new_values) { + if (typeof \$(key).val() == 'undefined' && input_new_values[key]) { + let display = (hidden_input_name[key].includes("_day_cost_item_") && "$username" == "handre") ? "" : "style='display:none;'" ; + \$(hidden_input_to_html_row[key]).append("") ; + } + if (input_new_values[key] != \$(key).val()) { + \$(key).val(input_new_values[key]) ; + } + } + + for (let key in checkbox_new_values) { + if (\$(key).is(":checked") && !checkbox_new_values[key]) { + \$(key).prop("checked",false) ; + } else if (!\$(key).is(":checked") && checkbox_new_values[key]) { + \$(key).prop("checked",true) ; + } + } + + for (let key in cals_totals_row) { + calc_totals(key,"costing_event") ; + } + + if (remove && !j) { + j++ ; + } + + if (j < i) { + for (let k=j+1;k<=i+1;k++) { + \$("#costing_event_"+k).html("") ; + if (k == j+1) { + \$("#btn_row_costing_event_"+k).show() ; + \$("#btn_costing_event_"+k).show() ; + } else { + \$("#btn_row_costing_event_"+k).hide() ; + \$("#btn_costing_event_"+k).hide() ; + } + } + } else if (j > i) { + for (let k=i+1;k<=j;k++) { + \$("#costing_event_"+k).show() ; + \$("#btn_row_costing_event_"+k).hide() ; + \$("#btn_costing_event_"+k).hide() ; + } + let k = j+1 ; + \$("#btn_row_costing_event_"+k).show() ; + \$("#btn_costing_event_"+k).show() ; + } + + let [sub_total,vat_total] = add_up_totals ("costing_event",j,\$("input[name='roe']").val(),0) ; + \$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; + update_overall_totals(sub_total,vat_total,"costing_event") ; + + prev_nr_days["full"] = nr_days["full"] ; + prev_nr_days["half"] = nr_days["half"] ; + + } + + \$("#content").on("change","[id^='selectSystem_name_']", function () { + + let corresponding_cost_item_exists = ((default_cost_item_rates["full,"+get_event_cost_id[\$(this).val()]] && nr_days["full"]) || (default_cost_item_rates["half,"+get_event_cost_id[\$(this).val()]] && nr_days["half"])) ? 1 : 0 ; + + if (corresponding_cost_item_exists) { + system_with_cost_item_rates_selected = 1 ; + } else if (system_with_cost_item_rates_selected && (!\$(this).val() || (\$(this).val() && !corresponding_cost_item_exists))) { + system_with_cost_item_rates_selected = 0 ; + let ij = 0 ; + while (true) { + ij++ ; + if (!\$("#system_name_row_"+ij).html()) { + break ; + } + if (!\$("#selectSystem_name_"+ij).val()) { + continue ; + } + if ((default_cost_item_rates["full,"+get_event_cost_id[\$("#selectSystem_name_"+ij).val()]] && nr_days["full"]) || (default_cost_item_rates["half,"+get_event_cost_id[\$("#selectSystem_name_"+ij).val()]] && nr_days["half"])) { + system_with_cost_item_rates_selected = 1 ; + } + } + } + + auto_select_cost_items_in_quote_tab(this.id) ; + + }) ; + + // \$("#content").on("change","[id^='selectDescription_']", async function () { + + // let this_id = this.id ; + + // let row_nr = get_row_nr(this_id) ; + + // let tab = (this_id.includes("_costing_event_")) ? "costing_event" : (this_id.includes("_workings_event_")) ? "workings_event" : "" ; + + // // if (!\$("input[name='added_half_day_cost_item_"+row_nr+"']").val() && !\$("input[name='added_half_day_cost_item_"+row_nr+"']")val() && ((nr_days["full"] && default_cost_item_rates["full,"+\$("#"+this_id).val()]) || (nr_days["full"] && default_cost_item_rates["full,"+\$("#"+this_id).val()]))) { + + // // if (nr_days["full"] && default_cost_item_rates["full,"+\$("#"+this_id).val()]) { + + // // "input[name='qty_costing_event_"+j+"']" + + // // } + + + // // if (nr_days["full"] && default_cost_item_rates["full,"+\$("#"+this_id).val()] && nr_days["half"] && default_cost_item_rates["half,"+\$("#"+this_id).val()]) { + + // // let j = row_nr + 1 ; + // // select_new_values["#selectDescription_costing_event_"+j] = \$(this).val() ; + // // input_new_values["input[name='qty_costing_event_"+j+"']"] = nr_days["half"] ; + // // input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = default_cost_item_rates["half,"+\$(this).val()] ; + // // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (nr_days["half"]*default_cost_item_rates["half,"+\$(this).val()]).toFixed(2) ; + // // checkbox_new_values["#checkboxVat_costing_event_"+j] = 1 ; + // // input_new_values["input[name='added_half_day_cost_item_"+j+"']"] = \$(this).val() ; + // // hidden_input_to_html_row["input[name='added_half_day_cost_item_"+j+"']"] = "#costing_half"+add_type+"_day_cost_item_"+j ; + // // \$("input[name='added_full_day_cost_item_"+j+"']").remove() ; + + // // // let ij = j ; + + // // // while (true) { + // // // select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+j).val() ; + // // // input_new_values["input[name='qty_costing_event_"+j+"']"] = \$("input[name='qty_costing_event_"+j+"']").val() ; + // // // input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = \$("input[name='amount_usd_costing_event_"+j+"']") ; + // // // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (nr_days["half"]*default_cost_item_rates["half,"+\$(this).val()]).toFixed(2) ; + // // // checkbox_new_values["#checkboxVat_costing_event_"+j] = 1 ; + // // // input_new_values["input[name='added_half_day_cost_item_"+j+"']"] = \$(this).val() ; + // // // hidden_input_to_html_row["input[name='added_half_day_cost_item_"+j+"']"] = "#costing_half"+add_type+"_day_cost_item_"+j ; + // // // \$("input[name='added_full_day_cost_item_"+j+"']").remove() ; + // // // } + + // // } + + // // } + + + + // if (\$("input[name='amount_usd_"+tab+"_"+row_nr+"']").val()) { + // // return ; + // } + + // let full_day_exists = nr_days["full"] ; let half_day_exists = nr_days["half"] ; + + // // [full_day_exists,half_day_exists] = count_nr_of_full_day_and_half_days() ; + + // let already_loaded_full_day = (\$("#"+this_id).val()) ? \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val() : "" ; + // let already_loaded_half_day = (\$("#"+this_id).val()) ? \$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val() : "" ; + + // already_loaded_full_day = (typeof already_loaded_full_day == 'undefined') ? "" : 1 ; + // already_loaded_half_day = (typeof already_loaded_half_day == 'undefined') ? "" : 1 ; + + // if (already_loaded_full_day && already_loaded_half_day) { + // return ; + // } + + // if (already_loaded_full_day == 1) { + // full_day_exists = 0 ; + // } + + // if (already_loaded_half_day == 1) { + // half_day_exists = 0 ; + // } + + // let date_from = \$("input[name='date_from']").val() ; + + // date_from = date_from.substring(0,10) ; + + // let full_half_day = 0 ; + + // // if (full_day_exists || (!already_loaded_full_day && already_loaded_half_day && !full_day_exists)) { + // if (full_day_exists != 0) { + // if ((typeof \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val() == 'undefined' || \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val()) && \$("#"+this_id).val()) { + // \$("#content").append("") ; + // } + // full_half_day = 1 ; + // // } else if (half_day_exists || (already_loaded_full_day && !half_day_exists && !already_loaded_half_day)) { + // } else if (half_day_exists != 0) { + // if ((typeof \$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val() == 'undefined' || !\$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val()) && \$("#"+this_id).val()) { + // \$("#content").append("") ; + // } + // full_half_day = 2 ; + // } + + // let rate_ = "" ; + + // if (default_cost_item_rates["full,"+\$("#"+this_id).val()] && full_half_day == 1) { + // rate_ = default_cost_item_rates["full,"+\$("#"+this_id).val()] ; + // } else if (default_cost_item_rates["half,"+\$("#"+this_id).val()] && full_half_day == 2) { + // rate_ = default_cost_item_rates["half,"+\$("#"+this_id).val()] ; + // } else if (full_half_day) { + // let rate_url = "$useropts{scripts}/get/get_event_cost_item_rates.pl?"+\$("#"+this_id).val()+"&"+date_from+"&"+full_half_day+"&"+this_id ; + // await \$.get(rate_url, function(json) { + // \$.each(json, function(key, data) { + // rate_ = data.rate ; + // }); + // },'json') ; + // } + + // if (rate_ == "") { + // return ; + // } + + // // let tab = "" ; + + // // if (this_id.includes("_costing_event_")) { + // // tab = "costing_event" ; + // // } else if (this_id.includes("_workings_event_")) { + // // tab = "workings_event" ; + // // } + + // full_half_day = (full_half_day == 1) ? "full" : (full_half_day == 2) ? "half" : "" ; + + // \$("input[name='qty_"+tab+"_"+row_nr+"']").val(nr_days[full_half_day]) ; + // \$("input[name='amount_usd_"+tab+"_"+row_nr+"']").val(rate_) ; + // \$("input[name='amount_ttl_"+tab+"_"+row_nr+"']").val((rate_*nr_days[full_half_day]).toFixed(2)) ; + // \$("#"+tab+"_"+row_nr).append("") ; + // calc_totals(row_nr,tab) ; + + // // amount_usd_costing_event_1 + // // amount_usd_workings_event_1 + + // }) ; + + + // \$("#content").on("change","[id^='selectSystem_name_']", function () { + + // }) ; + + ~ ; + + # --------------- END COSTING ---------------------------------------------------------------------------------------------------------------- + } + + if ($tab == 5) { # Notes + + # --------------- START NOTES ---------------------------------------------------------------------------------------------------------------- + + # # my $sec = '_notes' ; + + # # my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + # # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # # return if $ret ; + + # # $add_form_fields = '' ; + + # # &db_min_ro('quote_event_notes','*','','','') ; + + # # $add_form_fields .= qq~ + # #
    + # #
    + # #

    + # # Notes: + # #

    + # #
    + # #
    ~ ; + + # # &tab_build_terms_headers ; + + # # $cntnoteloop = 1 ; + # # for (1 .. 5) { + # # &tab_build_terms_fields('note',$_,$id) ; + # # } + + # # $add_form_fields .= qq~ + # #
    + # #
    + # #

    + # # Payment Terms: + # #

    + # #
    + # #
    ~ ; + # # &tab_build_terms_headers ; + + # # $cntnoteloop = 1 ; + # # for (1 .. 5) { + # # &tab_build_terms_fields('payment_term',$_,$id) ; + # # } + # # &event_tabs_content_box($sec_name,$sec_col) ; + + # --------------- END NOTES ---------------------------------------------------------------------------------------------------------------- + } + + if ($tab == 6) { # Workings + + # --------------- START Working ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + $lcol = 1 ; + $fcol = 2 ; + + my @docs = ('Slip') ; + + $add_form_fields .= qq~ +
    + ~ ; + + $file_cnt = 3 ; + + foreach (@docs) { + my $doc = lc $_ ; $doc =~ s/ /\_/ ; $doc =~ s/&/\_/ ; + $event_uploads = &common_get_field_uploads($id,"$doc",'id','delete-attached-slip') ; + if ($event_uploads) { + $add_form_fields .= qq~ +
    + $event_uploads +
    ~; + } else { + $add_form_fields .= qq~ +
    +
    + + +

    Upload file from PC.

    +
    +
    + ~; + } + } + + $trigger_jquery_raw .= qq( + \$('#delete-attached-slip').click(function (e) { + BootstrapDialog.confirm({ + title: 'Confirm Delete', + message: 'Are you sure you want to delete $doc?', + type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + callback: function(result) { + if (result) { + var url = "$useropts{scripts}/get/get_delete_attach.pl?slips/$id&$db{$table}{$id}{slip}&$table&$id&slip" ; + \$.get(url); + \$('#attach-$id-4').hide() ; + \$('#delete-attached-slip').hide() ; + } else { + // alert('Nope.'); + } + } + }); + }); + ) ; + + $event_uploads = '' ; + # $add_form_fields .= &common_min_form_label_col("Custom Set") ; + + my $custom_set_checked = ($db{$table}{$id}{custom_set} || $db{$table}{$id}{demo_id}) ? "CHECKED" : "" ; + + $add_form_fields .= qq~ +
    + + +
    + ~ ; # class="control-label" + # $add_form_fields .= &common_min_form_checkbox_col('custom_set','') ; + + $add_form_fields .= qq~ +
    + ~ ; + + our %sec_cnt = ('a_event' => "50-List Expenses") ; + + my $sec = 'workings' ; + my ($sec_name, $sec_cnt_workings, $sec_col) = &tab_sec_det($sec) ; + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt_workings . '|' ; + + return if $ret ; + + &event_tabs_build_sec($sec,$tab) ; + + foreach (sort keys %sec_cnt) { + $_k = substr($_, 1) ; + my @parts = split(/\-/, $sec_cnt{$_}) ; + $add_form_fields .= qq~ +
    +
    +

    + $parts[1] : +

    +
    +
    + ~ if $parts[1] ne 'Operators'; + + $add_form_fields .= qq~ +
    +
    +
    +

    + $parts[1] : +

    +
    + $icon_casuals +
    +
    + ~ if $parts[1] eq 'Operators' ; + + &tab_build_qt_col_headers_workings("$sec$_k") ; + # # # &db_min_ro('event_quotes_min', 'id, remarks_workings_event, supplier_workings_event, ref_nr_workings_event, qty_workings_event, amount_usd_workings_event, amount_workings_event, vat_workings_event, description_workings_event', "id = $id", '', '') if $id ; + &event_tabs_build_costs_forms($id,$tab,$parts[0],"$sec$_k") ; + } + + $add_form_fields .= qq~ +
    +
    +   +
    +
    ~ ; + $add_form_fields .= qq~ +
    +
    +   +
    + ~ ; + + my @ttlarr = ("sub_total", "vat_total", "grand_total") ; + $lcol = 1; + $fcol = 1; + foreach (@ttlarr) { + $lcol = 1; + $add_form_fields .= &common_min_form_label_col($_) ; + } + + $add_form_fields .= qq~
    ~ ; + + $trigger_jquery_raw .= qq~ + \$("#textareaAdditional_notes").change(function () { + if (\$(this).val()) { + \$('label[for="additional_notes_expenses"]').text('Additional Notes : ') ; + \$("#textareaAdditional_notes_expenses_input").html(\$(this).val()) ; + } else if (!\$(this).val() && \$('label[for="additional_notes_expenses"]').text()) { + \$('label[for="additional_notes_expenses"]').text('') ; + \$("#textareaAdditional_notes_expenses_input").html('') ; + } + }) ; + ~ ; + + my $add1 = ($db{$table}{$id}{additional_notes}) ? "Additional Notes : " : "" ; + my $add2 = ($db{$table}{$id}{additional_notes}) ? "$db{$table}{$id}{additional_notes}" : "" ; + + $add_form_fields .= qq~

    $add2

    ~ ; + $lcol = 2; + $add_form_fields .= &common_min_form_label_col('Total') ; + $lcol = 1; + + my @ttlarr = ("total_amount_workings_event","total_vat_amount_workings_event","total_grand_amount_workings_event"); + $lcol = 1 ; $fcol = 1 ; + + my %renamed_totals = ("total_amount_workings_event" => "sub_total_workings_event", "total_vat_amount_workings_event" => "vat_total_workings_event" , "total_grand_amount_workings_event" => "grand_total_workings_event") ; + + foreach (@ttlarr) { + $readonly{$renamed_totals{$_}} = "READONLY"; + $input_style{$renamed_totals{$_}} = qq~style="text-align:right;"~ ; + my $val = $db{$table}{$id}{$_} ? $db{$table}{$id}{$_} : '0.00' ; + $add_form_fields .= &common_min_form_input_col($renamed_totals{$_},$val) ; + } + + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= qq~ +
    +
    +   +
    +
    ~ ; + + &event_tabs_content_box($sec_name,$sec_col) ; + + # --------------- END WORKING ---------------------------------------------------------------------------------------------------------------- + } + + if ($tab == 7) { # Invoice Details + + # --------------- START INVOICE DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_invoice_details' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + $lcol = 3 ; + $fcol = 5 ; + + $add_form_fields = '' ; + + $add_form_fields .= &common_min_form_input('invoice_nr',$db{$table}{$id}{invoice_nr},'') ; + my $checked = 'CHECKED' if $db{$table}{$id}{annual_invoice} ; + $add_form_fields .= &common_min_form_input('po_nr',$db{$table}{$id}{po_nr},'') ; + $add_form_fields .= &common_min_form_datepicker('invoice_date',$db{$table}{$id}{invoice_date}) ; + + &event_tabs_content_box($sec_name,$sec_col); + + # --------------- END INVOICE DETAILS ---------------------------------------------------------------------------------------------------------- + } + +} #------------------------------------------------------------------------------------ + +sub event_tabs_build_sec { + + my ($sec_,$tab) = @_ ; + + # # # &db_min_ro('event_quotes_min', 'id,description_workings_event,operator_workings_event', "id = $i{id}", '', '') if $i{id}; + + my @saved_des = () ; my @saved_op = () ; + + # my %casual_name_dropdown_hash = () ; + + if ($sec_ eq "workings") { + @saved_des = split(";", $db{event_quotes_min}{$i{id}}{description_workings_event}) ; + @saved_op = split(";", $db{event_quotes_min}{$i{id}}{operator_workings_event}) ; + &db_min_ro('users','*',"user_type LIKE 'casual%' AND block <> 1 AND inactive <> 1",'','') if $iaction eq 'add' ; + foreach my $uid (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + # $casual_name_dropdown_hash{$uid} = $db{users}{$uid}{name} ; + $opts{operator_field} .= qq~~ ; + } + } else { + @saved_des = split(";", $db{event_quotes_min}{$i{id}}{item_costing_event}) ; + } + + unless ($opts{description_field}) { + $opts{description_field} = qq~~ ; + my $other_id = 0 ; + foreach (sort {$db{event_cost_items}{$a}{name} cmp $db{event_cost_items}{$b}{name}} keys %event_list_name_array_expenses) { + next if $db{event_cost_items}{$_}{excl_from_expenses} ; + if (lc $db{event_cost_items}{$_}{name} eq "other") { + $other_id = $_ ; + next ; + } + $opts{description_field} .= qq~~ ; + } + $opts{description_field} .= qq~~ ; + + } + + my @description_chosen_field_ids = () ; my @operator_chosen_field_ids = () ; my @desriptions_that_are_operators = () ; + + foreach (sort keys %sec_cnt) { + + $_k = substr($_,1) ; $k = substr($_,2) ; + + my @parts = split(/\-/,$sec_cnt{$_}) ; + + for my $p_ (1 .. $parts[0]) { # item_1_costing_systems + + my $field = "$sec_$_k\_$p_" ; + my $saved_val = $saved_des[$p_ - 1] ; + next if $p_ > 1 && !$saved_val ; + my $saved_val_2 = $saved_op[$p_ - 1] ; + + if ($_k eq '_event') { + $opts{"description_$field"} = $opts{description_field} ; + $trigger_jquery_raw .= qq~\$("#selectDescription_$field").val("$saved_val") ; \$("#selectDescription_$field").trigger("chosen:updated") ; ~ if $saved_val and $saved_val ne "14" ; + push @desriptions_that_are_operators,"#selectDescription_$field" if $saved_val eq "14" ; + + if ($sec_ eq "workings") { + $opts{"operator_$field"} = $opts{operator_field} ; + $trigger_jquery_raw .= qq~\$("#selectOperator_$field").val("$saved_val_2") ; \$("#selectOperator_$field").trigger("chosen:updated") ; ~ if $saved_val_2 ; + } + } + + $item_type = 'input' ; + + unless ($got{$field}) { + + $got{$field} = 1 ; + push @excl_field_ids,"#checkboxExcl_$field" ; + push @description_field_ids,"#selectDescription_$field" ; + push @operator_field_ids,"#selectOperator_$field" ; + push @description_chosen_field_ids,"#selectDescription_$field\_chosen" ; + push @operator_chosen_field_ids,"#selectOperator_$field\_chosen" ; + push @vat_field_ids,"#checkboxVat_$field" ; + push @qty_field_ids,"#inputQty_$field" ; + push @amount_usd_field_ids,"#inputAmount_usd_$field" ; + + } + } + } + + my $desriptions_that_are_operators_string = join (",",@desriptions_that_are_operators) ; + + $trigger_jquery_raw .= qq~\$("$desriptions_that_are_operators_string").val("14") ; \$("$desriptions_that_are_operators_string").trigger("chosen:updated") ; ~ if $desriptions_that_are_operators_string ; + + # if ($sec_ eq "demo_expenses") { + + $trigger_jquery .= qq~ + \$("#$cntxt{$tab} [id^='select']").filter( function() { + return this.id.endsWith("_chosen") ; + }).css("width","90%"); + ~ ; + + # $trigger_jquery .= qq~\$("#$cntxt{$tab} [id^='select']").css("width","90%");~ ; + # return ; + # } + + # my $description_chosen_field_ids_string = join(",",@description_chosen_field_ids) ; + + # $trigger_jquery .= qq~\$("$description_chosen_field_ids_string").css("width","90%");~ ; + + # if ($sec_ eq "workings") { + # my $operator_chosen_field_ids_string = join(",",@operator_chosen_field_ids) ; + # $trigger_jquery .= qq~\$("$operator_chosen_field_ids_string").css("width","90%");~ ; + # } + +} #------------------------------------------------------------------------------------------ + +sub event_tabs_customer_select_opts { + + my ($table,$dispfield,$where,$field) = @_ ; + + $where .= " AND " if $where ; + $where .= "events='1'" ; + + &db_min_ro($table,'*',$where,'','') ; + + foreach my $id (sort { $db{$table}{$a}{name} cmp $db{$table}{$b}{name} } keys %{$db{$table}}) { + + my $saved_val = $db{event_quotes}{$i{id}}{$field} ; + + if ($saved_val) { my @valarr = split(/\:/,$saved_val) ; $saved_val = $valarr[0] ; } + + if ($saved_val eq $id) { $selected = 'SELECTED' ; } else { $selected = '' ; } + + $opts{$field} .= qq~~ ; + unless ($got{$field}) { + $trigger_jquery .= qq~\$("#selectQuote_to_chosen").css( "width", "96%" );~ ; + $got{$field} = 1 ; + # $trigger_jquery_raw .= qq~ + # \$("#selectQuote_to").change(function() { + # dispCustomer() ; + # }); + # ~; + + + } + } + + $trigger_jquery_raw .= qq~ + function dispCustomer() { + var custval = \$("#selectQuote_to").val(); + var arrP = custval.split(":"); + \$("#inputContact_name").val(arrP[1]); + \$("#inputAddress").val(arrP[4]); + \$("#inputEmail").val(arrP[2]); + \$("#inputTel").val(arrP[3]); + } + ~; + +} #------------------------------------------------------------------------------------------ + +sub tab_build_terms_headers { + + $add_form_fields .= qq~ +
    +
    + +
    +
    + +
    +
    + ~ ; +} #------------------------------------------------------------------------------------ + +sub tab_build_terms_fields { + + my ($sec,$cnt,$id) = @_ ; + + my $exfield = "excl_$cnt\_$sec\s" ; + my $inpfield = "$sec\_$cnt" ; + + unless ($db{quote_event_notes}{1}{$inpfield}) { + $checkit{$exfield} = 1 ; + } + + if ($db{$table}{$id}{$inpfield}) { + $val = $db{$table}{$id}{$inpfield} ; + } else { + $val = $db{quote_event_notes}{1}{$inpfield} ; + } + + $note_display_style = '' ; $note_display_plus_btn = '' ; + unless ($cnt==1 or $db{quote_event_notes}{1}{$inpfield}) { + $note_display_style = qq~style='display:none;'~ ; + $trigger_jquery_raw .= qq~ \$("#btn_$cnt\_$sec").click(function () { + \$("#$cnt\_$sec").toggle(); + \$("#btn_$cnt\_$sec").hide(); + var v = $cnt + 1 ; + \$("#btn_"+v+"\_$sec").show(); + });~ ; + if ($cnt>$cntnoteloop) { + $note_display_butt = qq~display:none;~ ; + } else { + $note_display_butt = '' ; + } + $note_display_plus_btn = qq~~; + } else { + $cntnoteloop++ ; + } + + $add_form_fields .= qq~
    ~ ; + + if ($db{$table}{$id}{$exfield} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + + $label{$exfield} = 1 ; + $fcol=1 ; + $add_form_fields .= &common_min_form_checkbox_col($exfield,$checkit{$exfield},$checked) ; + $fcol=6 ; + $input_style{$inpfield} = qq~style='margin-bottom:4px;margin-top:-2px;'~ ; # add spaces between boxes + $add_form_fields .= &common_min_form_input_col($inpfield,$val,'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~ +
    +
    + $note_display_plus_btn +
    +
    + ~ ; + +} #------------------------------------------------------------------------------------ + +sub tab_build_qt_right { + + my ($id,$tab,$ret) = @_ ; + + if ($tab==1) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_office_details' ; + my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + $lcol = 3 ; + + $add_form_fields = '' ; + + $fcol = 8 ; + # $textarea_height{notes} = ($is_schools_manager) ? 102 : 93 ; + # $textarea_height{notes} = ($glod_user_level < 4) ? 102 : 93 ; + $textarea_height{notes} = ($glod_user_level < 3) ? 102 : 93 ; + $add_form_fields .= &common_min_form_textarea('notes',$db{$table}{$id}{notes},'') ; + $add_form_fields .= qq~
     
    ~ ; + + # unless ($is_schools_manager) { + if ($glod_user_level > 3) { + $textarea_height{office_notes} = 93 ; + $add_form_fields .= &common_min_form_textarea('office_notes',$db{$table}{$id}{office_notes},'') ; + $add_form_fields .= qq~
     
    ~ ; + } + + &event_tabs_content_box($sec_name,$sec_col); + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + + if ($tab==7) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + + my $sec = '_profit_loss' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + $lcol = 3 ; $fcol = 5 ; + + my $expenses = $db{$table}{$id}{total_grand_amount_workings_event} ? sprintf("%0.2f",$db{$table}{$id}{total_grand_amount_workings_event}) : '0.00' ; + # my $income = $db{$table}{$id}{grand_total} ? $db{$table}{$id}{grand_total} : '0.00' ; + my $income = $db{$table}{$id}{sub_total} ? sprintf("%0.2f",$db{$table}{$id}{sub_total}) : '0.00' ; + # my $profit_or_loss = $income - $expenses ; + my $profit_or_loss = sprintf("%0.2f",($income - $expenses)) ; + + $add_form_fields = '' ; + + $lcol = 3; + $fcol = 3; + + $readonly{income} = "READONLY"; + $readonly{expenses} = "READONLY"; + $readonly{profit_loss} = "READONLY"; + + $add_form_fields .= &common_min_form_input('income',$income,'') ; + $add_form_fields .= &common_min_form_input('expenses',$expenses,'') ; + $add_form_fields .= &common_min_form_input('profit_loss',$profit_or_loss,'') ; + + &event_tabs_content_box($sec_name,$sec_col); + + # my $sec = '_overall_revenue' ; + # my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + # my @ttlarr = ("total_grand_amount_workings_event", "grand_total") ; + + # foreach (@ttlarr) { + # $readonly{$_} = "READONLY"; + # $input_style{$_} = qq~style="text-align:right;"~; + # my $val = $db{$table}{$id}{$_} ? $db{$table}{$id}{$_} : '0.00' ; + # $add_form_fields .= &common_min_form_input_col($_,$val) ; + # } + + # &event_tabs_content_box($sec_name,$sec_col) ; + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + + } + +} #------------------------------------------------------------------------------------ + +sub tab_curr_symbols { + + $curr_symb{ZAR} = 'R'; + $curr_symb{USD} = '$'; + $curr_symb{GBP} = 'GBP'; + $curr_symb{EUR} = 'EUR'; + + our $js_curr_arr = '' ; + + foreach (keys %curr_symb) { + $js_curr_arr .= qq(currArr['$_'] = "$curr_symb{$_}";) ; + } + +} #------------------------------------------------------------------------------------ + +sub tab_build_qt_col_headers { + + my ($sec) = @_ ; + + my $style_vat = '' ; + + $style_vat = 'style="display:none;"' if $no_vat{$sec} ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ if $sec eq 'costing_event'; + $add_form_fields .= qq~
    ~ if $sec eq 'costing_casual_users'; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + %cost_desc = () ; + %def_qty = () ; + %def_zar = () ; + %min_zar = () ; + %vat_tick = () ; + %excl_tick = () ; + +} #---------------------------------------------------------------------------------------- + +sub tab_build_qt_col_headers_workings { + + my ($sec) = @_ ; + + my $style_vat = '' ; + + $style_vat = 'style="display:none;"' if $no_vat{$sec} ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ if $sec ne 'workings_casual_users'; + $add_form_fields .= qq~
    ~ if $sec ne 'workings_casual_users'; + # $add_form_fields .= qq~
    ~ if $sec eq '_workings_casual_users'; + $add_form_fields .= qq~
    ~ if $sec ne 'workings_casual_users'; + # $add_form_fields .= qq~
    ~ if $sec eq '_workings_casual_users'; + $add_form_fields .= qq~
    ~ if $sec ne 'workings_casual_users'; + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + %cost_desc = () ; + %def_qty = () ; + %def_zar = () ; + %min_zar = () ; + %vat_tick = () ; + %excl_tick = () ; + +} #---------------------------------------------------------------------------------------- + +sub event_tabs_content_box { + + my ($sec_name,$sec_col) = @_ ; + + $fcol=9 ; + $print_box_content_rows .= &common_min_box_top('indent-left',$sec_name,$sec_col,$cam_box_icon); + $print_box_content_rows .= qq~$add_form_fields~; + $print_box_content_rows .= &common_min_box_foot; + +} #---------------------------------------------------------------------------------------- + +sub tab_cnt { + + our %cntxt = () ; + + $cntxt{1} = 'one' ; + $cntxt{2} = 'two' ; + $cntxt{3} = 'three' ; + # return if $is_schools_manager ; + return if $glod_user_level < 4 ; + $cntxt{4} = 'four' ; + # $cntxt{5} = 'five' ; + $cntxt{6} = 'six' ; + $cntxt{7} = 'seven' ; + +} #---------------------------------------------------------------------------------------- + +sub tab_names { + + my ($tab) = @_ ; + + my $tabname = '' ; + + if ($tab==1) { $tabname = 'Customer Details' ; } + elsif ($tab==2) { $tabname = 'Event Details' ; } + elsif ($tab==3) { $tabname = 'Event Specifics' ; } + elsif ($tab==4) { $tabname = 'Quote' ; } + # elsif ($tab==5) { $tabname = 'Notes' ; } + elsif ($tab==6) { $tabname = 'Expenses' ; } + elsif ($tab==7) { $tabname = 'Invoice Details' ; } + + return ($tabname) ; + +} #------------------------------------------------------------------------------------ + +sub tab_hash { + + # &db_min_ro('users',"id","user_type like '%casual%'",'','') ; + # &db_min_ro('events',"id,event_quote_nr,user_id,category",'','','') ; + # &db_min_ro('event_cost_items','*','','name asc','') ; + + our @excl_field_ids = () ; our @description_field_ids = () ; our @operator_field_ids = () ; our @vat_field_ids = () ; our @qty_field_ids = () ; our @amount_usd_field_ids = () ; our @excl_field_ids = () ; our @btn_ids = () ; + + &tab_load_vars; + + for (1 .. 7) { + + next if $_ == 5 ; + + my $tname = &tab_names($_) ; + our $ret_pdf_link_sec = '' ; # _sa_out+16|_cl_del+13|_sa_in+17|_des_sa+13| + + &event_tabs_build_qt_left('',$_,1) ; + &tab_build_qt_right('',$_,1) ; + + $tabcnt{$tname} = $_ ; + $tabsec{$tname} = $ret_pdf_link_sec ; + } + + # &build_workings_costings_forms_jquery ; + +} #------------------------------------------------------------------------------------ + +sub tab_load_vars { + + # our %casuals = (); + our %available_casuals = () ; + our %not_available_casuals = () ; + + # unless (defined %casuals) { + unless (scalar keys %casuals > 0) { + &db_min_ro('users',"id","user_type like '%casual%'",'','') ; + + foreach my $user_id (keys %{$db{users}}){ + $casuals{$user_id} = 1 ; + } + } + + &db_min_ro('events',"id,event_quote_nr,user_id,category",'','','') ; + + foreach my $event_id (keys %{$db{events}}){ + next unless $casuals{$db{events}{$event_id}{user_id}} ; + if ($db{events}{$event_id}{event_quote_nr} == $id and $db{events}{$event_id}{category} eq 'available'){ + $available_casuals{$db{events}{$event_id}{user_id}} = 1 ; + } elsif ($db{events}{$event_id}{event_quote_nr} == $id and $db{events}{$event_id}{category} eq 'unavailable'){ + $not_available_casuals{$db{events}{$event_id}{user_id}} = 1 ; + } + } + + our %dlg_operator = () ; + + for (1 .. 50) { + next unless $db{$table}{$id}{"operator_workings_event_$_"} ; + if ($available_casuals{$db{$table}{$id}{"operator_workings_event_$_"}}) { + $dlg_operator{"operator_workings_event_$_"} = qq~
    ~ ; + } elsif ($not_available_casuals{$db{$table}{$id}{"operator_workings_event_$_"}}) { + $dlg_operator{"operator_workings_event_$_"} = qq~ ~ ; + } else { + $dlg_operator{"operator_workings_event_$_"} = qq~~ ; + } + } + + # &db_min_ro('event_cost_items','*','','name asc','') ; + &db_min_ro('event_cost_items','*',"excl_from_expenses < 1",'name asc','') ; + + our %event_list_name_array_quote = () ; + our %event_list_name_array_expenses = () ; + my @spl = () ; + + foreach my $iid (keys %{$db{event_cost_items}}) { + @spl = split(" ", $db{event_cost_items}{$iid}{name}); + for (@spl) {$_ = ucfirst $_ ; } + $db{event_cost_items}{$iid}{name} = join (" ", @spl) ; + $event_list_name_array_quote{$iid} = $db{event_cost_items}{$iid}{name} ; + $event_list_name_array_expenses{$iid} = $db{event_cost_items}{$iid}{name} ; + } + +} #------------------------------------------------------------------------------------ + +sub tab_sec_det { + + my ($sec) = @_ ; + + my ($sec_nam,$sec_cnt,$sec_col) ; + + $sec_col = '71919b' ; # '85acb8' ; + $sec_cnt = 20 ; + $sec_nam = substr($sec,1) ; + @array = split(/\_/,$sec_nam); + my @sec_nam = map ucfirst, @array; + $sec_nam = join(" ", @sec_nam) ; + + if ($sec eq 'costing') { + $sec_nam = 'Event Costings' ; + for (1 .. 30) { $vat_tick{$_} = 1 ; } + } + + if ($sec eq 'workings') { + $sec_nam = 'Event Expenses' ; + for (1 .. 50) { $vat_tick{$_} = 1 ; } + } + + return ($sec_nam,$sec_cnt,$sec_col) ; + +} #------------------------------------------------------------------------------------ + +sub event_tabs_build_boxes_top { + + my ($id,$demo_page) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(3,6) ; + + $add_form_fields = '' ; + + $fcol=8 ; + + $add_form_fields .= qq~
    ~ ; + $preferred_title{quote_nr} = "Nr" ; + $add_form_fields .= &common_min_form_input('quote_nr',$db{$table}{$id}{quote_nr},'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + if (($db{$table}{$id}{quote_date} eq '') or ($db{$table}{$id}{quote_date} eq '0000-00-00')) { + $db{$table}{$id}{quote_date} = $now_ccyy_mm_dd ; + } + $preferred_title{quote_date} = "Date" ; + $add_form_fields .= &common_min_form_datepicker('quote_date',$db{$table}{$id}{quote_date}) ; + my $plus_n_days_ccyy_mm_dd = &common_add_delta_days(14) ; + + $add_form_fields .= qq~
    ~ ; + + if (!$demo_page) { + $add_form_fields .= qq~
    ~ ; + $preferred_title{quote_to} = "Client" ; + $add_form_fields .= &common_min_form_select('quote_to',$db{$table}{$id}{quote_to},'') ; + $add_form_fields .= qq~
    ~ ; + $dlg{quote_to} = qq~ + ~ ; + } + + $fcol = 7; + + $add_form_fields .= qq~
    ~ ; + + $allow_deselect{country_id} = 1 ; + $add_form_fields .= &common_min_form_select('country_id',$db{$table}{$id}{country_id},'') ; + $trigger_jquery_raw .= qq~\$("#selectCountry_id").chosen({ allow_single_deselect:true });~ ; + $add_form_fields .= qq~
    ~ ; + + if ($demo_page) { + $add_form_fields .= qq~
    ~ ; + $allow_deselect{region_id} = '' ; + $add_form_fields .= &common_min_form_select('region_id',$db{$table}{$id}{region_id},'') ; + $add_form_fields .= qq~
    ~ ; + } + + $fcol = 8; + $print_box_content_rows .= &common_min_box_top('qrcode',"Quote",'BABEC2'); + $print_box_content_rows .= qq~ +
    +
    + $add_form_fields +
    +
    ~; + $print_box_content_rows .= qq~ +
    +
    +   +
    +
    ~ ; + $print_box_content_rows .= &common_min_box_foot; + +} #------------------------------------------------------------------------------------ + +sub event_tabs_build_costs_forms { + + my ($id,$tab,$rcnt,$suffix) = @_ ; + + $tab_sections{$tab} .= "$suffix+$rcnt|" ; + + $jq_work_cal = qq~ + var vat_totalW$suffix = 0 ; + var total_totalW$suffix = 0 ; + var subtotalW$suffix = 0 ; + var vat_amountW = 0 ; + ~ ; + $jq_fs = '' ; + + %cnt_specific_jquery = () ; + + &set_check_boxes_checked($id,$rcnt,"excl",$suffix); + &set_check_boxes_checked($id,$rcnt,"vat",$suffix); + + my $cntloop = 1 ; + my $field = "" ; + my $val = 0 ; + + my $table_ = "event_quotes_min" ; + + my @excl_old = split(";", $db{$table_}{$id}{"excl_$suffix"}) ; + my @qty_old = split(";", $db{$table_}{$id}{"qty_$suffix"}) ; + my @vat_old = split(";", $db{$table_}{$id}{"vat_$suffix"}) ; + my @remarks_old = () ; + my @supplier_old = () ; + my @ref_nr_old = () ; + my @amount_usd_old = () ; + my @amount_ttl_old = () ; + my @des_old = () ; + my @ops_old = () ; + my @curr_amnt_cost = () ; + + if ($suffix eq "workings_event") { + @remarks_old = split(";",$db{$table_}{$id}{remarks_workings_event}) ; + @supplier_old = split(";",$db{$table_}{$id}{supplier_workings_event}) ; + @ref_nr_old = split(";",$db{$table_}{$id}{ref_nr_workings_event}) ; + @amount_usd_old = split(";",$db{$table_}{$id}{amount_usd_workings_event}); + @amount_ttl_old = split(";",$db{$table_}{$id}{amount_workings_event}); + @des_old = split(";",$db{$table_}{$id}{description_workings_event}) ; + @ops_old = split(";",$db{$table_}{$id}{operator_workings_event}) ; + } else { + @amount_usd_old = split(";",$db{$table_}{$id}{usd_amnt_costing_event}); + @amount_ttl_old = split(";",$db{$table_}{$id}{item_ttl_costing_event}); + @des_old = split(";",$db{$table_}{$id}{item_costing_event}); + @curr_amnt_cost = split(";",$db{$table_}{$id}{curr_amnt_costing_event}); + } + + for (1 .. $rcnt) { + + $display_style = '' ; + $display_plus_btn = '' ; + my $style_display_butt = "" ; + unless ($_ == 1 or $des_old[$_ - 1]) { + $display_style = qq~style='display:none;'~ ; + push @btn_ids,"#btn_$suffix\_$_" ; + if ( $_>$cntloop ) { + $display_butt = qq~display:none;~ ; + $style_display_butt = qq~style="display:none;"~ ; + } else { + $display_butt = '' ; + } + $display_plus_btn = ($_>$cntloop) ? qq~~ : qq~~; + } else { + $cntloop++ ; + } + + $add_form_fields .= qq~
    ~ ; + + #---------------------------------------------------------------------------------------------------- + + if ($des_old[$_-1] || $_ == 1) { + + push @all_select_ids,"#selectDescription_$suffix\_$_" ; + push @all_select_ids,"#selectOperator_$suffix\_$_" if $suffix eq "workings_event" ; + + $field = "excl_$suffix\_$_" ; + $fcol = 1; + # if ($checkit{$field} == 1) { + if ($excl_old[$_ - 1]){ + $checked = 'CHECKED'; + } elsif (($excl_tick{$_}) and ($iaction eq 'add')) { + $checked = 'CHECKED'; + } else { + $checked = ''; + } + $label{$field} = 1; + $add_form_fields .= &common_min_form_checkbox_col($field,$checkit{$field},$checked) ; + + #---------------------------------------------------------------------------------------------------- + + $field = "description_$suffix\_$_" ; + $fcol = 2; + # $allow_deselect{$field} = 1; + $preferred_title{$field} = "Description $_" ; #if $suffix ne '_workings_casual_users'; + + $opts{$field} = $opts{description_field} unless $opts{$field} ; + + if ($des_old[$_-1] && $opts{$field} !~ /SELECTED/ && $opts{$field} !~ /selected/) { + $opts{$field} =~ s/\"/\'/g ; + $opts{$field} =~ s/value='$des_old[$_-1]'/value='$des_old[$_-1]' SELECTED/g ; + } + + $add_form_fields .= &common_min_form_select_col($field,'') ; + + #---------------------------------------------------------------------------------------------------- + + if ($suffix eq "workings_event") { + + $field = "operator_$suffix\_$_" ; + $fcol = 2; + # $allow_deselect{$field} = 1; + $preferred_title{$field} = "Operator $_" ; + + $opts{$field} = $opts{operators_field} unless $opts{$field} ; + + if ($ops_old[$_-1] && $opts{$field} !~ /SELECTED/ && $opts{$field} !~ /selected/) { + $opts{$field} =~ s/\"/\'/g ; + $opts{$field} =~ s/value='$ops_old[$_-1]'/value='$ops_old[$_-1]' SELECTED/g ; + } + + $add_form_fields .= &common_min_form_select_col($field,'') ; + + #---------------------------------------------------------------------------------------------------- + + $field = "remarks_$suffix\_$_" ; + $fcol = 1; + # $allow_deselect{$field} = 1; + $preferred_placeholder{$field} = "Remarks $_" ; + $add_form_fields .= &common_min_form_input_col($field, $remarks_old[$_ - 1]) ; + + #---------------------------------------------------------------------------------------------------- + + $field = "supplier_$suffix\_$_" ; + $fcol = 1; + # $allow_deselect{$field} = 1; + $preferred_placeholder{$field} = "Supplier $_" ; + $add_form_fields .= &common_min_form_input_col($field,$supplier_old[$_ - 1]) if $suffix ne '_workings_casual_users'; + + #---------------------------------------------------------------------------------------------------- + + $field = "ref_nr_$suffix\_$_" ; + $fcol = 1; + # $allow_deselect{$field} = 1; + $preferred_placeholder{$field} = "Ref Nr $_" ; + $add_form_fields .= &common_min_form_input_col($field,$ref_nr_old[$_ - 1]) ; + + #---------------------------------------------------------------------------------------------------- + + } + + $field = "qty_$suffix\_$_" ; + # $field .= '_costing_event'; + $fcol = 1; + $input_style{$field} = qq(style="text-align:right;"); + $preferred_placeholder{$field} = "Qty $_" ; + $val = $qty_old[$_ - 1] ; + unless ($val) { + $val = $def_qty{$_} ; + } + $val = &q_get_val($val) ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + + #---------------------------------------------------------------------------------------------------- + + $field = "amount_usd_$suffix\_$_" ; + $fcol = 1; + $input_style{$field} = qq(style="text-align:right;"); + $val = $amount_usd_old[$_ - 1] ; + unless ($val) { + $val = $def_usd{$_} ; + } + $val = &q_get_val($val) ; + $preferred_placeholder{$field} = "Amount $_" ; + # $excl_on_change{$field} = 1 ; + $val = '0.00' unless $val ; + $add_form_fields .= &common_min_form_input_col($field,$val,1) ; + + $add_form_fields .= qq~~ if $des_old[$_-1] && $amount_usd_old[$_ - 1] eq $default_cost_item_rates{$des_old[$_-1]}{half} ; + $add_form_fields .= qq~~ if $des_old[$_-1] && $amount_usd_old[$_ - 1] eq $default_cost_item_rates{$des_old[$_-1]}{full} ; + #---------------------------------------------------------------------------------------------------- + + # if ($suffix eq "costing_event") { + + # $field = "curr_amnt_$suffix\_$_" ; + # # $field .= '_costing_event'; + # $input_style{$field} = qq(style="text-align:right;"); + # $readonly{$field} = 'READONLY' ; # $fcol=2 ; + # $preferred_placeholder{$field} = "ZAR Amnt $_" ; + # # $val = &q_get_val($db{$table}{$id}{$field}) ; + # $val = &q_get_val($curr_amnt_cost[$_ -1]) ; + # our $type = 'hidden' ; + # $add_form_fields .= &common_min_form_input_col($field,$val,1) ; $type = '' ; + # $type = '' ; + + # } + + # #---------------------------------------------------------------------------------------------------- + + $field = "amount_ttl_$suffix\_$_" ; + $input_style{$field} = qq(style="text-align:right;"); + $val = $amount_ttl_old[$_ - 1] ; + $val = &q_get_val($val) ; + # $val = &common_commify($val) ; + # $val = sprintf("%0.2f",$val) ; + $preferred_placeholder{$field} = "Total Amount $_" ; + # $excl_on_change{$field} = 1 ; + $readonly{$field} = 'READONLY' ; + $val = '0.00' unless $val ; + $add_form_fields .= &common_min_form_input_col($field,$val,1) ; + + #---------------------------------------------------------------------------------------------------- + + $field = "vat_$suffix\_$_" ; + $fcol=1 ; + # if ($checkit{$field} == 1) { + if($vat_old[$_ - 1]){ + $checked = 'CHECKED'; + } elsif ($iaction eq 'add') { + $checked = 'CHECKED'; + } else { + $checked = ''; + } + $label{$field} = 1 ; + if ($no_vat{$suffix}) { + $style_field{$field} = 'style="display:none;"' ; + } + # $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_checkbox_col($field,$checkit{$field},$checked) ; + + #---------------------------------------------------------------------------------------------------- + + } else { + $tindex+=10 if $suffix eq "workings_event" ; + $tindex+=7 if $suffix eq "costing_event" ; + } + + my $f_h_val = substr($quote_tab_default_full_half_items[$_-1],2) ; + + $add_form_fields .= (substr($quote_tab_default_full_half_items[$_-1],0,2) eq '1:') ? qq~~ : (substr($quote_tab_default_full_half_items[$_-1],0,2) eq '2:') ? qq~~ : qq~~ ; + + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= qq~ +
    +
    + $display_plus_btn +
    +
    + ~ ; + + my $style_disp_row = ($des_old[$_-1]) ? "" : "style='display:none;'" ; + $add_form_fields .= qq~ +
    +
    +
    +
    + ~ ; + + } + +} #---------------------------------------------------------------------------------------- + +1; diff --git a/libs/modules/_FromProd/v1.0/event_tabs_test_demo_temp.pm b/libs/modules/_FromProd/v1.0/event_tabs_test_demo_temp.pm new file mode 100644 index 0000000..9bd83b8 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/event_tabs_test_demo_temp.pm @@ -0,0 +1,4978 @@ +sub build_workings_costings_forms_jquery { + + my $description_options_costing = $opts{"description_costing_event_1"} ; + $description_options_costing =~ s/\SELECTED//g ; + $description_options_costing =~ s/\"/\'/g ; + + my $description_options_workings = $opts{"description_workings_event_1"} ; + $description_options_workings =~ s/\SELECTED//g ; + $description_options_workings =~ s/\"/\'/g ; + + our $operator_options = $opts{"operator_workings_event_1"} ; + $operator_options =~ s/\SELECTED//g ; + $operator_options =~ s/\"/\'/g ; + + my $btn_ids_string = join(",",@btn_ids) ; + + my $excl_field_ids_string = join(",",@excl_field_ids) ; + my $description_field_ids_string = join(",",@description_field_ids) ; + my $operator_field_ids_string = join(",",@operator_field_ids) ; + my $vat_field_ids_string = join(",",@vat_field_ids) ; + my $qty_field_ids_string = join(",",@qty_field_ids) ; + my $amount_usd_field_ids_string = join(",",@amount_usd_field_ids) ; + + $trigger_jquery_raw .= qq~ + // function update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days + function get_tab (id) { + let tab = "" ; + if (id.includes("workings_event")) { + tab = "workings_event" ; + } else if (id.includes("costing_event")) { + tab = "costing_event" ; + } + return tab ; + } + + function changed_vat (id) { + let tab = get_tab (id) ; + let row_nr = get_row_nr(id) ; + calc_totals(row_nr,tab) ; + } + + function changed_others (id) { + + let row_nr = get_row_nr(id) ; + let firstIndex = id.indexOf('_'); + let col = id.substring(0,firstIndex); + let tab = get_tab (id) ; + if (col == "inputAmount") { + let inp = parseFloat(\$("#"+id).val()) ; + inp = parseFloat(inp) ; + \$("#"+id).val(inp.toFixed(2)) ; + } else if (\$("#selectDescription_"+tab+"_"+row_nr).val() && \$("#selectDescription_"+tab+"_"+row_nr).val() != 14 && \$("#selectOperator_"+tab+"_"+row_nr).val()) { + // \$("#selectOperator_"+tab+"_"+row_nr).val("") ; + // \$("#selectOperator_"+tab+"_"+row_nr).trigger("chosen:updated") ; + } + // else if (col == "selectOperator" && \$("#selectDescription"+tab+"_"+row_nr).val() != 14) { + + // } + + if (col == "selectOperator") { // || (col == "selectDescription" && \$("#selectDescription_"+tab+"_"+row_nr).val( + return ; + } + + calc_totals(row_nr,tab) ; + } + + // \$("$vat_field_ids_string").change(function() { + \$("#content").on("change","[id^='checkboxVat_']", function () { + const id = this.id ; + changed_vat(id) ; + }); + + // \$("$excl_field_ids_string,$description_field_ids_string,$qty_field_ids_string,$amount_usd_field_ids_string,$operator_field_ids_string").change(function() { + \$("#content").on("change","[id^='checkboxExcl_'],[id^='selectDescription_'],[id^='inputQty_'],[id^='inputAmount_usd_'],[id^='selectOperator_workings_event_']", function () { + const id = this.id ; + + if ((id.includes("inputQty_") || id.includes("inputAmount_usd_")) && id.includes("costing_event")) { + + let row_nr = get_row_nr(id) ; + + let f_t = (\$("input[name='added_full_day_cost_item_"+row_nr+"']").val()) ? "full" : (\$("input[name='added_half_day_cost_item_"+row_nr+"']").val()) ? "half" : "" ; + + if (f_t) { + + let col = (id.includes("inputQty_")) ? "-2" : "-1" ; + + let full_half_add = \$("input[name='added_"+f_t+"_day_cost_item_"+row_nr+"']").val() ; + + let get_e_cost_id = (id.includes("inputAmount_usd_")) ? get_row_nr(\$("input[name='added_"+f_t+"_day_cost_item_"+row_nr+"']").val()) : "" ; + + if (((id.includes("inputQty_") && \$(this).val() == nr_days[f_t]) || (id.includes("inputAmount_usd_") && \$(this).val() == default_cost_item_rates[f_t+","+get_e_cost_id])) && full_half_add && full_half_add.includes(col)) { + full_half_add = full_half_add.replace(col+"_","") ; + \$("input[name='added_"+f_t+"_day_cost_item_"+row_nr+"']").val(full_half_add) ; + } else if (full_half_add && !full_half_add.includes(col)) { + \$("input[name='added_"+f_t+"_day_cost_item_"+row_nr+"']").val(col+"_"+full_half_add) ; + } + } + + } else if (id.includes("selectDescription_")) { + + let this_id = id ; + + let row_nr = get_row_nr(id) ; + + let tab = (this_id.includes("_costing_event_")) ? "costing_event" : (this_id.includes("_workings_event_")) ? "workings_event" : "" ; + + let full_day_exists = nr_days["full"] ; let half_day_exists = nr_days["half"] ; + + let already_loaded_full_day = (\$("#"+this_id).val()) ? \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val() : "" ; + let already_loaded_half_day = (\$("#"+this_id).val()) ? \$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val() : "" ; + + already_loaded_full_day = (typeof already_loaded_full_day == 'undefined') ? "" : 1 ; + already_loaded_half_day = (typeof already_loaded_half_day == 'undefined') ? "" : 1 ; + + if (already_loaded_full_day && already_loaded_half_day) { + return ; + } + + if (already_loaded_full_day == 1) { + full_day_exists = 0 ; + } + + if (already_loaded_half_day == 1) { + half_day_exists = 0 ; + } + + let date_from = \$("input[name='date_from']").val() ; + + date_from = date_from.substring(0,10) ; + + let full_half_day = 0 ; + + if (full_day_exists != 0) { + if ((typeof \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val() == 'undefined' || \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val()) && \$("#"+this_id).val()) { + \$("#content").append("") ; + } + full_half_day = 1 ; + // } else if (half_day_exists || (already_loaded_full_day && !half_day_exists && !already_loaded_half_day)) { + } else if (half_day_exists != 0) { + if ((typeof \$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val() == 'undefined' || !\$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val()) && \$("#"+this_id).val()) { + \$("#content").append("") ; + } + full_half_day = 2 ; + } + + let rate_ = "" ; + + if (default_cost_item_rates["full,"+\$("#"+this_id).val()] && full_half_day == 1) { + rate_ = default_cost_item_rates["full,"+\$("#"+this_id).val()] ; + } else if (default_cost_item_rates["half,"+\$("#"+this_id).val()] && full_half_day == 2) { + rate_ = default_cost_item_rates["half,"+\$("#"+this_id).val()] ; + } + if (rate_ == "") { + \$("input[name='added_full_day_cost_item_"+row_nr+"']").remove() ; + \$("input[name='added_half_day_cost_item_"+row_nr+"']").remove() ; + return ; + } + full_half_day = (full_half_day == 1) ? "full" : (full_half_day == 2) ? "half" : "" ; + + \$("input[name='qty_"+tab+"_"+row_nr+"']").val(nr_days[full_half_day]) ; + \$("input[name='amount_usd_"+tab+"_"+row_nr+"']").val(rate_) ; + \$("input[name='amount_ttl_"+tab+"_"+row_nr+"']").val((rate_*nr_days[full_half_day]).toFixed(2)) ; + if (!\$("input[name='added_"+full_half_day+"_day_cost_item_"+row_nr+"']").val()) { + \$("#"+tab+"_"+row_nr).append("") ; + } else { + \$("input[name='added_"+full_half_day+"_day_cost_item_"+row_nr+"']").val("-3_"+\$(this).val()) ; + } + + calc_totals(row_nr,tab) ; + + + } + + changed_others(id) ; + }); + ~ ; + + $trigger_jquery_raw .= qq~ + + \$("#content").on("click","[id^='btn_workings_event_'],[id^='btn_costing_event_']", function () { + // \$("$btn_ids_string").click(function () { + const id = this.id ; + let tab = get_tab (id) ; + + console.log("id : "+id) ; + console.log("tab : "+tab) ; + + add_quote_expenses_row_all(id,tab) ; + }); + + function add_quote_expenses_row_all (id,tab) { + + let row_nr = get_row_nr(id) ; + \$("#"+tab+"_"+row_nr).show(); + let row_html = "" ; + if (tab == "workings_event") { + row_html = add_quote_expenses_row(row_nr,tab,"$description_options_workings","$operator_options") ; + } else if (tab == "costing_event") { + row_html = add_quote_expenses_row(row_nr,tab,"$description_options_costing","") ; + } + \$("#"+tab+"_"+row_nr).html(row_html); + // \$("#$suffix\_"+row_nr).trigger("chosen:updated") ; + + \$("#selectDescription_"+tab+"_"+row_nr).chosen({ allow_single_deselect:true }) ; + + if (tab == "workings_event") { + \$("#selectOperator_workings_event_"+row_nr).chosen({ allow_single_deselect:true }); + \$("#inputRemarks_workings_event_"+row_nr).css("text-align","") ; + \$("#inputSupplier_workings_event_"+row_nr).css("text-align","") ; + \$("#inputRef_nr_workings_event_"+row_nr).css("text-align","") ; + } + + \$("#btn_"+tab+"_"+row_nr).hide(); + \$("#btn_row_"+tab+"_"+row_nr).hide(); + var v = row_nr + 1 ; + + // \$("#btn_$suffix\_"+v).css("padding-left","16px") ; + \$("#btn_"+tab+"_"+v).html("") ; + \$("#btn_"+tab+"_"+v).show(); + \$("#btn_row_"+tab+"_"+v).show() ; + \$("#2_"+tab+"_"+row_nr).show() ; + + \$("#checkboxExcl_"+tab+"_"+row_nr).prop('checked',false) ; + + // \$("#"+tab+"_"+row_nr).on("change","#checkboxVat_"+tab+"_"+row_nr+"", function() { + // const id = this.id ; + // changed_vat(id) ; + // }); + + // \$("#"+tab+"_"+row_nr).on("change","#checkboxExcl_"+tab+"_"+row_nr+",#selectDescription_"+tab+"_"+row_nr+",#selectOperator_"+tab+"_"+row_nr+",#inputQty_"+tab+"_"+row_nr+",#inputAmount_usd_"+tab+"_"+row_nr+"", function() { + // const id = this.id ; + // changed_others(id) ; + // }); + + } + + ~ if $btn_ids_string ; + + $trigger_jquery_raw .= qq~ + + \$("#selectCurrency").change(function () { + + }) ; + + \$("input[name='roe']").change(function () { + + let roe = \$(this).val() ; + if (roe < 0 || !roe) { + roe = 1 ; + } + \$(this).val(parseFloat(roe).toFixed(2)) ; + + var sub_total = 0 ; var vat_total = 0 ; var sub_total_quote = 0 ; var vat_total_quote = 0 ; + + [sub_total,vat_total] = add_up_totals("workings_event",50,roe,1) ; + [sub_total_quote,vat_total_quote] = add_up_totals("costing_event",30,roe,1) ; + + // // // \$("input[name='income']").val((sub_total_quote+vat_total_quote).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("input[name='income']").val((sub_total_quote+vat_total_quote).toFixed(2)) ; + \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + update_overall_totals(sub_total,vat_total,"workings_event") ; + update_overall_totals(sub_total_quote,vat_total_quote,"costing_event") ; + + }) ; + + function add_up_totals (tab,nr_of_rows,roe,recalc_totals) { + + let sub_total = 0 ; let vat_total = 0 ; + for (let i=1; i<=nr_of_rows; i++) { + if (!\$("#"+tab+"_"+i).html()) { break ; } + if (\$("#selectDescription_"+tab+"_"+i).val()) { + if (\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { continue ; } + let ttl = 0 ; + if (recalc_totals) { + ttl = parseFloat(\$("#inputAmount_usd_"+tab+"_"+i).val()) * parseFloat(\$("#inputQty_"+tab+"_"+i).val()) * parseFloat(roe) ; + } else { + ttl = parseFloat(\$("#inputAmount_ttl_"+tab+"_"+i).val().replace(/,/g, '')) + } + // // // // \$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toFixed(2)) ; + if (!\$("#inputAmount_ttl_"+tab+"_"+i).val() || \$("#inputAmount_ttl_"+tab+"_"+i).val() == "NaN") { + \$("#inputAmount_ttl_"+tab+"_"+i).val("0.00") ; + ttl = 0 ; + } + sub_total += ttl ; + if (\$("#checkboxVat_"+tab+"_"+i).is(":checked")) { + vat_total += ttl*0.15 ; + } + } else if (!\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { + \$("#checkboxExcl_"+tab+"_"+i).prop('checked',true) ; + } + } + return [sub_total,vat_total] ; + } + + // function getNum(val) { + + // if (isNaN(val)) { + // return 0; + // } + // return val; + // } + + function calc_totals (row_cnt,tab) { + + var qty = \$("#inputQty_"+tab+"_"+row_cnt) ; + var usd = \$("#inputAmount_usd_"+tab+"_"+row_cnt) ; + var conv = \$("#inputAmount_ttl_"+tab+"_"+row_cnt) ; + var excl = \$("#checkboxExcl_"+tab+"_"+row_cnt) ; + var item = \$("#selectDescription_"+tab+"_"+row_cnt) ; + + if (!usd.val() && !conv.val() && !usd.val()) { + // console.log("skip calc_totals_workings") ; + if (!item.val()) { + excl.prop("checked",true) ; + } + return ; + } + + var vat = \$("#checkboxVat_"+tab+"_"+row_cnt) ; + + if (!item.val()) { + + excl.prop("checked",true) ; + vat.prop("checked",true) ; + qty.val("") ; + usd.val("") ; + conv.val(""); + if (tab == "workings_event") { + var rem = \$("#inputRemarks_"+tab+"_"+row_cnt) ; + var sup = \$("#inputSupplier_"+tab+"_"+row_cnt) ; + var ref = \$("#inputRef_nr_"+tab+"_"+row_cnt) ; + var op = \$("#selectOperator_"+tab+"_"+row_cnt) ; + rem.val("") ; + sup.val("") ; + ref.val("") ; + op.val("") ; + op.trigger("chosen:updated") ; + } + // } else if (excl.is(":checked") && item.val() && conv.val() == "0.00") { + } else if (excl.is(":checked")) { + excl.prop("checked",false) ; + } + + if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) ; } + + let roe = parseFloat(\$("#inputRoe").val()) ; + + let ttl = usd.val() * qty.val() * roe ; + + // // // conv.val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + conv.val(ttl.toFixed(2)) ; + + let sub_total = 0 ; let vat_total = 0 ; + + let nr_of_rows = 50 ; + if (tab == "costing_event") { + nr_of_rows = 30 ; + } + + [sub_total,vat_total] = add_up_totals (tab,nr_of_rows,roe,0) ; + + if (tab == "workings_event") { + // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + update_overall_totals(sub_total,vat_total,tab) ; + } else { + // // // \$("input[name='income']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; + update_overall_totals(sub_total,vat_total,tab) ; + // update_overall_totals_costings(sub_total,vat_total) ; + } + } + + function update_overall_totals (sub_total,vat_total,tab) { + + let profit_loss = parseFloat(\$("input[name='income']").val().replace(/,/g, '')) - parseFloat(\$("input[name='expenses']").val().replace(/,/g, '')) ; + + // // // \$("input[name='profit_loss']").val(profit_loss.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='sub_total_"+tab+"']").val(sub_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='vat_total_"+tab+"']").val(vat_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + + \$("input[name='profit_loss']").val(profit_loss.toFixed(2)) ; + \$("input[name='sub_total_"+tab+"']").val(sub_total.toFixed(2)) ; + \$("input[name='vat_total_"+tab+"']").val(vat_total.toFixed(2)) ; + \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toFixed(2)) ; + } + + function add_quote_expenses_row (row_nr,tab,options1,options2) { + + let tindex = $tindex ; + tindex = parseInt(tindex) ; + row_nr = parseInt(row_nr) ; + tindex = tindex - 10*(1+50-row_nr) ; + + let row = add_checkbox(row_nr,"excl_"+tab+"_"+row_nr,"checkboxExcl_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + + // row = row+""+add_select(row_nr,"description_"+tab+"_"+row_nr,"selectDescription_"+tab+"_"+row_nr,"Select Description "+row_nr,options1,tindex,2,90,'','') ; tindex++ ; + row = row+add_select(row_nr,"description_"+tab+"_"+row_nr,"selectDescription_"+tab+"_"+row_nr,"Select Description "+row_nr,options1,tindex,2,90,'','') ; tindex++ ; + if (tab == "workings_event") { + row = row+add_select(row_nr,"operator_workings_event_"+row_nr,"selectOperator_workings_event_"+row_nr,"Select Operator "+row_nr,options2,tindex,2,90,'','') ; tindex++ ; + row = row+add_input(row_nr,"remarks_workings_event_"+row_nr,"inputRemarks_workings_event_"+row_nr,"Remarks "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"supplier_workings_event_"+row_nr,"inputSupplier_workings_event_"+row_nr,"Supplier "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"ref_nr_workings_event_"+row_nr,"inputRef_nr_workings_event_"+row_nr,"Ref Nr "+row_nr,tindex,'',1) ; tindex++ ; + } + row = row+add_input(row_nr,"qty_"+tab+"_"+row_nr,"inputQty_"+tab+"_"+row_nr,"Qty "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"amount_usd_"+tab+"_"+row_nr,"inputAmount_usd_"+tab+"_"+row_nr,"Amount "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"amount_ttl_"+tab+"_"+row_nr,"inputAmount_ttl_"+tab+"_"+row_nr,"Total Amount "+row_nr,tindex,"readonly",1) ; tindex++ ; + row = row+add_checkbox(row_nr,"vat_"+tab+"_"+row_nr,"checkboxVat_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + return row ; + } + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub event_tabs_build_qt_left { + + my ($id,$tab,$ret,$demo_page) = @_ ; + + if ($tab == 1) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $title_ = ($demo_page) ? "Demo" : "Event" ; + + my $sec = '_customer_details' ; + + my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + $lcol = 3 ; $fcol = 1 ; $add_form_fields = '' ; + + # $add_form_fields .= qq~
    ~ if $is_schools_manager ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + + my $checked = ($db{$table}{$id}{quote_completed}) ? 'CHECKED' : '' ; + $preferred_title{quote_completed} = "$title_ Completed" ; + $add_form_fields .= &common_min_form_checkbox('quote_completed',$db{$table}{$id}{quote_completed},$checked) ; + + # my $checked = 'CHECKED' if $db{$table}{$id}{quote_accepted} ; + my $checked = ($db{$table}{$id}{quote_accepted}) ? 'CHECKED' : '' ; + $preferred_title{quote_accepted} = "$title_ Accepted" ; + $add_form_fields .= &common_min_form_checkbox('quote_accepted',$db{$table}{$id}{quote_accepted},$checked) ; + + my $checked = ($db{$table}{$id}{quote_rejected}) ? 'CHECKED' : '' ; + $preferred_title{quote_rejected} = "$title_ Rejected" ; + $add_form_fields .= &common_min_form_checkbox('quote_rejected',$db{$table}{$id}{quote_rejected},$checked) ; + + # my $checked = 'CHECKED' if $db{$table}{$id}{quote_pending} or $iaction eq 'add' ; + my $checked = ($db{$table}{$id}{quote_pending} || $iaction eq 'add') ? 'CHECKED' : '' ; + $preferred_title{quote_pending} = "$title_ Pending" ; + $add_form_fields .= &common_min_form_checkbox('quote_pending',$db{$table}{$id}{quote_pending},$checked) ; + + # my $checked = 'CHECKED' if $db{$table}{$id}{quote_cancelled} ; + my $checked = ($db{$table}{$id}{quote_cancelled}) ? 'CHECKED' : '' ; + $preferred_title{quote_cancelled} = "$title_ Cancelled" ; + $add_form_fields .= &common_min_form_checkbox('quote_cancelled',$db{$table}{$id}{quote_cancelled},$checked) ; + + # $add_form_fields .= qq~
    ~ if $is_schools_manager ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + + $fcol = 8 ; + $add_form_fields .= &common_min_form_input('contact_name',$db{$table}{$id}{contact_name},'') ; + $add_form_fields .= &common_min_form_input('address',$db{$table}{$id}{address},'') ; + $add_form_fields .= &common_min_form_input('email',$db{$table}{$id}{email},'') ; + $add_form_fields .= &common_min_form_input('tel',$db{$table}{$id}{tel},'') ; + $fcol = 5 ; + + $add_form_fields .= qq~
     
    ~ ; + + &event_tabs_content_box($sec_name,$sec_col); + + $trigger_jquery_raw .= qq~ + + if (!\$("#checkboxQuote_accepted").is(":checked") && !\$("#checkboxQuote_rejected").is(":checked") && !\$("#checkboxQuote_pending").is(":checked") && !\$("#checkboxQuote_cancelled").is(":checked") && !\$("#checkboxQuote_completed").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked","true") ; + } + + \$("#checkboxQuote_completed,#checkboxQuote_accepted,#checkboxQuote_rejected,#checkboxQuote_pending,#checkboxQuote_cancelled").click( function () { + + if (this.id != 'checkboxQuote_completed' && \$("#checkboxQuote_completed").is(":checked")) { + \$("#checkboxQuote_completed").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_accepted' && \$("#checkboxQuote_accepted").is(":checked")) { + \$("#checkboxQuote_accepted").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_rejected' && \$("#checkboxQuote_rejected").is(":checked")) { + \$("#checkboxQuote_rejected").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_pending' && \$("#checkboxQuote_pending").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_cancelled' && \$("#checkboxQuote_cancelled").is(":checked")) { + \$("#checkboxQuote_cancelled").prop("checked",false) ; + } + + if (this.id == 'checkboxQuote_completed' && !\$("#checkboxQuote_accepted").is(":checked")) { + \$("#checkboxQuote_accepted").prop("checked",true) ; + } + + if (!\$("#checkboxQuote_accepted").is(":checked") && !\$("#checkboxQuote_rejected").is(":checked") && !\$("#checkboxQuote_pending").is(":checked") && !\$("#checkboxQuote_cancelled").is(":checked") && !\$("#checkboxQuote_completed").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked","true") ; + } + + }) ; + + ~ ; + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + + if ($tab == 2) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_event_details' ; + + my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + # my $op_change = qq~~ ; + + # for (1 .. $nr_of_system_names_and_clubs) { + # $op_change .= qq~,#selectOperator_id_calibration_$_~ ; + # } + # $op_change = substr($op_change,1) ; + + $lcol = 2 ; $fcol = 3 ; + + $add_form_fields = '' ; + + $add_form_fields .= qq~ +
    +
    ~ ; + + # $fcol = 6 ; + $preferred_title{ref} = 'Event Name' ; + $preferred_title{date_from} = 'Event Date/Time From' ; + $preferred_title{date_to} = 'Event Date/Time To' ; + + my $current_day_of_week = Day_of_Week($now_year,$now_mm,$now_dd) ; + + my $delta_days = 6 - $current_day_of_week ; + $delta_days = 7 unless $delta_days ; + $delta_days = 6 if $delta_days < 0 ; + + my ($def_year,$def_mon,$def_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,$delta_days) ; + $def_mon = sprintf("%02d",$def_mon) ; + $def_day = sprintf("%02d",$def_day) ; + + $db{$table}{$id}{date_from} = "$def_year-$def_mon-$def_day 08:00:00" unless $db{$table}{$id}{date_from} ; + $db{$table}{$id}{date_to} = "$def_year-$def_mon-$def_day 17:00:00" unless $db{$table}{$id}{date_to} ; + + my $hide_select_1 = '' ; my $readonly_select = '' ; my $sport_type_ids_readonly = '' ; my $organisation_ids_readonly = '' ; my $linear_id_readonly = '' ; my $readonlyform = 0 ; # my $hide_select_2 = qq~~ ; + + my $quote_accepted = $db{$table}{$id}{quote_accepted} ; + my $quote_rejected = $db{$table}{$id}{quote_rejected} ; + my $quote_cancelled = $db{$table}{$id}{quote_cancelled} ; + my $quote_completed = $db{$table}{$id}{quote_completed} ; +# $db{$table}{$event_id}{quote_completed} + # if (($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 4) { + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { + + for (1 .. 20) { + $readonly{"time_from_$_"} = "READONLY"; + $readonly{"time_to_$_"} = "READONLY"; + } + + $readonlyform = 1 ; + + $readonly{ref} = "READONLY" ; $readonly{date_from} = "READONLY" ; $readonly{date_to} = "READONLY" ; $readonly{qty} = "READONLY" ; $readonly{city_id} = "READONLY" ; + $add_form_fields .= &common_min_form_input('ref',$db{$table}{$id}{ref},'') ; + $add_form_fields .= &common_min_form_input('date_from',$db{$table}{$id}{date_from}) ; + $add_form_fields .= &common_min_form_input('date_to',$db{$table}{$id}{date_to}) ; + $hide_select_1 = qq~~ ; + + $readonly{sport_type_ids_readonly} = "READONLY" ; $readonly{region_id_readonly} = "READONLY" ; $readonly{city_id_readonly} = "READONLY" ; $readonly{organisation_ids_readonly} = "READONLY" ; $readonly{linear_id_readonly} = "READONLY" ; + + $preferred_title{sport_type_ids_readonly} = "Sport Type(s)" ; $preferred_title{region_id_readonly} = "Regions" ; $preferred_title{city_id_readonly} = "City" ; $preferred_title{organisation_ids_readonly} = "Venue(s)" ; $preferred_title{linear_id_readonly} = "Linear" ; + + foreach (split(",",$db{$table}{$id}{sport_type_ids})) { + $sport_type_ids_readonly .= qq~$db{sport_types}{$_}{name},~ ; + } + chop $sport_type_ids_readonly if $sport_type_ids_readonly ; + + foreach (split(",",$db{$table}{$id}{organisation_ids})) { + $organisation_ids_readonly .= qq~$db{organisations}{$_}{name},~ ; + } + chop $organisation_ids_readonly if $organisation_ids_readonly ; + + local %linear_vals = () ; $linear_vals{1} = "Yes" ; $linear_vals{2} = "No" ; $linear_vals{3} = "Delayed" ; + + # my $cities_readoly = qq~~ ; + # foreach my $city_id (split(",",$db{$table}{$id}{city_id})) { + # $cities_readoly .= qq~$db{cities}{$city_id}{city}, ~ ; + # } + # chop $cities_readoly if $cities_readoly ; chop $cities_readoly if $cities_readoly ; + + my $cities_readoly = join (", ", map { "$db{cities}{$city_id}{name}" } split(/\,/,$db{$table}{$id}{city_id})) ; + + # $readonly_select .= &common_min_form_input('sport_type_ids_readonly',$db{sport_types}{$db{$table}{$id}{sport_type_ids}}{name},'') ; + $readonly_select .= &common_min_form_input('sport_type_ids_readonly',$sport_type_ids_readonly ,'') ; + $readonly_select .= &common_min_form_input('region_id_readonly',$db{regions}{$db{$table}{$id}{region_id}}{name},'') ; + $readonly_select .= &common_min_form_input('city_id_readonly',$cities_readoly,'') ; + # $readonly_select .= &common_min_form_input('organisation_ids_readonly',$db{organisations}{$db{$table}{$id}{organisation_ids}}{name},'') ; + $readonly_select .= &common_min_form_input('organisation_ids_readonly',$organisation_ids_readonly,'') ; + $readonly_select .= &common_min_form_input('linear_id_readonly',$linear_vals{$db{$table}{$id}{linear_id}},'') ; + } else { + $add_form_fields .= &common_min_form_input('ref',$db{$table}{$id}{ref},'') ; + $readonly{date_from} = "READONLY" ; $readonly{date_to} = "READONLY" ; + $add_form_fields .= &common_min_form_datetimepicker('date_from',$db{$table}{$id}{date_from}) ; + $add_form_fields .= &common_min_form_datetimepicker('date_to',$db{$table}{$id}{date_to}) ; + + $dlg{sport_type_ids} = qq~   $db{$table}{$id}{sports_type}~ ; + $dlg{sport_type_ids} .= qq~
    ~ ; + $dlg{city_id} .= qq~   $db{$table}{$id}{city}~ ; + $dlg{city_id} .= qq~
    ~ ; + $dlg{organisation_ids} .= qq~   $db{$table}{$id}{location}~ ; + $dlg{organisation_ids} .= qq~
    ~ ; + $dlg{region_id} .= qq~   $db{$table}{$id}{location}~ ; + $dlg{region_id} .= qq~
    ~ ; + } + + # $fcol = 1 ; + $preferred_title{qty} = 'Actual Days' ; $dont_end_row{qty} = 1 ; + + # if (($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 4) { $readonly{qty} = "READONLY" ; } + # if (($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) { $readonly{qty} = "READONLY" ; } + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { $readonly{qty} = "READONLY" ; } + + my @times_from = split(/\;/,";$db{$table}{$id}{times_from}") ; + my @times_to = split(/\;/,$db{$table}{$id}{times_to}) ; + + my @default = () ; my $saved_time_from = qq~~ ; my $saved_time_to = qq~~ ; + + my $year = ($db{$table}{$id}{date_from}) ? substr($db{$table}{$id}{date_from},0,4) : $now_year ; + my $month = ($db{$table}{$id}{date_from}) ? substr($db{$table}{$id}{date_from},5,2) : $now_mm ; + my $day = ($db{$table}{$id}{date_from}) ? substr($db{$table}{$id}{date_from},8,2) : $now_dd ; + + $fcol = 1 ; + + $radio_opts{event_length} = "Full Day+Half Day" ; + + # my $cnt_radio_opts = 0 ; + + # foreach (split(/\+/,$radio_opts{event_length})) { + # $cnt_radio_opts++ ; + # } + + my @timepicker_ids = () ; my @day_ids = () ; + + my %default_days_selected = () ; our %default_active_event_dates = () ; + + # our $final_day_active = 0 ; local $cnt_days = 0 ; + + # foreach (@defaut_days_active) { + # $cnt_days++ ; + # $final_day_active = $cnt_days if $_ ; + # } + + my ($year1,$month1,$day1) = split(/\-/,substr($db{$table}{$id}{date_from},0,10)); + my ($year2,$month2,$day2) = split(/\-/,substr($db{$table}{$id}{date_to},0,10)); + + our $final_day = Delta_Days($year1,$month1,$day1,$year2,$month2,$day2) + 1 ; + + our @defaut_days_active = split(/\;/,$db{$table}{$id}{days_active}) ; + + my $event_without_saved_defaults = 0 ; + + if (!$db{$table}{$id}{days_active}) { + $event_without_saved_defaults = 1 ; + # my $def_qty = ($db{$table}{$id}{qty}) ? $db{$table}{$id}{qty} : 1 ; + + for (1 .. $final_day) { + # for (1 .. $def_qty) { + $db{$table}{$id}{days_active} .= "1;" ; + } + # $trigger_jquery .= qq~\$("#selectDay_1_chosen").css("width","100%" );~ if $def_qty== 1 ; + } + my @default_event_length = split(/\;/,$db{$table}{$id}{event_length}) ; my %calc_default_event_length = () ; + + my @days_active = split(/\;/,$db{$table}{$id}{days_active}) ; + + my $cnt = 0 ; + # my $final_day = 0 ; + my $no_event_days_cnt = 0 ; + + my $hide_rows_1 = (substr($db{$table}{$id}{date_from},0,10) eq substr($db{$table}{$id}{date_to},0,10)) ? "style='display:none;'" : "" ; + my $hide_rows_2 = ($final_day <= 10) ? "style='display:none;'" : "" ; + + my %time_label_header_row = () ; + + $time_label_header_row{1} = qq~
    ~ ; + $time_label_header_row{2} = qq~
    ~ ; + + # foreach (@days_active) { + # $cnt++ ; + # $final_day = $cnt if $_ ; + # } + + # $final_day = 1 unless $final_day ; + # $final_day = $db{$table}{$id}{qty} if $db{$table}{$id}{qty} && !$days_active[$db{$table}{$id}{qty}-1] ; + + my $def_nr_of_full_days = 0 ; my $def_nr_of_half_days = 0 ; + + for (1 .. 20) { + + my $cnt_row = ($_ <= 10) ? 1 : 2 ; + + $default_days_selected{blank}{$_} = "SELECTED" unless $days_active[$_ - 1] ; + $default_days_selected{1}{$_} = "SELECTED" if $days_active[$_ - 1] ; + + push @timepicker_ids,"#timepickerTime_from_$_" ; + push @timepicker_ids,"#timepickerTime_to_$_" ; + push @day_ids,"#day_$_" ; + + my ($new_year,$new_month,$new_day) = ($_ > 1) ? Add_Delta_Days($year,$month,$day,$_-1) : ($year,$month,$day) ; + $new_day = sprintf("%02s",$new_day) ; + $new_month = sprintf("%02s",$new_month) ; + + # $default_active_event_dates{$_} = "$new_year-$new_month-$new_day" if $days_active[$_ - 1] ; + $default_active_event_dates{$_} = "$new_year-$new_month-$new_day" if $_ <= $final_day ; + + my $field = "time_from_$_" ; + $default[$_ - 1] = $times_from[$_ - 1] ; + $default[$_ - 1] = substr($db{$table}{$id}{date_from},11) if $db{$table}{$id}{date_from} && (!$times_from[$_ - 1] || $_ == 1) ; + my $default1 = $default[$_ - 1] ; + + $custom_style{$field} = ((!$event_without_saved_defaults && !$defaut_days_active[$_ - 1]) || $_ == 1 || ($_ > $final_day)) ? qq~display:none;~ : '' ; + # $days_time_row .= ($glod_user_level > 2) ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} ne "READONLY" || ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~ ; + $days_time_row{$cnt_row} .= ($readonly{qty} ne "READONLY") ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} eq "READONLY" && ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~ ; + + $trigger_jquery_raw .= qq~\$("#timepickerTime_from_1").css("display","none");~ ; + + # $default_time_from .= qq~"$_":"$default[$_ - 1]",~ ; + $saved_time_from .= qq~"$_":"$times_from[$_ - 1]",~ if $times_from[$_ - 1] ; + # $final_day = $_ if $times_from[$_ - 1] ; + $field = "time_to_$_" ; + + + $custom_style{$field} = ((!$event_without_saved_defaults && !$defaut_days_active[$_ - 1]) || $_ >= $final_day) ? qq~display:none;~ : '' ; + $default[$_ - 1] = $times_to[$_ - 1] ; + $default[$_ - 1] = substr($db{$table}{$id}{date_to},11) if $db{$table}{$id}{date_to} && (!$times_to[$_ - 1] || $_ == 6) ; + + # $days_time_row_2 .= ($readonly{qty} ne "READONLY") ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($final_day >= $_ && !$custom_style{$field}) ? &common_min_form_input_col($field,$default[$_ - 1],'',0) : qq~
    ~ ; + + # $days_time_row_2 .= ($glod_user_level > 2) ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} ne "READONLY" || ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~ ; + $days_time_row_2{$cnt_row} .= ($readonly{qty} ne "READONLY") ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} eq "READONLY" && ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~ ; + + # $trigger_jquery_raw .= qq~\$("#timepickerTime_from_$_").css("display","none");~ if $db{$table}{$id}{qty} < $_ ; + + # if (!$db{$table}{$id}{days_active} && ($db{$table}{$id}{qty} != 1 || !$db{$table}{$id}{event_length}) && $db{$table}{$id}{qty} >= $_) { + # if (!$db{$table}{$id}{days_active} || ($days_active[$_ - 1] && !$default_event_length[$_ - 1])) { + + # $trigger_jquery .= qq~ + # \$("#radio_1_1").prop('checked',true) ; + # ~ if $_ == 1 ; + + if ($default_event_length[$_ - 1] eq '1' && $days_active[$_ - 1]) { + $def_nr_of_full_days++ ; + } elsif ($default_event_length[$_ - 1] eq '2' && $days_active[$_ - 1]) { + $def_nr_of_half_days++ ; + } + + if (!$db{$table}{$id}{event_length}) { + + my ($h1,$m1,$s1) = ($_ == 1 || !$times_from[$_ - 1]) ? split(/\:/,substr($db{$table}{$id}{date_from},11)) : split(/\:/,$times_from[$_ - 1]) ; + my ($h2,$m2,$s2) = split(/\:/,substr($db{$table}{$id}{date_to},11)) ; + my $time_diff = 3600*($h2-$h1) + 60*($m2-$m1) + ($s2-$s1) ; + + if ($time_diff >= 18000) { + $calc_default_event_length{$_} = 1 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_1").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_full_days++ if $default_event_length[$_ - 1] ; + } elsif ($time_diff >= 0 && $time_diff < 18000) { + $calc_default_event_length{$_} = 2 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_2").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_half_days++ if $default_event_length[$_ - 1] ; + } + + $trigger_jquery .= qq~ + \$("#day_$_").val("1") ; + \$("#day_$_").trigger("chosen:updated") ; + ~ if $_ <= $final_day && $readonly{qty} ne "READONLY" ; + + } elsif ($_ <= $final_day) { + + # $days_active[$_ - 1 + + # my ($h1,$m1,$s1) = split(/\:/,$times_from[$_ - 1]) ; + # my ($h2,$m2,$s2) = split(/\:/,$times_to[$_ - 1]) ; + # my $time_diff = 3600*($h2-$h1) + 3600*($m2-$m1) + ($s2-$s1) ; + if ($default_event_length[$_ - 1]) { + if ($default_event_length[$_-1] eq "1") { + $trigger_jquery .= qq~ + // \$("input[name='selected_$_\_event_length']").val("1") ; + \$("#radio_$_\_1").prop('checked',true) ; + ~ ; + # $def_nr_of_full_days++ ; + } elsif ($default_event_length[$_-1] eq "2") { + $trigger_jquery .= qq~ + // \$("input[name='selected_$_\_event_length']").val("2") ; + \$("#radio_$_\_2").prop('checked',true) ; + ~ ; + # $def_nr_of_half_days++ ; + } + } else { + my ($h1,$m1,$s1) = split(/\:/,substr($db{$table}{$id}{date_from},11)) ; + my ($h2,$m2,$s2) = split(/\:/,substr($db{$table}{$id}{date_to},11)) ; + my $time_diff = 3600*($h2-$h1) + 60*($m2-$m1) + ($s2-$s1) ; + + if ($time_diff >= 18000) { + $calc_default_event_length{$_} = 1 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_1").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_full_days++ ; + } elsif ($time_diff >= 0 && $time_diff < 18000) { + $calc_default_event_length{$_} = 2 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_2").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_half_days++ ; + } + } + } + + if ((!$days_active[$_ - 1] && $_ > $final_day) || ($db{$table}{$id}{days_active} == ";;;;;") || (!$days_active[$_ - 1] && $_ <= $final_day)) { + $trigger_jquery .= qq~\$("#radio_$_\_1").css("display","none") ; ~ ; + $trigger_jquery .= qq~\$("#radio_$_\_2").css("display","none") ; ~ ; + } + + # $default_time_to .= qq~"$_":"$default[$_ - 1]",~ ; + $saved_time_to .= qq~"$_":"$times_to[$_ - 1]",~ if $times_to[$_ - 1] ; + + $field = "day_$_" ; + $custom_style{$field} = ($final_day < $_ || $final_day == 1) ? qq~display:none;~ : '' ; + + if ($readonly{qty} ne "READONLY") { + # if ($glod_user_level > 2) { + + $trigger_jquery .= qq~\$("#day_$_\_chosen").css("display","none");~ if $_ > $final_day || $final_day == 1 ; + + # $time_label_header_row .= qq~
    ~ ; + + $time_label_header_row{$cnt_row} .= qq~ +
    + +
    + ~ ; + + # $trigger_jquery .= qq~ console.log("Day $_ : ;$default_days_selected{blank}{$_};$default_days_selected{1}{$_}; "+\$("#day_$_").val()) ; ~ ; + + } else { + $time_label_header_row{$cnt_row} .= (!$default_days_selected{1}{$_}) ? qq~ +
    + ~ : qq~ +
    +
    + ~ ; + } + } + + $def_nr_of_full_days = 1 if !$def_nr_of_full_days && !$def_nr_of_half_days ; + + $trigger_jquery_raw .= qq~\$("#timepickerTime_to_$final_day").css("display","none");~ if $final_day ; + + my $day_ids_string = join(",",@day_ids) ; + + # chop $default_time_from if $default_time_from ; chop $default_time_to if $default_time_to ; + + $trigger_jquery_raw .= qq~ + + // let [nr_days["full"],nr_days["half"]] = count_nr_of_full_day_and_half_days() ; + + let nr_days = {} ; let prev_nr_days = {} ; + + nr_days["full"] = "$def_nr_of_full_days" ; + nr_days["half"] = "$def_nr_of_half_days" ; + + nr_days["full"] = parseInt(nr_days["full"]) ; + nr_days["half"] = parseInt(nr_days["half"]) ; + + prev_nr_days["full"] = nr_days["full"] ; prev_nr_days["half"] = nr_days["half"] ; + const default_cost_item_rates = {$default_cost_item_rates_javascript} ; + // const default_full_day_cost_item_rates = {$default_full_day_cost_item_rates_javascript} ; + // const default_half_day_cost_item_rates = {$default_half_day_cost_item_rates_javascript} ; + + let ij = 0 ; let orig_selected_system_names = {} ; + // const get_event_cost_id = {"63":"24","286":"25","285":"10"} ; // TESTING + const get_event_cost_id = {$get_event_cost_id_from_system_id_javascript} ; // TESTING + let cnt_systems_per_cost_item = {} ; + + let changed_radio_cnt = 0 ; let system_with_cost_item_rates_selected = 0 ; + + let saved_time_from = {$saved_time_from} ; + let saved_time_to = {$saved_time_to} ; + + // while (true) { + // ij++ ; + // if (!\$("#system_name_row_"+ij).html()) { + // break ; + // } + // orig_selected_system_names[ij] = (\$("#selectSystem_name_"+ij).val()) ? \$("#selectSystem_name_"+ij).val() : "" ; + // if (default_cost_item_rates[get_event_cost_id[\$("#selectSystem_name_"+ij).val()]]) { + // system_with_cost_item_rates_selected = 1 ; + // } + + // } + + cnt_selected_systems_per_cost_item() ; + + \$("$day_ids_string").change(function (e) { + + // console.log("changed day") ; + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + + const id = this.id ; + let col_nr = get_row_nr(id) ; + // const secondLastIndex = beforeLastUnderscore.lastIndexOf('_'); + // const changedInput = beforeLastUnderscore.substring(secondLastIndex + 1); + + let nr_days = \$("input[name='qty']").val() ; + + let nr_of_active_days = calc_nr_of_active_days() ; + + let datesBetween ; + + let date_counter = 0 ; let dates_map = {} ; + + // if ((\$\(this).val() && (nr_of_active_days == 7 || nr_of_active_days == 11)) || (!\$\(this).val() && (nr_of_active_days == 6 || nr_of_active_days == 10))) { + datesBetween = getDatesBetween(\$("input[name='date_from']").val(),\$("input[name='date_to']").val(),0) ; + for (const date of datesBetween) { + date_counter++ ; + dates_map[date_counter] = date ; + // console.log("date_counter : "+date_counter+" , dates_map[date_counter] : "+dates_map[date_counter]) ; + } + // } + + let all_added_dropdowns = "#1" ; + let all_added_dropdowns_chosen = "#1" ; + + // let select_chosen_ids_1 = '#3' ; + // let select_chosen_ids_2 = '#4' ; + + // let def_val = 0 ; + + // if (\$("#day_"+b).val()) { + + // def_val = \$("#selectCustom_operator_"+a+"_"+b).val() ; + // add_operator_dropdown("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,0) ; + // select_chosen_ids_1 = select_chosen_ids_1+",#selectCustom_operator_"+a+"_"+b ; + // select_chosen_ids_2 = select_chosen_ids_2+",#selectCustom_operator_"+a+"_"+b+"_chosen" ; + // names_to_display = names_to_display + ",#day_"+b+"_name_"+a+"_extra_1" ; + // } + + // delete_operator_dropdown ("day_"+b+"_name","day_"+a+"_"+b) ; + // delete_operator_dropdown ("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_2") ; + + // if (!\$("#selectCustom_operator_"+a+"_"+b).val() && def_val) { + // \$("#selectCustom_operator_"+a+"_"+b).val(def_val) ; + // \$("#selectCustom_operator_"+a+"_"+b).trigger("chosen:updated") ; + // } + // } + + let def_val = 0 ; + + let hide_this_1 = '' ; + let hide_this_2 = '' ; + + if (!\$\(this).val()) { + + \$("#timepickerTime_from_"+col_nr+"").css("display","none") ; + \$("#timepickerTime_to_"+col_nr+"").css("display","none") ; + \$("#radio_"+col_nr+"_1").css("display","none") ; + \$("#radio_"+col_nr+"_2").css("display","none") ; + nr_days=nr_days-1; + if (nr_of_active_days < 6) { + \$("#day_"+col_nr+"_name").css("display","none") ; + \$("#day_"+col_nr+"_name").removeClass('col-md-1').addClass('col-md-0') ; + } + for (let q=1;q<=15;q++) { + if (\$("input[name='clicked_button_"+q+"']").val()) { + + if (nr_of_active_days <= 6 && q > 1 && !\$("#extra_heading_"+q).is(":hidden")) { + \$("#extra_heading_"+q).hide() ; + console.log("Hide Heading") ; + } else if (nr_of_active_days > 6 && q > 1 && \$("#extra_heading_"+q).length && \$("#extra_heading_"+q).is(":hidden") && \$("input[name='clicked_button_"+q+"']").val()) { + \$("#extra_heading_"+q).show() ; + console.log("Display Heading") ; + } else if (nr_of_active_days > 6 && q > 1 && !\$("#extra_heading_"+q).length && \$("input[name='clicked_button_"+q+"']").val()) { + console.log("Add Heading") ; + \$("#system_name_row_"+q).before("
    ") ; + + } + + if (nr_of_active_days < 6) { + \$("#day_"+q+"_"+col_nr).css("display","none") ; + \$("#day_"+q+"_"+col_nr).removeClass('col-md-1').addClass('col-md-0') ; + } else if (nr_of_active_days == 6) { + + if (q > 1 && !\$("#extra_heading_"+q).is(":hidden")) { + \$("#extra_heading_"+q).hide() ; + } + + for (let col=1;col<=20;col++) { + if (\$("#day_"+col).val() && !\$("#day_"+q+"_"+col).html()) { + add_operator_dropdown ("day_"+col+"_name","day_"+q+"_"+col,"custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,0) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (!\$("#day_"+col).val() && dates_map[col] && !\$("#day_"+q+"_"+col).html()) { + add_operator_dropdown ("day_"+col+"_name","day_"+q+"_"+col,"custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,1) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (\$("#day_"+col).val() && \$("#day_"+q+"_"+col).html() && \$("#day_"+q+"_"+col).is(":hidden")) { + display_non_empty_operator_dropdown("day_"+col+"_name","day_"+q+"_"+col) ; + } + delete_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1") ; + // console.log("hide_operator_dropdown : ) ; + } + \$("#system_name_row_"+q+"_extra_1").hide() ; + \$("#day_names_"+q+"_extra_1").hide() ; + } else if (nr_of_active_days > 6 && nr_of_active_days < 10) { + // hide_non_empty_operator_dropdown("day_"+col_nr+"_name","day_"+q+"_"+col_nr) ; + hide_non_empty_operator_dropdown("day_"+col_nr+"_name_"+q+"_extra_1","day_"+q+"_"+col_nr+"_extra_1") ; + } else if (nr_of_active_days == 10) { + for (let col=1;col<=20;col++) { + if (\$("#day_"+col).val() && dates_map[col]) { + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,0) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (!\$("#day_"+col).val() && dates_map[col]) { + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,1) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (\$("#day_"+col).val() && \$("#day_"+q+"_"+col+"_extra_1").html() && \$("#day_"+q+"_"+col+"_extra_1").is(":hidden")) { + display_non_empty_operator_dropdown("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1") ; + } + delete_operator_dropdown ("day_"+col+"_name_"+q+"_extra_2","day_"+q+"_"+col+"_extra_2") ; + } + hide_non_empty_operator_dropdown("day_"+col_nr+"_name_"+q+"_extra_1","day_"+q+"_"+col_nr+"_extra_1") ; + \$("#system_name_row_"+q+"_extra_1").show() ; + \$("#day_names_"+q+"_extra_1").show() ; + \$("#system_name_row_"+q+"_extra_2").hide() ; + \$("#day_names_"+q+"_extra_2").hide() ; + } else if (nr_of_active_days > 10) { + + let nr_dates_used = 0 ; + + console.log("de select : #nr_of_active_days : "+nr_of_active_days) ; + + for (let col=1;col<=20;col++) { + + if (nr_dates_used == 10 && !dates_map[col]) { + break ; + } + if (\$("#day_"+col).val() && dates_map[col] && nr_dates_used < 10) { + nr_dates_used++ ; + if (\$("#day_"+q+"_"+col+"_extra_1").is(":hidden")) { + def_val = \$("#selectCustom_operator_"+q+"_"+col).val() ; + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,0) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + delete_operator_dropdown("day_"+col+"_name_"+q+"_extra_2","day_"+q+"_"+col+"_extra_2",0) ; + if (!\$("#selectCustom_operator_"+q+"_"+col).val() && def_val) { + \$("#selectCustom_operator_"+q+"_"+col).val(def_val) ; + \$("#selectCustom_operator_"+q+"_"+col).trigger("chosen:updated") ; + } + } + } else if (!\$("#day_"+col).val() && dates_map[col]) { + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,1) ; + if (!\$("#day_"+q+"_"+col+"_extra_1").is(":hidden")) { + hide_this_1 = "day_"+col+"_name_"+q+"_extra_1" ; + hide_this_2 = "day_"+q+"_"+col+"_extra_1" ; + } + if (!\$("#day_"+q+"_"+col+"_extra_2").is(":hidden") && col > 10) { + hide_this_1 = "day_"+col+"_name_"+q+"_extra_2" ; + hide_this_2 = "day_"+q+"_"+col+"_extra_2" ; + } + } + } + } + } + if (hide_this_1) { + console.log("hide this : "+hide_this_1+" , "+hide_this_2) ; + hide_non_empty_operator_dropdown (hide_this_1,hide_this_2) ; + } + } + } else { + if (col_nr != "1") { + \$("#timepickerTime_from_"+col_nr).css("display","") ; + } + \$("#timepickerTime_to_"+col_nr).css("display","") ; + \$("#radio_"+col_nr+"_1").css("display","") ; + \$("#radio_"+col_nr+"_2").css("display","") ; + nr_days=parseInt(nr_days)+1; + + for (let q=1;q<=15;q++) { + if (\$("input[name='clicked_button_"+q+"']").val()) { + \$("#day_"+q+"_"+col_nr).css("display","") ; + if (\$("#selectCustom_operator_"+q+"_"+col_nr+"_chosen").css("width") !== "100%"){ + \$("#selectCustom_operator_"+q+"_"+col_nr+"_chosen").css("width","100%") ; + } + } + } + + if (nr_of_active_days <= 6 && \$("#clicked_any_button").text() && \$("#day_"+col_nr+"_name").css("display") === "none") { + \$("#day_"+col_nr+"_name").show() ; + \$("#day_"+col_nr+"_name").removeClass('col-md-0').addClass('col-md-1') ; + } + for (let q=1;q<=15;q++) { + + if (\$("input[name='clicked_button_"+q+"']").val()) { + + if (nr_of_active_days <= 6 && q > 1 && !\$("#extra_heading_"+q).is(":hidden")) { + \$("#extra_heading_"+q).hide() ; + console.log("Hide Heading") ; + } else if (nr_of_active_days > 6 && q > 1 && \$("#extra_heading_"+q).length && \$("#extra_heading_"+q).is(":hidden") && \$("input[name='clicked_button_"+q+"']").val()) { + \$("#extra_heading_"+q).show() ; + console.log("Display Heading") ; + } else if (nr_of_active_days > 6 && q > 1 && !\$("#extra_heading_"+q).length && \$("input[name='clicked_button_"+q+"']").val()) { + console.log("Add Heading") ; + \$("#system_name_row_"+q).before("
    ") ; + + } + + if (q > 1 && \$("#extra_heading_"+q).is(":hidden")) { + \$("#extra_heading_"+q).show() ; + } + + if (nr_of_active_days <= 6) { + \$("#day_"+q+"_"+col_nr).show() ; + \$("#day_"+q+"_"+col_nr).removeClass('col-md-0').addClass('col-md-1') ; + console.log("#day_"+q+"_"+col_nr) ; + } else if (nr_of_active_days == 7) { + for (let col=1;col<=20;col++) { + def_val = \$("#selectCustom_operator_"+q+"_"+col).val() ; + if (\$("#day_"+col).val()) { + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,0) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (!\$("#day_"+col).val() && dates_map[col]) { + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,1) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (\$("#day_"+col).val() && \$("#day_"+q+"_"+col).html() && \$("#day_"+q+"_"+col).is(":hidden")) { + display_non_empty_operator_dropdown("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1") ; + } + delete_operator_dropdown ("day_"+col+"_name","day_"+q+"_"+col) ; + if (!\$("#selectCustom_operator_"+q+"_"+col).val() && def_val) { + \$("#selectCustom_operator_"+q+"_"+col).val(def_val) ; + \$("#selectCustom_operator_"+q+"_"+col).trigger("chosen:updated") ; + } + } + \$("#day_"+col_nr+"_name").hide() ; + \$("#system_name_row_"+q+"_extra_1").show() ; + \$("#day_names_"+q+"_extra_1").show() ; + } else if (nr_of_active_days > 7 && nr_of_active_days <= 10) { + display_non_empty_operator_dropdown("day_"+col_nr+"_name_"+q+"_extra_1","day_"+q+"_"+col_nr+"_extra_1") ; + hide_non_empty_operator_dropdown("day_"+col_nr+"_name","day_"+q+"_"+col_nr) ; + } else if (nr_of_active_days >= 11) { + let date_used = {} ; let date_used_hidden = {} ; let nr_dates_used = 0 ; + for (let col=1;col<=20;col++) { + + if (nr_dates_used == 10 && !dates_map[col]) { + break ; + } + if (\$("#day_"+col).val() && dates_map[col] && nr_dates_used < 10) { + date_used[col] = 1 ; + nr_dates_used++ ; + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,0) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + } else if (!\$("#day_"+col).val() && dates_map[col]) { + date_used_hidden[col] = 1 ; + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q,1) ; + } + } + + for (let col=11;col<=20;col++) { + // if (col > 10) { + if (\$("#day_"+col).val() && !date_used[col]) { + def_val = \$("#selectCustom_operator_"+q+"_"+col).val() ; + add_operator_dropdown ("day_"+col+"_name_"+q+"_extra_2","day_"+q+"_"+col+"_extra_2","custom_operator_"+q+"_"+col,"selectCustom_operator_"+q+"_"+col,dates_map[col],q) ; + all_added_dropdowns = all_added_dropdowns + ",#selectCustom_operator_"+q+"_"+col ; + all_added_dropdowns_chosen = all_added_dropdowns_chosen + ",#selectCustom_operator_"+q+"_"+col+"_chosen" ; + delete_operator_dropdown("day_"+col+"_name_"+q+"_extra_1","day_"+q+"_"+col+"_extra_1",0) ; + if (!\$("#selectCustom_operator_"+q+"_"+col).val() && def_val) { + \$("#selectCustom_operator_"+q+"_"+col).val(def_val) ; + \$("#selectCustom_operator_"+q+"_"+col).trigger("chosen:updated") ; + } + } else { + delete_operator_dropdown ("day_"+col+"_name_"+q+"_extra_2","day_"+q+"_"+col+"_extra_2",0) ; + } + } + \$("#system_name_row_"+q+"_extra_2").show() ; + \$("#day_names_"+q+"_extra_2").show() ; + \$("#system_name_row_"+q+"_extra_1").show() ; + \$("#day_names_"+q+"_extra_1").show() ; + } + } + } + } + + // hide_non_empty_operator_dropdown (hide_this_1,hide_this_2) ; + + \$(all_added_dropdowns).chosen({allow_single_deselect:true}) ; + \$(all_added_dropdowns_chosen).css("width","100%") ; + + // \$(select_chosen_ids_1).chosen({allow_single_deselect:true}) ; + // \$(select_chosen_ids_2).css("width","100%") ; + \$("input[name='qty']").val(nr_days) ; + }) ; + ~ if $readonly{qty} ne "READONLY" ; + + my $timepicker_ids_string = join(",",@timepicker_ids) ; + + # $trigger_jquery_raw .= qq~ \$("$timepicker_ids_string").datetimepicker({language:'pt-BR',pickDate:false});~ ; + + if ($readonly{qty} ne "READONLY") { + + $trigger_jquery_raw .= qq~ + + function set_full_half_day (beforeUnderscore,afterUnderscore) { + + let start_time = \$("input[name='time_from_"+afterUnderscore+"']").val() ; + let end_time = \$("input[name='time_to_"+afterUnderscore+"']").val() ; + + let seconds1 = timeStringToSeconds(start_time) ; + let seconds2 = timeStringToSeconds(end_time) ; + + let diffSeconds = seconds2 - seconds1 ; + + // let nr_days = \$("#inputQty").val() ; + + let changed_a_full_half_day_toggle = 0 ; + if (diffSeconds >= 18000) { + if (\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + nr_days["half"]-- ; + } + if (!\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + \$("#radio_"+afterUnderscore+"_1").prop('checked',true) ; + changed_a_full_half_day_toggle = 1 ; + nr_days["full"]++ ; + } + } else if (diffSeconds >= 0 && diffSeconds < 18000) { + if (\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + nr_days["full"]-- ; + } + if (!\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + \$("#radio_"+afterUnderscore+"_2").prop('checked',true) ; + changed_a_full_half_day_toggle = 1 ; + nr_days["half"]++ ; + } + } else { + // nr_days = parseInt(nr_days) ; + // nr_days-- ; + // \$("#inputQty").val(nr_days) ; + + if (\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + \$("#radio_"+afterUnderscore+"_1").prop('checked',false) ; + changed_a_full_half_day_toggle = 1 ; + nr_days["full"]-- ; + } + if (\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + \$("#radio_"+afterUnderscore+"_2").prop('checked',false) ; + changed_a_full_half_day_toggle = 1 ; + nr_days["half"]-- ; + } + if (beforeUnderscore == 'timepickerTime_from') { + \$("input[name='time_from_"+afterUnderscore+"']").val(end_time) ; + } else if (beforeUnderscore == 'timepickerTime_to') { + \$("input[name='time_to_"+afterUnderscore+"']").val(start_time) ; + } + } + if (changed_a_full_half_day_toggle == 1) { + changed_radio_cnt++ ; + } + + } + + \$("$timepicker_ids_string").datetimepicker({language:'pt-BR',pickDate:false}); + + // \$("#timepickerTime_from_1").on('changeDate', function() { + // let dateString1 = \$("input[name='time_from").val() ; + // }) ; + + \$("$timepicker_ids_string").on('changeDate', function() { + + const id = this.id ; + const lastIndex = id.lastIndexOf('_'); + const beforeUnderscore = id.substring(0,lastIndex); + let afterUnderscore = id.substring(lastIndex+1); + afterUnderscore = parseInt(afterUnderscore) ; + // const from_to_toggle = {"timepickerTime_from":"time_to","timepickerTime_to":"time_from"} ; + // console.log("timepicker change id : "+id+" , beforeUnderscore : "+beforeUnderscore+" , afterUnderscore : "+afterUnderscore) ; + // let date_to = \$("input[name='date_to']").val() ; + // let datetimeValue = \$("#datetimepickerDate_to").data("date"); + // // // if (beforeUnderscore == 'from' && afterUnderscore == 1) { + + // // // let dateString = \$("input[name='time_from").val() ; + // // // let timePart = dateString.split(' ')[1]; + // // // \$("input[name='time_from_1']").val(timePart) ; + // // // return ; + // // // } + // // // if (beforeUnderscore == 'to') { + // // // let dateString1 = \$("input[name='time_from").val() ; + // // // let dateString2 = \$("input[name='time_to").val() ; + // // // const count_dates = getDatesBetween(dateFromInput,dateToInput,1) ; + // // // if (afterUnderscore == count_dates) { + // // // let timePart = dateString.split(' ')[1]; + // // // \$("input[name='time_to_"+count_dates+"']").val(timePart) ; + // // // return ; + // // // } + // // // } + + if (id.includes("timepickerTime_from_")) { + saved_time_from[afterUnderscore] = \$("input[name='time_from_"+afterUnderscore+"']").val() ; + } else if (id.includes("timepickerTime_to_")) { + saved_time_to[afterUnderscore] = \$("input[name='time_to_"+afterUnderscore+"']").val() ; + } + + // console.log("input[name='time_from_"+afterUnderscore+"']") ; + // console.log("input[name='time_to_"+afterUnderscore+"']") ; + + changed_radio_cnt = 0 ; + + set_full_half_day(beforeUnderscore,afterUnderscore) ; + + if (changed_radio_cnt) { + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + } + + // let start_time = \$("input[name='time_from_"+afterUnderscore+"']").val() ; + // let end_time = \$("input[name='time_to_"+afterUnderscore+"']").val() ; + // let seconds1 = timeStringToSeconds(start_time) ; + // let seconds2 = timeStringToSeconds(end_time) ; + + // let diffSeconds = seconds2 - seconds1 ; + // if (diffSeconds >= 18000) { + // if (!\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + // \$("#radio_"+afterUnderscore+"_1").prop('checked',true) ; + // } + // } else if (diffSeconds >= 0 && diffSeconds < 18000) { + // if (!\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + // \$("#radio_"+afterUnderscore+"_2").prop('checked',true) ; + // } + // } else { + // if (\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + // \$("#radio_"+afterUnderscore+"_1").prop('checked',false) ; + // } + // if (\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + // \$("#radio_"+afterUnderscore+"_2").prop('checked',false) ; + // } + // if (beforeUnderscore == 'timepickerTime_from') { + // \$("input[name='time_from_"+afterUnderscore+"']").val(end_time) ; + // } else { + // \$("input[name='time_to_"+afterUnderscore+"']").val(start_time) ; + // } + + // } + // console.log("start_time : "+start_time+" , end_time : "+end_time+" , seconds1 : "+seconds1+" , seconds2 : "+seconds2+" , diffSeconds : "+diffSeconds) ; + }) ; + ~ ; + } + + chop $default_time_from if $default_time_from ; chop $default_time_to if $default_time_to ; + + $fcol = 3 ; $lcol = 2 ; my $expenses_html_for_javascript = qq~~ ; my $vat_default_for_hidden_expenses = qq~~ ; my $cnt_hidden_rows = 0 ; my $changed_opid_as_level_3 = 0 ; + + # my $default_event_length_1 = qq~~ ; my $default_event_length_2 = qq~~ ; my $e_cnt = 0 ; + # foreach (split(/\;/,$db{$table}{$id}{event_length})) { + # $e_cnt++ ; + # $default_event_length_1 .= qq~$_;~ if $e_cnt <= 10 ; + # $default_event_length_2 .= qq~$_;~ if $e_cnt > 10 ; + # } + # chop $default_event_length_1 if $default_event_length_1 ; + # chop $default_event_length_2 if $default_event_length_2 ; + + my %event_length_rows = () ; + + if ($readonly{qty} eq "READONLY") { + + $readonly{nr_of_systems} = "READONLY" ; + + $event_length_rows{1} .= qq~ +
    ~ ; + + $event_length_rows{1} .= qq~ +
    + +
    + ~ ; + + # $event_length_rows{2} = $event_length_rows{1} ; + + if ($db{$table}{$id}{event_length}) { + + # my + my @words = split /\;/, $db{$table}{$id}{event_length} ; + my $output = join ' ', map { ucfirst lc $_ } @words; + # style="top:4px;left:-4px;" + + # my $time_label_header_row = qq~
    ~ ; +# + my $cnt = 0 ; + foreach (@words) { + $cnt++ ; + + $event_length_rows{2} = qq~
    ~ if $cnt >= 11 && $_ && !$event_length_rows{2} ; + + my $el_row_cnt = ($cnt <= 10) ? 1 : 2 ; + + $event_length_rows{$el_row_cnt} .= ($_ eq '1') ? qq~ +
    + +
    + ~ : ($_ eq '2') ? qq~ +
    + +
    ~ : qq~ +
    +
    ~ ; + + } + } else { + for (1 .. $final_day) { # + + my $el_row_cnt = ($cnt <= 10) ? 1 : 2 ; + $event_length_rows{$el_row_cnt} .= ($calc_default_event_length{$_} eq '1') ? qq~ +
    + +
    + ~ : ($calc_default_event_length{$_} eq '2') ? qq~ +
    + +
    + ~ : qq~ +
    +
    + ~ ; + } + } + + # $add_form_fields .= &common_min_form_label('event_length',$output) ; + # $add_form_fields .= qq~
    ~ ; + $event_length_rows{1} .= qq~ +
    ~ if $event_length_rows{1} ; + + $event_length_rows{2} .= qq~ +
    ~ if $event_length_rows{2} ; + # $add_form_fields .= &common_min_form_input('qty',$db{$table}{$id}{qty},'',1) ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + + } else { + + $fcol = 1 ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'',10,$final_day) ; + + $event_length_rows{1} .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'',10,$final_day,"",1) ; + my $final_day_second = $final_day - 10 ; + $final_day_second = -1 if $final_day_second <= 0 ; + $event_length_rows{2} .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'',10,$final_day_second,"radio_row_id_2",2) ; + + # my $sec = &common_min_form_radio_col('event_length',$default_event_length_2,'',10,$final_day_second) ; + + # $add_form_fields .= qq~
    ~ ; + $fcol = 3 ; + # $add_form_fields .= &common_min_form_input('qty',$db{$table}{$id}{qty},'',1) ; + # $add_form_fields .= qq~
    ~ ; + if ($glod_user_level < 4) { + + $changed_opid_as_level_3 = 1 ; + + my @excl_def = split(/\;/,$db{event_quotes_min}{$id}{excl_workings_event}) ; + my @saved_des = split(/\;/,$db{event_quotes_min}{$id}{description_workings_event}) ; + my @saved_op = split(/\;/,$db{event_quotes_min}{$id}{operator_workings_event}) ; + my @remarks_def = split(/\;/,$db{event_quotes_min}{$id}{remarks_workings_event}) ; + my @supp_def = split(/\;/,$db{event_quotes_min}{$id}{supplier_workings_event}) ; + my @ref_nr_def = split(/\;/,$db{event_quotes_min}{$id}{ref_nr_workings_event}) ; + my @qty_old = split(/\;/,$db{event_quotes_min}{$id}{qty_workings_event}); + my @amount_usd_old = split(/\;/,$db{event_quotes_min}{$id}{amount_usd_workings_event}); + my @amount_old = split(/\;/,$db{event_quotes_min}{$id}{amount_workings_event}); + my @vat_default = split(/\;/,$db{event_quotes_min}{$id}{vat_workings_event}) ; + + my %expenses_html = () ; + + &db_min_ro('users','id',"user_type LIKE 'casual%' AND block <> 1 AND inactive <> 1",'','') ; + + foreach (keys %{$db{users}}) { + $opts{users} .= qq~~ ; + } + $opts{description} = qq~~ ; + + $add_form_fields .= qq~
    ~ ; + $db{$table}{$id}{roe} = 1 unless $db{$table}{$id}{roe} ; + + my $custom_set_checked = ($db{$table}{$id}{custom_set}) ? "CHECKED" : "" ; + + $add_form_fields .= qq~ + + + + + + + ~ ; + + for (1 .. 50) { + if ($qty_old[50-$_] || $amount_usd_old[50-$_] || $amount_old[50-$_] || $saved_des[50-$_] || $saved_op[50-$_]) { + $cnt_hidden_rows = 51-$_ ; + last ; + } + } + + my @ttlarr = ("sub_total_workings_event","vat_total_workings_event","grand_total_workings_event") ; + + if ($cnt_hidden_rows) { + + # &db_min_ro('event_cost_items','id','','','') ; + &db_min_ro('event_cost_items','id',"excl_from_expenses < 1",'','') ; + + for my $row_cnt (1 .. $cnt_hidden_rows) { + + foreach (keys %{$db{event_cost_items}}) { + my $sel = ($saved_des[$row_cnt-1] and $saved_des[$row_cnt-1] eq $_) ? "SELECTED" : "" ; + $opts{"description_$row_cnt"} .= qq~~ ; + } + foreach (keys %{$db{users}}) { + my $sel = ($saved_op[$row_cnt-1] and $saved_op[$row_cnt-1] eq $_) ? "SELECTED" : "" ; + $opts{"users_$row_cnt"} .= qq~~ ; + } + + $vat_default_for_hidden_expenses .= qq~$row_cnt:"$vat_default[$row_cnt-1],"~ ; + + $add_form_fields .= qq~
    ~ ; + my $excl_checked = ($excl_def[$row_cnt-1]) ? "CHECKED" : "" ; + my $vat_checked = ($vat_default[$row_cnt-1]) ? "CHECKED" : "" ; + + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + + $add_form_fields .= qq~
    ~ ; + + last if $cnt_hidden_rows == $row_cnt ; + } + + $add_form_fields .= qq~
    ~ ; + foreach (@ttlarr) { + my $inp_name = "input" . ucfirst $_ ; + $add_form_fields .= qq~~ ; + } + $add_form_fields .= qq~
    ~ ; + # chop $vat_default_for_hidden_expenses if $vat_default_for_hidden_expenses ; + } + + for ($cnt_hidden_rows+1 .. 50) { + # next if $cnt_hidden_rows && $_ <= $cnt_hidden_rows ; + $add_form_fields .= qq~
    ~ ; + # $expenses_html{$_} = qq~$_:""~ ; + } + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + foreach (@ttlarr) { + my $inp_name = "input" . ucfirst $_ ; + $expenses_html{1000} .= qq~~ ; + } + $expenses_html{1000} = qq~1000:"$expenses_html{1000}"~ ; + + foreach (sort keys %expenses_html) { + $expenses_html_for_javascript .= qq~$expenses_html{$_},~ ; + } + chop $expenses_html_for_javascript if $expenses_html_for_javascript ; + + } + } + + $add_form_fields .= qq~$time_label_header_row{1}
    ~ ; + $add_form_fields .= qq~
    $days_time_row{1}
    ~ ; + $add_form_fields .= qq~
    $days_time_row_2{1}
    ~ ; + $add_form_fields .= qq~$event_length_rows{1}~ ; + + $add_form_fields .= qq~$time_label_header_row{2}
    ~ ; + $add_form_fields .= qq~
    $days_time_row{2}
    ~ ; + $add_form_fields .= qq~
    $days_time_row_2{2}
    ~ ; + $add_form_fields .= qq~$event_length_rows{2}~ ; + + $add_form_fields .= &common_min_form_input('qty',$db{$table}{$id}{qty},'',1) ; + $add_form_fields .= qq~
    ~ ; + + $db{$table}{$id}{nr_of_systems} = 0 unless $db{$table}{$id}{nr_of_systems} ; + + $preferred_title{nr_of_systems} = "Number of Systems" ; + + # if ($glod_user_level > 3) { + # if ($glod_user_level > 2) { + + if ($glod_user_level > 3 || (!$quote_completed && $glod_user_level == 3)) { + $preferred_title{type} = "Type of System" ; + $add_form_fields .= &common_min_form_select('type',$db{$table}{$id}{type},'') ; + $trigger_jquery .= qq~\$("#selectType\_chosen").css( "width", "100%" );~ ; + $add_form_fields .= &common_min_form_input('nr_of_systems',$db{$table}{$id}{nr_of_systems},'') ; + $preferred_title{type_details_id} = "Type Details" ; + $add_form_fields .= &common_min_form_select('type_details_id',$db{$table}{$id}{type_details_id},'') ; + $trigger_jquery .= qq~\$("#selectType_details_id\_chosen").css("width","100%") ;~ ; + # } elsif ($glod_user_level < 4 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + } + # elsif ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + elsif ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { + &db_min_ro('event_types','id,name',"`id`='$db{$table}{$id}{type}'",'','') if $db{$table}{$id}{type} ; + $readonly{type_of_system} = "READONLY" ; $readonly{system_details} = "READONLY" ; $readonly{system_name} = "READONLY" ; $readonly{club_name} = "READONLY" ; + $preferred_title{type_of_system} = "Type of System" ; + $add_form_fields .= &common_min_form_input('type_of_system',$db{event_types}{$db{$table}{$id}{type}}{name},'') ; + $add_form_fields .= &common_min_form_input('nr_of_systems',$db{$table}{$id}{nr_of_systems},'') ; + + &db_min_ro('event_type_details','id,name',"`id`='$db{$table}{$id}{type_details_id}'",'','') unless $db{$table}{$id}{type_details_id} =~ /;/ ; + &db_min_ro('event_type_details','id,name',"",'','') if $db{$table}{$id}{type_details_id} =~ /;/ ; + my $input_val = qq~~ ; + foreach my $type_id (split(",",$db{$table}{$id}{type_details_id})) { + next unless $db{event_type_details}{$type_id}{name} ; + $input_val .= qq~$db{event_type_details}{$type_id}{name}, ~ ; + } + chop $input_val if $input_val ; chop $input_val if $input_val ; + $add_form_fields .= &common_min_form_input('system_details',$input_val,'') ; + } else { + $preferred_title{type} = "Type of System" ; + $add_form_fields .= &common_min_form_select('type',$db{$table}{$id}{type},'') ; + $trigger_jquery .= qq~\$("#selectType\_chosen").css("width","100%" );~ ; + $add_form_fields .= &common_min_form_input('nr_of_systems',$db{$table}{$id}{nr_of_systems},'') ; + } + + our $remaining_op_ids = qq~~ ; + + &build_system_name_form($db{$table}{$id}{event_system_id_multiple},$db{$table}{$id}{club_ids},$quote_accepted,$quote_rejected,$quote_cancelled,$db{$table}{$id}{daily_operator_ids},$db{$table}{$id}{days_active},$db{$table}{$id}{quote_completed}) ; + + my $hide_club_name1 = qq~~ ; my $hide_club_name2 = qq~~ ; my $required_fields_full = 0 ; + + $required_fields_full = 1 if $db{$table}{$id}{ref} and $db{$table}{$id}{type} and $db{$table}{$id}{event_system_id} + and $db{$table}{$id}{qty} and $db{$table}{$id}{region_id} and $db{$table}{$id}{city_id} ; + + $add_form_fields .= qq~
    ~ ; + + $fcol = 3 ; + + # # if ($glod_user_level > 3) { + # if ($glod_user_level > 2) { + # $dlg{operator_ids} .= qq~
    ~ ; + # $preferred_title{operator_ids} = "Operator(s)" ; + # $add_form_fields .= &common_min_form_select('operator_ids',$remaining_op_ids,'') ; + # $trigger_jquery .= qq~\$("#selectOperator_ids\_chosen").css( "width", "100%" );~ ; + # # } elsif ($glod_user_level < 4 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + # } + + # if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { + my @op_names = map { $db{users}{$_}{name} } @multi_select_op_ids; + $op_names = join(", ",@op_names) ; + $preferred_title{operators} = "Operator(s)" ; $readonly{operators} = "READONLY" ; + $add_form_fields .= &common_min_form_input('operators',$op_names,'') ; + } else { + + if ($glod_user_level > 2) { + $dlg{operator_ids} .= qq~
    ~ ; + $preferred_title{operator_ids} = "Operator(s)" ; + $trigger_jquery .= qq~\$("#selectOperator_ids\_chosen").css( "width", "100%" );~ ; + } + + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + $add_form_fields .= &common_min_form_select('operator_ids',$remaining_op_ids,'') ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + # } elsif ($glod_user_level < 4 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + } + + my @casuals = () ; + + foreach (keys %{$db{events}}) { + $qnr = $db{events}{$_}{event_quote_nr} ; + $uid = $db{events}{$_}{user_id} ; + next unless $db{events}{$_}{category} eq 'available' ; + push @casuals, "$casual_name{$uid} [$casual_type{$uid}]" ; + } + + $add_form_fields .= &common_min_form_input('casual_worker','A','hidden') ; + $add_form_fields .= &common_min_form_input('casual_worker_2','B','hidden') ; + + my $nr_of_casuals = 0 + $db{$table}{$id}{nr_of_casuals} + $db{$table}{$id}{nr_of_casuals_2} ; + + $add_form_fields .= &common_min_form_input('nr_of_casuals',$nr_of_casuals,'hidden') ; + $add_form_fields .= &common_min_form_input('nr_of_casuals_2',0,'hidden') ; + + $fcol = 3 ; + # $add_form_fields .= &common_min_form_input('sports_type',$db{$table}{$id}{sports_type},'') ; + + if ($hide_select_1) { + $add_form_fields .= qq~$readonly_select~ ; + } + + $preferred_title{sport_type_ids} = "Sport Type(s)" ; $preferred_title{organisation_ids} = "Venue(s)" ; + $add_form_fields .= qq~$hide_select_1~ ; + $add_form_fields .= &common_min_form_select('sport_type_ids',$db{$table}{$id}{sport_type_ids},'') ; + # $add_form_fields .= &common_min_form_input('ligr',$db{$table}{$id}{ligr},'') ; + # if ($db{$table}{$id}{ligr} eq 'Yes') { $checked = 'CHECKED'; } else { $checked = ''; } + # $add_form_fields .= &common_min_form_checkbox('ligr',$db{$table}{$id}{ligr},$checked) ; + # $add_form_fields .= &common_min_form_input('Location',$db{$table}{$id}{location},'') ; + $add_form_fields .= &common_min_form_select('region_id',$db{$table}{$id}{region_id},'') ; + + $add_form_fields .= &common_min_form_select('city_id',$db{$table}{$id}{city_id},'') ; + $add_form_fields .= &common_min_form_select('organisation_ids',$db{$table}{$id}{organisation_ids},'') ; + + $allow_deselect{linear_id} = 1 ; + my %linear_def = () ; $linear_def{$db{$table}{$id}{linear_id}} = 'SELECTED' ; + $opts{linear_id} .= qq~~ ; + $add_form_fields .= &common_min_form_select('linear_id',$db{$table}{$id}{linear_id},'') ; + + # $supplier_type_ids + + $preferred_title{supplier_type_ids} = "Supplier Type(s)" ; + $add_form_fields .= qq~~ . &common_min_form_select('supplier_type_ids',$db{$table}{$id}{supplier_type_ids},'') if $db{$table}{$id}{sss_quote_nr} ; + + if ($hide_select_1) { + $add_form_fields .= qq~
    ~ ; + } + + # $opts{event_length} = qq~~ ; + # $radio_opts{event_length} = "Full Day+Half Day" ; + # $fcol = 1 ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'') ; + # $add_form_fields .= qq~
    ~ ; + # $fcol = 6 ; + # $add_form_fields .= qq~$hide_select_2~ ; + + # $ignore{club} = 1 ; + # $add_form_fields .= &common_min_form_input('club','','') ; + # $add_form_fields .= &common_min_form_input('City',$db{$table}{$id}{city},'') ; + + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + + # $operator_options = qq~~ ; + + $trigger_jquery_raw .= qq~ + + // // // \$("input[name='event_length']").change( function () { + + // // // let radio_sel = \$(this).val() ; + + // // // for (let i = 1; i<=50; i++) { + + // // // let usd = \$("#inputAmount_usd_workings_event_"+i) ; + // // // let item = \$("#selectDescription_workings_event_"+i) ; + + // // // let amnt = 0 ; + // // // if (\$('input[name="event_length"][value="full_day"]').is(":checked") && usd.val() == '500.00' && item.val() == 14) { + // // // amnt = 750 ; + // // // } else if (\$('input[name="event_length"][value="half_day"]').is(":checked") && usd.val() == '750.00' && item.val() == 14) { + // // // amnt = 500 ; + // // // } else { + // // // continue ; + // // // } + + // // // let qty = \$("#inputQty_workings_event_"+i) ; + // // // let conv = \$("#inputAmount_ttl_workings_event_"+i) ; + + // // // usd.val(amnt.toFixed(2)) ; + // // // let total_amnt = qty.val()*amnt ; + // // // conv.val(total_amnt.toFixed(2)) ; + // // // } + // // // if ($changed_opid_as_level_3) { + // // // calc_hidden_totals() ; + // // // } else { + // // // calcAllWorkings() ; + // // // } + // // // }) ; + + \$("#selectRegion_id").change(function() { + + var vid = \$("#selectCity_id") ; + + var selected_city = \$("#selectCity_id").chosen().val() ; + selected_city = String(selected_city); + let splittedNumbers = selected_city.split(',') ; + + vid.empty(); // remove old options + vid.append(""); + vid.trigger("chosen:updated"); + var url = "$useropts{scripts}/get/get_cities_from_region.pl?region_id=" + \$(this).val() ; + + \$.get(url, function(json) { + \$.each(json, function(key, data) { + if (splittedNumbers.includes(data.id)) { + vid.append(""); + } else { + vid.append(""); + } + vid.trigger("chosen:updated"); + }); + }, + 'json'); + + var vid2 = \$("#selectOrganisation_ids") ; + + var selected_venues = \$("#selectOrganisation_ids").chosen().val() ; + selected_venues = String(selected_venues); + let splittedNumbers2 = selected_venues.split(',') ; + + vid2.empty(); // remove old options + vid2.append(""); + vid2.trigger("chosen:updated"); + url = "$useropts{scripts}/get/get_venues_from_region.pl?region_id=" + \$(this).val() ; + + \$.get(url, function(json) { + \$.each(json, function(key, data) { + if (splittedNumbers2.includes(data.id)) { + vid2.append(""); + } else { + vid2.append(""); + } + vid2.trigger("chosen:updated"); + }); + }, + 'json'); + + }); + + + let prev_date_part_from = \$("input[name='date_from']").val() ; + prev_date_part_from = prev_date_part_from.split(' ')[0] ; + let prev_date_part_to = \$("input[name='date_to']").val() ; + prev_date_part_to = prev_date_part_to.split(' ')[0] ; + + \$('#datetimepickerDate_from,#datetimepickerDate_to').on('changeDate', function(e) { + let from_to = get_row_nr(this.id) ; + // saved_time_from["1"] = $("input[name='date_from']").val() ; + if (this.id == "datetimepickerDate_from") { + let date_new = \$("input[name='date_from']").val() ; + let time_part = date_new.split(' ')[1]; + \$("input[name='time_from_1']").val(time_part) ; + } + calc_date_diff_in_days(this.id) ; + // \$("#day_4_name_1_extra_1").css("display","none") ; + }) ; + + // function javascript_sprintf_sort_off (num) { + // if (num < 10) { + // num = "0"+num.toString() ; + // } + // return num ; + // } + + + + // // function move_system_operators_drop_downs_between_short_to_long () { + + // // let cnt_active_days = 0 ; let cnt_dates_between = 0 ; + // // for (let col=1; col<=20; col++) { + // // if (\$("#day_"+col).val()) { + // // cnt_active_days++ ; cnt_dates_between = col ; + // // } + // // } + // // if ((cnt_active_days <= 6 && \$("#day_1_1").html()) || (cnt_active_days <= 20 && cnt_active_days > 6 && \$("#day_1_1_1").html())) { + // // return ; + // // } + + // // if (cnt_active_days && &cnt_active_days <= 6 && !\$("#day_1_1").html() && \$("#day_1_1_extra_1").html()) { + // // for (let row=1; row<=15; col++) { + // // if (!\$("input[name='clicked_button_"+row+"']").val()) { continue ; } + + // // \$("#system_name_row_"+row+"_extra_1").css("display","none") ; + // // \$("#system_name_row_"+row+"_extra_2").css("display","none") ; + // // \$("day_names_extra_1").css("display","none") ; + // // \$("day_names_extra_2").css("display","none") ; + + // // for (let col=1; col<=20; col++) { + // // if (\$("#day_"+col).val()) { + // // \$("#day_"+row+"_"+col).append(\$("#day_"+row+"_"+col+"_extra").contents()); + // // \$("#day_"+row+"_"+col).css("display","") ; + // // } + // // } + // // } + + // // // \$("#2").append(\$("#1").contents()); + // // } else if (cnt_active_days > 6 && \$("#day_1_1").html() && !\$("#day_1_1_1").html()) { + // // for (let row=1; row<=15; col++) { + // // if (!\$("input[name='clicked_button_"+row+"']").val()) { continue ; } + + // // if (\$("#system_name_row_"+row+"_1").is(":hidden")) { + // // (\$("#system_name_row_"+row+"_1").css("display","") ; + // // } + // // if (\$("#system_name_row_"+row+"_2").is(":hidden") && cnt_active_days > 10) { + // // (\$("#system_name_row_"+row+"_2").css("display","") ; + // // } + // // let active_day_counter = 0 ; + // // for (let col=1; col<=20; col++) { + // // if (\$("#day_"+col).val()) { + // // active_day_counter++ ; + // // \$("#day_"+row+"_"+active_day_counter+"_extra").append(\$("#day_"+row+"_"+col+"").contents()); + // // } + // // } + // // } + // // } + + // // } + + function calc_date_diff_in_days(from_to) { + + // console.log("from_to : "+from_to) ; + + let dateFromInput = \$("input[name='date_from']").val(); + // const dateToInput = \$("#datetimepickerDate_to").data("date"); + let dateToInput = \$("input[name='date_to']").val() ; + + let date_part_from = dateFromInput.split(' ')[0]; + let date_part_to = dateToInput.split(' ')[0]; + + let time_part_from = dateFromInput.split(' ')[1]; + let time_part_to = dateToInput.split(' ')[1]; + + if (prev_date_part_from == date_part_from && date_part_to == prev_date_part_to) { + + changed_radio_cnt = 0 ; + + const datesBetween = getDatesBetween(dateFromInput,dateToInput,0) ; let date_counter = 0 ; + + for (const date of datesBetween) { + + date_counter++ ; + + if (date_counter > 20) { date_counter = 20 ; break ; } + + if (((!saved_time_to[date_counter] || datesBetween.length == date_counter) && from_to.includes("Date_to")) || (date_counter > 1 && !saved_time_from[date_counter] && from_to.includes("Date_from"))) { + + if (from_to.includes("Date_from")) { + \$("input[name='time_from_"+date_counter+"']").val(time_part_from) ; + } else { + \$("input[name='time_to_"+date_counter+"']").val(time_part_to) ; + } + + set_full_half_day('',date_counter) ; + if ((nr_days["full"] && !prev_nr_days["full"]) || (nr_days["half"] && !prev_nr_days["half"]) || (!nr_days["full"] && prev_nr_days["full"]) || (!nr_days["half"] && prev_nr_days["half"])) { + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + changed_radio_cnt = 0 ; + } + prev_nr_days["full"] = nr_days["full"] ; + prev_nr_days["half"] = nr_days["half"] ; + + } + } + + // if (saved_time_to[date_counter] && from_to.includes("Date_to")) { + // \$("input[name='time_to_"+date_counter+"']").val(time_part_to) ; + // } + + if (from_to.includes("Date_to")) { + saved_time_to[date_counter] = time_part_to ; + } else { + saved_time_from["1"] = time_part_from ; + } + + // if (from_to.includes("Date_from")) { + // \$("input[name='time_from_1']").val(time_part_from) ; + // set_full_half_day('',1) ; + // } else { + // let diffInDays = 1 + (new Date(date_part_to) - new Date(date_part_from)) / (1000 * 60 * 60 * 24) ; + // \$("input[name='time_to_"+diffInDays+"']").val(time_part_to) ; + // set_full_half_day('',diffInDays) ; + // } + + if (changed_radio_cnt) { + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + } + return ; + } + + prev_date_part_from = date_part_from ; + prev_date_part_to = date_part_to ; + + const date1 = new Date(dateFromInput) ; + const date2 = new Date(dateToInput) ; + + let hide_date_names = "#1" ; + + let glod_user_level = parseInt("$glod_user_level") ; + + let y1 = date1.getFullYear() ; let m1 = date1.getMonth() ; let d1 = date1.getDate() ; let y2 = date2.getFullYear() ; let m2 = date2.getMonth() ; let d2 = date2.getDate() ; + + m1 = m1 + 1 ; + if (m1 < 10) { + m1 = "0"+m1.toString() ; + } + m2 = m2 + 1 ; + if (m2 < 10) { + m2 = "0"+m2.toString() ; + } + + if ((y1 == y2 && m1 == m2 && d1 == d2) || date1 > date2) { + + if (date1 > date2 && from_to == "datetimepickerDate_from") { + \$("#datetimepickerDate_to").datetimepicker("setDate",date_part_from+" "+time_part_to) ; + \$("#day_1_name label.control-label").text(date_part_from) ; + } else if (date1 > date2 && from_to == "datetimepickerDate_to") { + \$("#datetimepickerDate_from").datetimepicker("setDate",date_part_to+" "+time_part_from) ; + \$("#day_1_name label.control-label").text(date_part_to) ; + } + + \$("input[name='time_from_1']").val(time_part_from) ; + \$("input[name='time_to_1']").val(time_part_to) ; + + changed_radio_cnt = 0 ; + + set_full_half_day('',1) ; + + \$("#radio_1_1").css("display",""); + \$("#radio_1_2").css("display",""); + + \$("#radio_row_id_2_1").hide() ; + \$("#radio_row_id_2_2").hide() ; + + if (!\$("#days_drop_downs_1").is(":hidden")) { + \$("#start_times_row_1").hide() ; + \$("#end_times_row_1").hide() ; + \$("#days_drop_downs_1").hide() ; + } + + if (!\$("#days_drop_downs_2").is(":hidden")) { + \$("#start_times_row_2").hide() ; + \$("#end_times_row_2").hide() ; + \$("#days_drop_downs_2").hide() ; + } + + let reduced_nr_of_days = 0 ; + + for (let i=2; i<=20; i++) { + \$("#day_"+i+"_chosen").css("display","none") ; + + if (\$("#day_"+i).val()) { + \$("#day_"+i).val("") ; + \$("#day_"+i).trigger("chosen:updated") ; + \$("#radio_"+i+"_1").css("display","none") ; + \$("#radio_"+i+"_2").css("display","none") ; + reduced_nr_of_days = 1 ; + } + } + + if (changed_radio_cnt || reduced_nr_of_days) { + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + } + + if (!\$("#day_1").val()) { + \$("#day_1").val("1") ; + \$("#day_1").trigger("chosen:updated") ; + } + \$("#inputQty").val("1") ; + + if (\$("#clicked_any_button").text()) { + + // if (!\$("#days_drop_downs_1").is(":hidden")) { + // \$("#days_drop_downs_1").css("display","none") ; + // \$("#start_times_row_1").css("display","none") ; + // \$("#end_times_row_1").css("display","none") ; + // } + + // if (!\$("#days_drop_downs_2").is(":hidden")) { + // \$("#days_drop_downs_2").css("display","none") ; + // \$("#start_times_row_2").css("display","none") ; + // \$("#end_times_row_2").css("display","none") ; + // } + // if (\$("#day_1_1").is(":hidden")) { + // \$("#day_1_1").removeClass('col-md-0').addClass('col-md-1') ; + // \$("#day_1_1").css("display","") ; + // } + + // if (!\$("#day_1_1").html()) { + // let select_1_1_raw = add_select_raw (1,"custom_operator_1_1","selectCustom_operator_1_1","Select an Option","$operator_options",-1,100) ; + // \$("#day_1_1").html(select_1_1_raw) ; + // } + + add_operator_dropdown("day_1_name","day_1_1","custom_operator_1_1","selectCustom_operator_1_1",y1+"-"+m1+"-"+d1,1,0) ; + + for (let a=1;a<=15;a++) { + if (!\$("input[name='clicked_button_"+a+"']").val()) { continue ; } + + if (a > 1 && !\$("#extra_heading_"+a).is(":hidden")) { + \$("#extra_heading_"+a).hide() ; + } + + if (!\$("#day_names_"+a+"_extra_1").is(":hidden")) { + \$("#day_names_"+a+"_extra_1").css("display","none") ; + \$("#system_name_row_"+a+"_extra_1").css("display","none") ; + } + if (!\$("#day_names_"+a+"_extra_2").is(":hidden")) { + \$("#day_names_"+a+"_extra_2").css("display","none") ; + \$("#system_name_row_"+a+"_extra_2").css("display","none") ; + } + + // \$("#day_"+row+"_"+active_day_counter+"_extra").append(\$("#day_"+row+"_"+col+"").contents()); + + \$("#day_1_name").css("display","") ; + \$("#day_"+a+"_1").css("display","") ; + + for (let b=2;b<=20;b++) { + if (!\$("#day_"+b+"_name").is(":hidden")) { + \$("#day_"+b+"_name").css("display","none") ; + } + if (!\$("#day_"+a+"_"+b).is(":hidden")) { + \$("#day_"+a+"_"+b).css("display","none") ; + } + } + } + } + + return ; + } + + // if (\$("#clicked_any_button").text()) { + + // for (let a=1;a<=15;a++) { + + // if (!\$("input[name='clicked_button_"+a+"']").val()) { continue ; } + + // for (let b=1;b<=date_counter;b++) { + // if (!\$("#day_"+b+"_name").is(":hidden")) { + // \$("#day_"+a+"_"+b).css("display","") ; + // \$("#selectCustom_operator_"+a+"_"+b+"_chosen").css("width","100%") ; + // } else { + // \$("#day_"+a+"_"+b).css("display","none") ; + // } + // } + // } + // } + + + if (\$("#days_drop_downs_1").is(":hidden")) { + // if (glod_user_level > 3) { + \$("#days_drop_downs_1").css("display","") ; + \$("#start_times_row_1").css("display","") ; + \$("#end_times_row_1").css("display","") ; + } + + // if (date1 > date2 ) { + + // \$("#inputQty").val("0") ; + // for (let k=1;k<=6;k++) { + // \$("#day_"+k).val('') ; + // \$("#day_"+k).trigger("chosen:updated") ; + // \$("input[name='time_from_"+k+"']").val('') ; + // \$("input[name='time_to_"+k+"']").val('') ; + // \$("#timepickerTime_from_"+k).css("display","none") ; + // \$("#timepickerTime_to_"+k).css("display","none") ; + // \$("#radio_"+k+"_1").css("display","none") ; + // \$("#radio_"+k+"_2").css("display","none") ; + // \$("#day_"+k+"_chosen").css("display","none") ; + // } + + // return ; + + + // let date_part_from = dateFromInput.split(' ')[0]; + // \$("#datetimepickerDate_to").datetimepicker("setDate",date_part_from+" "+time_part_to) ; + + // \$("input[name='time_from_1']").val(time_part_from) ; + // \$("input[name='time_to_1']").val(time_part_to) ; + + // let time_1 = timeStringToSeconds(time_part_from) ; + // let time_2 = timeStringToSeconds(time_part_to) ; + + // if (time_2 < time_1 || !\$("#day_1").val()) { + // \$("#inputQty").val("0") ; + // } else { + // \$("#inputQty").val("1") ; + // let time_diff_ = time_2 - time_1 ; + // if (time_diff_ >= 18000) { + // \$("#radio_1_1").prop('checked',true) ; + // } else { + // \$("#radio_1_2").prop('checked',true) ; + // } + // } + + // \$("#days_drop_downs").css("display","none") ; + // \$("#start_times_row").css("display","none") ; + // \$("#end_times_row").css("display","none") ; + + // for (let k=2;k<=6;k++) { + // if (\$("#day_"+k).val()) { + // \$("#day_"+k).val('') ; + // \$("#day_"+k).trigger("chosen:updated") ; + // \$("#radio_"+k+"_1").css("display","none") ; + // \$("#radio_"+k+"_2").css("display","none") ; + // } + // } + + // return ; + // } + + \$("input[name='time_from_1']").val(time_part_from) ; + + const datesBetween = getDatesBetween(dateFromInput,dateToInput,0) ; + let date_counter = 0 ; let dates_count = 0 ; let count_days = 0 ; + + let count_days_after = 0 ; let nr_of_active_days = 0 ; + + // for (const date of datesBetween) { + // date_counter++ ; dates_count++ ; + // if (\$("#day_"+date_counter+"_chosen").is(":hidden")) { + + // \$("#radio_"+date_counter+"_1").css("display",""); + // \$("#radio_"+date_counter+"_2").css("display",""); + // \$("#day_"+date_counter).val("1") ; + // \$("#day_"+date_counter).trigger("chosen:updated") ; + // \$("#day_"+date_counter+"_chosen").css("display",""); + // \$("#day_"+date_counter+"_chosen").css("width","100%"); + // \$("#day_"+date_counter).val('1') ; + // \$("#day_"+date_counter).trigger("chosen:updated") ; + // if (date_counter > 1) { + // console.log("1 . display timepickerTime_from_"+date_counter) ; + // \$("#timepickerTime_from_"+date_counter).css("display",""); + // } + // } + // if (\$("#day_"+date_counter).val()) { + // nr_of_active_days++ ; + // } + // } + + // date_counter = 0 ; + + let dates_map = {} ; + + changed_radio_cnt = 0 ; let changed_nr_of_days = 0 ; + + for (const date of datesBetween) { + + date_counter++ ; + + dates_map[date_counter] = date ; + + // console.log("1 . date_counter : "+dates_map[date_counter]) ; + + // if (date_counter > 6) { date_counter = 6 ; count_days_after++ ; continue ; } + if (date_counter > 20) { date_counter = 20 ; break ; } + if (date_counter > 1 && !saved_time_from[date_counter]) { + \$("input[name='time_from_"+date_counter+"']").val(time_part_from) ; + } + if (!saved_time_to[date_counter]) { + \$("input[name='time_to_"+date_counter+"']").val(time_part_to) ; + } + + set_full_half_day('',date_counter) ; + + if (\$("#day_"+date_counter+"_chosen").is(":hidden")) { + + \$("#radio_"+date_counter+"_1").css("display",""); + \$("#radio_"+date_counter+"_2").css("display",""); + \$("#day_"+date_counter).val("1") ; + \$("#day_"+date_counter).trigger("chosen:updated") ; + \$("#day_"+date_counter+"_chosen").css("display",""); + \$("#day_"+date_counter+"_chosen").css("width","100%"); + \$("#day_"+date_counter).val('1') ; + \$("#day_"+date_counter).trigger("chosen:updated") ; + if (date_counter > 1) { + // console.log("1 . display timepickerTime_from_"+date_counter) ; + \$("#timepickerTime_from_"+date_counter).css("display",""); + } + changed_nr_of_days = 1 ; + } + + if (\$("#day_"+date_counter).val()) { + \$("#timepickerTime_to_"+date_counter).css("display","") ; + nr_of_active_days++ ; + } + + \$("#day_"+date_counter+" option[value='1']").text(date); + \$("#day_"+date_counter+" option[value='1']").trigger("chosen:updated") ; + + if (\$("#day_"+date_counter).val()) { + count_days++ ; + } + } + + if (\$("#days_drop_downs_2").is(":hidden") && date_counter > 10) { + // if (glod_user_level > 3) { + \$("#days_drop_downs_2").css("display","") ; + \$("#start_times_row_2").css("display","") ; + \$("#end_times_row_2").css("display","") ; + \$("#radio_row_id_2_1").css("display","") ; + \$("#radio_row_id_2_2").css("display","") ; + } else if (!\$("#days_drop_downs_2").is(":hidden") && date_counter <= 10) { + \$("#days_drop_downs_2").css("display","none") ; + \$("#start_times_row_2").css("display","none") ; + \$("#end_times_row_2").css("display","none") ; + \$("#radio_row_id_2_1").css("display","none") ; + \$("#radio_row_id_2_2").css("display","none") ; + } + + if (count_days_after) { + + date2.setDate(date2.getDate() - count_days_after); + \$("#datetimepickerDate_to").datetimepicker("setDate",date2) ; + + } + + let select_raw ; + + // console.log("nr_of_active_days : "+nr_of_active_days) ; + + let select_chosen_ids_1 = '#1' ; + let select_chosen_ids_2 = '#2' ; + let names_to_display = '#3' ; + + let def_val = 0 ; + + if (\$("#clicked_any_button").text()) { + + if (nr_of_active_days <= 6) { + for (let b=1;b<=date_counter;b++) { + + if (from_to == "datetimepickerDate_from") { + \$("#day_"+b+"_name label.control-label").text('') ; + } + + // if (!\$("#day_"+date_counter+"_name label.control-label").text()) { + if (\$("#day_"+b+"_name").is(":hidden")) { + \$("#day_"+b+"_name label.control-label").text(dates_map[b]) ; + \$("#day_"+b+"_name").css("display","") ; + \$("#day_"+b+"_name").removeClass('col-md-0').addClass('col-md-1') ; + } + + if (!\$("#day_"+b).val() || !\$("#clicked_any_button").text()) { + \$("#day_"+b+"_name").css("display","none") ; + } + } + } + + for (let a=1;a<=15;a++) { + + if (!\$("input[name='clicked_button_"+a+"']").val()) { + let prev_row_nr = a - 1 ; + if (!\$("extra_heading_"+a).html() && \$("input[name='clicked_button_"+a+"']").val() && prev_row_nr && nr_of_active_days > 6) { + + console.log("hello world Add Heading") ; + + \$("#system_name_row_"+a).before("
    ") ; + } else if (\$("extra_heading_"+a).is(":hidden") && \$("input[name='clicked_button_"+a+"']").val() && prev_row_nr && nr_of_active_days > 6) { + \$("#system_name_row_"+a).show() ; + } else if (!\$("extra_heading_"+a).is(":hidden") && \$("input[name='clicked_button_"+a+"']").val() && prev_row_nr && nr_of_active_days <= 6) { + \$("#extra_heading_"+a).hide() ; + } + continue ; + } + + // let prev_row = a - 1 ; + + if (nr_of_active_days <= 6 && a > 1 && !\$("#extra_heading_"+a).is(":hidden")) { + \$("#extra_heading_"+a).hide() ; + console.log("Hide Heading") ; + } else if (nr_of_active_days > 6 && a > 1 && \$("#extra_heading_"+a).length && \$("#extra_heading_"+a).is(":hidden") && \$("input[name='clicked_button_"+a+"']").val()) { + \$("#extra_heading_"+a).show() ; + console.log("Display Heading") ; + } else if (nr_of_active_days > 6 && a > 1 && !\$("#extra_heading_"+a).length && \$("input[name='clicked_button_"+a+"']").val()) { + console.log("123 Add Heading") ; + \$("#system_name_row_"+a).before("
    ") ; + + } + + if (nr_of_active_days <= 6) { + + + if (!\$("#day_names_"+a+"_extra_1").is(":hidden")) { + \$("#day_names_"+a+"_extra_1").css("display","none") ; + \$("#system_name_row_"+a+"_extra_1").css("display","none") ; + } + if (!\$("#day_names_"+a+"_extra_2").is(":hidden")) { + \$("#day_names_"+a+"_extra_2").css("display","none") ; + \$("#system_name_row_"+a+"_extra_2").css("display","none") ; + } + for (let b=1;b<=date_counter;b++) { + // if (!\$("#day_"+b+"_name").is(":hidden")) { + + def_val = \$("#selectCustom_operator_"+a+"_"+b).val() ; + + if (!\$("#day_"+a+"_"+b).html() && \$("#day_"+b).val()) { + \$("#day_"+a+"_"+b).show() ; + \$("#day_"+a+"_"+b).removeClass('col-md-0').addClass('col-md-1') ; + if (!\$("#day_"+a+"_"+b).html()) { + let select_raw = add_select_raw (a,"custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,"Select an Option","$operator_options",-1,100) ; + \$("#day_"+a+"_"+b).html(select_raw) ; + \$("#day_"+a+"_"+b).trigger("chosen:updated") ; + \$("#selectCustom_operator_"+a+"_"+b).chosen({allow_single_deselect:true}) ; + \$("#selectCustom_operator_"+a+"_"+b+"_chosen").css("width","100%") ; + } + + // \$("#selectCustom_operator_"+a+"_"+b+"_chosen").css("width","100%") ; + } + + if (!\$("#selectCustom_operator_"+a+"_"+b).val() && def_val) { + \$("#selectCustom_operator_"+a+"_"+b).val(def_val) ; + \$("#selectCustom_operator_"+a+"_"+b).trigger("chosen:updated") ; + } + + // else { + // \$("#day_"+a+"_"+b).css("display","none") ; + // } + } + } else if (nr_of_active_days > 6 && nr_of_active_days <= 10) { + + // console.log("EXTRA TAB 1 nr_of_active_days : "+nr_of_active_days) ; + + if (\$("#day_names_"+a+"_extra_1").is(":hidden")) { + \$("#day_names_"+a+"_extra_1").show() ; + } + \$("#system_name_row_"+a+"_extra_1").show() ; + if (!\$("#day_names_"+a+"_extra_2").is(":hidden")) { + \$("#day_names_"+a+"_extra_2").hide() ; + } + \$("#system_name_row_"+a+"_extra_2").hide() ; + + for (let b=1;b<=date_counter;b++) { + // for (let b=1;b<=20;b++) { + + // if (\$("#day_"+b).val()) { + + def_val = \$("#selectCustom_operator_"+a+"_"+b).val() ; + add_operator_dropdown("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,0) ; + select_chosen_ids_1 = select_chosen_ids_1+",#selectCustom_operator_"+a+"_"+b ; + select_chosen_ids_2 = select_chosen_ids_2+",#selectCustom_operator_"+a+"_"+b+"_chosen" ; + names_to_display = names_to_display + ",#day_"+b+"_name_"+a+"_extra_1" ; + \$("#day_"+b+"_name_"+a+"_extra_1 label.control-label").text(dates_map[b]) ; + // } + console.log("#day_"+b+"_name_"+a+"_extra_1") ; + if (!\$("#day_"+b).val()) { + + hide_non_empty_operator_dropdown("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1") ; + // \$("#day_"+b+"_name_"+a+"_extra_1").css("display","none") ; + hide_date_names = hide_date_names + ",#day_"+b+"_name_"+a+"_extra_1" ; + // \$("#day_4_name_1_extra_1").css("display","none") ; + } + + delete_operator_dropdown ("day_"+b+"_name","day_"+a+"_"+b) ; + delete_operator_dropdown ("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_2") ; + + if (!\$("#selectCustom_operator_"+a+"_"+b).val() && def_val) { + \$("#selectCustom_operator_"+a+"_"+b).val(def_val) ; + \$("#selectCustom_operator_"+a+"_"+b).trigger("chosen:updated") ; + } + } + } else if (nr_of_active_days > 10) { + + if (\$("#day_names_"+a+"_extra_1").is(":hidden")) { + \$("#day_names_"+a+"_extra_1").show() ; + } + if (\$("#day_names_"+a+"_extra_2").is(":hidden")) { + \$("#day_names_"+a+"_extra_2").show() ; + } + \$("#system_name_row_"+a+"_extra_1").show() ; + \$("#system_name_row_"+a+"_extra_2").show() ; + + let used_dates = 0 ; + + for (let b=1;b<=date_counter;b++) { + + // if (used_dates <= 10) { + + let def_val = 0 ; + def_val = \$("#selectCustom_operator_"+a+"_"+b).val() ; + + if (used_dates < 10 && \$("#day_"+b).val()) { + + used_dates++ ; + add_operator_dropdown("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,0) ; + select_chosen_ids_1 = select_chosen_ids_1+",#selectCustom_operator_"+a+"_"+b ; + select_chosen_ids_2 = select_chosen_ids_2+",#selectCustom_operator_"+a+"_"+b+"_chosen" ; + delete_operator_dropdown ("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_2") ; + \$("#day_"+b+"_name_"+a+"_extra_2 label.control-label").text(dates_map[b]) ; + + } else if (!\$("#day_"+b).val() && dates_map[b]) { + add_operator_dropdown("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,1) ; + select_chosen_ids_1 = select_chosen_ids_1+",#selectCustom_operator_"+a+"_"+b ; + select_chosen_ids_2 = select_chosen_ids_2+",#selectCustom_operator_"+a+"_"+b+"_chosen" ; + hide_non_empty_operator_dropdown("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_2") ; + } else if (\$("#day_"+b).val() && used_dates == 10) { + add_operator_dropdown("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_2","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,0) ; + delete_operator_dropdown ("day_"+b+"_name_"+a+"_extra_1","day_"+a+"_"+b+"_extra_1") ; + select_chosen_ids_1 = select_chosen_ids_1+",#selectCustom_operator_"+a+"_"+b ; + select_chosen_ids_2 = select_chosen_ids_2+",#selectCustom_operator_"+a+"_"+b+"_chosen" ; + } + + delete_operator_dropdown ("day_"+b+"_name","day_"+a+"_"+b) ; + + if (!\$("#selectCustom_operator_"+a+"_"+b).val() && def_val) { + \$("#selectCustom_operator_"+a+"_"+b).val(def_val) ; + \$("#selectCustom_operator_"+a+"_"+b).trigger("chosen:updated") ; + } + + // if (\$("#day_"+a+"_"+b+"_extra_2").html()) { + // \$("#day_"+a+"_"+b+"_extra_2").html('') ; + // \$("#day_"+a+"_"+b+"_extra_2").removeClass('col-md-1').addClass('col-md-0') ; + // \$("#day_"+a+"_"+b+"_extra_2").css("display","none") ; + // } + + // } + + // else { + + // if (\$("#day_"+b).val()) { + + // add_operator_dropdown("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_1","custom_operator_"+a+"_"+b,"selectCustom_operator_"+a+"_"+b,dates_map[b],a,0) ; + + // } else if (!\$("#day_"+b).val() && dates_map[b]) { + // hide_non_empty_operator_dropdown("day_"+b+"_name_"+a+"_extra_2","day_"+a+"_"+b+"_extra_2") ; + // } + + // } + } + } + } + + } + + \$("#inputQty").val(count_days) ; + + \$("#timepickerTime_to_"+date_counter).css("display","none"); + + // console.log("date_counter : "+date_counter) ; + + if (date_counter <= 20) { + for (let j=date_counter+1;j<=20;j++) { + for (let k=1; k<=15; k++) { + if (\$("input[name='clicked_button_"+k+"']").val()) { + if ( \$("#day_"+k+"_"+j).html()) { + \$("#day_"+k+"_"+j).html('') ; + \$("#day_"+k+"_"+j).removeClass('col-md-1').addClass('col-md-0') ; + \$("#day_"+k+"_"+j).hide() ; + } + // delete_operator_dropdown("day_"+j+"_name_"+k,"day_"+k+"_"+j) ; + delete_operator_dropdown("day_"+j+"_name_"+k+"_extra_1","day_"+k+"_"+j+"_extra_1") ; + delete_operator_dropdown("day_"+j+"_name_"+k+"_extra_2","day_"+k+"_"+j+"_extra_2") ; + } + } + if (\$("#day_"+j).val()) { + \$("#day_"+j).val("").trigger("chosen:updated") ; changed_nr_of_days = 1 ; + } + if (!\$("#day_"+j+"_chosen").is(":hidden")) { + \$("#day_"+j+"_name label.control-label").text('') ; + \$("#day_"+j+"_name").css("display","none") ; + \$("#radio_"+j+"_1").css("display","none") ; + \$("#radio_"+j+"_2").css("display","none") ; + \$("#day_"+j+"_chosen").css("display","none") ; + // console.log("col : "+j) ; + } + if (!\$("#timepickerTime_from_"+j).is(":hidden")) { + \$("#timepickerTime_from_"+j).css("display","none") ; + } + if (!\$("#timepickerTime_to_"+j).is(":hidden")) { + \$("#timepickerTime_to_"+j).css("display","none") ; + } + + } + } + + + if (changed_radio_cnt || changed_nr_of_days) { + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days() ; + } + + + \$(names_to_display).removeClass('col-md-0').addClass('col-md-1'); + \$(names_to_display).show() ; + \$(select_chosen_ids_1).chosen({allow_single_deselect:true}) ; + \$(select_chosen_ids_2).css("width","100%") ; + + // // // for (let k=1;k<=50;k++) { + // // // if (\$("#selectDescription_workings_event_"+k).val() == 14) { + // // // \$("#inputQty_workings_event"+k).val(0) ; + // // // let ttl_amnt = 0 ; + // // // \$("#inputAmount_workings_event"+k).val(ttl_amnt.toFixed(2)) ; + // // // } + // // // } + // // // calcAllWorkings() ; + + // // // for (let k=1;k<=50;k++) { + // // // if (\$("#selectDescription_workings_event"+k).val() == 14) { + // // // let inp_qty = differenceDays ; + // // // \$("#inputQty_workings_event"+k).val(inp_qty) ; + // // // let amnt = \$("#inputAmount_usd_workings_event"+k).val() ; + // // // let ttl_amnt = amnt*inp_qty ; + // // // \$("#inputAmount_workings_event"+k).val(ttl_amnt.toFixed(2)) ; + // // // } + // // // } + // // // if ($changed_opid_as_level_3) { + // // // calc_hidden_totals() ; + // // // } else { + // // // calcAllWorkings() ; + // // // } + + // \$("#day_4_name_1_extra_1").css("display","none") ; + + if (hide_date_names != "#1") { + \$(hide_date_names).css("display","none") ; + } + + } + + + + + function timeStringToSeconds(timeString) { + + const [hours, minutes, seconds] = timeString.split(':').map(Number); + return hours * 3600 + minutes * 60 + seconds; + } + + function getDatesBetween(startDateStr,endDateStr,count_dates) { + if (!startDateStr || !endDateStr) { + return ; + } + const dates = []; + let currentDate = new Date(startDateStr); + let endDate = new Date(endDateStr) ; + // currentDate.setHours(currentDate.getHours() + 2); + // endDate.setHours(endDate.getHours() + 2); + currentDate.setHours(+2); + currentDate.setMinutes(0); + currentDate.setSeconds(0); + endDate.setHours(+2); + endDate.setMinutes(59); + endDate.setSeconds(59); + + // console.log("2 . currentDate : "+currentDate.toISOString().split('T')[0]) ; + while (currentDate < endDate) { + // console.log("3 . currentDate : "+currentDate.toISOString().split('T')[0]) ; + dates.push(currentDate.toISOString().split('T')[0]); + currentDate.setDate(currentDate.getDate() + 1); + if (count_dates) { count_dates++ ; } + } + if (count_dates) { + count_dates-- ; + return count_dates; + } else { + return dates; + } + } + ~ ; + + &event_tabs_content_box($sec_name,$sec_col); + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + + if ($tab == 3) { # Event Specifics + + # --------------- START DOCUMENT UPLOADS ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + my $sec = '_event_specifics' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $add_form_fields = '' ; + + my %selected_1 = () ; my %selected_2 = () ; + + &db_min_ro('event_quotes_categories','*','','','') ; + + $selected_1{$db{$table}{$id}{category_id_1}} = 'SELECTED' ; + $selected_2{$db{$table}{$id}{category_id_2}} = 'SELECTED' ; + my $none_id = 0 ; + + foreach (sort {$db{event_quotes_categories}{$a}{category} cmp $db{event_quotes_categories}{$b}{category}} keys %{$db{event_quotes_categories}}) { + + if ($db{event_quotes_categories}{$_}{category} eq 'None') { + $none_id = $_ ; + next ; + } + $opts{category_id_2} .= qq~~ ; + $opts{category_id_1} .= qq~~ ; + } + $opts{category_id_2} .= qq~~ ; + $opts{category_id_1} .= qq~~ ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + $fcol = 8 ; $lcol = 3 ; + + my @cat_details = split('\|;\|',$db{event_quotes_min}{$id}{category_details}) ; + + $preferred_title{category_1_details} = "Category 1 Sub Categories" ; + $preferred_title{category_2_details} = "Category 2 Sub Categories" ; + + # $add_form_fields .= &common_min_form_input('poc_name',$db{$table}{$id}{poc_name},'') ; + # $add_form_fields .= &common_min_form_input('poc_contact_nr',$db{$table}{$id}{poc_contact_nr},'') ; + + # $db{$table}{$id}{poc_id} = 1 ; + + &db_min_ro('event_quotes_poc','id,name,contact_nr',"",'','') ; + + my %seen; + my @unique_keys = grep { + my $name = $db{event_quotes_poc}{$_}{name}; + !$seen{$name}++ + } sort { + $db{event_quotes_poc}{$a}{name} cmp $db{event_quotes_poc}{$b}{name} + } keys %{$db{event_quotes_poc}}; + + $opts{poc_name} = qq~~ ; + + my $len = scalar @unique_keys ; + + $opts{poc_name} =~ s/value="$db{event_quotes_poc}{$db{$table}{$id}{poc_id}}{name}"/value="$db{event_quotes_poc}{$db{$table}{$id}{poc_id}}{name}" SELECTED/g if $db{$table}{$id}{poc_id} ; + + my @filtered = grep { + $db{event_quotes_poc}{$_}{name} eq $db{event_quotes_poc}{$db{$table}{$id}{poc_id}}{name} + } keys %{$db{event_quotes_poc}}; + + $opts{poc_contact_nr} = qq~~ ; + + $opts{poc_contact_nr} =~ s/value='$db{event_quotes_poc}{$db{$table}{$id}{poc_id}}{contact_nr}'/value='$db{event_quotes_poc}{$db{$table}{$id}{poc_id}}{contact_nr}' SELECTED/g if $db{event_quotes_poc}{$db{$table}{$id}{poc_id}}{contact_nr} ; + + $dlg{poc_name} .= qq~
    ~ ; + + my $add_poc_contact_nr_style = (!$db{$table}{$id}{poc_id} || ($db{event_quotes_poc}{$db{$table}{$id}{poc_id}}{name} && !$db{event_quotes_poc}{$db{$table}{$id}{poc_id}}{contact_nr})) ? "style='display:none;'" : "" ; + + $dlg{poc_contact_nr} .= qq~
    ~ unless $db{event_quotes_poc}{$db{$table}{$id}{poc_id}}{contact_nr} ; + + $add_form_fields .= &common_min_form_select('poc_name',$db{$table}{$id}{poc_name}) ; + $add_form_fields .= &common_min_form_select('poc_contact_nr',$db{$table}{$id}{poc_contact_nr}) ; + $add_form_fields .= qq~~ ; + + $trigger_jquery .= qq~ + \$("#selectPoc_name_chosen,#selectPoc_contact_nr_chosen").css("width","100%") ; + ~ ; + + $trigger_jquery_raw .= qq~ + \$("#selectPoc_name").change( async function () { + var vid = \$("#selectPoc_contact_nr") ; + vid.empty() ; + vid.append("").trigger("chosen:updated") ; + let sel_val = \$(this).val() ; + var url = "$useropts{scripts}/get/get_poc_contact_nr.pl?poc_name="+sel_val ; + console.log("url : "+url) ; + let nrs_cnt = 0 ; let def_val = "" ; let disp_val = "" ; let poc_id = 0 ; + await \$.get(url, function(json) { + \$.each(json, function(key, data) { + disp_val = data.contact_nr ; + disp_val = disp_val.toString() ; + if (disp_val.length === 11 && disp_val.match(/^27/)) { + disp_val = `+27 \${disp_val.slice(2, 4)} \${disp_val.slice(4, 7)} \${disp_val.slice(7)}` + } + vid.append("").trigger("chosen:updated") ; + if (data.contact_nr) { + nrs_cnt++ ; + } + def_val = data.contact_nr ; + poc_id = data.id ; + }) ; + },'json') ; + if (nrs_cnt == 1) { + vid.val(def_val).trigger("chosen:updated") ; + \$("input[name='poc_id']").val(poc_id) ; + } else { + \$("input[name='poc_id']").val("") ; + } + if (\$(this).val() && nrs_cnt == 0 && \$("#add_poc_contact_nr").is(":hidden")) { + \$("#add_poc_contact_nr").show() ; + } else if (!\$("#add_poc_contact_nr").is(":hidden")) { + \$("#add_poc_contact_nr").hide() ; + } + + }) ; + ~ ; + + $add_form_fields .= &common_min_form_select('category_id_1',$db{$table}{$id}{category_id_1},'') ; + $add_form_fields .= &common_min_form_textarea('category_1_details',$cat_details[0],'') ; + $add_form_fields .= &common_min_form_select('category_id_2',$db{$table}{$id}{category_id_2},'') ; + $add_form_fields .= &common_min_form_textarea('category_2_details',$cat_details[1],'') ; + + $trigger_jquery .= qq~\$("#selectCategory_id_1\_chosen").css( "width", "100%" );~ ; + $trigger_jquery .= qq~\$("#selectCategory_id_2\_chosen").css( "width", "100%" );~ ; + + $preferred_title{format_of_title} = "Format of TITLE to be followed when scheduling events" ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= &common_min_form_input('recipient_name',$db{$table}{$id}{recipient_name},'') ; + $add_form_fields .= &common_min_form_input('recipient_nr',$db{$table}{$id}{recipient_nr},'') ; + $add_form_fields .= &common_min_form_textarea('additional_notes',$db{$table}{$id}{additional_notes},'') ; + $add_form_fields .= &common_min_form_textarea('format_of_title',$db{$table}{$id}{format_of_title},'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + my @docs = ('1','2','3') ; + + $add_form_fields .= qq~ +
     
    +
    + ~ ; + + foreach (@docs) { + my $doc = lc $_ ; $doc =~ s/ /\_/ ; $doc =~ s/&/\_/ ; + $working_uploads = &common_get_field_uploads($id,"upload_$doc",'id') ; + if ($working_uploads) { + $add_form_fields .= qq~ +
    + $working_uploads +
    ~; + } else { + $add_form_fields .= qq~ +
    +
    + + +

    Upload file from PC.

    +
    +
    + ~; + } + } + + $add_form_fields .= qq~ +
    + ~ ; + + &event_tabs_content_box($sec_name,$sec_col); + + # --------------- END DOCUMENT UPLOADS ---------------------------------------------------------------------------------------------------------------- + } + + if ($tab == 4) { # Costing + + # --------------- START COSTING ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + $lcol = 1; + $fcol = 2; + $preferred_title{currency} = 'Currency' ; + $add_form_fields .= &common_min_form_select('currency',$db{$table}{$id}{currency},1) ; # don't end row + $trigger_jquery .= qq~\$("#selectCurrency_chosen").css( "width", "96%" );~ ; + $preferred_title{roe} = ' ROE ' ; $fcol=1; # $fcol=2 ; + $add_form_fields .= &common_min_form_label_col('roe') ; + $db{$table}{$id}{roe} = 1 if not $db{$table}{$id}{roe} ; + $add_form_fields .= &common_min_form_input_col('roe',$db{$table}{$id}{roe},1) ; + # $preferred_title{roe} = ' Discount ' ; + # $add_form_fields .= &common_min_form_label_col('discount') ; + # $add_form_fields .= &common_min_form_select_col('discount',$db{$table}{$id}{discount}) ; + $trigger_jquery .= qq~\$("#selectDiscount_chosen").css( "width", "96%" );~ ; + $add_form_fields .= qq~
    ~ ; + + our %sec_cnt = ('a_event' => "30-List Event Costings"); + + my $sec = 'costing' ; + my ($sec_name, $sec_cnt, $sec_col) = &tab_sec_det($sec) ; + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret; + + &event_tabs_build_sec($sec,$tab) ; + + foreach (sort keys %sec_cnt) { + $_k = substr($_, 1) ; + my @parts = split(/\-/, $sec_cnt{$_}) ; + $add_form_fields .= qq~ +
    +
    +

    + $parts[1] : +

    +
    +
    + ~ ; + &tab_build_qt_col_headers("$sec$_k"); + # # # &db_min_ro('event_quotes_min','id,excl_costing_event,item_costing_event,qty_costing_event,usd_amnt_costing_event,item_ttl_costing_event,vat_costing_event,curr_amnt_costing_event',"id=$id",'','') if $id ; + &event_tabs_build_costs_forms($id,$tab,$parts[0],"$sec$_k"); + } + + $add_form_fields .= qq~ +
    +
    +   +
    +
    ~ ; + $add_form_fields .= qq~ +
    +
    +   +
    + ~ ; + + my @ttlarr = ("sub_total","vat_total","grand_total") ; + $lcol = 1 ; + $fcol = 1 ; + foreach (@ttlarr) { + $lcol = 1 ; $add_form_fields .= &common_min_form_label_col($_) ; + } + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $lcol = 2 ; + $add_form_fields .= &common_min_form_label_col('Total') ; + $lcol = 1 ; $fcol = 1 ; + + foreach (@ttlarr) { + $readonly{"$_\_costing_event"} = "READONLY" ; + $input_style{"$_\_costing_event"} = qq~style="text-align:right;"~ ; + my $val = $db{$table}{$id}{$_} ? $db{$table}{$id}{$_} : '0.00' ; + $add_form_fields .= &common_min_form_input_col("$_\_costing_event",$val) ; + } + + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= qq~ +
    +
    +   +
    +
    + ~ ; + + &event_tabs_content_box($sec_name,$sec_col); + + my $display_hidden_input = ($username eq 'handre') ? "" : "style='display:none;'" ; + + $trigger_jquery_raw .= qq~ + + function count_nr_of_full_day_and_half_days () { + + let full_day_exists = 0 ; let half_day_exists = 0 ; + + console.log("count_nr_of_full_day_and_half_days") ; + + for (let i = 1; i<=20; i++) { + if (\$("#radio_"+i+"_1").is(":checked") && \$("#day_"+i).val()) { + full_day_exists++ ; + } else if (\$("#radio_"+i+"_2").is(":checked") && \$("#day_"+i).val()) { + half_day_exists++ ; + } + } + + console.log("full_day_exists : "+full_day_exists) ; + + return [full_day_exists,half_day_exists] ; + + } + + function cnt_selected_systems_per_cost_item () { + + let i = 0 ; + cnt_systems_per_cost_item = {} ; + while (true) { + i++ ; + + let system_id = \$("#selectSystem_name_"+i).val() ; + + if (!cnt_systems_per_cost_item[get_event_cost_id[system_id]]) { + cnt_systems_per_cost_item[get_event_cost_id[system_id]] = 0 ; + } + if (!\$("#system_name_row_"+i).html()) { + i-- ; + break ; + } + if (system_id && get_event_cost_id[system_id]) { + cnt_systems_per_cost_item[get_event_cost_id[system_id]]++ ; + } + } + } + + function auto_deselect_cost_items_in_quote_tab (row_nr) { + + let orig_system_id = orig_selected_system_names[row_nr] ; + let orig_cost_item = get_event_cost_id[orig_system_id] ; // Check whether get_event_cost_id exists + + if (!orig_system_id || (orig_system_id && !orig_cost_item)) { + return ; + } + let i = 0 ; + // Chech if the corresponding cost item exists for a diffent selected system + + while (true) { + i++ ; + if (!\$("#system_name_row_"+i).html()) { + break ; + } + if (i == row_nr) { + continue ; + } + if (orig_cost_item == get_event_cost_id[\$("#selectSystem_name_"+i).val()]) { + return ; + } + } + + i = 0 ; let j = 0 ; let select_new_values = {} ; let input_new_values = {} ; let checkbox_new_values = {} ; + + while (true) { + + i++ ; j++ ; + if (!\$("#costing_event_"+i).html()) { + i-- ; j-- ; + break ; + } + + let hidden_input = (\$("input[name='added_full_day_cost_item_"+i+"']").val()) ? \$("input[name='added_full_day_cost_item_"+i+"']").val() : (\$("input[name='added_half_day_cost_item_"+i+"']").val()) ? \$("input[name='added_full_day_cost_item_"+i+"']").val() : "" ; + + if (hidden_input.includes("-1") || hidden_input.includes("-2")) { + continue ; + } + + if (orig_cost_item == \$("#selectDescription_costing_event_"+i).val()) { + + j-- ; + \$("#selectDescription_costing_event_"+i).val("").trigger("chosen:updated") ; + \$("#inputQty_costing_event_"+i).val("") ; + \$("#inputAmount_usd_costing_event_"+i).val("") ; + + // calc_totals(i,"costing_event") ; + } else { + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = \$("input[name='qty_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; ; + input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = \$("input[name='amount_ttl_costing_event_"+i+"']").val() ; ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + } + + if (i != j) { + \$("input[name='added_full_day_cost_item_"+i+"']").remove() ; + \$("input[name='added_half_day_cost_item_"+i+"']").remove() ; + } + + } + + for (let key in select_new_values) { + console.log("select_new_values : "+key) ; + if (select_new_values[key] != \$(key).val()) { + \$(key).val(select_new_values[key]).trigger("chosen:updated") ; + } + } + + for (let key in input_new_values) { + if (typeof \$(key).val() == 'undefined' && input_new_values[key]) { + let display = (hidden_input_name[key].includes("_day_cost_item_")) ? "" : "" ; + \$(hidden_input_to_html_row[key]).append("") ; + } + + if (input_new_values[key] != \$(key).val()) { + \$(key).val(input_new_values[key]) ; + } + } + + for (let key in checkbox_new_values) { + if (\$(key).is(":checked") && !checkbox_new_values[key]) { + \$(key).prop("checked",false) ; + } else if (!\$(key).is(":checked") && checkbox_new_values[key]) { + \$(key).prop("checked",true) ; + } + } + + if (j < i) { + for (let k=j+1;k<=i+1;k++) { + if ((j == 0 && k > 1) || j > 0) { + \$("#costing_event_"+k).html("") ; + } + if ((k == j+1 && j > 0) || (j == 0 && k == 2)) { + console.log("SHOW : #btn_row_costing_event_"+k) ; + \$("#btn_row_costing_event_"+k).show() ; + \$("#btn_costing_event_"+k).show() ; + } else if (j > 0 || (j == 0 && k > 2)) { + console.log("HIDE : #btn_row_costing_event_"+k) ; + \$("#btn_row_costing_event_"+k).hide() ; + \$("#btn_costing_event_"+k).hide() ; + } + } + } + + } + + function auto_select_cost_items_in_quote_tab (id,row_number) { + + cnt_selected_systems_per_cost_item() ; + + let system_id = \$("#"+id).val() ; + + let row_nr = (row_number) ? row_number : get_row_nr(id) ; + + if (orig_selected_system_names[row_nr] && get_event_cost_id[orig_selected_system_names[row_nr]] != get_event_cost_id[system_id]) { + auto_deselect_cost_items_in_quote_tab(row_nr) ; + } + + let event_cost_id = get_event_cost_id[system_id] ; + + let i = 0 ; + + if (!event_cost_id) { + + while (true) { + i++ ; + if (!\$("#costing_event_"+i).html()) { + break ; + } + if (\$("#selectDescription_costing_event_"+i).val() && \$("#selectDescription_costing_event_"+i).val() == get_event_cost_id[orig_selected_system_names[row_nr]] && i != row_nr) { + event_cost_id = get_event_cost_id[orig_selected_system_names[row_nr]] ; + } + } + + if (!event_cost_id) { + orig_selected_system_names[row_nr] = \$("#selectSystem_name_"+row_nr).val() ; + return ; + } + + } else if (event_cost_id && get_event_cost_id[orig_selected_system_names[row_nr]] && get_event_cost_id[orig_selected_system_names[row_nr]] != event_cost_id) { + + while (true) { + i++ ; + if (!\$("#costing_event_"+i).html()) { + break ; + } + if (\$("#selectDescription_costing_event_"+i).val() && \$("#selectDescription_costing_event_"+i).val() == get_event_cost_id[orig_selected_system_names[row_nr]]) { + + let hidden_input_val = (\$("input[name='added_full_day_cost_item_"+i+"']").val()) ? \$("input[name='added_full_day_cost_item_"+i+"']").val() : (\$("input[name='added_half_day_cost_item_"+i+"']").val()) ? \$("input[name='added_half_day_cost_item_"+i+"']").val() : "" ; + if (hidden_input_val && !hidden_input_val.includes("-2")) { + let hidden_input_fh = (\$("input[name='added_full_day_cost_item_"+i+"']").val()) ? "full" : (\$("input[name='added_half_day_cost_item_"+i+"']").val()) ? "half" : "" ; + if (hidden_input_fh) { + \$("#inputQty_costing_event_"+i).val(nr_days[hidden_input_fh]*cnt_systems_per_cost_item[get_event_cost_id[orig_selected_system_names[row_nr]]]) ; + calc_totals(i,"costing_event") ; + } + } + + } + } + } + + orig_selected_system_names[row_nr] = \$("#selectSystem_name_"+row_nr).val() ; + + let default_full_day_cost_item_rate = default_cost_item_rates["full,"+event_cost_id] ; + let default_half_day_cost_item_rate = default_cost_item_rates["half,"+event_cost_id] ; + + if (!default_full_day_cost_item_rate && !default_half_day_cost_item_rate) { + return ; + } + + if (!nr_days["full"] && !nr_days["half"]) { + return ; + } + + if (nr_days["full"] && !default_full_day_cost_item_rate && !nr_days["half"] && default_half_day_cost_item_rate) { + return ; + } + + if (!nr_days["full"] && default_full_day_cost_item_rate && nr_days["half"] && !default_half_day_cost_item_rate) { + return ; + } + + let last_used_row = 0 ; i = 0 ; let cnt_systems = cnt_systems_per_cost_item[event_cost_id] ; + + if (\$("#costing_event_1").html() && !\$("#costing_event_2").html() && !\$("#selectDescription_costing_event_1").val()) { + last_used_row = 0 ; + } else { + + let nr_of_blank_rows_needed = (nr_days["full"] && nr_days["half"]) ? 2 : 1 ; + + while (true) { + i++ ; + let j = 1 + i ; + if (\$("#selectDescription_costing_event_"+i).val() && \$("#selectDescription_costing_event_"+i).val() != event_cost_id) { + last_used_row = i ; + console.log(" 5.1 last_used_row : "+last_used_row) ; + } else if (\$("#costing_event_"+i).html() && \$("#selectDescription_costing_event_"+i).val() && \$("#selectDescription_costing_event_"+i).val() == event_cost_id) { + last_used_row = i - 1 ; + break ; + } else if ((!\$("#selectDescription_costing_event_"+i).val() && nr_of_blank_rows_needed == 1) || (nr_of_blank_rows_needed == 2 && !\$("#selectDescription_costing_event_"+i).val() && !\$("#selectDescription_costing_event_"+j).val())) { + i-- ; + break ; + } + } + } + + let full_half_loop = (nr_days["full"] && nr_days["half"]) ? ["full","half"] : (nr_days["full"]) ? ["full"] : (nr_days["half"]) ? ["half"] : [] ; + + let = f_t_h = {"full":"half","half":"full"} ; + + i = 0 ; let j = 0 ; last_used_row++ ; let need_to_shift_data_below_down = 0 ; let select_new_values = {} ; let input_new_values = {} ; let checkbox_new_values = {} ; let hidden_input_to_html_row = {} ;let hidden_input_name = {} ; let add_html_row = {} ; let already_moved_this_row = {} ; let break_loop = 0 ; let cals_totals_row = {} ; + + while (true) { + + i++ ; j++ ; + + if (last_used_row > i) { + continue ; + } + + let k = last_used_row ; + + if (j > i && \$("#selectDescription_costing_event_"+i).val() && !already_moved_this_row[i]) { + + need_to_shift_data_below_down = 1 ; + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = \$("input[name='qty_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = \$("input[name='amount_ttl_costing_event_"+i+"']").val() ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + let hidden_input_value = (\$("input[name='added_full_day_cost_item_"+i+"']").val()) ? "full" : (\$("input[name='added_half_day_cost_item_"+i+"']").val()) ? "half" : "" ; + if (hidden_input_value && hidden_input_value != "") { + input_new_values["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = \$("input[name='added_"+hidden_input_value+"_day_cost_item_"+i+"']").val() ; + hidden_input_to_html_row["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = "added_"+hidden_input_value+"_day_cost_item_"+j ; + \$("input[name='added_"+hidden_input_value+"_day_cost_item_"+i+"']").remove() ; + } + + if (!\$("#costing_event_"+j).html()) { + add_html_row[j] = 1 ; + } + cals_totals_row[j] = 1 ; + + } + + if (i == last_used_row) { + + for (let f_h in full_half_loop) { + + let default_rate = (full_half_loop[f_h] == "full") ? default_full_day_cost_item_rate : default_half_day_cost_item_rate ; + + if (nr_days[full_half_loop[f_h]] && default_rate) { + + i++ ; j++ ; + if (f_h == 0 && full_half_loop[1] && \$("#selectDescription_costing_event_"+i).val() && \$("#selectDescription_costing_event_"+i).val() != event_cost_id) { + + j++ ; + already_moved_this_row[i] = 1 ; + need_to_shift_data_below_down = 1 ; + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = \$("input[name='qty_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = \$("input[name='amount_ttl_costing_event_"+i+"']").val() ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + let hidden_input_value = (\$("input[name='added_full_day_cost_item_"+i+"']").val()) ? "full" : (\$("input[name='added_half_day_cost_item_"+i+"']").val()) ? "half" : "" ; + if (hidden_input_value && hidden_input_value != "") { + input_new_values["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = \$("input[name='added_"+hidden_input_value+"_day_cost_item_"+i+"']").val() ; + hidden_input_to_html_row["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+hidden_input_value+"_day_cost_item_"+j+"']"] = "added_"+hidden_input_value+"_day_cost_item_"+j ; + \$("input[name='added_"+hidden_input_value+"_day_cost_item_"+i+"']").remove() ; + } + cals_totals_row[j] = 1 ; + } + i-- ; j-- ; + + if (!\$("#costing_event_"+k).html()) { + add_quote_expenses_row_all("costing_event_"+k,"costing_event") ; + \$("#selectDescription_costing_event_"+k+"_chosen").css("width","90%") ; + \$("#costing_event_"+k).append("") ; + break_loop = 1 ; + } else if (\$("#costing_event_"+k).html() && typeof \$("input[name='added_"+full_half_loop[f_h]+"_day_cost_item_"+k+"']").val() == 'undefined') { + \$("#costing_event_"+k).append("") ; + \$("input[name='added_"+f_t_h[full_half_loop[f_h]]+"_day_cost_item_"+k+"']").remove() ; + } else { + \$("input[name='added_"+full_half_loop[f_h]+"_day_cost_item_"+k+"']").val(event_cost_id) ; + } + + \$("#selectDescription_costing_event_"+k).val(event_cost_id).trigger("chosen:updated") ; + \$("#inputQty_costing_event_"+k).val(nr_days[full_half_loop[f_h]]*cnt_systems) ; + \$("#inputAmount_usd_costing_event_"+k).val(default_rate) ; + calc_totals(k,"costing_event") ; + + k++ ; + + } + } + } + + if (!\$("#costing_event_"+i).html() || break_loop) { + i-- ; j-- ; + break ; + } + + } + + if (need_to_shift_data_below_down) { + + for (let row_nr in add_html_row) { + add_quote_expenses_row_all("costing_event_"+row_nr,"costing_event") ; + \$("#selectDescription_costing_event_"+row_nr+"_chosen").css("width","90%") ; + } + + for (let key in select_new_values) { + if (select_new_values[key] != \$(key).val()) { + \$(key).val(select_new_values[key]).trigger("chosen:updated") ; + } + } + + for (let key in input_new_values) { + if (typeof \$(key).val() == 'undefined' && input_new_values[key]) { + let display = (hidden_input_name[key].includes("_day_cost_item_")) ? "" : "" ; + \$(hidden_input_to_html_row[key]).append("") ; + } + if (input_new_values[key] != \$(key).val()) { + \$(key).val(input_new_values[key]) ; + } + } + + for (let key in checkbox_new_values) { + if (\$(key).is(":checked") && !checkbox_new_values[key]) { + \$(key).prop("checked",false) ; + } else if (!\$(key).is(":checked") && checkbox_new_values[key]) { + \$(key).prop("checked",true) ; + } + } + + for (let key in cals_totals_row) { + calc_totals(key,"costing_event") ; + } + + if (j > i) { + for (let k=i+1;k<=j;k++) { + \$("#costing_event_"+k).show() ; + \$("#btn_row_costing_event_"+k).hide() ; + \$("#btn_costing_event_"+k).hide() ; + } + let k = j+1 ; + \$("#btn_row_costing_event_"+k).show() ; + \$("#btn_costing_event_"+k).show() ; + } + + // let [sub_total,vat_total] = add_up_totals ("costing_event",j,\$("input[name='roe']").val(),0) ; + // \$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; + // update_overall_totals(sub_total,vat_total,"costing_event") ; + + } + } + + \$("#content").on("change","[id^='radio_']", function () { + + // [nr_days["full"],nr_days["half"]] = count_nr_of_full_day_and_half_days() ; + update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days () ; + + }) ; + + function update_qty_in_quote_tab_when_changing_nr_of_full_or_half_days () { + + [nr_days["full"],nr_days["half"]] = count_nr_of_full_day_and_half_days() ; + + let opp_add = {"full":"half","half":"full"} ; + + let i = 0 ; let j = 0 ; let select_new_values = {} ; let input_new_values = {} ; let checkbox_new_values = {} ; + + if (!prev_nr_days["full"] && !prev_nr_days["half"] && (nr_days["full"] || nr_days["half"])) { + // return ; + } + + let add = + (!prev_nr_days["full"] && !prev_nr_days["half"] && nr_days["full"]) ? "blank_full" : + (!prev_nr_days["half"] && !prev_nr_days["full"] && nr_days["half"]) ? "blank_half" : + (!prev_nr_days["full"] && nr_days["full"]) ? "full" : + (!prev_nr_days["half"] && nr_days["half"]) ? "half" : + "" ; + + let remove = + (prev_nr_days["full"] && !nr_days["full"]) ? "full" : + (prev_nr_days["half"] && !nr_days["half"]) ? "half" : + "" ; + + let change = + (prev_nr_days["full"] != nr_days["full"] && prev_nr_days["half"] != nr_days["half"] && prev_nr_days["full"] && nr_days["full"] && prev_nr_days["half"] && nr_days["half"]) ? "both" : + (prev_nr_days["full"] && nr_days["full"] && prev_nr_days["full"] != nr_days["full"]) ? "full" : + (prev_nr_days["half"] != nr_days["half"] && prev_nr_days["half"] && nr_days["half"]) ? "half" : + "" ; + + let hidden_input_to_html_row = {} ; let hidden_input_name = {} ; let add_html_row = {} ; let remove_input = {} ; let cals_totals_row = {} ; + + while (true) { + + i++ ; j++ ; + + if (!\$("#costing_event_"+i).html()) { + i-- ; j-- ; + break ; + } + + let added_full_cost_item = \$("input[name='added_full_day_cost_item_"+i+"']").val() ; + let added_half_cost_item = \$("input[name='added_half_day_cost_item_"+i+"']").val() ; + + let event_cost_id = (added_full_cost_item) ? added_full_cost_item : (added_half_cost_item) ? added_half_cost_item : "" ; + + let event_cost_id_extract = (event_cost_id.includes("_")) ? get_row_nr(event_cost_id) : event_cost_id ; + + let added = (added_full_cost_item) ? "full" : (added_half_cost_item) ? "half" : "" ; + + if ((added && add && added == add) || (add == "blank_full" && add == "full") || (add == "blank_half" && add == "half")) { + continue ; + } + + let do_not_remove_this_row = (event_cost_id.includes("-1") || event_cost_id.includes("-2")) ? 1 : 0 ; + + if (event_cost_id && event_cost_id != "") { + + let change_row = (change && (change == added || change == "both")) ? added : 0 ; + + let rate = (event_cost_id.includes("-1")) ? \$("input[name='amount_usd_costing_event_"+i+"']").val() : default_cost_item_rates[added+","+event_cost_id_extract] ; + // let rate = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; + let qty = (event_cost_id.includes("-2")) ? \$("input[name='qty_costing_event_"+i+"']").val() : (!cnt_systems_per_cost_item[event_cost_id_extract]) ? nr_days[added] : nr_days[added]*cnt_systems_per_cost_item[event_cost_id_extract] ; + + if (!qty) { qty = 0 ; } + + if (change_row) { + input_new_values["input[name='qty_costing_event_"+j+"']"] = qty ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = rate ; + // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (qty*rate).toFixed(2) ; + if (i != j) { + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + input_new_values["input[name='added_"+change_row+"_day_cost_item_"+j+"']"] = event_cost_id ; + hidden_input_to_html_row["input[name='added_"+change_row+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+change_row+"_day_cost_item_"+j+"']"] = "added_"+change_row+"_day_cost_item_"+j ; + \$("input[name='added_"+change_row+"_day_cost_item_"+i+"']").remove() ; + } + cals_totals_row[j] = 1 ; + if (!add || event_cost_id.includes("-3")) { + continue ; + } + } + + if (add == "full") { + \$("input[name='added_"+added+"_day_cost_item_"+i+"']").remove() ; + j++ ; + } + + if (i != j && ((add && add != added && added != remove) || (!do_not_remove_this_row && remove && remove != added))) { + + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = qty ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = rate ; + // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (qty*rate).toFixed(2) ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + if (!\$("#costing_event_"+j).html()) { + add_html_row[j] = 1 ; + console.log("add_html_row : "+j) ; + input_new_values["input[name='added_"+added+"_day_cost_item_"+j+"']"] = event_cost_id ; + hidden_input_to_html_row["input[name='added_"+added+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+added+"_day_cost_item_"+j+"']"] = "added_"+added+"_day_cost_item_"+j ; + } + cals_totals_row[j] = 1 ; + + } + + if (add == "half") { + if (i != j) { + \$("input[name='added_full_day_cost_item_"+i+"']").remove() ; + input_new_values["input[name='added_"+added+"_day_cost_item_"+j+"']"] = event_cost_id ; + hidden_input_to_html_row["input[name='added_"+added+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+added+"_day_cost_item_"+j+"']"] = "added_"+added+"_day_cost_item_"+j ; + } + + j++ ; + } + + if (remove && remove == added && !add) { + if (do_not_remove_this_row) { + continue ; + } + j-- ; + \$("#selectDescription_costing_event_"+i).val("").trigger("chosen:updated") ; + \$("input[name='qty_costing_event_"+i+"']").val("") ; + \$("input[name='amount_usd_costing_event_"+i+"']").val("") ; + \$("input[name='amount_ttl_costing_event_"+i+"']").val("") ; + \$("input[name='added_"+remove+"_day_cost_item_"+i+"']").remove() ; + continue ; + } else if (!do_not_remove_this_row && remove && remove == added && add) { + if (add == "half") { + j-- ; + } + \$("input[name='added_"+remove+"_day_cost_item_"+i+"']").remove() ; + } + + let jj = (add == "full") ? j - 1 : (add == "half") ? j : j ; + + if (add) { + if (!\$("#costing_event_"+jj).html()) { + add_html_row[jj] = 1 ; + // console.log("add : "+add) ; + } + if (!do_not_remove_this_row && remove == "half") { + j-- ; + } + + rate = default_cost_item_rates[add+","+event_cost_id_extract] ; + qty = (!cnt_systems_per_cost_item[event_cost_id_extract]) ? nr_days[add] : nr_days[add]*cnt_systems_per_cost_item[event_cost_id_extract] ; + + // select_new_values["#selectDescription_costing_event_"+jj] = \$("#selectDescription_costing_event_"+i).val() ; + select_new_values["#selectDescription_costing_event_"+jj] = event_cost_id_extract ; + input_new_values["input[name='qty_costing_event_"+jj+"']"] = qty ; + input_new_values["input[name='amount_usd_costing_event_"+jj+"']"] = rate ; + // input_new_values["input[name='amount_ttl_costing_event_"+jj+"']"] = (rate*qty).toFixed(2) ; + input_new_values["input[name='added_"+add+"_day_cost_item_"+jj+"']"] = (event_cost_id.includes("-3")) ? "-3_"+event_cost_id_extract : event_cost_id_extract ; + hidden_input_to_html_row["input[name='added_"+add+"_day_cost_item_"+jj+"']"] = "#costing_event_"+jj ; + hidden_input_name["input[name='added_"+add+"_day_cost_item_"+jj+"']"] = "added_"+add+"_day_cost_item_"+jj ; + if (add != added && \$("input[name='added_"+added+"_day_cost_item_"+jj+"']").val()) { + // \$("input[name='added_"+added+"_day_cost_item_"+jj+"']").remove() ; + remove_input["input[name='added_"+added+"_day_cost_item_"+jj+"']"] = 1 ; + } + cals_totals_row[jj] = 1 ; + } + } else if (!event_cost_id && i != j) { + select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+i).val() ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = \$("input[name='qty_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; + input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = \$("input[name='amount_ttl_costing_event_"+i+"']").val() ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = (\$("#checkboxVat_costing_event_"+i).is(":checked")) ? 1 : 0 ; + if (!\$("#costing_event_"+j).html()) { + add_html_row[j] = 1 ; + } + // cals_totals_row[j] = 1 ; + + } else if (!event_cost_id && (add == "blank_full" || add == "blank_half")) { + + let k = j + 1 ; + + if (\$("#selectDescription_costing_event_"+j).val() && !\$("#costing_event_"+k).html()) { + j++ ; + } + + if (!\$("#selectDescription_costing_event_"+j).val()) { + + let ij = 0 ; let add_type = (add == "blank_full") ? "full" : "half" ; + + while (true) { + + ij++ ; + if (!\$("#system_name_row_"+ij).html()) { + break ; + } + + if (default_cost_item_rates[add_type+","+get_event_cost_id[\$("#selectSystem_name_"+ij).val()]]) { + + if (!\$("#costing_event_"+j).html()) { + add_html_row[j] = 1 ; + } else { + \$("#checkboxExcl_costing_event_"+j).prop("checked",false) ; + } + + select_new_values["#selectDescription_costing_event_"+j] = get_event_cost_id[\$("#selectSystem_name_"+ij).val()] ; + input_new_values["input[name='qty_costing_event_"+j+"']"] = nr_days[add_type] ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = default_cost_item_rates[add_type+","+get_event_cost_id[\$("#selectSystem_name_"+ij).val()]] ; + // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (nr_days[add_type]*default_cost_item_rates[add_type+","+get_event_cost_id[\$("#selectSystem_name_"+ij).val()]]).toFixed(2) ; + checkbox_new_values["#checkboxVat_costing_event_"+j] = 1 ; + input_new_values["input[name='added_"+add_type+"_day_cost_item_"+j+"']"] = get_event_cost_id[\$("#selectSystem_name_"+ij).val()] ; ; + hidden_input_to_html_row["input[name='added_"+add_type+"_day_cost_item_"+j+"']"] = "#costing_event_"+j ; + hidden_input_name["input[name='added_"+add_type+"_day_cost_item_"+j+"']"] = "added_"+add_type+"_day_cost_item_"+j ; + cals_totals_row[j] = 1 ; + j++ ; + } + } + j-- ; + break ; + + } + } else if (event_cost_id.includes("-3")) { + + let rate = (event_cost_id.includes("-1")) ? \$("input[name='amount_usd_costing_event_"+i+"']").val() : default_cost_item_rates[added+","+event_cost_id_extract] ; + // let rate = \$("input[name='amount_usd_costing_event_"+i+"']").val() ; + let qty = (event_cost_id.includes("-2")) ? \$("input[name='qty_costing_event_"+i+"']").val() : (!cnt_systems_per_cost_item[event_cost_id_extract]) ? nr_days[added] : nr_days[added]*cnt_systems_per_cost_item[event_cost_id_extract] ; + + if (!qty) { qty = 0 ; } + + input_new_values["input[name='qty_costing_event_"+j+"']"] = qty ; + input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = rate ; + // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (qty*rate).toFixed(2) ; + cals_totals_row[j] = 1 ; + + } + } + + for (let key in remove_input) { + \$(key).remove() ; + } + + for (let row_nr in add_html_row) { + add_quote_expenses_row_all("costing_event_"+row_nr,"costing_event") ; + \$("#selectDescription_costing_event_"+row_nr+"_chosen").css("width","90%") ; + } + + for (let key in select_new_values) { + if (select_new_values[key] != \$(key).val()) { + \$(key).val(select_new_values[key]).trigger("chosen:updated") ; + } + } + + for (let key in input_new_values) { + if (typeof \$(key).val() == 'undefined' && input_new_values[key]) { + let display = (hidden_input_name[key].includes("_day_cost_item_")) ? "" : "" ; + \$(hidden_input_to_html_row[key]).append("") ; + } + if (input_new_values[key] != \$(key).val()) { + \$(key).val(input_new_values[key]) ; + } + } + + for (let key in checkbox_new_values) { + if (\$(key).is(":checked") && !checkbox_new_values[key]) { + \$(key).prop("checked",false) ; + } else if (!\$(key).is(":checked") && checkbox_new_values[key]) { + \$(key).prop("checked",true) ; + } + } + + for (let key in cals_totals_row) { + calc_totals(key,"costing_event") ; + } + + if (remove && !j) { + j++ ; + } + + if (j < i) { + for (let k=j+1;k<=i+1;k++) { + \$("#costing_event_"+k).html("") ; + if (k == j+1) { + \$("#btn_row_costing_event_"+k).show() ; + \$("#btn_costing_event_"+k).show() ; + } else { + \$("#btn_row_costing_event_"+k).hide() ; + \$("#btn_costing_event_"+k).hide() ; + } + } + } else if (j > i) { + for (let k=i+1;k<=j;k++) { + \$("#costing_event_"+k).show() ; + \$("#btn_row_costing_event_"+k).hide() ; + \$("#btn_costing_event_"+k).hide() ; + } + let k = j+1 ; + \$("#btn_row_costing_event_"+k).show() ; + \$("#btn_costing_event_"+k).show() ; + } + + let [sub_total,vat_total] = add_up_totals ("costing_event",j,\$("input[name='roe']").val(),0) ; + \$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; + update_overall_totals(sub_total,vat_total,"costing_event") ; + + prev_nr_days["full"] = nr_days["full"] ; + prev_nr_days["half"] = nr_days["half"] ; + + } + + \$("#content").on("change","[id^='selectSystem_name_']", function () { + + let corresponding_cost_item_exists = ((default_cost_item_rates["full,"+get_event_cost_id[\$(this).val()]] && nr_days["full"]) || (default_cost_item_rates["half,"+get_event_cost_id[\$(this).val()]] && nr_days["half"])) ? 1 : 0 ; + + if (corresponding_cost_item_exists) { + system_with_cost_item_rates_selected = 1 ; + } else if (system_with_cost_item_rates_selected && (!\$(this).val() || (\$(this).val() && !corresponding_cost_item_exists))) { + system_with_cost_item_rates_selected = 0 ; + let ij = 0 ; + while (true) { + ij++ ; + if (!\$("#system_name_row_"+ij).html()) { + break ; + } + if (!\$("#selectSystem_name_"+ij).val()) { + continue ; + } + if ((default_cost_item_rates["full,"+get_event_cost_id[\$("#selectSystem_name_"+ij).val()]] && nr_days["full"]) || (default_cost_item_rates["half,"+get_event_cost_id[\$("#selectSystem_name_"+ij).val()]] && nr_days["half"])) { + system_with_cost_item_rates_selected = 1 ; + } + } + } + + auto_select_cost_items_in_quote_tab(this.id) ; + + }) ; + + // \$("#content").on("change","[id^='selectDescription_']", async function () { + + // let this_id = this.id ; + + // let row_nr = get_row_nr(this_id) ; + + // let tab = (this_id.includes("_costing_event_")) ? "costing_event" : (this_id.includes("_workings_event_")) ? "workings_event" : "" ; + + // // if (!\$("input[name='added_half_day_cost_item_"+row_nr+"']").val() && !\$("input[name='added_half_day_cost_item_"+row_nr+"']")val() && ((nr_days["full"] && default_cost_item_rates["full,"+\$("#"+this_id).val()]) || (nr_days["full"] && default_cost_item_rates["full,"+\$("#"+this_id).val()]))) { + + // // if (nr_days["full"] && default_cost_item_rates["full,"+\$("#"+this_id).val()]) { + + // // "input[name='qty_costing_event_"+j+"']" + + // // } + + + // // if (nr_days["full"] && default_cost_item_rates["full,"+\$("#"+this_id).val()] && nr_days["half"] && default_cost_item_rates["half,"+\$("#"+this_id).val()]) { + + // // let j = row_nr + 1 ; + // // select_new_values["#selectDescription_costing_event_"+j] = \$(this).val() ; + // // input_new_values["input[name='qty_costing_event_"+j+"']"] = nr_days["half"] ; + // // input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = default_cost_item_rates["half,"+\$(this).val()] ; + // // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (nr_days["half"]*default_cost_item_rates["half,"+\$(this).val()]).toFixed(2) ; + // // checkbox_new_values["#checkboxVat_costing_event_"+j] = 1 ; + // // input_new_values["input[name='added_half_day_cost_item_"+j+"']"] = \$(this).val() ; + // // hidden_input_to_html_row["input[name='added_half_day_cost_item_"+j+"']"] = "#costing_half"+add_type+"_day_cost_item_"+j ; + // // \$("input[name='added_full_day_cost_item_"+j+"']").remove() ; + + // // // let ij = j ; + + // // // while (true) { + // // // select_new_values["#selectDescription_costing_event_"+j] = \$("#selectDescription_costing_event_"+j).val() ; + // // // input_new_values["input[name='qty_costing_event_"+j+"']"] = \$("input[name='qty_costing_event_"+j+"']").val() ; + // // // input_new_values["input[name='amount_usd_costing_event_"+j+"']"] = \$("input[name='amount_usd_costing_event_"+j+"']") ; + // // // input_new_values["input[name='amount_ttl_costing_event_"+j+"']"] = (nr_days["half"]*default_cost_item_rates["half,"+\$(this).val()]).toFixed(2) ; + // // // checkbox_new_values["#checkboxVat_costing_event_"+j] = 1 ; + // // // input_new_values["input[name='added_half_day_cost_item_"+j+"']"] = \$(this).val() ; + // // // hidden_input_to_html_row["input[name='added_half_day_cost_item_"+j+"']"] = "#costing_half"+add_type+"_day_cost_item_"+j ; + // // // \$("input[name='added_full_day_cost_item_"+j+"']").remove() ; + // // // } + + // // } + + // // } + + + + // if (\$("input[name='amount_usd_"+tab+"_"+row_nr+"']").val()) { + // // return ; + // } + + // let full_day_exists = nr_days["full"] ; let half_day_exists = nr_days["half"] ; + + // // [full_day_exists,half_day_exists] = count_nr_of_full_day_and_half_days() ; + + // let already_loaded_full_day = (\$("#"+this_id).val()) ? \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val() : "" ; + // let already_loaded_half_day = (\$("#"+this_id).val()) ? \$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val() : "" ; + + // already_loaded_full_day = (typeof already_loaded_full_day == 'undefined') ? "" : 1 ; + // already_loaded_half_day = (typeof already_loaded_half_day == 'undefined') ? "" : 1 ; + + // if (already_loaded_full_day && already_loaded_half_day) { + // return ; + // } + + // if (already_loaded_full_day == 1) { + // full_day_exists = 0 ; + // } + + // if (already_loaded_half_day == 1) { + // half_day_exists = 0 ; + // } + + // let date_from = \$("input[name='date_from']").val() ; + + // date_from = date_from.substring(0,10) ; + + // let full_half_day = 0 ; + + // // if (full_day_exists || (!already_loaded_full_day && already_loaded_half_day && !full_day_exists)) { + // if (full_day_exists != 0) { + // if ((typeof \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val() == 'undefined' || \$("input[name='full_"+tab+"_"+\$("#"+this_id).val()+"']").val()) && \$("#"+this_id).val()) { + // \$("#content").append("") ; + // } + // full_half_day = 1 ; + // // } else if (half_day_exists || (already_loaded_full_day && !half_day_exists && !already_loaded_half_day)) { + // } else if (half_day_exists != 0) { + // if ((typeof \$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val() == 'undefined' || !\$("input[name='half_"+tab+"_"+\$("#"+this_id).val()+"']").val()) && \$("#"+this_id).val()) { + // \$("#content").append("") ; + // } + // full_half_day = 2 ; + // } + + // let rate_ = "" ; + + // if (default_cost_item_rates["full,"+\$("#"+this_id).val()] && full_half_day == 1) { + // rate_ = default_cost_item_rates["full,"+\$("#"+this_id).val()] ; + // } else if (default_cost_item_rates["half,"+\$("#"+this_id).val()] && full_half_day == 2) { + // rate_ = default_cost_item_rates["half,"+\$("#"+this_id).val()] ; + // } else if (full_half_day) { + // let rate_url = "$useropts{scripts}/get/get_event_cost_item_rates.pl?"+\$("#"+this_id).val()+"&"+date_from+"&"+full_half_day+"&"+this_id ; + // await \$.get(rate_url, function(json) { + // \$.each(json, function(key, data) { + // rate_ = data.rate ; + // }); + // },'json') ; + // } + + // if (rate_ == "") { + // return ; + // } + + // // let tab = "" ; + + // // if (this_id.includes("_costing_event_")) { + // // tab = "costing_event" ; + // // } else if (this_id.includes("_workings_event_")) { + // // tab = "workings_event" ; + // // } + + // full_half_day = (full_half_day == 1) ? "full" : (full_half_day == 2) ? "half" : "" ; + + // \$("input[name='qty_"+tab+"_"+row_nr+"']").val(nr_days[full_half_day]) ; + // \$("input[name='amount_usd_"+tab+"_"+row_nr+"']").val(rate_) ; + // \$("input[name='amount_ttl_"+tab+"_"+row_nr+"']").val((rate_*nr_days[full_half_day]).toFixed(2)) ; + // \$("#"+tab+"_"+row_nr).append("") ; + // calc_totals(row_nr,tab) ; + + // // amount_usd_costing_event_1 + // // amount_usd_workings_event_1 + + // }) ; + + + // \$("#content").on("change","[id^='selectSystem_name_']", function () { + + // }) ; + + ~ ; + + # --------------- END COSTING ---------------------------------------------------------------------------------------------------------------- + } + + if ($tab == 5) { # Notes + + # --------------- START NOTES ---------------------------------------------------------------------------------------------------------------- + + # # my $sec = '_notes' ; + + # # my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + # # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # # return if $ret ; + + # # $add_form_fields = '' ; + + # # &db_min_ro('quote_event_notes','*','','','') ; + + # # $add_form_fields .= qq~ + # #
    + # #
    + # #

    + # # Notes: + # #

    + # #
    + # #
    ~ ; + + # # &tab_build_terms_headers ; + + # # $cntnoteloop = 1 ; + # # for (1 .. 5) { + # # &tab_build_terms_fields('note',$_,$id) ; + # # } + + # # $add_form_fields .= qq~ + # #
    + # #
    + # #

    + # # Payment Terms: + # #

    + # #
    + # #
    ~ ; + # # &tab_build_terms_headers ; + + # # $cntnoteloop = 1 ; + # # for (1 .. 5) { + # # &tab_build_terms_fields('payment_term',$_,$id) ; + # # } + # # &event_tabs_content_box($sec_name,$sec_col) ; + + # --------------- END NOTES ---------------------------------------------------------------------------------------------------------------- + } + + if ($tab == 6) { # Workings + + # --------------- START Working ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + $lcol = 1 ; + $fcol = 2 ; + + my @docs = ('Slip') ; + + $add_form_fields .= qq~ +
    + ~ ; + + foreach (@docs) { + my $doc = lc $_ ; $doc =~ s/ /\_/ ; $doc =~ s/&/\_/ ; + $event_uploads = &common_get_field_uploads($id,"$doc",'id') ; + if ($event_uploads) { + $add_form_fields .= qq~ +
    + $event_uploads +
    ~; + } else { + $add_form_fields .= qq~ +
    +
    + + +

    Upload file from PC.

    +
    +
    + ~; + } + } + + $event_uploads = '' ; + # $add_form_fields .= &common_min_form_label_col("Custom Set") ; + + my $custom_set_checked = ($db{$table}{$id}{custom_set}) ? "CHECKED" : "" ; + + $add_form_fields .= qq~ +
    + + +
    + ~ ; # class="control-label" + # $add_form_fields .= &common_min_form_checkbox_col('custom_set','') ; + + $add_form_fields .= qq~ +
    + ~ ; + + our %sec_cnt = ('a_event' => "50-List Expenses") ; + + my $sec = 'workings' ; + my ($sec_name, $sec_cnt_workings, $sec_col) = &tab_sec_det($sec) ; + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt_workings . '|' ; + + return if $ret ; + + &event_tabs_build_sec($sec,$tab) ; + + foreach (sort keys %sec_cnt) { + $_k = substr($_, 1) ; + my @parts = split(/\-/, $sec_cnt{$_}) ; + $add_form_fields .= qq~ +
    +
    +

    + $parts[1] : +

    +
    +
    + ~ if $parts[1] ne 'Operators'; + + $add_form_fields .= qq~ +
    +
    +
    +

    + $parts[1] : +

    +
    + $icon_casuals +
    +
    + ~ if $parts[1] eq 'Operators' ; + + &tab_build_qt_col_headers_workings("$sec$_k") ; + # # # &db_min_ro('event_quotes_min', 'id, remarks_workings_event, supplier_workings_event, ref_nr_workings_event, qty_workings_event, amount_usd_workings_event, amount_workings_event, vat_workings_event, description_workings_event', "id = $id", '', '') if $id ; + &event_tabs_build_costs_forms($id,$tab,$parts[0],"$sec$_k") ; + } + + $add_form_fields .= qq~ +
    +
    +   +
    +
    ~ ; + $add_form_fields .= qq~ +
    +
    +   +
    + ~ ; + + my @ttlarr = ("sub_total", "vat_total", "grand_total") ; + $lcol = 1; + $fcol = 1; + foreach (@ttlarr) { + $lcol = 1; + $add_form_fields .= &common_min_form_label_col($_) ; + } + + $add_form_fields .= qq~
    ~ ; + + $trigger_jquery_raw .= qq~ + \$("#textareaAdditional_notes").change(function () { + if (\$(this).val()) { + \$('label[for="additional_notes_expenses"]').text('Additional Notes : ') ; + \$("#textareaAdditional_notes_expenses_input").html(\$(this).val()) ; + } else if (!\$(this).val() && \$('label[for="additional_notes_expenses"]').text()) { + \$('label[for="additional_notes_expenses"]').text('') ; + \$("#textareaAdditional_notes_expenses_input").html('') ; + } + }) ; + ~ ; + + my $add1 = ($db{$table}{$id}{additional_notes}) ? "Additional Notes : " : "" ; + my $add2 = ($db{$table}{$id}{additional_notes}) ? "$db{$table}{$id}{additional_notes}" : "" ; + + $add_form_fields .= qq~

    $add2

    ~ ; + $lcol = 2; + $add_form_fields .= &common_min_form_label_col('Total') ; + $lcol = 1; + + my @ttlarr = ("total_amount_workings_event","total_vat_amount_workings_event","total_grand_amount_workings_event"); + $lcol = 1 ; $fcol = 1 ; + + my %renamed_totals = ("total_amount_workings_event" => "sub_total_workings_event", "total_vat_amount_workings_event" => "vat_total_workings_event" , "total_grand_amount_workings_event" => "grand_total_workings_event") ; + + foreach (@ttlarr) { + $readonly{$renamed_totals{$_}} = "READONLY"; + $input_style{$renamed_totals{$_}} = qq~style="text-align:right;"~ ; + my $val = $db{$table}{$id}{$_} ? $db{$table}{$id}{$_} : '0.00' ; + $add_form_fields .= &common_min_form_input_col($renamed_totals{$_},$val) ; + } + + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= qq~ +
    +
    +   +
    +
    ~ ; + + &event_tabs_content_box($sec_name,$sec_col) ; + + # --------------- END WORKING ---------------------------------------------------------------------------------------------------------------- + } + + if ($tab == 7) { # Invoice Details + + # --------------- START INVOICE DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_invoice_details' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + $lcol = 3 ; + $fcol = 5 ; + + $add_form_fields = '' ; + + $add_form_fields .= &common_min_form_input('invoice_nr',$db{$table}{$id}{invoice_nr},'') ; + my $checked = 'CHECKED' if $db{$table}{$id}{annual_invoice} ; + $add_form_fields .= &common_min_form_input('po_nr',$db{$table}{$id}{po_nr},'') ; + $add_form_fields .= &common_min_form_datepicker('invoice_date',$db{$table}{$id}{invoice_date}) ; + + &event_tabs_content_box($sec_name,$sec_col); + + # --------------- END INVOICE DETAILS ---------------------------------------------------------------------------------------------------------- + } + +} #------------------------------------------------------------------------------------ + +sub event_tabs_build_sec { + + my ($sec_,$tab) = @_ ; + + # # # &db_min_ro('event_quotes_min', 'id,description_workings_event,operator_workings_event', "id = $i{id}", '', '') if $i{id}; + + my @saved_des = () ; my @saved_op = () ; + + # my %casual_name_dropdown_hash = () ; + + if ($sec_ eq "workings") { + @saved_des = split(";", $db{event_quotes_min}{$i{id}}{description_workings_event}) ; + @saved_op = split(";", $db{event_quotes_min}{$i{id}}{operator_workings_event}) ; + &db_min_ro('users','*',"user_type LIKE 'casual%' AND block <> 1 AND inactive <> 1",'','') if $iaction eq 'add' ; + foreach my $uid (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + # $casual_name_dropdown_hash{$uid} = $db{users}{$uid}{name} ; + $opts{operator_field} .= qq~~ ; + } + } else { + @saved_des = split(";", $db{event_quotes_min}{$i{id}}{item_costing_event}) ; + } + + unless ($opts{description_field}) { + $opts{description_field} = qq~~ ; + my $other_id = 0 ; + foreach (sort {$db{event_cost_items}{$a}{name} cmp $db{event_cost_items}{$b}{name}} keys %event_list_name_array_expenses) { + next if $db{event_cost_items}{$_}{excl_from_expenses} ; + if (lc $db{event_cost_items}{$_}{name} eq "other") { + $other_id = $_ ; + next ; + } + $opts{description_field} .= qq~~ ; + } + $opts{description_field} .= qq~~ ; + + } + + my @description_chosen_field_ids = () ; my @operator_chosen_field_ids = () ; my @desriptions_that_are_operators = () ; + + foreach (sort keys %sec_cnt) { + + $_k = substr($_,1) ; $k = substr($_,2) ; + + my @parts = split(/\-/,$sec_cnt{$_}) ; + + for my $p_ (1 .. $parts[0]) { # item_1_costing_systems + + my $field = "$sec_$_k\_$p_" ; + my $saved_val = $saved_des[$p_ - 1] ; + next if $p_ > 1 && !$saved_val ; + my $saved_val_2 = $saved_op[$p_ - 1] ; + + if ($_k eq '_event') { + $opts{"description_$field"} = $opts{description_field} ; + $trigger_jquery_raw .= qq~\$("#selectDescription_$field").val("$saved_val") ; \$("#selectDescription_$field").trigger("chosen:updated") ; ~ if $saved_val and $saved_val ne "14" ; + push @desriptions_that_are_operators,"#selectDescription_$field" if $saved_val eq "14" ; + + if ($sec_ eq "workings") { + $opts{"operator_$field"} = $opts{operator_field} ; + $trigger_jquery_raw .= qq~\$("#selectOperator_$field").val("$saved_val_2") ; \$("#selectOperator_$field").trigger("chosen:updated") ; ~ if $saved_val_2 ; + } + } + + $item_type = 'input' ; + + unless ($got{$field}) { + + $got{$field} = 1 ; + push @excl_field_ids,"#checkboxExcl_$field" ; + push @description_field_ids,"#selectDescription_$field" ; + push @operator_field_ids,"#selectOperator_$field" ; + push @description_chosen_field_ids,"#selectDescription_$field\_chosen" ; + push @operator_chosen_field_ids,"#selectOperator_$field\_chosen" ; + push @vat_field_ids,"#checkboxVat_$field" ; + push @qty_field_ids,"#inputQty_$field" ; + push @amount_usd_field_ids,"#inputAmount_usd_$field" ; + + } + } + } + + my $desriptions_that_are_operators_string = join (",",@desriptions_that_are_operators) ; + + $trigger_jquery_raw .= qq~\$("$desriptions_that_are_operators_string").val("14") ; \$("$desriptions_that_are_operators_string").trigger("chosen:updated") ; ~ if $desriptions_that_are_operators_string ; + + # if ($sec_ eq "demo_expenses") { + + $trigger_jquery .= qq~ + \$("#$cntxt{$tab} [id^='select']").filter( function() { + return this.id.endsWith("_chosen") ; + }).css("width","90%"); + ~ ; + + # $trigger_jquery .= qq~\$("#$cntxt{$tab} [id^='select']").css("width","90%");~ ; + # return ; + # } + + # my $description_chosen_field_ids_string = join(",",@description_chosen_field_ids) ; + + # $trigger_jquery .= qq~\$("$description_chosen_field_ids_string").css("width","90%");~ ; + + # if ($sec_ eq "workings") { + # my $operator_chosen_field_ids_string = join(",",@operator_chosen_field_ids) ; + # $trigger_jquery .= qq~\$("$operator_chosen_field_ids_string").css("width","90%");~ ; + # } + +} #------------------------------------------------------------------------------------------ + +sub event_tabs_customer_select_opts { + + my ($table,$dispfield,$where,$field) = @_ ; + + $where .= " AND " if $where ; + $where .= "events='1'" ; + + &db_min_ro($table,'*',$where,'','') ; + + foreach my $id (sort { $db{$table}{$a}{name} cmp $db{$table}{$b}{name} } keys %{$db{$table}}) { + + my $saved_val = $db{event_quotes}{$i{id}}{$field} ; + + if ($saved_val) { my @valarr = split(/\:/,$saved_val) ; $saved_val = $valarr[0] ; } + + if ($saved_val eq $id) { $selected = 'SELECTED' ; } else { $selected = '' ; } + + $opts{$field} .= qq~~ ; + unless ($got{$field}) { + $trigger_jquery .= qq~\$("#selectQuote_to_chosen").css( "width", "96%" );~ ; + $got{$field} = 1 ; + $trigger_jquery_raw .= qq~ + \$("#selectQuote_to").change(function() { + dispCustomer() ; + }); + ~; + + $trigger_jquery_raw .= qq~ + function dispCustomer() { + var custval = \$("#selectQuote_to").val(); + var arrP = custval.split(":"); + \$("#inputContact_name").val(arrP[1]); + \$("#inputAddress").val(arrP[4]); + \$("#inputEmail").val(arrP[2]); + \$("#inputTel").val(arrP[3]); + } + ~; + } + } +} #------------------------------------------------------------------------------------------ + +sub tab_build_terms_headers { + + $add_form_fields .= qq~ +
    +
    + +
    +
    + +
    +
    + ~ ; +} #------------------------------------------------------------------------------------ + +sub tab_build_terms_fields { + + my ($sec,$cnt,$id) = @_ ; + + my $exfield = "excl_$cnt\_$sec\s" ; + my $inpfield = "$sec\_$cnt" ; + + unless ($db{quote_event_notes}{1}{$inpfield}) { + $checkit{$exfield} = 1 ; + } + + if ($db{$table}{$id}{$inpfield}) { + $val = $db{$table}{$id}{$inpfield} ; + } else { + $val = $db{quote_event_notes}{1}{$inpfield} ; + } + + $note_display_style = '' ; $note_display_plus_btn = '' ; + unless ($cnt==1 or $db{quote_event_notes}{1}{$inpfield}) { + $note_display_style = qq~style='display:none;'~ ; + $trigger_jquery_raw .= qq~ \$("#btn_$cnt\_$sec").click(function () { + \$("#$cnt\_$sec").toggle(); + \$("#btn_$cnt\_$sec").hide(); + var v = $cnt + 1 ; + \$("#btn_"+v+"\_$sec").show(); + });~ ; + if ($cnt>$cntnoteloop) { + $note_display_butt = qq~display:none;~ ; + } else { + $note_display_butt = '' ; + } + $note_display_plus_btn = qq~~; + } else { + $cntnoteloop++ ; + } + + $add_form_fields .= qq~
    ~ ; + + if ($db{$table}{$id}{$exfield} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + + $label{$exfield} = 1 ; + $fcol=1 ; + $add_form_fields .= &common_min_form_checkbox_col($exfield,$checkit{$exfield},$checked) ; + $fcol=6 ; + $input_style{$inpfield} = qq~style='margin-bottom:4px;margin-top:-2px;'~ ; # add spaces between boxes + $add_form_fields .= &common_min_form_input_col($inpfield,$val,'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~ +
    +
    + $note_display_plus_btn +
    +
    + ~ ; + +} #------------------------------------------------------------------------------------ + +sub tab_build_qt_right { + + my ($id,$tab,$ret) = @_ ; + + if ($tab==1) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_office_details' ; + my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + $lcol = 3 ; + + $add_form_fields = '' ; + + $fcol = 8 ; + # $textarea_height{notes} = ($is_schools_manager) ? 102 : 93 ; + # $textarea_height{notes} = ($glod_user_level < 4) ? 102 : 93 ; + $textarea_height{notes} = ($glod_user_level < 3) ? 102 : 93 ; + $add_form_fields .= &common_min_form_textarea('notes',$db{$table}{$id}{notes},'') ; + $add_form_fields .= qq~
     
    ~ ; + + # unless ($is_schools_manager) { + if ($glod_user_level > 3) { + $textarea_height{office_notes} = 93 ; + $add_form_fields .= &common_min_form_textarea('office_notes',$db{$table}{$id}{office_notes},'') ; + $add_form_fields .= qq~
     
    ~ ; + } + + &event_tabs_content_box($sec_name,$sec_col); + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + + if ($tab==7) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + + my $sec = '_profit_loss' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + $lcol = 3 ; $fcol = 5 ; + + my $expenses = $db{$table}{$id}{total_grand_amount_workings_event} ? sprintf("%0.2f",$db{$table}{$id}{total_grand_amount_workings_event}) : '0.00' ; + # my $income = $db{$table}{$id}{grand_total} ? $db{$table}{$id}{grand_total} : '0.00' ; + my $income = $db{$table}{$id}{sub_total} ? sprintf("%0.2f",$db{$table}{$id}{sub_total}) : '0.00' ; + # my $profit_or_loss = $income - $expenses ; + my $profit_or_loss = sprintf("%0.2f",($income - $expenses)) ; + + $add_form_fields = '' ; + + $lcol = 3; + $fcol = 3; + + $readonly{income} = "READONLY"; + $readonly{expenses} = "READONLY"; + $readonly{profit_loss} = "READONLY"; + + $add_form_fields .= &common_min_form_input('income',$income,'') ; + $add_form_fields .= &common_min_form_input('expenses',$expenses,'') ; + $add_form_fields .= &common_min_form_input('profit_loss',$profit_or_loss,'') ; + + &event_tabs_content_box($sec_name,$sec_col); + + # my $sec = '_overall_revenue' ; + # my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + # my @ttlarr = ("total_grand_amount_workings_event", "grand_total") ; + + # foreach (@ttlarr) { + # $readonly{$_} = "READONLY"; + # $input_style{$_} = qq~style="text-align:right;"~; + # my $val = $db{$table}{$id}{$_} ? $db{$table}{$id}{$_} : '0.00' ; + # $add_form_fields .= &common_min_form_input_col($_,$val) ; + # } + + # &event_tabs_content_box($sec_name,$sec_col) ; + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + + } + +} #------------------------------------------------------------------------------------ + +sub tab_curr_symbols { + + $curr_symb{ZAR} = 'R'; + $curr_symb{USD} = '$'; + $curr_symb{GBP} = 'GBP'; + $curr_symb{EUR} = 'EUR'; + + our $js_curr_arr = '' ; + + foreach (keys %curr_symb) { + $js_curr_arr .= qq(currArr['$_'] = "$curr_symb{$_}";) ; + } + +} #------------------------------------------------------------------------------------ + +sub tab_build_qt_col_headers { + + my ($sec) = @_ ; + + my $style_vat = '' ; + + $style_vat = 'style="display:none;"' if $no_vat{$sec} ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ if $sec eq 'costing_event'; + $add_form_fields .= qq~
    ~ if $sec eq 'costing_casual_users'; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + %cost_desc = () ; + %def_qty = () ; + %def_zar = () ; + %min_zar = () ; + %vat_tick = () ; + %excl_tick = () ; + +} #---------------------------------------------------------------------------------------- + +sub tab_build_qt_col_headers_workings { + + my ($sec) = @_ ; + + my $style_vat = '' ; + + $style_vat = 'style="display:none;"' if $no_vat{$sec} ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ if $sec ne 'workings_casual_users'; + $add_form_fields .= qq~
    ~ if $sec ne 'workings_casual_users'; + # $add_form_fields .= qq~
    ~ if $sec eq '_workings_casual_users'; + $add_form_fields .= qq~
    ~ if $sec ne 'workings_casual_users'; + # $add_form_fields .= qq~
    ~ if $sec eq '_workings_casual_users'; + $add_form_fields .= qq~
    ~ if $sec ne 'workings_casual_users'; + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + %cost_desc = () ; + %def_qty = () ; + %def_zar = () ; + %min_zar = () ; + %vat_tick = () ; + %excl_tick = () ; + +} #---------------------------------------------------------------------------------------- + +sub event_tabs_content_box { + + my ($sec_name,$sec_col) = @_ ; + + $fcol=9 ; + $print_box_content_rows .= &common_min_box_top('indent-left',$sec_name,$sec_col,$cam_box_icon); + $print_box_content_rows .= qq~$add_form_fields~; + $print_box_content_rows .= &common_min_box_foot; + +} #---------------------------------------------------------------------------------------- + +sub tab_cnt { + + our %cntxt = () ; + + $cntxt{1} = 'one' ; + $cntxt{2} = 'two' ; + $cntxt{3} = 'three' ; + # return if $is_schools_manager ; + return if $glod_user_level < 4 ; + $cntxt{4} = 'four' ; + # $cntxt{5} = 'five' ; + $cntxt{6} = 'six' ; + $cntxt{7} = 'seven' ; + +} #---------------------------------------------------------------------------------------- + +sub tab_names { + + my ($tab) = @_ ; + + my $tabname = '' ; + + if ($tab==1) { $tabname = 'Customer Details' ; } + elsif ($tab==2) { $tabname = 'Event Details' ; } + elsif ($tab==3) { $tabname = 'Event Specifics' ; } + elsif ($tab==4) { $tabname = 'Quote' ; } + # elsif ($tab==5) { $tabname = 'Notes' ; } + elsif ($tab==6) { $tabname = 'Expenses' ; } + elsif ($tab==7) { $tabname = 'Invoice Details' ; } + + return ($tabname) ; + +} #------------------------------------------------------------------------------------ + +sub tab_hash { + + # &db_min_ro('users',"id","user_type like '%casual%'",'','') ; + # &db_min_ro('events',"id,event_quote_nr,user_id,category",'','','') ; + # &db_min_ro('event_cost_items','*','','name asc','') ; + + our @excl_field_ids = () ; our @description_field_ids = () ; our @operator_field_ids = () ; our @vat_field_ids = () ; our @qty_field_ids = () ; our @amount_usd_field_ids = () ; our @excl_field_ids = () ; our @btn_ids = () ; + + &tab_load_vars; + + for (1 .. 7) { + + next if $_ == 5 ; + + my $tname = &tab_names($_) ; + our $ret_pdf_link_sec = '' ; # _sa_out+16|_cl_del+13|_sa_in+17|_des_sa+13| + + &event_tabs_build_qt_left('',$_,1) ; + &tab_build_qt_right('',$_,1) ; + + $tabcnt{$tname} = $_ ; + $tabsec{$tname} = $ret_pdf_link_sec ; + } + + # &build_workings_costings_forms_jquery ; + +} #------------------------------------------------------------------------------------ + +sub tab_load_vars { + + # our %casuals = (); + our %available_casuals = () ; + our %not_available_casuals = () ; + + # unless (defined %casuals) { + unless (scalar keys %casuals > 0) { + &db_min_ro('users',"id","user_type like '%casual%'",'','') ; + + foreach my $user_id (keys %{$db{users}}){ + $casuals{$user_id} = 1 ; + } + } + + &db_min_ro('events',"id,event_quote_nr,user_id,category",'','','') ; + + foreach my $event_id (keys %{$db{events}}){ + next unless $casuals{$db{events}{$event_id}{user_id}} ; + if ($db{events}{$event_id}{event_quote_nr} == $id and $db{events}{$event_id}{category} eq 'available'){ + $available_casuals{$db{events}{$event_id}{user_id}} = 1 ; + } elsif ($db{events}{$event_id}{event_quote_nr} == $id and $db{events}{$event_id}{category} eq 'unavailable'){ + $not_available_casuals{$db{events}{$event_id}{user_id}} = 1 ; + } + } + + our %dlg_operator = () ; + + for (1 .. 50) { + next unless $db{$table}{$id}{"operator_workings_event_$_"} ; + if ($available_casuals{$db{$table}{$id}{"operator_workings_event_$_"}}) { + $dlg_operator{"operator_workings_event_$_"} = qq~
    ~ ; + } elsif ($not_available_casuals{$db{$table}{$id}{"operator_workings_event_$_"}}) { + $dlg_operator{"operator_workings_event_$_"} = qq~ ~ ; + } else { + $dlg_operator{"operator_workings_event_$_"} = qq~~ ; + } + } + + # &db_min_ro('event_cost_items','*','','name asc','') ; + &db_min_ro('event_cost_items','*',"excl_from_expenses < 1",'name asc','') ; + + our %event_list_name_array_quote = () ; + our %event_list_name_array_expenses = () ; + my @spl = () ; + + foreach my $iid (keys %{$db{event_cost_items}}) { + @spl = split(" ", $db{event_cost_items}{$iid}{name}); + for (@spl) {$_ = ucfirst $_ ; } + $db{event_cost_items}{$iid}{name} = join (" ", @spl) ; + $event_list_name_array_quote{$iid} = $db{event_cost_items}{$iid}{name} ; + $event_list_name_array_expenses{$iid} = $db{event_cost_items}{$iid}{name} ; + } + +} #------------------------------------------------------------------------------------ + +sub tab_sec_det { + + my ($sec) = @_ ; + + my ($sec_nam,$sec_cnt,$sec_col) ; + + $sec_col = '71919b' ; # '85acb8' ; + $sec_cnt = 20 ; + $sec_nam = substr($sec,1) ; + @array = split(/\_/,$sec_nam); + my @sec_nam = map ucfirst, @array; + $sec_nam = join(" ", @sec_nam) ; + + if ($sec eq 'costing') { + $sec_nam = 'Event Costings' ; + for (1 .. 30) { $vat_tick{$_} = 1 ; } + } + + if ($sec eq 'workings') { + $sec_nam = 'Event Expenses' ; + for (1 .. 50) { $vat_tick{$_} = 1 ; } + } + + return ($sec_nam,$sec_cnt,$sec_col) ; + +} #------------------------------------------------------------------------------------ + +sub event_tabs_build_boxes_top { + + my ($id) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(3,6) ; + + $add_form_fields = '' ; + + $fcol=8 ; + + $add_form_fields .= qq~
    ~ ; + $preferred_title{quote_nr} = "Nr" ; + $add_form_fields .= &common_min_form_input('quote_nr',$db{$table}{$id}{quote_nr},'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + if (($db{$table}{$id}{quote_date} eq '') or ($db{$table}{$id}{quote_date} eq '0000-00-00')) { + $db{$table}{$id}{quote_date} = $now_ccyy_mm_dd ; + } + $preferred_title{quote_date} = "Date" ; + $add_form_fields .= &common_min_form_datepicker('quote_date',$db{$table}{$id}{quote_date}) ; + my $plus_n_days_ccyy_mm_dd = &common_add_delta_days(14) ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $preferred_title{quote_to} = "Client" ; + $add_form_fields .= &common_min_form_select('quote_to',$db{$table}{$id}{quote_to},'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $dlg{quote_to} = qq~ + ~ ; + $fcol = 7; + $add_form_fields .= &common_min_form_select('country_id',$db{$table}{$id}{country_id},'') ; + $add_form_fields .= qq~
    ~ ; + $fcol = 8; + $print_box_content_rows .= &common_min_box_top('qrcode',"Quote",'BABEC2'); + $print_box_content_rows .= qq~ +
    +
    + $add_form_fields +
    +
    ~; + $print_box_content_rows .= qq~ +
    +
    +   +
    +
    ~ ; + $print_box_content_rows .= &common_min_box_foot; + +} #------------------------------------------------------------------------------------ + +sub event_tabs_build_costs_forms { + + my ($id,$tab,$rcnt,$suffix) = @_ ; + + $tab_sections{$tab} .= "$suffix+$rcnt|" ; + + $jq_work_cal = qq~ + var vat_totalW$suffix = 0 ; + var total_totalW$suffix = 0 ; + var subtotalW$suffix = 0 ; + var vat_amountW = 0 ; + ~ ; + $jq_fs = '' ; + + %cnt_specific_jquery = () ; + + &set_check_boxes_checked($id,$rcnt,"excl",$suffix); + &set_check_boxes_checked($id,$rcnt,"vat",$suffix); + + my $cntloop = 1 ; + my $field = "" ; + my $val = 0 ; + + my $table_ = "event_quotes_min" ; + + my @excl_old = split(";", $db{$table_}{$id}{"excl_$suffix"}) ; + my @qty_old = split(";", $db{$table_}{$id}{"qty_$suffix"}) ; + my @vat_old = split(";", $db{$table_}{$id}{"vat_$suffix"}) ; + my @remarks_old = () ; + my @supplier_old = () ; + my @ref_nr_old = () ; + my @amount_usd_old = () ; + my @amount_ttl_old = () ; + my @des_old = () ; + my @ops_old = () ; + my @curr_amnt_cost = () ; + + if ($suffix eq "workings_event") { + @remarks_old = split(";",$db{$table_}{$id}{remarks_workings_event}) ; + @supplier_old = split(";",$db{$table_}{$id}{supplier_workings_event}) ; + @ref_nr_old = split(";",$db{$table_}{$id}{ref_nr_workings_event}) ; + @amount_usd_old = split(";",$db{$table_}{$id}{amount_usd_workings_event}); + @amount_ttl_old = split(";",$db{$table_}{$id}{amount_workings_event}); + @des_old = split(";",$db{$table_}{$id}{description_workings_event}) ; + @ops_old = split(";",$db{$table_}{$id}{operator_workings_event}) ; + } else { + @amount_usd_old = split(";",$db{$table_}{$id}{usd_amnt_costing_event}); + @amount_ttl_old = split(";",$db{$table_}{$id}{item_ttl_costing_event}); + @des_old = split(";",$db{$table_}{$id}{item_costing_event}); + @curr_amnt_cost = split(";",$db{$table_}{$id}{curr_amnt_costing_event}); + } + + for (1 .. $rcnt) { + + $display_style = '' ; + $display_plus_btn = '' ; + my $style_display_butt = "" ; + unless ($_ == 1 or $des_old[$_ - 1]) { + $display_style = qq~style='display:none;'~ ; + push @btn_ids,"#btn_$suffix\_$_" ; + if ( $_>$cntloop ) { + $display_butt = qq~display:none;~ ; + $style_display_butt = qq~style="display:none;"~ ; + } else { + $display_butt = '' ; + } + $display_plus_btn = ($_>$cntloop) ? qq~~ : qq~~; + } else { + $cntloop++ ; + } + + $add_form_fields .= qq~
    ~ ; + + #---------------------------------------------------------------------------------------------------- + + if ($des_old[$_-1] || $_ == 1) { + + push @all_select_ids,"#selectDescription_$suffix\_$_" ; + push @all_select_ids,"#selectOperator_$suffix\_$_" if $suffix eq "workings_event" ; + + $field = "excl_$suffix\_$_" ; + $fcol = 1; + # if ($checkit{$field} == 1) { + if ($excl_old[$_ - 1]){ + $checked = 'CHECKED'; + } elsif (($excl_tick{$_}) and ($iaction eq 'add')) { + $checked = 'CHECKED'; + } else { + $checked = ''; + } + $label{$field} = 1; + $add_form_fields .= &common_min_form_checkbox_col($field,$checkit{$field},$checked) ; + + #---------------------------------------------------------------------------------------------------- + + $field = "description_$suffix\_$_" ; + $fcol = 2; + # $allow_deselect{$field} = 1; + $preferred_title{$field} = "Description $_" ; #if $suffix ne '_workings_casual_users'; + + $opts{$field} = $opts{description_field} unless $opts{$field} ; + + if ($des_old[$_-1] && $opts{$field} !~ /SELECTED/ && $opts{$field} !~ /selected/) { + $opts{$field} =~ s/\"/\'/g ; + $opts{$field} =~ s/value='$des_old[$_-1]'/value='$des_old[$_-1]' SELECTED/g ; + } + + $add_form_fields .= &common_min_form_select_col($field,'') ; + + #---------------------------------------------------------------------------------------------------- + + if ($suffix eq "workings_event") { + + $field = "operator_$suffix\_$_" ; + $fcol = 2; + # $allow_deselect{$field} = 1; + $preferred_title{$field} = "Operator $_" ; + + $opts{$field} = $opts{operators_field} unless $opts{$field} ; + + if ($ops_old[$_-1] && $opts{$field} !~ /SELECTED/ && $opts{$field} !~ /selected/) { + $opts{$field} =~ s/\"/\'/g ; + $opts{$field} =~ s/value='$ops_old[$_-1]'/value='$ops_old[$_-1]' SELECTED/g ; + } + + $add_form_fields .= &common_min_form_select_col($field,'') ; + + #---------------------------------------------------------------------------------------------------- + + $field = "remarks_$suffix\_$_" ; + $fcol = 1; + # $allow_deselect{$field} = 1; + $preferred_placeholder{$field} = "Remarks $_" ; + $add_form_fields .= &common_min_form_input_col($field, $remarks_old[$_ - 1]) ; + + #---------------------------------------------------------------------------------------------------- + + $field = "supplier_$suffix\_$_" ; + $fcol = 1; + # $allow_deselect{$field} = 1; + $preferred_placeholder{$field} = "Supplier $_" ; + $add_form_fields .= &common_min_form_input_col($field,$supplier_old[$_ - 1]) if $suffix ne '_workings_casual_users'; + + #---------------------------------------------------------------------------------------------------- + + $field = "ref_nr_$suffix\_$_" ; + $fcol = 1; + # $allow_deselect{$field} = 1; + $preferred_placeholder{$field} = "Ref Nr $_" ; + $add_form_fields .= &common_min_form_input_col($field,$ref_nr_old[$_ - 1]) ; + + #---------------------------------------------------------------------------------------------------- + + } + + $field = "qty_$suffix\_$_" ; + # $field .= '_costing_event'; + $fcol = 1; + $input_style{$field} = qq(style="text-align:right;"); + $preferred_placeholder{$field} = "Qty $_" ; + $val = $qty_old[$_ - 1] ; + unless ($val) { + $val = $def_qty{$_} ; + } + $val = &q_get_val($val) ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + + #---------------------------------------------------------------------------------------------------- + + $field = "amount_usd_$suffix\_$_" ; + $fcol = 1; + $input_style{$field} = qq(style="text-align:right;"); + $val = $amount_usd_old[$_ - 1] ; + unless ($val) { + $val = $def_usd{$_} ; + } + $val = &q_get_val($val) ; + $preferred_placeholder{$field} = "Amount $_" ; + # $excl_on_change{$field} = 1 ; + $val = '0.00' unless $val ; + $add_form_fields .= &common_min_form_input_col($field,$val,1) ; + + $add_form_fields .= qq~~ if $des_old[$_-1] && $amount_usd_old[$_ - 1] eq $default_cost_item_rates{$des_old[$_-1]}{half} ; + $add_form_fields .= qq~~ if $des_old[$_-1] && $amount_usd_old[$_ - 1] eq $default_cost_item_rates{$des_old[$_-1]}{full} ; + #---------------------------------------------------------------------------------------------------- + + # if ($suffix eq "costing_event") { + + # $field = "curr_amnt_$suffix\_$_" ; + # # $field .= '_costing_event'; + # $input_style{$field} = qq(style="text-align:right;"); + # $readonly{$field} = 'READONLY' ; # $fcol=2 ; + # $preferred_placeholder{$field} = "ZAR Amnt $_" ; + # # $val = &q_get_val($db{$table}{$id}{$field}) ; + # $val = &q_get_val($curr_amnt_cost[$_ -1]) ; + # our $type = 'hidden' ; + # $add_form_fields .= &common_min_form_input_col($field,$val,1) ; $type = '' ; + # $type = '' ; + + # } + + # #---------------------------------------------------------------------------------------------------- + + $field = "amount_ttl_$suffix\_$_" ; + $input_style{$field} = qq(style="text-align:right;"); + $val = $amount_ttl_old[$_ - 1] ; + $val = &q_get_val($val) ; + # $val = &common_commify($val) ; + # $val = sprintf("%0.2f",$val) ; + $preferred_placeholder{$field} = "Total Amount $_" ; + # $excl_on_change{$field} = 1 ; + $readonly{$field} = 'READONLY' ; + $val = '0.00' unless $val ; + $add_form_fields .= &common_min_form_input_col($field,$val,1) ; + + #---------------------------------------------------------------------------------------------------- + + $field = "vat_$suffix\_$_" ; + $fcol=1 ; + # if ($checkit{$field} == 1) { + if($vat_old[$_ - 1]){ + $checked = 'CHECKED'; + } elsif ($iaction eq 'add') { + $checked = 'CHECKED'; + } else { + $checked = ''; + } + $label{$field} = 1 ; + if ($no_vat{$suffix}) { + $style_field{$field} = 'style="display:none;"' ; + } + # $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_checkbox_col($field,$checkit{$field},$checked) ; + + #---------------------------------------------------------------------------------------------------- + + } else { + $tindex+=10 if $suffix eq "workings_event" ; + $tindex+=7 if $suffix eq "costing_event" ; + } + + my $display_hidden_input = ($username eq 'handre') ? "" : "style='display:none;'" ; + + my $f_h_val = substr($quote_tab_default_full_half_items[$_-1],2) ; + $add_form_fields .= (substr($quote_tab_default_full_half_items[$_-1],0,2) eq '1:') ? qq~~ : (substr($quote_tab_default_full_half_items[$_-1],0,2) eq '2:') ? qq~~ : qq~~ ; + + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= qq~ +
    +
    + $display_plus_btn +
    +
    + ~ ; + + my $style_disp_row = ($des_old[$_-1]) ? "" : "style='display:none;'" ; + $add_form_fields .= qq~ +
    +
    +
    +
    + ~ ; + + } + +} #---------------------------------------------------------------------------------------- + +1; diff --git a/libs/modules/_FromProd/v1.0/fixedsystem.pm b/libs/modules/_FromProd/v1.0/fixedsystem.pm new file mode 100644 index 0000000..3754db8 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/fixedsystem.pm @@ -0,0 +1,430 @@ +sub fixedsystem_build_table_and_or_excel { + + my ($report) = @_ ; + + our @sql_col_display = ("cnt","event","start_date","start_time","venue","region","system_name","online_status","network_test","system_test","test_event","sound_test","overall_status","additional_comments") ; + + &report_xlsx_export_header("$xlsxreportname",$xlsxdir,'',$xlsx_title_heading) ; + + $xlsxrow-- ; + + my $event_cnt = 0 ; our $found_after_date = 0 ; + + # $format84->set_align('center'); + # $format88->set_align('center'); + # $format89->set_align('center'); + # $format90->set_align('center'); + # $format91->set_align('center'); + + my %defualt_color = () ; + $defualt_color{-1} = "#F90D0D" ; + $defualt_color{1} = "#51B529" ; + + my %defualt_color2 = () ; + $defualt_color2{1} = "#51B529" ; + $defualt_color2{2} = "#F6E305" ; + $defualt_color2{3} = "#F90D0D" ; + + + foreach my $id (sort {$db{$table}{$a}{date_from} cmp $db{$table}{$b}{date_from}} keys %{$db{$table}}) { + + next unless $id ; + unless (&common_check_if_string_contains_an_integer($db{$table}{$id}{event_system_id_multiple})) { + $db{$table}{$id}{event_system_id_multiple} = ";-1;" ; + } + + my $now_date = int("$now_year$now_mm$now_dd") ; + my $end_date = substr($db{$table}{$id}{date_to},0,10) ; + $end_date =~ s/\-//g ; + $end_date = int($end_date) ; + my $is_in_future = ($now_date < $end_date) ? 1 : 0 ; + + my @system_name_ids = split(/\;/,$db{$table}{$id}{event_system_id_multiple}) ; + + my @fixed_system_online_status = split(/\;/,$db{$table}{$id}{fixed_system_online_status}) ; + my @fixed_system_network_test = split(/\;/,$db{$table}{$id}{fixed_system_network_test}) ; + my @fixed_system_system_test = split(/\;/,$db{$table}{$id}{fixed_system_system_test}) ; + my @fixed_system_test_event = split(/\;/,$db{$table}{$id}{fixed_system_test_event}) ; + my @fixed_system_sound_test = split(/\;/,$db{$table}{$id}{fixed_system_sound_test}) ; + my @fixed_system_overall_status = split(/\;/,$db{$table}{$id}{fixed_system_overall_status}) ; + my @fixed_system_additional_comments = split(/\;/,$db{$table}{$id}{fixed_system_additional_comments}) ; + + my $cnt_sys_ids = -1 ; + + # my @table_op_ids = () ; + + # for (1 .. $cnt_rows) { + # push @table_op_ids,$op_ids[$_ - 1] if $op_ids[$_ - 1] ; + # push @table_op_ids,0 unless $op_ids[$_ - 1] ; + # } + + my $system_count = 0 ; + + # foreach my $event_id (split(";",$db{$table}{$id}{event_system_id_multiple})) { + foreach my $event_id (@system_name_ids) { + + $cnt_sys_ids++ ; + + next unless $event_id ; + next unless $db{event_systems}{$event_id}{system_type} eq 'fixed' ; + next if $i{overall_status} ne 'all' and $i{overall_status} and $i{overall_status} ne $fixed_system_overall_status[$cnt_sys_ids] ; + + $event_cnt++ ; + $system_count++ ; + $xlsxcol = 0 ; + $print_tbody .= qq~~ if $report ; + + foreach (@sql_col_display) { + + next unless $_ ; # blank for the buttons column + + my $formatting = $format84 ; + my $val = $db{$table}{$id}{$_} ; + my $val_min = $val ; + my $align = '' ; + my $nowrap = '' ; + + if ($_ eq 'cnt') { + $val = $event_cnt ; + } elsif ($_ eq 'event') { + $val = "$db{$table}{$id}{ref} ($id)" ; + } elsif ($_ eq 'start_date') { + $nowrap = 'nowrap' ; + $val = substr($db{$table}{$id}{date_from},0,10) ; $align = qq~ class="dt-center"~ ; + } elsif ($_ eq 'venue') { + my @oids = split(/\,/,$db{$table}{$id}{organisation_ids}) ; + foreach $_oid (@oids) { + $val .= $db{organisations}{$_oid}{name} . '
    ' ; + } + $val = substr($val,0,-4) if $val ; ; + } elsif ($_ eq 'region') { + $val = $db{regions}{$db{$table}{$id}{region_id}}{code} ; $align = qq~ class="dt-center"~ ; + } elsif ($_ eq 'system_name') { + $val = '' ; + $val = qq~$db{event_systems}{$event_id}{name}~ ; + $val .= qq~ ($db{event_systems}{$event_id}{description})~ if $db{event_systems}{$event_id}{description} ; + } elsif ($_ eq 'sport') { + $val = '' ; + foreach my $sport_id (split(",",$db{$table}{$id}{sport_type_ids})) { + $db{sport_types}{$sport_id}{name} = uc $db{sport_types}{$sport_id}{name} ; + $val .= qq~$db{sport_types}{$sport_id}{name}
    ~ ; + } + $val = substr($val,0,-4) if $val ; + } elsif ($_ eq 'operator') { + $val = '' ; + $val = $db{users}{$op_ids[$system_count - 1]}{name} if $op_ids[$system_count - 1] ; + } elsif ($_ eq 'start_time') { + $val = substr($db{$table}{$id}{date_from},11,5) ; $align = qq~ class="dt-center"~ ; + } elsif ($_ eq 'online_status') { + if ($is_in_future && $report && ($glod_user_level > 2 || $is_installation_partner || $is_schools_manager)) { + my $field = "online_status_$id\_$event_id" ; $align = qq~ class="dt-center $_"~ ; + $preferred_title{$field} = "Online Status" ; + $opts{$field} = $opts{$_} ; + $allow_deselect{$field} = 1 ; + $useropts{'common'}{'css'} .= qq~.$_ { min-width:170px; } ~ ; + my $ucfirstfield = ucfirst $field ; + $val = qq~~ ; + + if ($fixed_system_online_status[$cnt_sys_ids]) { + $trigger_jquery_raw .= qq~ + \$("#select$ucfirstfield").val("$fixed_system_online_status[$cnt_sys_ids]") ; + \$("#select$ucfirstfield").trigger("chosen:updated") ; + ~ ; + } + $trigger_jquery_raw .= qq~\$("#select$ucfirstfield").chosen({ allow_single_deselect:true });~ ; + $val_min = "Online" if $fixed_system_online_status[$cnt_sys_ids] eq '1' ; + $val_min = "Offline" if $fixed_system_online_status[$cnt_sys_ids] eq '-1' ; + $val_min = "None" unless $val_min ; + } else { + $val = "Online" if $fixed_system_online_status[$cnt_sys_ids] eq '1' ; + $val = "Offline" if $fixed_system_online_status[$cnt_sys_ids] eq '-1' ; + $val = "None" unless $val ; + $val_min = $val ; + } + $trigger_jquery_raw .= qq~\$("#itv-table tr:eq($event_cnt) td:nth-last-child(7)").css("background-color","$defualt_color{$fixed_system_online_status[$cnt_sys_ids]}");~ if $fixed_system_online_status[$cnt_sys_ids] ; + $formatting = $format94 if $fixed_system_online_status[$cnt_sys_ids] eq '1' ; + $formatting = $format96 if $fixed_system_online_status[$cnt_sys_ids] eq '-1' ; + } elsif ($_ eq 'network_test') { + if ($is_in_future && $report && ($glod_user_level > 2 || $is_installation_partner || $is_schools_manager)) { + my $field = "network_test_$id\_$event_id" ; $align = qq~ class="dt-center $_"~ ; + $preferred_title{$field} = "Test Network" ; + $opts{$field} = $opts{$_} ; + $allow_deselect{$field} = 1 ; + $useropts{'common'}{'css'} .= qq~.$_ { min-width:170px; } ~ ; + my $ucfirstfield = ucfirst $field ; + $val = qq~~ ; + if ($fixed_system_network_test[$cnt_sys_ids]) { + $trigger_jquery_raw .= qq~ + \$("#select$ucfirstfield").val("$fixed_system_network_test[$cnt_sys_ids]") ; + \$("#select$ucfirstfield").trigger("chosen:updated") ; + ~ ; + } + $trigger_jquery_raw .= qq~\$("#select$ucfirstfield").chosen({ allow_single_deselect:true });~ ; + $val_min = "Passed" if $fixed_system_network_test[$cnt_sys_ids] eq '1' ; + $val_min = "Failed" if $fixed_system_network_test[$cnt_sys_ids] eq '-1' ; + $val_min = "None" unless $val_min ; + } else { + $val = "Passed" if $fixed_system_network_test[$cnt_sys_ids] eq '1' ; + $val = "Failed" if $fixed_system_network_test[$cnt_sys_ids] eq '-1' ; + $val = "None" unless $val ; + $val_min = $val ; + } + $trigger_jquery_raw .= qq~\$("#itv-table tr:eq($event_cnt) td:nth-last-child(6)").css("background-color","$defualt_color{$fixed_system_network_test[$cnt_sys_ids]}");~ if $fixed_system_network_test[$cnt_sys_ids] ; + $formatting = $format94 if $fixed_system_network_test[$cnt_sys_ids] eq '1' ; + $formatting = $format96 if $fixed_system_network_test[$cnt_sys_ids] eq '-1' ; + } elsif ($_ eq 'system_test') { + if ($is_in_future && $report && ($glod_user_level > 2 || $is_installation_partner || $is_schools_manager)) { + my $field = "system_test_$id\_$event_id" ; $align = qq~ class="dt-center $_"~ ; + $preferred_title{$field} = "System Test" ; + $opts{$field} = $opts{$_} ; + $allow_deselect{$field} = 1 ; + $useropts{'common'}{'css'} .= qq~.$_ { min-width:170px; } ~ ; + # $val = &common_min_form_select_col($field,'') ; + my $ucfirstfield = ucfirst $field ; + $val = qq~~ ; + if ($fixed_system_system_test[$cnt_sys_ids]) { + $trigger_jquery_raw .= qq~ + \$("#select$ucfirstfield").val("$fixed_system_system_test[$cnt_sys_ids]") ; + \$("#select$ucfirstfield").trigger("chosen:updated") ; + ~ ; + } + $trigger_jquery_raw .= qq~\$("#select$ucfirstfield").chosen({ allow_single_deselect:true });~ ; + $val_min = "Passed" if $fixed_system_system_test[$cnt_sys_ids] eq '1' ; + $val_min = "Failed" if $fixed_system_system_test[$cnt_sys_ids] eq '-1' ; + $val_min = "None" unless $val_min ; + + } else { + $val = "Passed" if $fixed_system_system_test[$cnt_sys_ids] eq '1' ; + $val = "Failed" if $fixed_system_system_test[$cnt_sys_ids] eq '-1' ; + $val = "None" unless $val ; + $val_min = $val ; + } + $trigger_jquery_raw .= qq~\$("#itv-table tr:eq($event_cnt) td:nth-last-child(5)").css("background-color","$defualt_color{$fixed_system_system_test[$cnt_sys_ids]}");~ if $fixed_system_system_test[$cnt_sys_ids] ; + $formatting = $format94 if $fixed_system_system_test[$cnt_sys_ids] eq '1' ; + $formatting = $format96 if $fixed_system_system_test[$cnt_sys_ids] eq '-1' ; + } elsif ($_ eq 'test_event') { + if ($is_in_future && $report && ($glod_user_level > 2 || $is_installation_partner || $is_schools_manager)) { + my $field = "test_event_$id\_$event_id" ; $align = qq~ class="dt-center $_"~ ; + $preferred_title{$field} = "Test Event" ; + $opts{$field} = $opts{$_} ; + $allow_deselect{$field} = 1 ; + $useropts{'common'}{'css'} .= qq~.$_ { min-width:170px; } ~ ; + # $val = &common_min_form_select_col($field,'') ; + my $ucfirstfield = ucfirst $field ; + $val = qq~~ ; + if ($fixed_system_test_event[$cnt_sys_ids]) { + $trigger_jquery_raw .= qq~ + \$("#select$ucfirstfield").val("$fixed_system_test_event[$cnt_sys_ids]") ; + \$("#select$ucfirstfield").trigger("chosen:updated") ; + ~ ; + } + $trigger_jquery_raw .= qq~\$("#select$ucfirstfield").chosen({ allow_single_deselect:true });~ ; + $val_min = "Good" if $fixed_system_test_event[$cnt_sys_ids] eq '1' ; + $val_min = "Not Good" if $fixed_system_test_event[$cnt_sys_ids] eq '-1' ; + $val_min = "None" unless $val_min ; + } else { + $val = "Good" if $fixed_system_test_event[$cnt_sys_ids] eq '1' ; + $val = "Not Good" if $fixed_system_test_event[$cnt_sys_ids] eq '-1' ; + $val = "None" unless $val ; + $val_min = $val ; + } + $trigger_jquery_raw .= qq~\$("#itv-table tr:eq($event_cnt) td:nth-last-child(4)").css("background-color","$defualt_color{$fixed_system_test_event[$cnt_sys_ids]}");~ if $fixed_system_test_event[$cnt_sys_ids] ; + $formatting = $format94 if $fixed_system_test_event[$cnt_sys_ids] eq '1' ; + $formatting = $format96 if $fixed_system_test_event[$cnt_sys_ids] eq '-1' ; + } elsif ($_ eq 'sound_test') { + if ($is_in_future && $report && ($glod_user_level > 2 || $is_installation_partner || $is_schools_manager)) { + my $field = "sound_test_$id\_$event_id" ; $align = qq~ class="dt-center $_"~ ; + $preferred_title{$field} = "Test Sound" ; + $opts{$field} = $opts{$_} ; + $allow_deselect{$field} = 1 ; + $useropts{'common'}{'css'} .= qq~.$_ { min-width:170px; } ~ ; + # $val = &common_min_form_select_col($field,'') ; + my $ucfirstfield = ucfirst $field ; + $val = qq~~ ; + if ($fixed_system_sound_test[$cnt_sys_ids]) { + $trigger_jquery_raw .= qq~ + \$("#select$ucfirstfield").val("$fixed_system_sound_test[$cnt_sys_ids]") ; + \$("#select$ucfirstfield").trigger("chosen:updated") ; + ~ ; + } + $trigger_jquery_raw .= qq~\$("#select$ucfirstfield").chosen({ allow_single_deselect:true });~ ; + $val = "None" unless $val ; + $val_min = $db{fixed_system_sound_test}{$fixed_system_sound_test[$cnt_sys_ids]}{name} if $fixed_system_sound_test[$cnt_sys_ids] ; + $val_min = "None" unless $val_min ; + } else { + $val = $db{fixed_system_sound_test}{$fixed_system_sound_test[$cnt_sys_ids]}{name} if $fixed_system_sound_test[$cnt_sys_ids] ; + $val = "None" unless $val ; + $val_min = $val ; + } + $trigger_jquery_raw .= qq~\$("#itv-table tr:eq($event_cnt) td:nth-last-child(3)").css("background-color","$defualt_color2{$fixed_system_sound_test[$cnt_sys_ids]}");~ if $fixed_system_sound_test[$cnt_sys_ids] ; + $formatting = $format94 if $fixed_system_sound_test[$cnt_sys_ids] eq '1' ; + $formatting = $format95 if $fixed_system_sound_test[$cnt_sys_ids] eq '2' ; + $formatting = $format96 if $fixed_system_sound_test[$cnt_sys_ids] eq '3' ; + } elsif ($_ eq 'overall_status') { + if ($is_in_future && $report && ($glod_user_level > 2 || $is_installation_partner || $is_schools_manager)) { + $found_after_date = 1 ; + my $field = "overall_status_$id\_$event_id" ; $align = qq~ class="dt-center $_"~ ; + $preferred_title{$field} = "Overall Status" ; + $opts{$field} = $opts{$_} ; + $allow_deselect{$field} = 1 ; + $useropts{'common'}{'css'} .= qq~.$_ { min-width:170px; } ~ ; + # $val = &common_min_form_select_col($field,'') ; + my $ucfirstfield = ucfirst $field ; + $val = qq~~ ; + if ($fixed_system_overall_status[$cnt_sys_ids]) { + $trigger_jquery_raw .= qq~ + \$("#select$ucfirstfield").val("$fixed_system_overall_status[$cnt_sys_ids]") ; + \$("#select$ucfirstfield").trigger("chosen:updated") ; + ~ ; + } + $trigger_jquery_raw .= qq~\$("#select$ucfirstfield").chosen({ allow_single_deselect:true });~ ; + $val_min = $db{fixed_system_status}{$fixed_system_overall_status[$cnt_sys_ids]}{status} if $fixed_system_overall_status[$cnt_sys_ids] ; + $val_min = "None" unless $val_min ; + } else { + $val = $db{fixed_system_status}{$fixed_system_overall_status[$cnt_sys_ids]}{status} if $fixed_system_overall_status[$cnt_sys_ids] ; + $val = "None" unless $val ; + $val_min = $val ; + } + $trigger_jquery_raw .= qq~\$("#itv-table tr:eq($event_cnt) td:nth-last-child(2)").css("background-color","$defualt_color2{$fixed_system_overall_status[$cnt_sys_ids]}");~ if $fixed_system_overall_status[$cnt_sys_ids] ; + $formatting = $format94 if $fixed_system_overall_status[$cnt_sys_ids] eq '1' ; + $formatting = $format95 if $fixed_system_overall_status[$cnt_sys_ids] eq '2' ; + $formatting = $format96 if $fixed_system_overall_status[$cnt_sys_ids] eq '3' ; + } elsif ($_ eq 'additional_comments') { + if ($is_in_future && $report && ($glod_user_level > 2 || $is_installation_partner || $is_schools_manager)) { + my $field = "additional_comments_$id\_$event_id" ; my $ucfirstfield = ucfirst $field ; $align = qq~ class="dt-center $_ controls"~ ; + $preferred_title{$field} = "Additional Comments" ; $useropts{'common'}{'css'} .= qq~.$_ { min-width:170px; } ~ ; + # $val = &common_min_form_input_col($field,'') ; + $val = qq~~ ; + if ($fixed_system_additional_comments[$cnt_sys_ids]) { + $trigger_jquery_raw .= qq~ + \$("#inputAdditional_comments_$id\_$event_id").val("$fixed_system_additional_comments[$cnt_sys_ids]") ; + ~ ; + } + $val_min = $fixed_system_additional_comments[$cnt_sys_ids] ; + $val_min = "None" unless $val_min ; + } else { + $val = $fixed_system_additional_comments[$cnt_sys_ids] ; + $val = "None" unless $val ; + $val_min = $val ; + } + } + + if ($_ ne 'online_status' && $_ ne 'network_test' && $_ ne 'system_test' && $_ ne 'test_event' && $_ ne 'sound_test' && $_ ne 'overall_status' && $_ ne 'additional_comments') { + $val_min = $val ; + $val_min =~ s/\
    /\;/g ; + } + $print_tbody .= qq~$val~ if $report ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$formatting) ; + $xlsxcol++ ; + } + $print_tbody .= qq~~ if $report ; + $xlsxrow++ ; + } + } + + $worksheet{$ws}->set_column(0,0,10); + $worksheet{$ws}->set_column(1,1,30); + $worksheet{$ws}->set_column(2,3,15); + $worksheet{$ws}->set_column(4,4,45); + $worksheet{$ws}->set_column(5,5,15); + $worksheet{$ws}->set_column(6,6,45); + $worksheet{$ws}->set_column(7,12,15); + $worksheet{$ws}->set_column(13,13,45); + + &report_xlsx_export_footer('N',15,$xlsxdir) ; + +} #------------------------------------------------------------------------------- + +sub fixedsystem_check_for_overlapping_dates { + + my ($check_table,$checked_column,$date_from_input,$date_to_input,$sys_ids_input,$get_periods) = @_ ; + + my %seen_system_id = () ; my %checked_system_id = () ; my %system_start_date = () ; my %system_end_date = () ; + + my $sys_ids = "" ; + + if ($get_periods) { + $sys_ids = $sys_ids_input ; + } + + + foreach my $id (sort keys %{$db{$table}}) { + + unless ($get_periods) { + $sys_ids = $db{$table}{$id}{$checked_column} ; + } + foreach (split(";",$sys_ids)) { + + $system_start_date{$_}{$id} = $db{$table}{$id}{date_from} ; + $system_end_date{$_}{$id} = $db{$table}{$id}{date_to} ; + } + } + + if ($date_from_input and $date_to_input and $sys_ids_input) { + + foreach (split(";",$sys_ids_input)) { + + $system_start_date{$_}{-1} = $date_from_input ; + $system_end_date{$_}{-1} = $date_to_input ; + } + } + + foreach my $id (sort keys %{$db{$table}}) { + + unless ($get_periods) { + $sys_ids = $db{$table}{$id}{$checked_column} ; + } + + foreach my $sys_id (split(";",$sys_ids)) { + + next unless $sys_id ; + + if ($seen_system_id{$sys_id} and not $checked_system_id{$sys_id}) { + + $checked_system_id{$sys_id} = 1 ; + foreach my $id2 (keys %{$system_start_date{$sys_id}}) { + + next if $id2 eq $id ; + my $t1 = &common_check_if_time_is_greater($system_start_date{$sys_id}{$id2},$db{$table}{$id}{date_to}) ; ## 21<12 + my $t2 = &common_check_if_time_is_greater($system_end_date{$sys_id}{$id2},$db{$table}{$id}{date_to}) ; ## 22<12 + my $t3 = &common_check_if_time_is_greater($system_start_date{$sys_id}{$id2},$db{$table}{$id}{date_from}) ; ## 21<11 + my $t4 = &common_check_if_time_is_greater($system_end_date{$sys_id}{$id2},$db{$table}{$id}{date_from}) ; ## 22<11 + + if (($t1 and not $t2) or ($t3 and not $t4) or (not $t3 and $t2) or ($t3 and not $t2)) { + my $system_name = qq~$db{$check_table}{$sys_id}{name}~ ; + $system_name .= qq~ ($db{$check_table}{$sys_id}{description})~ if $db{$check_table}{$sys_id}{description} ; + + if ($get_periods) { + $overlap_dates{$sys_id}{$id2} = "$db{$table}{$id2}{date_from} - $db{$table}{$id2}{date_to}" ; + } else { + $trigger_jquery_raw .= qq~ + noty({text:'System $system_name and cannot be used in both event $db{$table}{$id}{ref} and $db{$table}{$id2}{ref} as the times ovelap!!',layout:"center",type:"error",timeout:30000}) ; + ~ ; + } + } + } + } + $seen_system_id{$sys_id} = 1 ; + } + } +} #------------------------------------------------------------------------------- + +1 ; \ No newline at end of file diff --git a/libs/modules/_FromProd/v1.0/getmail.pm b/libs/modules/_FromProd/v1.0/getmail.pm new file mode 100644 index 0000000..15870f5 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/getmail.pm @@ -0,0 +1,287 @@ +sub getmail_fetch { + +# $mail_psw = 'znMpCa6pikZF' ; +# $mail_host = 'pop.yandex.com' ; +# $mail_user = 'itv.k@re8it.com' ; + +# $mail_psw = 'vf1VBE6AGuPE' ; +$mail_psw = $send_mail_psw ; +# $mail_host = 'envoy.aserv.co.za' ; +$mail_host = 'pop3.interactivetvafrica.com' ; +$mail_user = 'tickets@interactivetvafrica.com' ; + +# $mail_psw = "Jat20161" ; +# $mail_host = "outlook.office365.com" ; +# $mail_user = "tickets\@aisport.africa" ; + +use IO::Socket::SSL; + +$socket = IO::Socket::SSL->new( PeerAddr => $mail_host, + PeerPort => 995, + SSL_verify_mode => SSL_VERIFY_NONE, + Proto => 'tcp') || die "No socket!"; + +$pop = new Mail::POP3Client( USER => $mail_user, PASSWORD => $mail_psw, HOST => $mail_host, USESSL => true, SOCKET => $socket ) || die $pop->Message(); +# $pop = new Mail::POP3Client( USER => $mail_user, PASSWORD => $mail_psw, HOST => $mail_host, PORT => 995, AUTH_MODE => 'PASS', USESSL => true, SOCKET => $socket ) || die $pop->Message(); + +# # OR with SSL +# $pop = new Mail::POP3Client( USER => $mail_user, + # PASSWORD => $mail_psw, + # HOST => $mail_host, + # USESSL => true, + # ) || die $pop->Message(); + +#connect to POP3 sever +# my $pop = new Mail::POP3Client( HOST => $mail_host ); +# $pop->User($mail_user); +# $pop->Pass($mail_psw); +# $pop->Connect() || die "Unable to connect to POP3 server: ".$pop->Message()."\n"; + +if ($debug) { + use Data::Dumper; + print Dumper(\$pop); + &common_debug ("get_mail : office_user = $mail_user") ; + } + +$nummsgs = $pop->Count; + +&common_debug ("get_mail : nummsgs [$nummsgs]") ; + +for ($i = 1; $i <= $pop->Count(); $i++) { + + # # sometimes the 'To' is like this : 'graham evens <12345+gevens-bookings@eccotours.co.za>' + # # sometimes the 'To' is like this : '12345+gevens-bookings@eccotours.co.za' + # # so we split it by '<' to just get the bit we want + # my @to_array = split (/\Head( $i ) ; + $head = &getmail_clean($head) ; + + &common_debug ("get_mail : head [$head]") ; + + %mailcontent = () ; + + my $subject_auto_conf = '' ; + my $subject_auto_decline = '' ; + + # if ($head =~ /[\d]+\++[\w]+-bookings@[\w\.\-]+\w+/) { # 18398+autoreq-bookings@ecco.co.za + # $to = $& ; + # } + # elsif ($head =~ /AUTO+\s+CONFIRMATION+\s:\s+[\d]+\s:\s+[\w]+-+[\w]+\s+\(+[\w]+\)/) { # If subject = AUTO CONFIRMATION : 123456 : hotelcode-room (789123) + # $subject_auto_conf = $& ; + # } + # else + # { + foreach ( $pop->Head( $i ) ) { + chomp; + /^(From|Subject|To|Cc):\s+/i; + my ($index,$value) = split(/:/); + $mailcontent{$index} = $value; + } + + my @to_array = split (/\//g ; + # } + + # $mailaccount = '' ; + # $junk = '' ; + + &common_debug ("get_mail : to [$to]") ; + + $uniqueid = $pop->Uidl($i); + $uniqueid =~ s/\s//g; # strip whitespace + + $headandbody = $pop->HeadAndBody( $i ) ; + + # &common_debug ("get_mail : uniqueid [$uniqueid] headandbody [$headandbody]") ; + &common_debug ("get_mail : uniqueid [$uniqueid]") ; + + &getmail_mailparse ; + + $pop->Delete( $i ) ; # temp comment out + + } + +$pop->Close(); + +} #------------------------------------------------------------------------------------------ + +sub getmail_clean { + +my ($item) = @_ ; + +$item =~ s/\|/-/g; # remove any pipes +$item =~ s/\n//g; # remove any newlines +$item =~ s/\r//g; # remove any carriage returns +$item =~ s/\"//g; # remove " marks +$item =~ s/\'//g; # remove ' marks + +return ($item) ; + +} #------------------------------------------------------------------------------------------ + +sub getmail_mailparse { + +$parser = MIME::Parser->new; + +### Keep parsed message bodies in core (default outputs to disk): +# $parser->output_to_core(1); # don't write attachments to disk +$parser->output_to_core('NONE') ; # or die "can't output_to_core: $!" ; + +### Change how nameless message-component files are named: +$parser->output_prefix("msg") or die "can't output_prefix: $!" ; + +&getmail_make_dir ; + +binmode(STDOUT, ":utf8"); + +### Output each message body to the same directory: +# $parser->output_under($outputdir); +$parser->output_dir($outputdir) or die "can't output into $outputdir: $!" ; + +# $entity->dump_skeleton; # for debugging + +$entity = $parser->parse_data($headandbody) or die "can't parse_data $headandbody: $!" ; + +&getmail_process_entity_header ; +&getmail_process_output_dir ; + +} #------------------------------------------------------------------------------------------ + +sub getmail_process_output_dir { + +$i{unique_id} = $uniqueid ; +$i{date_time} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; +$i{client_id} = '0' ; +$i{staff_id} = '0' ; +$i{sent_date} = $mailparsedate ; +$i{doctype} = 'ticket' ; +$i{mailtype} = 'EMAILI' ; +$i{subject} = $mailparsesubject ; +$i{sent_from} = $mailparsefrom ; +$i{sent_to} = $to ; +$i{cc} = $mailcontent{'Cc'} ; +$i{bcc} = $mailcontent{'Bcc'} ; +$i{reply_to} = $mailparsereplyto ; +# $i{action_time} = ; +$i{completed} = '0' ; + +&db_min_insert('tickets') ; + +my @hash_split = split /\#\#/, $mailparsesubject ; +my @subj_uid = split / /, $hash_split[1] ; +my $suid = $subj_uid[0] ; + +if ($suid && length($suid)>5) { + %i = () ; + $i{completed} = '0' ; + &db_min_upd('tickets',"suid='$suid' OR unique_id='$suid' OR suid='$uniqueid' OR unique_id='$uniqueid'") ; +} + +} #------------------------------------------------------------------------------------------ + +sub getmail_make_dir { + +our $outputdir = "$mailpath/tickets/$uniqueid" ; + +return if -d $outputdir ; + +mkdir ($outputdir,0777) or die "mkdir $outputdir: $!" ; +chmod (0777, $outputdir) ; + +} #------------------------------------------------------------------------------------------ + +sub getmail_process_entity_header { + +use Encode qw(decode); + +$mailparsesubject = $entity->head->get('subject'); + +&common_debug ("getmail_process_entity_header : subject [$mailparsesubject]") ; + +$mailparsesubject = decode("MIME-Header", $mailparsesubject) ; + +&common_debug ("getmail_process_entity_header : subject [$mailparsesubject]") ; + +$mailparsesubject =~ s/\|/-/g; # remove any pipes +$mailparsesubject =~ s/\n//g; # remove any newlines +$mailparsesubject =~ s/\r//g; # remove any carriage returns +$mailparsesubject =~ s/\'//g; # remove any apostrophes + +$mailparsesubject =~ s/\/\///g; # remove the '//' from TLF chasers +$mailparsesubject =~ s/\\//g; # remove the '\' from TLF chasers + +unless ($mailparsesubject) { $mailparsesubject = "(No Subject)" ; } + +$mailparsefrom = $entity->head->get('from'); +$mailparsefrom =~ s/\|/-/g; # remove any pipes +$mailparsefrom =~ s/\n//g; # remove any newlines +$mailparsefrom =~ s/\r//g; # remove any carriage returns +$mailparsefrom =~ s/\"//g; # remove " marks +$mailparsefrom =~ s/\'//g; # remove ' marks + +$mailpamailparsefrom = decode("MIME-Header", $mailparsefrom) ; + +$mailparsereplyto = $entity->head->get('Reply-To'); +$mailparsereplyto =~ s/\|/-/g; # remove any pipes +$mailparsereplyto =~ s/\n//g; # remove any newlines +$mailparsereplyto =~ s/\r//g; # remove any carriage returns +$mailparsereplyto =~ s/\"//g; # remove " marks +$mailparsereplyto =~ s/\'//g; # remove ' marks + +$mailparsedate = $entity->head->get('date'); + +my ($dayofweek, $day, $month, $ccyy, $time, $gmt) = split /\s/, $mailparsedate ; + +$day = sprintf("%02d", ($day)) ; + +$m{jan} = '01' ; $m{feb} = '02' ; $m{mar} = '03' ; $m{apr} = '04' ; $m{may} = '05' ; $m{jun} = '06' ; $m{jul} = '07' ; $m{aug} = '08' ; $m{sep} = '09' ; $m{oct} = '10' ; $m{nov} = '11' ; $m{dec} = '12' ; + +my $hashkey = lc $month ; +# $mailparsedate = "$day." . $m{$hashkey} ."." . substr($ccyy,2,2) . " (" . substr($time,0,5) . ")" ; # 15.06.22 (12:49) +$mailparsedate = "$ccyy-$m{$hashkey}-$day " . substr($time,0,8) ; # 2022-06-21 12:49:35 + +chomp $mailparsesubject ; +chomp $mailparsedate ; +chomp $mailparsefrom ; +chomp $mailparsereplyto ; + +unless ($mailparsereplyto) { + $mailparsereplyto = $mailparsefrom ; + } + +&getmail_auto_reply ; + +&common_debug ("getmail_process_entity_header : mailparsereplyto [$mailparsereplyto]") ; + +} #------------------------------------------------------------------------------------------ + +sub getmail_auto_reply { + + my @hash_split = split /\#\#/, $mailparsesubject ; + my @subj_uid = split / /, $hash_split[1] ; + + &common_debug ("getmail_auto_reply : subj_uid=[$subj_uid[0]]") ; + + unless ($subj_uid[0] && length($subj_uid[0])>5) { + my $resubject = ($mailparsesubject =~ /Re:/iog) ? '' : 'Re: ' ; + my $resubject .= "$mailparsesubject ##$uniqueid##" ; + my $remsg = qq~Hello, thank you for contacting ITV. + +Your ticket ID is $uniqueid. + +One of our consultants will reply to you shortly to assist you with your query - typically within a few hours. + +For after-hour emergencies please contact Technical Support on support\@aisport.africa or telephonically on (+27) 10 534 7011. + +Best regards, + +The ITV Africa Team~ ; + &common_debug ("getmail_auto_reply : to=[$mailparsefrom] subject=[$resubject]") ; + &common_send_mail($mailparsefrom,'','','','',"$remsg","$resubject") ; + } + +} #------------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/_FromProd/v1.0/logistics.pm b/libs/modules/_FromProd/v1.0/logistics.pm new file mode 100644 index 0000000..51cea75 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/logistics.pm @@ -0,0 +1,710 @@ +sub logistics_load_db_vars { + + &db_min_ro('organisations','*',"",'','') ; + &db_min_ro('logistics_locations','*',"",'','') ; + &db_min_ro('logistics_suppliers','*',"active = '1'",'','') ; + &db_min_ro('logistics_items','*',"",'','') ; + &db_min_ro('event_systems','id,logistics_location_id',"(`system_type` = 'mobile' OR `system_type` = 'solo' OR `description` lIKE 'cricket%')",'','') ; + + foreach (keys %i) { + local @abc = split("_",$_) ; + if (substr($_,0,7) eq 'update_') { + $seen_event_id{$abc[-1]} = 1 ; + } + } + # create_waybill_out_5136 + local @event_ids = () ; + foreach (keys %seen_event_id) { + push @event_ids , "`id` = '$_'" ; + } + local $e_q_sql = join (" OR ",@event_ids) ; + + &db_min_ro($table,'id,event_system_id_multiple,logistics_suppliers,logistics_waybill_nrs,logistics_status_ids,logistics_venue_id,logistics_item_ids,poc_id,recipient_id,logistics_special_instructions,logistics_complete,logistics_dcb_waybill,date_from,date_to,logistics_delivery_datetime,logistics_received_by,logistics_location_other,logistics_system_location_id,logistics_last_changed_by,logistics_dcb_comments,logistics_shipment_operator_id',"$e_q_sql",'','') ; + +} #------------------------------------------------------------------------------------------ + +sub logistics_dates { + + my ($from_to,$id) = @_ ; + + $nowrap = 'nowrap' ; + my ($year1,$month1,$day1) = split(/\-/,substr($db{$table}{$id}{date_from},0,10)) ; + my ($year2,$month2,$day2) = split(/\-/,substr($db{$table}{$id}{date_to},0,10)) ; + $val = qq~~ ; + if ($year1 ne $year2 && $month1 ne $month2 && $day1 ne $day2) { + $val = qq~ $day1 $month_names[$month1] $year1 -
    $day2 $month_names[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 ne $month2) { + $val = qq~ $day1 $month_names[$month1] -
    $day2 $month_names[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 eq $month2 && $day1 ne $day2) { + $val = qq~ $day1 - $day2 $month_names[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 eq $month2 && $day1 eq $day2) { + $val = qq~ $day2 $month_names[$month2] $year2~ ; + } + my $stime = substr($db{$table}{$id}{date_from},11,5) ; + my $etime = substr($db{$table}{$id}{date_to},11,5) ; + $valxlsx = $val ; + $valxlsx =~ s/
    //g ; + # $val = qq~$val~ ; + + # &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol+1,$stime,$formatting) ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol+2,$etime,$formatting) ; + +} #------------------------------------------------------------------------------------------ + +sub logistics_venue { + + my ($from_to,$id) = @_ ; + + $val = '' ; $nowrap = 'nowrap' ; + foreach my $_oid (@venue_ids) { + $val .= qq~$db{organisations}{$_oid}{name}~ ; + $val .= qq~ [$db{organisations}{$_oid}{region_code}]~ if $db{organisations}{$_oid}{region_code} ; + $val .= ',' ; + } + $val = substr($val,0,-1) if $val ; + $valxlsx = $val ; + $valxlsx =~ s/\,/\;/g ; + if (length($val) > 30) { + $val =~ s/\,/\
    /g ; + $val = substr($val,0,27) . qq~~ ; + } else { + $val =~ s/\,/\
    /g ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_system { + + my ($from_to,$id) = @_ ; + + $val = '' ; my $tooltip = '' ; + + foreach my $event_sys_id (@system_name_ids) { + next unless $event_sys_id ; + next unless $db{event_systems}{$event_sys_id}{system_type} ; + $system_count++ ; + $tooltip .= qq~
    $db{event_systems}{$event_sys_id}{name}~ ; + $tooltip .= qq~ [$db{event_systems}{$event_sys_id}{description}]~ if $db{event_systems}{$event_sys_id}{description} ; + } + + $tooltip = substr($tooltip,4) if $tooltip ; + $val = $tooltip ; + # $val = ($system_count > 1) ? qq~~ : ($system_count == 1) ? qq~~ : "" ; + $valxlsx = $tooltip ; + $valxlsx =~ s/\
    /\;/g ; + +} #------------------------------------------------------------------------------------------ + +sub logistics_from_to { + + my ($from_to,$id) = @_ ; + + $val = '' ; $valxlsx = 'MUSTBEBLANK' ; + + if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + $found_editable = 1 ; + $trigger_jquery_raw .= qq~\$("#$ucfirstfield{1},#$ucfirstfield{2}").chosen({allow_single_deselect:true}) ; ~ ; + + my $col_venue = ($from_to eq 'to') ? 10 : 11 ; + my $col_log_loc = ($from_to eq 'to') ? 11 : 10 ; + + if (($_ eq 'to' && $from_to eq 'to') || ($_ eq 'from' && $iaction eq 'report_from')) { # && $iaction eq 'report') || ($_ eq 'from' && $_ eq 'report_from') + $val = qq~ + + ~ ; + $trigger_jquery_raw .= qq~ + \$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child($col_venue)").css("z-index","$cali_cnt") ; + ~ ; + if ($db{$table}{$id}{logistics_venue_id}) { + $valxlsx = "$db{organisations}{$db{$table}{$id}{logistics_venue_id}}{name} [$db{organisations}{$db{$table}{$id}{logistics_venue_id}}{region_code}]" if $db{organisations}{$db{$table}{$id}{logistics_venue_id}}{region_code} ; + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{1}").val("$db{$table}{$id}{logistics_venue_id}") ; + ~ ; + push @selects_with_default_ids,"#$ucfirstfield{1}" if $ucfirstfield{1} ; + push @table_with_default_ids,"#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child($col_venue)" ; + + $default_javascript .= qq~"$field{1}":"$db{$table}{$id}{logistics_venue_id}",~ ; + } elsif ($venue_ids[0]) { + $valxlsx = "$db{organisations}{$venue_ids[0]}{name} [$db{organisations}{$venue_ids[0]}{region_code}]" if $db{organisations}{$venue_ids[0]}{region_code} ; + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{1}").val("$venue_ids[0]") ; + ~ ; + push @selects_with_default_ids,"#$ucfirstfield{1}" if $ucfirstfield{1} ; + $default_javascript .= qq~"$field{1}":"$venue_ids[0]",~ ; + } else { + $default_javascript .= qq~"$field{1}":"",~ ; + } + } else { + $val = qq~ + + ~ ; + my $found_loc = 0 ; + + $trigger_jquery_raw .= qq~ + \$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child($col_log_loc)").css("z-index","$cali_cnt") ; + ~ ; + foreach my $event_sys_id (@system_name_ids) { + next unless $event_sys_id ; + next unless $db{event_systems}{$event_sys_id}{system_type} ; + if ($db{event_systems}{$event_sys_id}{logistics_location_id}) { + $valxlsx = $db{logistics_locations}{$db{event_systems}{$event_sys_id}{logistics_location_id}}{location} ; + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{2}").val("$db{event_systems}{$event_sys_id}{logistics_location_id}") ; + ~ ; + $found_loc = 1 ; + push @selects_with_default_ids,"#$ucfirstfield{2}" if $ucfirstfield{2} ; + push @table_with_default_ids,"#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child($col_log_loc)" ; + $default_javascript .= qq~"$field{2}":"$db{event_systems}{$event_sys_id}{logistics_location_id}",~ ; + } + last ; + } + if (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Johannesburg/) { + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{2}").val("1") ; + ~ ; + $default_javascript .= qq~"$field{2}":"1",~ ; + push @selects_with_default_ids,"#$ucfirstfield{2}" if $ucfirstfield{2} ; + } elsif (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Cape Town/) { + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{2}").val("2") ; + ~ ; + $default_javascript .= qq~"$field{2}":"2",~ ; + push @selects_with_default_ids,"#$ucfirstfield{2}" if $ucfirstfield{2} ; + } elsif (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Durban/) { + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{2}").val("3") ; + ~ ; + push @selects_with_default_ids,"#$ucfirstfield{2}" if $ucfirstfield{2} ; + $default_javascript .= qq~"$field{2}":"3",~ ; + } elsif (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Bloemfontein/) { + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{2}").val("4") ; + ~ ; + push @selects_with_default_ids,"#$ucfirstfield{2}" if $ucfirstfield{2} ; + $default_javascript .= qq~"$field{2}":"4",~ ; + } elsif (!$found_loc) { + $default_javascript .= qq~"$field{2}":"",~ ; + } + } + push @dropdown_chosen_ids,"#$ucfirstfield{1}\_chosen,#$ucfirstfield{2}\_chosen" if $ucfirstfield{1} && $ucfirstfield{2} ; + } else { + if (($_ eq 'to' && $from_to eq 'to') || ($_ eq 'from' && $iaction eq 'report_from')) { + if ($db{$table}{$id}{logistics_venue_id}) { + $val = qq~$db{organisations}{$db{$table}{$id}{logistics_venue_id}}{name}~ ; + $val .= qq~ [$db{organisations}{$db{$table}{$id}{logistics_venue_id}}{region_code}]~ if $db{organisations}{$db{$table}{$id}{logistics_venue_id}}{region_code} ; + } elsif ($venue_ids[0]) { + $val = qq~$db{organisations}{$venue_ids[0]}{name}~ ; + $val .= qq~ [$db{organisations}{$venue_ids[0]}{region_code}]~ if $db{organisations}{$venue_ids[0]}{region_code} ; + } + } else { + my $found_loc = 0 ; + foreach my $event_sys_id (@system_name_ids) { + next unless $event_sys_id ; + next unless $db{event_systems}{$event_sys_id}{system_type} ; + if ($db{event_systems}{$event_sys_id}{logistics_location_id}) { + $val = $db{logistics_locations}{$db{event_systems}{$event_sys_id}{logistics_location_id}}{location} ; + $found_loc = 1 ; + last ; + } + } + if (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Johannesburg/) { + $val = $db{logistics_locations}{1}{location} ; + } elsif (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Cape Town/) { + $val = $db{logistics_locations}{2}{location} ; + } elsif (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Durban/) { + $val = $db{logistics_locations}{3}{location} ; + } elsif (!$found_loc && $db{cities}{$db{$table}{$id}{city_id}}{name} =~ /Bloemfontein/) { + $val = $db{logistics_locations}{4}{location} ; + } + } + $valxlsx = $val ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_supplier { + + my ($from_to,$id) = @_ ; + + $val = '' ; $valxlsx = 'MUSTBEBLANK' ; + if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + $found_editable = 1 ; + $preferred_title{$field{supplier}} = "Supplier" ; + $opts{$field{supplier}} = $opts{logistics_supplier} ; + $trigger_jquery_raw .= qq~\$("#$ucfirstfield{supplier}").chosen({ allow_single_deselect:true });~ ; + $val = qq~~ ; + + $trigger_jquery_raw .= qq~ + \$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(9)").css("z-index","$cali_cnt") ; + ~ ; + + if ($logistics_supplier_ids_hash{$id}{$from_to}) { + $valxlsx = $db{logistics_suppliers}{$logistics_supplier_ids_hash{$id}{$from_to}}{supplier} ; + push @selects_with_default_ids,"#$ucfirstfield{supplier}" if $ucfirstfield{supplier} ; + push @table_with_default_ids,"#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(9)" ; + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{supplier}").val("$logistics_supplier_ids_hash{$id}{$from_to}") ; + // \$("#$ucfirstfield{supplier}").trigger("chosen:updated") ; + // \$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(9)").css("background-color","#424949") ; + ~ ; + } + push @dropdown_chosen_ids,"#$ucfirstfield{supplier}\_chosen" if $ucfirstfield{supplier} ; + } elsif ($logistics_supplier_ids_hash{$id}{$from_to}) { + $val = $db{logistics_suppliers}{$logistics_supplier_ids_hash{$id}{$from_to}}{supplier} ; + $valxlsx = $val ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_status { + + my ($from_to,$id) = @_ ; + + local %status_hash = (1 =>"Booked",2 => "Pending",3=>"In Transit",4 =>"Delivered") ; + $val = '' ; $valxlsx = 'MUSTBEBLANK' ; + # if (($from_to eq 'to' && $current_date <= $end_date) || ($from_to eq 'from' && $current_date <= $start_date)) { + if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + $found_editable = 1 ; + $preferred_title{$field{status}} = "Status" ; + $opts{$field{status}} = $opts{status} ; + $trigger_jquery_raw .= qq~\$("#$ucfirstfield{status}").chosen({ allow_single_deselect:true });~ ; + $val = qq~~ ; + + $trigger_jquery_raw .= qq~ + \$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(8)").css("z-index","$cali_cnt") ; + ~ ; + + $val = &common_min_form_select_col($field{status},'') ; ########### >= OR > + if ($logistics_status_ids_hash{$id}{$from_to}) { + $valxlsx = $status_hash{$logistics_status_ids_hash{$id}{$from_to}} ; + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{status}").val("$logistics_status_ids_hash{$id}{$from_to}") ; + // \$("#$ucfirstfield{status}").trigger("chosen:updated") ; + ~ ; + $default_javascript .= qq~"$field{status}":"$logistics_status_ids_hash{$id}{$from_to}",~ ; + push @selects_with_default_ids,"#$ucfirstfield{status}" if $ucfirstfield{status} ; + if ($logistics_status_ids_hash{$id}{$from_to} eq '1') { #Booked + $trigger_jquery_raw .= qq~\$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(8)").css("background-color","rgb(81,203,242)") ; ~ ; + } elsif ($logistics_status_ids_hash{$id}{$from_to} eq '2') { #Pending + $trigger_jquery_raw .= qq~\$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(8)").css("background-color","rgb(66,73,73)") ; ~ ; + } elsif ($logistics_status_ids_hash{$id}{$from_to} eq '3') { #In Transit + $trigger_jquery_raw .= qq~\$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(8)").css("background-color","rgb(255,165,0) ") ; ~ ; + } elsif ($logistics_status_ids_hash{$id}{$from_to} eq '4') { #Delivered + $trigger_jquery_raw .= qq~\$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(8)").css("background-color","rgb(46,204,113)") ; ~ ; + } + } else { + $default_javascript .= qq~"$field{status}":"2",~ ; + } + push @dropdown_chosen_ids,"#$ucfirstfield{status}\_chosen" if $ucfirstfield{status} ; + } elsif ($logistics_status_ids_hash{$id}{$from_to}) { + $val = $logistics_status_ids_hash{$logistics_status_ids_hash{$id}{$from_to}} ; + $valxlsx = $status_hash{$logistics_status_ids_hash{$id}{$from_to}} ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_waybill_nr { + + my ($from_to,$id) = @_ ; + + my $fname = 'waybill_nr' ; $val = '' ; $valxlsx = 'MUSTBEBLANK' ; + my $wb_code = 'AIS' . uc substr($from_to,0,1) . '_' ; + + if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + $found_editable = 1 ; + my $print_field = &common_min_print_field($field{$fname}) ; $tindex++ ; + my $wb_nr = ($logistics_waybill_ids_hash{$id}{$from_to}) ? $logistics_waybill_ids_hash{$id}{$from_to} : $wb_code . $id ; + $default_javascript .= qq~"$field{$fname}":"$wb_nr",~ ; + $val = qq~
    +
    ~ ; + $valxlsx = $wb_nr ; + $trigger_jquery .= qq~ \$("#$ucfirstfield{$fname}").css("width","100%") ;~ ; + $trigger_jquery_raw .= qq~\$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(7)").css("background-color","#424949") ; ~ if $logistics_waybill_ids_hash{$id}{$from_to} ; + } else { + $val = ($logistics_waybill_ids_hash{$id}{$from_to}) ? $logistics_waybill_ids_hash{$id}{$from_to} : (!$readlonly_row) ? $id : "" ; + print "\n logistics_waybill_nr" ; + $valxlsx = $val ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_item { + + my ($from_to,$id) = @_ ; + + $val = '' ; $valxlsx = 'MUSTBEBLANK' ; + if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + + $all_ids .= qq~,$id~ ; + $found_editable = 1 ; + $preferred_title{$field{item}} = "Item" ; + $opts{$field{item}} = $opts{logistics_items} ; + $trigger_jquery_raw .= qq~\$("#$ucfirstfield{item}").chosen({ allow_single_deselect:true });~ ; + + if ($logistics_item_ids_hash{$id}) { + push @table_with_default_ids,"#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(6)" ; + foreach my $item_id (split(/\,/,$logistics_item_ids_hash{$id})) { + next unless $item_id ; + $opts{$field{item}} =~ s/\Q"$item_id"/"$item_id" SELECTED/g ; + } + $valxlsx = join (';', map { $db{logistics_items}{$_}{name} } split /,/, $logistics_item_ids_hash{$id}); + } + + $val = qq~ + + ~ ; + + $trigger_jquery .= qq~ \$("#$ucfirstfield{item}\_chosen").css("width","100%") ;~ if $ucfirstfield{item} ; + + $extra_form_fields .= qq~~; + + $jquery_chosen_sel .= qq~ + item_val = \$("#selectItem_$id").chosen().val() ; + \$('#item-$id').val(item_val) ; + ~ ; + } elsif ($logistics_item_ids_hash{$id}) { + $val = join (',', map { $db{logistics_items}{$_}{name} } split /,/, $logistics_item_ids_hash{$id}); + $valxlsx = $val ; + $valxlsx =~ s/\,/\;/g ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_poc { + + my ($from_to,$id) = @_ ; + + $val = '' ; $valxlsx = 'MUSTBEBLANK' ; + if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + $found_editable = 1 ; + $preferred_title{$field{poc}} = "poc" ; + $opts{$field{poc}} = $opts{poc}{$id} ; + + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{poc}").chosen({ allow_single_deselect:true }) ; \$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(5)").css("z-index","$cali_cnt") ; + ~ ; + $val = qq~ + + ~ ; + + if ($logistics_poc_hash{$id}) { + $valxlsx = $logistics_poc_hash{$id} ; + $valxlsx =~ s/\_/ \[/g ; + $valxlsx .= qq~]~ ; + push @table_with_default_ids,"#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(5)" ; + push @selects_with_default_ids,"#$ucfirstfield{poc}" ; + $trigger_jquery_raw .= qq~ + \$("#$ucfirstfield{poc}").val("$logistics_poc_hash{$id}") ; + ~ ; + $default_javascript .= qq~"$field{poc}":"$logistics_poc_hash{$id}",~ ; + } else { + $default_javascript .= qq~"$field{poc}":"",~ ; + } + push @dropdown_chosen_ids,"#$ucfirstfield{poc}\_chosen" if $ucfirstfield{poc} ; + + } elsif ($logistics_poc_hash{$id}) { + $val = $logistics_poc_hash{$id} ; + $val =~ s/\_/\[/g ; + $val .= qq~]~ ; + $valxlsx = $val ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_special_instructions { + + my ($from_to,$id) = @_ ; + + $val = '' ; $valxlsx = 'MUSTBEBLANK' ; + # if (($from_to eq 'to' && $current_date <= $end_date) || ($from_to eq 'from' && $current_date <= $start_date)) { + if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + $found_editable = 1 ; + my $print_field = &common_min_print_field($field{special_instructions}) ; + $tindex++ ; + + my $defualt = ($logistics_special_instructions_hash{$id}{$from_to}) ? $logistics_special_instructions_hash{$id}{$from_to} : "" ; + + $valxlsx = $defualt if $defualt ; + $val = qq~ +
    +
    + +
    +
    + ~ ; + + $trigger_jquery .= qq~ + \$("#$ucfirstfield{special_instructions}").css("width","100%") ; + ~ ; + $trigger_jquery_raw .= qq~ + \$("#$useropts{table_id} tr:eq($cali_cnt) td:nth-last-child(4)").css("background-color","#424949") ; + ~ if $logistics_special_instructions_hash{$id}{$from_to} ; + } elsif ($logistics_special_instructions_hash{$id}{$from_to}) { + $val = $logistics_special_instructions_hash{$id}{$from_to} ; + $valxlsx = $val ; + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_create_waybill { + + my ($from_to,$id) = @_ ; + + # if (($from_to eq 'to' && $current_date <= $start_date) || ($from_to eq 'from' && $current_date <= $end_date)) { + if (!$readlonly_row) { + + $ignore{"$_\_$id"} = 1 ; + $valxlsx = '' ; + + # if ($_ eq 'process_complete') { + # $val = qq~~ ; + # } elsif (!$dcb_waybill_nr{$from_to} && $logistics_waybill_ids_hash{$id}{$from_to} && $items && $supp{$from_to} == 2) { # 2 = DCB Logistics + + if ($logistics_waybill_ids_hash{$id}{$from_to} && $db{$table}{$id}{logistics_item_ids} && $supp{$from_to} == 2) { + # if ($waybill_nr_default_val && $item_default_val && $supplier_default_val == 2) { + if ($dcb_waybill_nr{$from_to}) { + my $arrow_class = ($dcb_waybill_nr{$from_to} && $logistics_waybill_ids_hash{$id}{$from_to}) ? 'success' : 'danger' ; + my $arrow_direction = ($from_to eq 'to') ? 'right' : 'left' ; + my $dlg = qq~javascript:dlgMdl('$useropts{'scripts'}/dialog/dcb_trackntrace.pl?debug=1&waybillnr~; + my $uc_from_to = uc $from_to ; + $val = qq~~ ; + $nowrap = 'nowrap' ; + } else { + $val = qq~~ ; + } + } elsif ($waybill_nr_default_val && $item_default_val && $supplier_default_val == 2) { + $val = qq~~ ; + } else { + + my $tool_tip = qq~~ ; + + $tool_tip .= qq~
    - Add WayBillNr~ unless $waybill_nr_default_val ; + $tool_tip .= qq~
    - Add Item(s)~ unless $item_default_val ; + $tool_tip .= qq~
    - Set Supplier to DCB~ if $supplier_default_val != 2 ; + + $val = qq~~ ; + } + + # # # if (!$dcb_waybill_nr{$from_to} && $logistics_waybill_ids_hash{$id}{$from_to} && $db{$table}{$id}{logistics_item_ids} && $supp{$from_to} == 2) { # 2 = DCB Logistics + # # # $val = qq~~ ; + # # # } elsif ($dcb_waybill_nr{$from_to} && $logistics_waybill_ids_hash{$id}{$from_to} && $db{$table}{$id}{logistics_item_ids} && $supp{$from_to} == 2) { # 2 = DCB Logistics + + # # # my $arrow_class = ($dcb_waybill_nr{$from_to} && $logistics_waybill_ids_hash{$id}{$from_to}) ? 'success' : 'danger' ; + # # # # my $to_arrow_class = ($dcb_waybill_nr{to} && $logistics_waybill_ids_hash{$id}{to}) ? 'success' : 'danger' ; + # # # # my $from_arrow_class = ($dcb_waybill_nr{from} && $logistics_waybill_ids_hash{$id}{from}) ? 'success' : 'danger' ; + + # # # my $arrow_direction = ($from_to eq 'to') ? 'rigth' : 'left' ; + + # # # my $dlg = qq~javascript:dlgMdl('$useropts{'scripts'}/dialog/dcb_trackntrace.pl?debug=1&waybillnr~; + + # # # my $uc_from_to = uc $from_to ; + + # # # $val = qq~~ ; + # # # # $val = qq~ + # # # # ~ ; + # # # $nowrap = 'nowrap' ; + # # # } else { + # # # $val = qq~~ ; + # # # } + } + +} #------------------------------------------------------------------------------------------ + +sub logistics_jquery { + + my ($from_to) = @_ ; + + foreach my $system_id (keys %seen_system_cnt) { + chop $all_location_ids_per_system{$system_id} if $all_location_ids_per_system{$system_id} ; + } + + my $update_ids_str = join(',',@update_ids) ; + my $selects_with_default_ids_str = join(',',@selects_with_default_ids) ; + my $table_with_default_ids_str = join(',',@table_with_default_ids) ; + my $dropdown_chosen_ids_str = join(',',@dropdown_chosen_ids) ; +# + my $plus_item = ($is_dcb_partner) ? qq~ITEM~ : qq~ITEM~ ; + + $trigger_jquery .= qq~ + \$("#$useropts{table_id} tr th:nth-last-child($last_child{item})").html("$plus_item") ; + \$("#$useropts{table_id} tr th:nth-last-child($last_child{from})").html("FROM") ; + \$("#$useropts{table_id} tr th:nth-last-child($last_child{to})").html("TO") ; + \$('[data-toggle="tooltip"]').tooltip({ + container: 'body' + }); + ~ ; + + my $plus_poc = ($is_dcb_partner) ? 'POC' : qq~POC~ ; + + $trigger_jquery .= qq~ + \$("#$useropts{table_id} tr th:nth-last-child($last_child{poc})").html("$plus_poc") ; + ~ ; + + my $icon = qq~~ ; + + $trigger_jquery .= qq~ + \$("#$useropts{table_id}_wrapper").css("overflow","scroll"); + \$("#$useropts{table_id}_wrapper").css("height","60vh"); + // \$("#$useropts{table_id}_wrapper").css("overflow-y","hidden"); + \$("#$useropts{table_id}").css("width","175%") ; + \$("#$useropts{table_id}").css("max-width","175%"); + \$("#$useropts{table_id} tr th").slice(-3, -1).css("width","0%"); + \$("#$useropts{table_id} tr th:nth-last-child(1)").css("width","0%"); + ~ ; + + # if ($from_to eq 'to') { + + # $icon = qq~~ ; + + # $trigger_jquery .= qq~ + # \$("#$useropts{table_id} tr th:nth-last-child(3)").html("$icon") ; + # \$("#$useropts{table_id} tr th:nth-last-child(3) .glyphicons-disk-open").tooltip(); + # ~ ; + + # $trigger_jquery .= qq~ + # \$("#$useropts{table_id} tr th").slice(-7, -3).css("width","7.5%"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{item})").css("width","13%"); + # \$("#$useropts{table_id} tr th").slice(-15, -10).css("width","7.5%"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_time})").css("width","4%"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_date})").css("width","4.5%"); + # ~ ; + + # $icon = qq~~ ; + + # } else { + + # $icon = qq~~ ; + # $icon = qq~~ ; + + # $trigger_jquery .= qq~ + # \$("#$useropts{table_id} tr th:nth-last-child(3)").html("$icon") ; + # \$("#$useropts{table_id} tr th:nth-last-child(3) .glyphicons-disk-save").tooltip(); + # ~ ; + + # foreach (keys %last_child) { $trigger_jquery .= qq~\$("#$useropts{table_id} tr th:nth-last-child($last_child{$_})").css("width","7.5%");~ ; } + + $trigger_jquery .= qq~ + \$("#$useropts{table_id} tr th:nth-last-child($last_child{other_from})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{other_to})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{system})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{from})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{to})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{supplier})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{poc})").css("width","7%"); + // \$("#$useropts{table_id} tr th:nth-last-child($last_child{item})").css("width","16%"); + // \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_time})").css("width","4%"); + // \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_date})").css("width","4.5%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{special_instructions})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{other_special_instructions})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{waybill_nr})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{status})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{received_by})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{dcb_comments})").css("width","7%"); + \$("#$useropts{table_id} tr th:nth-last-child($last_child{shipment_operator})").css("width","7%"); + ~ ; + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{other_from})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{other_to})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{system})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{from})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{to})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{supplier})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{poc})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{item})").css("min-width","320px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{item})").css("max-width","320px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_time})").css("min-width","105px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_time})").css("max-width","105px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_date})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_date})").css("max-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{special_instructions})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{other_special_instructions})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{waybill_nr})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{status})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{received_by})").css("min-width","120px"); + # \$("#$useropts{table_id} tr th:nth-last-child($last_child{dcb_comments})").css("min-width","120px"); + # ~ ; + + # $icon = qq~~ ; + # } + + # $icon = ($from_to eq 'from') ? qq~~ : qq~~ ; + + $icon = qq~~ ; + + $trigger_jquery .= qq~ + \$("#$useropts{table_id} tr th:nth-last-child(2)").html("$icon").trigger("chosen:updated") ; + \$("#$useropts{table_id} tr th:nth-last-child(2) .glyphicons-disk-open").tooltip(); + ~ ; + + $icon = qq~~ ; + + $trigger_jquery .= qq~ + \$("#$useropts{table_id} tr th:nth-last-child(1)").html("$icon") ; + \$("#$useropts{table_id} tr th:nth-last-child(1) .glyphicons-ok").tooltip() ; + ~ ; + + chop $quote_and_ops_ids if $quote_and_ops_ids ; + + $trigger_jquery_raw .= qq~ + function selectAll(col) { + + let from_to = \$("#from_to").text() ; + let col_id = "" ; + if (col == '1') { + col_id = "create_waybill_out_" ; + } else if (col == '2') { + col_id = "create_waybill_in_" ; + } + // else if (col == '3') { + // col_id = "process_complete_from_" ; + // } else if (col == '4') { + // col_id = "process_complete_to_" ; + // } + let jsObject = { + $quote_and_ops_ids + }; + for (let key in jsObject) { + let event_id = key ; + \$(\$("#$useropts{table_id}").dataTable().fnGetNodes()).find(\$("input[name='"+col_id+""+event_id+"']")).each(function () { + if(!\$(this).is(':checked')) { + \$(this).prop('checked',true); + } else { + \$(this).prop('checked',false); + } + }) ; + } + } + ~ ; + + $trigger_jquery .= qq~ + \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_date})").html("DELIVERY DATE BY") ; + // \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_date})").html("$icon") ; + // \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_date}) .glyphicons-calendar").tooltip() ; + ~ ; + + $trigger_jquery .= qq~ + \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_time})").html("DELIVERY TIME BY") ; + // \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_time})").html("$icon") ; + // \$("#$useropts{table_id} tr th:nth-last-child($last_child{delivery_time}) .glyphicon-time").tooltip() ; + ~ ; + +} #------------------------------------------------------------------------------------------ + +1 ; \ No newline at end of file diff --git a/libs/modules/_FromProd/v1.0/mailsend.pm b/libs/modules/_FromProd/v1.0/mailsend.pm new file mode 100644 index 0000000..aa58a37 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/mailsend.pm @@ -0,0 +1,89 @@ +sub mailsend { + +my ($from,$to,$subject,$emailmsg) = @_ ; + +use Mail::Sendmail; + +#------------------------------------------------------------------------------- + +my $boundary = "====" . time() . "===="; + +#--------------------------------------------------------------------------------- + +my %mail = () ; + +# if ($username eq 'rory') { $to = 'rory@kre8it.co.za' ; } + +unless ($from) { $from = qq(Film Freight ) ; } +# unless ($from) { $from = 'Film Freight ' ; } + +%mail = ( + smtp => 'localhost', + From => $from, + To => $to, + Subject => $subject + ); + +#--------------------------------------------------------------------------------- + +$mail{'content-type'} = "multipart/alternative; boundary=\"$boundary\""; + +# filmfreight + + +$boundary = '--'.$boundary; + +$mail{body} = < + + + + + + +

    + +

    +

    +$emailmsg +

    + + + +$boundary-- + +END_OF_BODY + +sendmail(%mail) ; + +# $mail{'content-type'} = "multipart/mixed; boundary=\"$boundary\""; + +# $boundary = '--'.$boundary; + +# $mail{body} = < +# +# +# $subject +# +# +# $email_msg +# +# + +# $boundary-- + +# END_OF_BODY + +# sendmail(%mail) ; + +} #------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/_FromProd/v1.0/match_event_production_time.pm b/libs/modules/_FromProd/v1.0/match_event_production_time.pm new file mode 100644 index 0000000..9f934c6 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/match_event_production_time.pm @@ -0,0 +1,603 @@ +sub read_db_to_match_events_and_systems { + + &common_date_array($last_start_ccyymmdd,$last_end_ccyymmdd); + + &db_min_ro('event_systems','id,name,description,system_type','','','') ; + foreach my $id (keys %{$db{event_systems}}) { + $event_system_description{$id} = $db{event_systems}{$id}{description} ; + $event_system_name{$id} = $db{event_systems}{$id}{name} ; + } + + $start_sql = substr($start_sql,0,11) . '00:00:00' ; + $end_sql = substr($end_sql,0,11) . '23:59:59' ; + + # &db_min_ro('event_quotes','id,ref,event_system_id_multiple,format_of_title,date_from,date_to',"(date_from BETWEEN '$start_sql' AND '$end_sql') OR (date_to BETWEEN '$start_sql' AND '$end_sql')",'','') ; + + &db_min_ro('event_quotes','id,ref,event_system_id_multiple,format_of_title,date_from,date_to,sport_type_ids,club_ids',"((date_from BETWEEN '$start_sql' AND '$end_sql') OR (date_to BETWEEN '$start_sql' AND '$end_sql')) AND event_system_id_multiple IS NOT NULL AND event_system_id_multiple <> ''",'','') ; + + our %seen_event_system_in_event_quotes = () ; + + foreach my $event_id (keys %{$db{event_quotes}}) { + + $db{event_quotes}{$event_id}{ref} =~ s/\'//g ; + + $db{event_quotes}{$event_id}{event_system_id_multiple} =~ s/;+/;/g; # Replace multiple semicolons with one + $db{event_quotes}{$event_id}{event_system_id_multiple} =~ s/^;+|;+$//g; # Remove leading or trailing semicolons + + # next unless $db{event_quotes}{$event_id}{event_system_id_multiple} ; + + $opts{matched_event} .= qq~~ ; + + foreach (split(";",$db{event_quotes}{$event_id}{event_system_id_multiple})) { + + # $opts{matched_system} .= $seen_event_system_in_event_quotes{$_} + $seen_event_system_in_event_quotes{$_} = 1 ; + + } + } + + foreach (sort {$seen_event_system_in_event_quotes{$a} cmp $seen_event_system_in_event_quotes{$b}} keys %seen_event_system_in_event_quotes) { + $opts{matched_system} .= qq~~ ; + } + + $opts{matched_system_none} .= qq~~ ; + + &db_min_ro('sport_types','*','','','') ; + + our %sport_name_to_id = () ; + + foreach (keys %{$db{sport_types}}) { + $db{sport_types}{$_}{name} = lc $db{sport_types}{$_}{name} ; + $db{sport_types}{$_}{name} =~ s/ //g ; + $sport_name_to_id{$db{sport_types}{$_}{name}} = $_ ; + } + + &db_min_ro('clubs','id,name','','','') ; + + foreach (keys %{$db{clubs}}) { + my $c_name = lc $db{clubs}{$_}{name} ; + $c_name =~ s/\'//g ; + $club_name_to_id{$c_name} = $_ ; + } + + # foreach my $id (keys %{$db{event_quotes}}) { + # # $match_bank_trans{$db{event_quotes}{$id}{trans_date}}{$db{event_quotes}{$id}{description}} = 1 ; + + # foreach my $event_id (split(";",$db{$tables}{$id}{event_system_id_multiple})) { + # $val .= qq~$db{event_systems}{$event_id}{name} [$db{event_systems}{$event_id}{description}], ~ ; + # } + # } + +} #------------------------------------------------------------------------------------------ + +sub process_matched_events_and_systems { + + my %system_match = () ; my %matched_event_name = () ; my %csv_line_possible_match = () ; my %matched_events = () ; + + $system_match{"None"}{"None"} = -1 ; + + foreach my $event_code (keys %csv_line) { + + next if $matched_event{$event_code} ; + + my ($club_name,$system_desc_clue) = split("-",$csv_line{$event_code}{club_name}) ; + $club_name =~ s/ $//g ; $system_desc_clue =~ s/^ //g ; # remove whitespace + $club_name =~ s/\'//g ; + + $system_desc_clue = "None" unless $system_desc_clue ; + + my @eventdetails = split(/ /,$club_name) ; + + my $system_name_clue = $eventdetails[-1] ; $system_name_clue = "None" if $system_name_clue !~ /\d+/ ; + + if ($system_desc_clue =~ /\d+/ && length($system_desc_clue) == 5) { + $system_name_clue = $system_desc_clue ; + $system_desc_clue = 'None' ; + } + + if ($system_desc_clue =~ /AISA/ && $system_desc_clue =~ /SOLO/) { + my @sysparts = split(/\_/,$system_desc_clue) ; + $system_name_clue = $sysparts[2] ; + $system_desc_clue =~ s/\_/ /g ; + } + + $csv_line{$event_code}{system_id} = -1 if $system_name_clue eq 'None' && $system_desc_clue eq 'None' ; + + $system_desc_clue = lc $system_desc_clue ; + + $csv_line{$event_code}{system_id} = $system_match{$system_name_clue}{$system_desc_clue} if $system_match{$system_name_clue}{$system_desc_clue} ; + + if (!$csv_line{$event_code}{system_id}) { + + foreach my $system_id (keys %{$db{event_systems}}) { + # foreach my $system_id (keys %seen_event_system_in_event_quotes) { + + my $sys_desc = lc $db{event_systems}{$system_id}{description} ; + my $sys_name = $db{event_systems}{$system_id}{name} ; + + if (($sys_name =~ /\b$system_name_clue\b/ || $sys_name =~ /_$system_name_clue\b/) && $sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue ne 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + last ; + } elsif (($sys_name =~ /\b$system_name_clue\b/ || $sys_name =~ /_$system_name_clue\b/) && $system_name_clue ne 'None' && $system_desc_clue eq 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + last ; + } elsif ($sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue eq 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + last ; + } + } + } + + my @sport_split = split(":",$csv_line{$event_code}{event_name}) ; + + $sport_split[0] =~ s/ //g ; + $sport_split[0] = lc $sport_split[0] ; + + my $sport_id = ($csv_line{$event_code}{event_name} =~ /:/) ? $sport_name_to_id{$sport_split[0]} : '' ; + + my @event_name_details = split(/-/,$csv_line{$event_code}{event_name}) ; + + my $to_match_event_name = $event_name_details[-1] ; + + $to_match_event_name =~ s/^ //g ; + $to_match_event_name =~ s/ $//g ; + + $to_match_event_name = ($csv_line{$event_code}{event_name} =~ /:/ && $csv_line{$event_code}{event_name} !~ /-/) ? $sport_split[1] : $to_match_event_name ; + + $to_match_event_name =~ s/\'//g ; + + my $club_id = $club_name_to_id{$club_name} ; + + $club_name = ($csv_line{$event_code}{club_name} =~ /AISA/ && $csv_line{$event_code}{club_name} =~ /SOLO/) ? lc $club_name : lc $csv_line{$event_code}{club_name} ; + + if (!$csv_line{$event_code}{system_id}) { + + foreach my $id (keys %{$db{event_quotes}}) { + + next unless $id ; + + next if $sport_id && $db{event_quotes}{$id}{sport_type_ids} !~ /\b$sport_id\b/ ; + + next if $club_id && $db{event_quotes}{$id}{club_ids} !~ /\b$club_id\b/ ; + + next if !$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ ; + + my $event_end = substr($db{event_quotes}{$id}{date_to},0,11) . '23:59:59' ; + + my $event_start = substr($db{event_quotes}{$id}{date_from},0,11) . '00:00:00' ; + + my $after_event_end = &greater_date_time($event_end,$csv_line{$event_code}{start_time}) ; + next if $after_event_end ; + + my $before_event_start = &greater_date_time($csv_line{$event_code}{end_time},$event_start) ; + next if $before_event_start ; + + if ($to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + $csv_line{$event_code}{event_id} = $id ; + $matched_events{$event_code} .= qq~$id;~ ; + } + + my $found_match = 0 ; + + foreach my $system_id (split(";",$db{event_quotes}{$id}{event_system_id_multiple})) { + + my $sys_desc = lc $db{event_systems}{$system_id}{description} ; + my $sys_name = $db{event_systems}{$system_id}{name} ; + + if ($sys_name =~ /\b$system_name_clue\b/ && $sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue ne 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + } elsif ($sys_name =~ /\b$system_name_clue\b/ && $system_name_clue ne 'None' && $system_desc_clue eq 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + } elsif ($sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue eq 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + } + + # my $sys_desc = $db{event_systems}{$system_id}{description} ; + # my $sys_name = $db{event_systems}{$system_id}{name} ; + + # # my @sysparts = split(/\_/,$system) ; + + # if ($sys_name =~ /\b$sysno\b/ && $sys_desc =~ /\b$system\b/iog) { + # $csv_line{$event_code}{system_id} = $system_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } elsif ($system =~ /\d+/ && $sys_name =~ /\b$system\b/) { + # $csv_line{$event_code}{system_id} = $system_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } elsif ($system =~ /AISA/ && $system =~ /SOLO/ && $sysparts[2] && $sys_name =~ /\b$sysparts[2]\b/) { + # $csv_line{$event_code}{system_id} = $system_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } elsif ($sys_desc eq 'St Stithians Hockey Red' && $clubname =~ /Red/i && $clubname =~ /Stithians/i) { + # $csv_line{$event_code}{system_id} = $event_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } + } + + if ($found_match && !$csv_line{$event_code}{event_id}) { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + } + } + + if ($csv_line{$event_code}{system_id} && !$csv_line{$event_code}{event_id}) { + + foreach my $id (keys %{$db{event_quotes}}) { + + next if $sport_id && $db{event_quotes}{$id}{sport_type_ids} && $db{event_quotes}{$id}{sport_type_ids} !~ /\b$sport_id\b/ ; + + next if $club_id && $db{event_quotes}{$id}{club_ids} !~ /\b$club_id\b/ ; + + my $event_end = substr($db{event_quotes}{$id}{date_to},0,11) . '23:59:59' ; + + my $event_start = substr($db{event_quotes}{$id}{date_from},0,11) . '00:00:00' ; + + my $after_event_end = &greater_date_time($event_end,$csv_line{$event_code}{start_time}) ; + next if $after_event_end ; + + my $before_event_start = &greater_date_time($csv_line{$event_code}{end_time},$event_start) ; + next if $before_event_start ; + + if (!$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\b$csv_line{$event_code}{system_id}\b/) { + if ($csv_line{$event_code}{system_id} && !$seen_event_system_in_event_quotes{$csv_line{$event_code}{system_id}}) { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + next ; + } + + # if ($to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + if ($db{event_quotes}{$id}{sport_type_ids} && $to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } elsif ($db{event_quotes}{$id}{sport_type_ids}) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } else { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + } + } + + if ((!$csv_line{$event_code}{system_id}) && !$csv_line{$event_code}{event_id}) { + + foreach my $id (keys %{$db{event_quotes}}) { + + next if $sport_id && $db{event_quotes}{$id}{sport_type_ids} && $db{event_quotes}{$id}{sport_type_ids} !~ /\b$sport_id\b/ ; + + next if $club_id && $db{event_quotes}{$id}{club_ids} !~ /\b$club_id\b/ ; + + next if !$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ ; + + my $event_end = substr($db{event_quotes}{$id}{date_to},0,11) . '23:59:59' ; + + my $event_start = substr($db{event_quotes}{$id}{date_from},0,11) . '00:00:00' ; + + my $after_event_end = &greater_date_time($event_end,$csv_line{$event_code}{start_time}) ; + next if $after_event_end ; + + my $before_event_start = &greater_date_time($csv_line{$event_code}{end_time},$event_start) ; + next if $before_event_start ; + + # if (!$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\b$csv_line{$event_code}{system_id}\b/) { + # if ($csv_line{$event_code}{system_id} && !$seen_event_system_in_event_quotes{$csv_line{$event_code}{system_id}}) { + # $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + # } + # next ; + # } + + if ($db{event_quotes}{$id}{sport_type_ids} && $to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } elsif ($db{event_quotes}{$id}{sport_type_ids}) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } else { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + } + } + + chop $csv_line_possible_match{$event_code}{event_id} if $csv_line_possible_match{$event_code}{event_id} ; + + } + + $print_box_content_rows .= &common_min_forms_start("$lcpage") ; + + our @sql_col_display = ("club_system","system_nr","matched_system","production_hours","production_seconds","cloud_recording_seconds","club_name","start","end","event_name","matched_event","match") ; + + my $row_cnt = 0 ; my %no_system_or_event = () ; + + foreach my $event_code (sort {$csv_line{$a}{line_cnt} cmp $csv_line{$b}{line_cnt}} keys %csv_line) { + + next if $matched_event{$event_code} ; + + $row_cnt++ ; + + $print_tbody .= qq~~ ; + + my $cell_id = qq~~ ; + + my ($system,$sysno) = split(" - ",$csv_line{$event_code}{club_name}) ; + + my @get_sport = (!$csv_line{$event_code}{system_id} || (!$csv_line{$event_code}{event_id} && !$csv_line_possible_match{$event_code}{event_id}) || (!$csv_line{$event_code}{event_id} && $csv_line_possible_match{$event_code}{event_id} =~ /;/)) ? split(/\:/,$csv_line{$event_code}{event_name}) : () ; + + $extra_form_fields .= qq~~ if !$csv_line{$event_code}{system_id} || !$csv_line{$event_code}{event_id} ; + + foreach my $col (@sql_col_display) { + + my $val = '' ; $nowrap = '' ; + + if ($col eq 'club_name') { + $val = $csv_line{$event_code}{club_name} ; + } elsif ($col eq 'system_nr') { + $val = $sysno ; + } elsif ($col eq 'start') { + $val = $csv_line{$event_code}{start_time} ; + $nowrap = 'nowrap' ; + } elsif ($col eq 'end') { + $val = $csv_line{$event_code}{end_time} ; + $nowrap = 'nowrap' ; + } elsif ($col eq 'club_system') { + $val = $system ; + } elsif ($col eq 'matched_system') { + + $preferred_placeholder{"system_$row_cnt"} = "Select System" ; + + $found_system_drop_down = 1 if !$csv_line{$event_code}{system_id} || $csv_line{$event_code}{system_id} eq '-1' ; + + # $allow_deselect{"system_$row_cnt"} = 1 ; + + $val = ($csv_line{$event_code}{system_id} && $csv_line{$event_code}{system_id} ne '-1') ? "$db{event_systems}{$csv_line{$event_code}{system_id}}{name} [$db{event_systems}{$csv_line{$event_code}{system_id}}{description}]" : ($csv_line{$event_code}{system_id} eq '-1') ? &common_min_table_select("system_$row_cnt","",'','','','','',"matched_system_none") : &common_min_table_select("system_$row_cnt","",'','','','','',"matched_system") ; + # $val = ($csv_line{$event_code}{system_id} && $csv_line{$event_code}{system_id} ne '-1') ? "$db{event_systems}{$csv_line{$event_code}{system_id}}{name} [$db{event_systems}{$csv_line{$event_code}{system_id}}{description}]" : &common_min_table_select("system_$row_cnt","",'','','','','',"matched_system") ; + + if (!$csv_line{$event_code}{system_id} || $csv_line{$event_code}{system_id} eq '-1') { + + my $sport_name = ($csv_line{$event_code}{event_name} =~ /:/) ? $get_sport[0] : $csv_line{$event_code}{event_name} ; + $no_system_or_event{$csv_line{$event_code}{club_name}}{substr($csv_line{$event_code}{start_time},0,10)}{$sport_name}{system} .= qq~"#selectSystem_$row_cnt",~ ; + + } + + $cell_id = qq~id="matched_system_$row_cnt"~ ; + + } elsif ($col eq 'production_hours') { + $val = $csv_line{$event_code}{production_hours} ; + $val =~ s/\,/\./g ; + } elsif ($col eq 'production_seconds') { + $val = &common_commify($csv_line{$event_code}{production_seconds}) ; + } elsif ($col eq 'cloud_recording_seconds') { + $val = &common_commify($csv_line{$event_code}{cloud_seconds}) ; + } elsif ($col eq 'event_name') { + $val = $csv_line{$event_code}{event_name} ; + } elsif ($col eq 'matched_event') { + + $csv_line_possible_match{$event_code}{event_id} =~ s/\;/\_/g ; + + my $col_name = (!$csv_line{$event_code}{event_id} && $csv_line_possible_match{$event_code}{event_id}) ? "matched_event_$csv_line_possible_match{$event_code}{event_id}" : "matched_event" ; + + $opts{$col_name} = + ($csv_line_possible_match{$event_code}{event_id} && !$csv_line{$event_code}{event_id}) ? join "~ ; + + foreach (split(";",$db{event_quotes}{$event_id}{event_system_id_multiple})) { + + # $opts{matched_system} .= $seen_event_system_in_event_quotes{$_} + $seen_event_system_in_event_quotes{$_} = 1 ; + + } + } + + foreach (sort {$seen_event_system_in_event_quotes{$a} cmp $seen_event_system_in_event_quotes{$b}} keys %seen_event_system_in_event_quotes) { + $opts{matched_system} .= qq~~ ; + } + + $opts{matched_system_none} .= qq~~ ; + + &db_min_ro('sport_types','*','','','') ; + + our %sport_name_to_id = () ; + + foreach (keys %{$db{sport_types}}) { + $db{sport_types}{$_}{name} = lc $db{sport_types}{$_}{name} ; + $db{sport_types}{$_}{name} =~ s/ //g ; + $sport_name_to_id{$db{sport_types}{$_}{name}} = $_ ; + } + + &db_min_ro('clubs','id,name','','','') ; + + foreach (keys %{$db{clubs}}) { + my $c_name = lc $db{clubs}{$_}{name} ; + $c_name =~ s/\'//g ; + $club_name_to_id{$c_name} = $_ ; + } + + # foreach my $id (keys %{$db{event_quotes}}) { + # # $match_bank_trans{$db{event_quotes}{$id}{trans_date}}{$db{event_quotes}{$id}{description}} = 1 ; + + # foreach my $event_id (split(";",$db{$tables}{$id}{event_system_id_multiple})) { + # $val .= qq~$db{event_systems}{$event_id}{name} [$db{event_systems}{$event_id}{description}], ~ ; + # } + # } + +} #------------------------------------------------------------------------------------------ + +sub production_time_process_matched_events_and_systems { + + my %system_match = () ; my %matched_event_name = () ; my %csv_line_possible_match = () ; my %matched_events = () ; + + $system_match{"None"}{"None"} = -1 ; + + foreach my $event_code (keys %csv_line) { + + next if $matched_event{$event_code} ; + + my ($club_name,$system_desc_clue) = split("-",$csv_line{$event_code}{club_name}) ; + $club_name =~ s/ $//g ; $system_desc_clue =~ s/^ //g ; # remove whitespace + $club_name =~ s/\'//g ; + + $system_desc_clue = "None" unless $system_desc_clue ; + + my @eventdetails = split(/ /,$club_name) ; + + my $system_name_clue = $eventdetails[-1] ; $system_name_clue = "None" if $system_name_clue !~ /\d+/ ; + + if ($system_desc_clue =~ /\d+/ && length($system_desc_clue) == 5) { + $system_name_clue = $system_desc_clue ; + $system_desc_clue = 'None' ; + } + + if ($system_desc_clue =~ /AISA/ && $system_desc_clue =~ /SOLO/) { + my @sysparts = split(/\_/,$system_desc_clue) ; + $system_name_clue = $sysparts[2] ; + $system_desc_clue =~ s/\_/ /g ; + } + + $csv_line{$event_code}{system_id} = -1 if $system_name_clue eq 'None' && $system_desc_clue eq 'None' ; + + $system_desc_clue = lc $system_desc_clue ; + + $csv_line{$event_code}{system_id} = $system_match{$system_name_clue}{$system_desc_clue} if $system_match{$system_name_clue}{$system_desc_clue} ; + + if (!$csv_line{$event_code}{system_id}) { + + foreach my $system_id (keys %{$db{event_systems}}) { + # foreach my $system_id (keys %seen_event_system_in_event_quotes) { + + my $sys_desc = lc $db{event_systems}{$system_id}{description} ; + my $sys_name = $db{event_systems}{$system_id}{name} ; + + if (($sys_name =~ /\b$system_name_clue\b/ || $sys_name =~ /_$system_name_clue\b/) && $sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue ne 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + last ; + } elsif (($sys_name =~ /\b$system_name_clue\b/ || $sys_name =~ /_$system_name_clue\b/) && $system_name_clue ne 'None' && $system_desc_clue eq 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + last ; + } elsif ($sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue eq 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + last ; + } + } + } + + my @sport_split = split(":",$csv_line{$event_code}{event_name}) ; + + $sport_split[0] =~ s/ //g ; + $sport_split[0] = lc $sport_split[0] ; + + my $sport_id = ($csv_line{$event_code}{event_name} =~ /:/) ? $sport_name_to_id{$sport_split[0]} : '' ; + + my @event_name_details = split(/-/,$csv_line{$event_code}{event_name}) ; + + my $to_match_event_name = $event_name_details[-1] ; + + $to_match_event_name =~ s/^ //g ; + $to_match_event_name =~ s/ $//g ; + + $to_match_event_name = ($csv_line{$event_code}{event_name} =~ /:/ && $csv_line{$event_code}{event_name} !~ /-/) ? $sport_split[1] : $to_match_event_name ; + + $to_match_event_name =~ s/\'//g ; + + my $club_id = $club_name_to_id{$club_name} ; + + $club_name = ($csv_line{$event_code}{club_name} =~ /AISA/ && $csv_line{$event_code}{club_name} =~ /SOLO/) ? lc $club_name : lc $csv_line{$event_code}{club_name} ; + + if (!$csv_line{$event_code}{system_id}) { + + foreach my $id (keys %{$db{event_quotes}}) { + + next unless $id ; + + next if $sport_id && $db{event_quotes}{$id}{sport_type_ids} !~ /\b$sport_id\b/ ; + + next if $club_id && $db{event_quotes}{$id}{club_ids} !~ /\b$club_id\b/ ; + + next if !$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ ; + + my $event_end = substr($db{event_quotes}{$id}{date_to},0,11) . '23:59:59' ; + + my $event_start = substr($db{event_quotes}{$id}{date_from},0,11) . '00:00:00' ; + + my $after_event_end = &greater_date_time($event_end,$csv_line{$event_code}{start_time}) ; + next if $after_event_end ; + + my $before_event_start = &greater_date_time($csv_line{$event_code}{end_time},$event_start) ; + next if $before_event_start ; + + if ($to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + $csv_line{$event_code}{event_id} = $id ; + $matched_events{$event_code} .= qq~$id;~ ; + } + + my $found_match = 0 ; + + foreach my $system_id (split(";",$db{event_quotes}{$id}{event_system_id_multiple})) { + + my $sys_desc = lc $db{event_systems}{$system_id}{description} ; + my $sys_name = $db{event_systems}{$system_id}{name} ; + + if ($sys_name =~ /\b$system_name_clue\b/ && $sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue ne 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + } elsif ($sys_name =~ /\b$system_name_clue\b/ && $system_name_clue ne 'None' && $system_desc_clue eq 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + } elsif ($sys_desc =~ /\b$system_desc_clue\b/ && $system_name_clue eq 'None' && $system_desc_clue ne 'none') { + $csv_line{$event_code}{system_id} = $system_id ; + $system_match{$system_name_clue}{$system_desc_clue} = $system_id ; + } + + # my $sys_desc = $db{event_systems}{$system_id}{description} ; + # my $sys_name = $db{event_systems}{$system_id}{name} ; + + # # my @sysparts = split(/\_/,$system) ; + + # if ($sys_name =~ /\b$sysno\b/ && $sys_desc =~ /\b$system\b/iog) { + # $csv_line{$event_code}{system_id} = $system_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } elsif ($system =~ /\d+/ && $sys_name =~ /\b$system\b/) { + # $csv_line{$event_code}{system_id} = $system_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } elsif ($system =~ /AISA/ && $system =~ /SOLO/ && $sysparts[2] && $sys_name =~ /\b$sysparts[2]\b/) { + # $csv_line{$event_code}{system_id} = $system_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } elsif ($sys_desc eq 'St Stithians Hockey Red' && $clubname =~ /Red/i && $clubname =~ /Stithians/i) { + # $csv_line{$event_code}{system_id} = $event_id ; + # $system_match{$system}{$sysno} = $system_id ; + # $found_match = 1 ; + # } + } + + if ($found_match && !$csv_line{$event_code}{event_id}) { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + } + } + + if ($csv_line{$event_code}{system_id} && !$csv_line{$event_code}{event_id}) { + + foreach my $id (keys %{$db{event_quotes}}) { + + next if $sport_id && $db{event_quotes}{$id}{sport_type_ids} && $db{event_quotes}{$id}{sport_type_ids} !~ /\b$sport_id\b/ ; + + next if $club_id && $db{event_quotes}{$id}{club_ids} !~ /\b$club_id\b/ ; + + my $event_end = substr($db{event_quotes}{$id}{date_to},0,11) . '23:59:59' ; + + my $event_start = substr($db{event_quotes}{$id}{date_from},0,11) . '00:00:00' ; + + my $after_event_end = &greater_date_time($event_end,$csv_line{$event_code}{start_time}) ; + next if $after_event_end ; + + my $before_event_start = &greater_date_time($csv_line{$event_code}{end_time},$event_start) ; + next if $before_event_start ; + + if (!$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\b$csv_line{$event_code}{system_id}\b/) { + if ($csv_line{$event_code}{system_id} && !$seen_event_system_in_event_quotes{$csv_line{$event_code}{system_id}}) { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + next ; + } + + # if ($to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + if ($db{event_quotes}{$id}{sport_type_ids} && $to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } elsif ($db{event_quotes}{$id}{sport_type_ids}) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } else { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + } + } + + if ((!$csv_line{$event_code}{system_id}) && !$csv_line{$event_code}{event_id}) { + + foreach my $id (keys %{$db{event_quotes}}) { + + next if $sport_id && $db{event_quotes}{$id}{sport_type_ids} && $db{event_quotes}{$id}{sport_type_ids} !~ /\b$sport_id\b/ ; + + next if $club_id && $db{event_quotes}{$id}{club_ids} !~ /\b$club_id\b/ ; + + next if !$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ ; + + my $event_end = substr($db{event_quotes}{$id}{date_to},0,11) . '23:59:59' ; + + my $event_start = substr($db{event_quotes}{$id}{date_from},0,11) . '00:00:00' ; + + my $after_event_end = &greater_date_time($event_end,$csv_line{$event_code}{start_time}) ; + next if $after_event_end ; + + my $before_event_start = &greater_date_time($csv_line{$event_code}{end_time},$event_start) ; + next if $before_event_start ; + + # if (!$db{event_quotes}{$id}{event_system_id_multiple} || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\d+/ || $db{event_quotes}{$id}{event_system_id_multiple} !~ /\b$csv_line{$event_code}{system_id}\b/) { + # if ($csv_line{$event_code}{system_id} && !$seen_event_system_in_event_quotes{$csv_line{$event_code}{system_id}}) { + # $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + # } + # next ; + # } + + if ($db{event_quotes}{$id}{sport_type_ids} && $to_match_event_name && ($db{event_quotes}{$id}{ref} eq $to_match_event_name || $db{event_quotes}{$id}{ref} =~ /$to_match_event_name/)) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } elsif ($db{event_quotes}{$id}{sport_type_ids}) { + $csv_line{$event_code}{event_id} = $id ; + last ; + } else { + $csv_line_possible_match{$event_code}{event_id} .= qq~$id;~ ; + } + } + } + + chop $csv_line_possible_match{$event_code}{event_id} if $csv_line_possible_match{$event_code}{event_id} ; + + } + + $print_box_content_rows .= &common_min_forms_start("$lcpage") ; + + our @sql_col_display = ("club_system","system_nr","matched_system","production_hours","production_seconds","cloud_recording_seconds","club_name","start","end","event_name","matched_event","match") ; + + my $row_cnt = 0 ; my %no_system_or_event = () ; + + foreach my $event_code (sort {$csv_line{$a}{line_cnt} cmp $csv_line{$b}{line_cnt}} keys %csv_line) { + + next if $matched_event{$event_code} ; + + $row_cnt++ ; + + $print_tbody .= qq~~ ; + + my $cell_id = qq~~ ; + + my ($system,$sysno) = split(" - ",$csv_line{$event_code}{club_name}) ; + + my @get_sport = (!$csv_line{$event_code}{system_id} || (!$csv_line{$event_code}{event_id} && !$csv_line_possible_match{$event_code}{event_id}) || (!$csv_line{$event_code}{event_id} && $csv_line_possible_match{$event_code}{event_id} =~ /;/)) ? split(/\:/,$csv_line{$event_code}{event_name}) : () ; + + $extra_form_fields .= qq~~ if !$csv_line{$event_code}{system_id} || !$csv_line{$event_code}{event_id} ; + + foreach my $col (@sql_col_display) { + + my $val = '' ; $nowrap = '' ; + + if ($col eq 'club_name') { + $val = $csv_line{$event_code}{club_name} ; + } elsif ($col eq 'system_nr') { + $val = $sysno ; + } elsif ($col eq 'start') { + $val = $csv_line{$event_code}{start_time} ; + $nowrap = 'nowrap' ; + } elsif ($col eq 'end') { + $val = $csv_line{$event_code}{end_time} ; + $nowrap = 'nowrap' ; + } elsif ($col eq 'club_system') { + $val = $system ; + } elsif ($col eq 'matched_system') { + + $preferred_placeholder{"system_$row_cnt"} = "Select System" ; + + $found_system_drop_down = 1 if !$csv_line{$event_code}{system_id} || $csv_line{$event_code}{system_id} eq '-1' ; + + # $allow_deselect{"system_$row_cnt"} = 1 ; + + $val = ($csv_line{$event_code}{system_id} && $csv_line{$event_code}{system_id} ne '-1') ? "$db{event_systems}{$csv_line{$event_code}{system_id}}{name} [$db{event_systems}{$csv_line{$event_code}{system_id}}{description}]" : ($csv_line{$event_code}{system_id} eq '-1') ? &common_min_table_select("system_$row_cnt","",'','','','','',"matched_system_none") : &common_min_table_select("system_$row_cnt","",'','','','','',"matched_system") ; + # $val = ($csv_line{$event_code}{system_id} && $csv_line{$event_code}{system_id} ne '-1') ? "$db{event_systems}{$csv_line{$event_code}{system_id}}{name} [$db{event_systems}{$csv_line{$event_code}{system_id}}{description}]" : &common_min_table_select("system_$row_cnt","",'','','','','',"matched_system") ; + + if (!$csv_line{$event_code}{system_id} || $csv_line{$event_code}{system_id} eq '-1') { + + my $sport_name = ($csv_line{$event_code}{event_name} =~ /:/) ? $get_sport[0] : $csv_line{$event_code}{event_name} ; + $no_system_or_event{$csv_line{$event_code}{club_name}}{substr($csv_line{$event_code}{start_time},0,10)}{$sport_name}{system} .= qq~"#selectSystem_$row_cnt",~ ; + + } + + $cell_id = qq~id="matched_system_$row_cnt"~ ; + + } elsif ($col eq 'production_hours') { + $val = $csv_line{$event_code}{production_hours} ; + $val =~ s/\,/\./g ; + } elsif ($col eq 'production_seconds') { + $val = &common_commify($csv_line{$event_code}{production_seconds}) ; + } elsif ($col eq 'cloud_recording_seconds') { + $val = &common_commify($csv_line{$event_code}{cloud_seconds}) ; + } elsif ($col eq 'event_name') { + $val = $csv_line{$event_code}{event_name} ; + } elsif ($col eq 'matched_event') { + + $csv_line_possible_match{$event_code}{event_id} =~ s/\;/\_/g ; + + my $col_name = (!$csv_line{$event_code}{event_id} && $csv_line_possible_match{$event_code}{event_id}) ? "matched_event_$csv_line_possible_match{$event_code}{event_id}" : "matched_event" ; + + $opts{$col_name} = + ($csv_line_possible_match{$event_code}{event_id} && !$csv_line{$event_code}{event_id}) ? join "~ ; + # $opts{head_operator} .= qq~~ ; + foreach my $_uid (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + next if $useropts{it}{$db{users}{$_uid}{username}} ; + + my $regions = qq~~ ; + foreach (split(/\,/,$db{users}{$_uid}{region_ids})) { + $regions .= qq~$db{regions}{$_}{code},~ ; + } + chop $regions if $regions ; + $regions = qq~[$regions]~ if $regions ; + + # if ($db{users}{$_uid}{user_type} eq 'support' || $db{users}{$_uid}{user_type} eq 'manager' || $db{users}{$_uid}{user_type} eq 'casual_calibrator' || $monitoring_report) { + if ($db{users}{$_uid}{user_type} eq 'casual_calibrator' || (($monitoring_report || $troubleshoot_monitoring_report) && $db{users}{$_uid}{user_type} ne 'casual_c' && $db{users}{$_uid}{user_type} ne 'schools_manager' && $db{users}{$_uid}{user_type} ne 'support' && $db{users}{$_uid}{user_type} ne 'permanent')) { + $opts{schedule_users} .= qq~~ ; + } + + if (($db{users}{$_uid}{user_type} eq 'support' || $db{users}{$_uid}{user_type} eq 'casual_calibrator') && $temp_calibrator_report) { + $opts{support_users} .= qq~~ ; + $tot_support_users_cnt++; + } + + if ($db{users}{$_uid}{user_type} eq 'casual_c') { + $opts{fixture_check} .= qq~~ ; + } + } + + my $event_systems_sql_where = ($monitoring_report || $troubleshoot_monitoring_report) ? "" : "system_type = 'mobile'" ; + + &db_min_ro('event_systems','*',$event_systems_sql_where,'','') ; + + &db_min_ro($table,"id,club_ids,qty,ref,organisation_ids,quote_accepted,event_system_id_multiple,region_id,sport_type_ids,operator_ids,date_from,date_to,times_from,times_to,daily_operator_ids,days_active,monitor_ids,temp_calibrator_ids$extra_column","$where AND `quote_accepted` = '1'",'','') ; + + my $min_id = 0 ; my $max_id = 0 ; + + foreach my $id (keys %{$db{$table}}) { + + next unless $id ; my $cnt = 0 ; + + my @ed_from = &common_split_sql_time($db{$table}{$id}{date_from}) ; + my @ed_to = &common_split_sql_time($db{$table}{$id}{date_to}) ; + + &common_date_array("$ed_from[0]$ed_from[1]$ed_from[2]","$ed_to[0]$ed_to[1]$ed_to[2]") ; + + $sort_calibration_by_time_ref{"$ed_from[0]$ed_from[1]$ed_from[2]$ed_from[3]$ed_from[4]-$id"} = $id ; + + } + + &db_min_ro('sport_types','*','','','') ; + &db_min_ro('organisations','id,name','','','') ; + &db_min_ro('clubs','id,name','','','') if $monitoring_report || $troubleshoot_monitoring_report ; + + our $table_ = "shift_operator_ids" ; + my $col_ = ($monitoring_report) ? "monitor_ids" : ($troubleshoot_monitoring_report) ? "troubleshoot_monitor_ids" : "temp_calibrator_ids,temp_calibrator_support_shifts" ; + my $col2_ = ($monitoring_report) ? ",monitor_notes" : ($troubleshoot_monitoring_report) ? ",troubleshoot_monitor_notes" : "" ; + + &db_min_ro($table_,"date$col2_,$col_","`date` >= '$i{date_from}' AND `date` <= '$i{date_to}'") ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_build_extra_table { + + my ($field_name,$table_name,$table_col_name,$table_col_name_notes,$table_id) = @_ ; + + my $ws2 = join ' ', map { ucfirst $_ } split /_/, $field_name ; + $ws2 .= "s" ; + + &xlsxcreator_add_worksheet($ws2) ; + + my $col2 = 0 ; + foreach (@sql_col_display_extra) { + next if $_ eq "update" || !$_ || $_ eq 'notes' ; + my $coltitle = $_ ; + $coltitle =~ s/\_id//g ; + $coltitle =~ s/\_/ /g ; + my $ucfirst = join '', map { ucfirst lc } split /(\s+)/, $coltitle; + &xlsxcreator_write_xlsx($ws2,0,$col2,$ucfirst,$format_management_report_headings) ; + $col2++; + } + $col2=0 ; + &xlsxcreator_freeze_panes($ws2,1,0) ; # Freeze the first 3 rows + + my $uc_field_name = ucfirst $field_name ; + + # $db{$table_name}{$i{date}}{$table_col_name} = qq~147;132|||~ ; + + # for (0 .. 3) { $schedule_ids[$_] = "null" unless $schedule_ids[$_] ; } + $format84 -> set_left('1') ; + + my ($s_year,$s_mon,$s_day) = split("-",$i{date_from}) ; + my ($e_year,$e_mon,$e_day) = split("-",$i{date_to}) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + + our $date_cnt = 1 ; my $row_cnt = 0 ; + + return if int("$s_year$s_mon$s_day") > int("$e_year$e_mon$e_day") ; + + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + my %row_cnt_shifts = () ; my $max_row_cnt = 0 ; + + while (int("$s_year$s_mon$s_day") <= int("$e_year$e_mon$e_day")) { + + $db{$table_name}{"$s_year-$s_mon-$s_day"}{$table_col_name} =~ s/\;/\,/g ; + my @schedule_ids = split(/\|/,$db{$table_name}{"$s_year-$s_mon-$s_day"}{$table_col_name}) ; + + my $date = "$s_year-$s_mon-$s_day" ; + + my $date_str = &common_min_date_as_string($date) ; + + our $default_javascript = "" ; my %default_javascript_short = () ; + + my $val_notes = qq~~ ; + + foreach my $col (@sql_col_display_extra) { + + my $formatting = $format92 ; + next if substr($col,0,5) eq 'shift' && substr($col,0,7) ne 'shift_1' ; + my $val = '' ; my $nowrap = '' ; my $align = qq~~ ; my $val_min = "" ; + + my $row_span = '' ; + + if ($col eq 'date') { + + $row_cnt++ ; + $row_span = qq~rowspan="2"~ if $monitoring_report || $troubleshoot_monitoring_report ; + $val = $date_str . qq~~ ; + $nowrap = "nowrap" ; + &xlsxcreator_write_xlsx($ws2,$max_row_cnt+1,0,$date_str ,$formatting) ; + + } elsif (substr($col,0,7) eq 'shift_1') { + + $align = qq~ class="dt-center"~ ; + + local $place_holder = substr($ws2,0,-1) ; + + for (1 .. 4) { + $row_cnt_shifts{$_} = $max_row_cnt + 1 ; + } + + for my $shift_cnt (1 .. 4) { + + # $row_cnt_shifts{$shift_cnt} = ($max_row_cnt && $shift_cnt == 1) ? $max_row_cnt + 1 : 1 ; + my $field = "$field_name\_$shift_cnt\_1_1_$date_cnt" ; + $opts{$field} = $opts{schedule_users} ; + $preferred_placeholder{$field} = ($troubleshoot_monitoring_report) ? "Shift Troubleshoot Monitor $shift_cnt $date_cnt" : "$place_holder $shift_cnt $date_cnt" ; + $multiple{$field} = 1 ; + + my $table_col = 6-$shift_cnt ; + push @first_table_multi_select_table_cells,"#$table_id tr:eq($row_cnt) td:nth-last-child($table_col)" ; + + $val .= &common_min_table_select($field,$schedule_ids[$shift_cnt - 1],'',$row_cnt,$table_col,'',$schedule_ids[$shift_cnt - 1],'shift',$table_id) ; + foreach (split(/\,/,$schedule_ids[$shift_cnt - 1])) { + next unless $_ ; + $trigger_jquery_raw .= qq~\$("#select$uc_field_name\_$shift_cnt\_1_1_$date_cnt option[value='$_']").prop("selected",true);~ ; + &xlsxcreator_write_xlsx($ws2,$row_cnt_shifts{$shift_cnt},$shift_cnt,"$db{users}{$_}{name}",$formatting) ; + $row_cnt_shifts{$shift_cnt}++ ; + } + $max_row_cnt = $row_cnt_shifts{$shift_cnt} if !$max_row_cnt || $max_row_cnt < $row_cnt_shifts{$shift_cnt} ; + $val .= qq~~ if $shift_cnt < 4 ; + } + + } elsif ($col eq 'notes') { + + $row_cnt++ ; + + my @notes = split(/\:\|\:/,$db{$table_name}{$date}{$table_col_name_notes}) ; + # $max_row_cnt-- ; + # $max_row_cnt++ if $db{$table_name}{$date}{$table_col_name_notes} =~ /(\d+)/g || $db{$table_name}{$date}{$table_col_name_notes} =~ /[a-zA-Z]/ ; + + for my $shift_cnt (1 .. 4) { + + my $field = "$field_name\_notes_$shift_cnt\_1_1_$date_cnt" ; + $preferred_placeholder{$field} = ($troubleshoot_monitoring_report) ? "Shift Troubleshoot Monitor Notes $shift_cnt $date_cnt" : "Shift Monitor Notes $shift_cnt $date_cnt" ; + $val_notes .= &common_min_table_textarea($field,$notes[$shift_cnt-1],'',$row_cnt,5-$shift_cnt,'',$notes[$shift_cnt-1],'',$table_id) ; + &xlsxcreator_write_xlsx($ws2,$max_row_cnt,$shift_cnt,$notes[$shift_cnt-1],$format97) if $db{$table_name}{$date}{$table_col_name_notes} =~ /(\d+)/g || $db{$table_name}{$date}{$table_col_name_notes} =~ /[a-zA-Z]/ ; + $val_notes .= qq~~ if $shift_cnt < 4 ; + + } + + $val_notes = qq~$val_notes~ ; + + } elsif ($col eq "update") { + + $row_span = qq~rowspan="2"~ if $monitoring_report || $troubleshoot_monitoring_report ; + $align = qq~ class="dt-center"~ ; + my $field = "update_1_1_$date_cnt" ; + $val = &common_min_form_checkbox_col($field,'') ; + + chop $default_javascript if $default_javascript ; + + if ($default_javascript) { + + push @default_javascript_by_id, qq~"1_1_$date_cnt":{$default_javascript}~ ; ## ??? + + for (1 .. 4) { + my $field = "#textarea" . ucfirst "$field_name\_notes\_$_\_1_1_$date_cnt" ; + push @all_update_field_ids,"$field" if $monitoring_report || $troubleshoot_monitoring_report ; + $field = "#select" . ucfirst "$field_name\_$_\_1_1_$date_cnt" ; + push @all_update_field_ids,"$field" ; + } + } + } + + $print_tbody_extra .= qq~$val~ if $col ne 'notes' ; + + $print_tbody_extra .= qq~$val_notes~ if $col eq 'update' ; + + } + + ($s_year,$s_mon,$s_day) = Add_Delta_Days($s_year,$s_mon,$s_day,1) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + $date_cnt++ ; + } + + $date_cnt-- ; + + # &common_min_table_select_fixed_width_jquery(1) ; + # &common_min_table_select_default_values_jquery ; + + # @all_select_ids = () ; @selects_with_default_ids = () ; %col_name_select_ids = () ; %table_with_default_ids = () ; %selects_by_def_val = () ; + + @sql_col_display_extra = ("date","shift_1_(08:00-11:00)","shift_2_(11:00-14:00)","shift_3_(14:00-17:00)","shift_4_(17:00-21:00)","update") if $monitoring_report || $troubleshoot_monitoring_report ; + + $worksheet{$ws2}->set_column(0,0,10) ; + $worksheet{$ws2}->set_column(1,5,50) if $monitoring_report || $troubleshoot_monitoring_report ; + $worksheet{$ws2}->set_column(1,5,20) if $temp_calibrator_report ; + + $trigger_jquery_raw .= qq~\$("#$table_id tr:eq(0) th:nth-last-child(2),#$table_id tr th:nth-last-child(3),#$table_id tr th:nth-last-child(4),#$table_id tr th:nth-last-child(5)").css("width","23%")~ ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_build_extra_second_table { + + my ($field_name,$table_name,$table_col_name) = @_ ; + + my $ws2 = join ' ', map { ucfirst $_ } split /_/, $field_name ; + $ws2 .= "s" ; + + &xlsxcreator_add_worksheet($ws2) ; + + my $col2 = 0 ; + foreach (@sql_col_display_2) { + next if $_ eq "update" || !$_ ; + my $coltitle = $_ ; + $coltitle =~ s/\_id//g ; + $coltitle =~ s/\_/ /g ; + my $ucfirst = join '', map { ucfirst lc } split /(\s+)/, $coltitle; + &xlsxcreator_write_xlsx($ws2,0,$col2,$ucfirst,$format_management_report_headings) ; + $col2++; + } + $col2=0 ; + &xlsxcreator_freeze_panes($ws2,1,0) ; # Freeze the first 3 rows + + my ($s_year,$s_mon,$s_day) = split("-",$i{date_from}) ; + my ($e_year,$e_mon,$e_day) = split("-",$i{date_to}) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + + $opts{name} = $opts{support_users} ; + + $radio_opts{shift} = "Half Day (<7 hours);Full Day (7 hours+)" ; + + my $nr_of_options = scalar split("option> int("$e_year$e_mon$e_day") ; + + my $date1 = "$s_year-$s_mon-$s_day" ; + my $date2 = "$e_year-$e_mon-$e_day" ; + my $d1 = Time::Piece->strptime($date1, "%Y-%m-%d") ; + my $d2 = Time::Piece->strptime($date2, "%Y-%m-%d") ; + my $diff_in_days = ($d2 - $d1)->days + 1; + + my $date_cnt= 0 ; + + &common_min_thead_2 ; + + for my $day_cnt (1 .. $diff_in_days) { + + my $date = "$s_year-$s_mon-$s_day" ; + + $db{$table_name}{$date}{$table_col_name} = "None" unless $db{$table_name}{$date}{$table_col_name} ; + + $date_cnt++ ; + + push @second_table_ids,"#select_temp_calibrators_2_$date_cnt" ; + push @second_table_ids_2,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(2)" ; + push @second_table_ids_3,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(3)" ; + push @second_table_ids_4,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(4)" ; + push @second_table_ids_5,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(5)" ; + + $print_tbody_extra_2 .= qq~~ ; + $print_tbody_extra_2 .= qq~$print_thead_2~ if $date_cnt == 1 ; + $print_tbody_extra_2 .= qq~~ ; + + my $row_cnt = 0 ; + + $opts{name} = $opts{support_users} ; + + my $z_index = $tot_support_users_cnt * ($diff_in_days - $day_cnt + 1) + 1 ; + + foreach my $row (split(/\|/,$db{$table_name}{$date}{$table_col_name})) { + + $z_index-- ; + + next unless $row ; + + $row_cnt++ ; + $print_tbody_extra_2 .= qq~~ ; + + our $default_javascript = qq~~ ; + + $xlsxrow++ ; $xlsxcol = 0 ; + + foreach my $col (@sql_col_display_2) { + + my $formatting = $format84 ; + my $val = '' ; my $nowrap = '' ; my $align = qq~class="dt-center"~ ; + + my $field_id = "$col\_2_$row_cnt\_$date_cnt" ; + + my $default_val_html = qq~~ ; + + if ($col eq 'date') { + my $date_str = &common_min_date_as_string($date) ; + $val = $date_str ; + $nowrap = "nowrap" ; + $align = qq~class="dt-left"~ ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow,$xlsxcol,"$date_str",$formatting) ; + } elsif ($col eq 'name') { + my @abc = split(/\:/,$row) ; + $abc[0] = "" if $abc[0] eq "None" ; + $default_val = $abc[0] ; + $default_val_is_saved = ($default_val) ? 1 : 0 ; + $preferred_placeholder{$field_id} = "Select Temp Support Name $row_cnt" ; + $opts{$field_id} = $opts{name} ; + + my $table_row_cnt = ($date_cnt == 1) ? $row_cnt + 1 : $row_cnt - 1 ; + + $val = &common_min_table_select($field_id,$default_val,'',$table_row_cnt,4,'',$default_val_is_saved,'',"select_temp_calibrators_2_$date_cnt") ; + # $default_val_html = qq~~ ; + + $trigger_jquery_raw .= qq~ + \$("#select_temp_calibrators_2_$date_cnt tr:eq($table_row_cnt) td:nth-last-child(4)").css("z-index","$z_index") ; + ~ ; + $support_users_cnt-- ; + $opts{name} =~ s/.*?<\/option>// if $default_val ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow,$xlsxcol,$db{users}{$default_val}{name},$formatting) ; + } elsif ($col eq 'shift') { + $radio_opts{$field_id} = $radio_opts{shift} ; + my @abc = split(/\:/,$row) ; + $default_val = $abc[1] ; + $default_val_is_saved = ($default_val) ? 1 : 0 ; + # $default_val_html = qq~~ ; + our $val_min = "" ; + my $table_row_cnt = ($date_cnt == 1) ? $row_cnt + 1 : $row_cnt - 1 ; + $val = &table_radio_button($field_id,$default_val,'',$table_row_cnt,3,'',$default_val_is_saved,$col,"select_temp_calibrators_2_$date_cnt") ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow,$xlsxcol,$val_min,$formatting) ; + } elsif ($col eq 'update') { + $val = &common_min_table_checkbox($field_id) ; + chop $default_javascript if $default_javascript ; + if ($default_javascript) { + push @default_javascript_by_id, qq~"2_$row_cnt\_$date_cnt":{$default_javascript}~ ; + push @all_update_field_ids, "#shift_1_2_$row_cnt\_$date_cnt,#shift_2_2_$row_cnt\_$date_cnt,#selectName_2_$row_cnt\_$date_cnt" ; + } + } elsif (!$col) { + $val = ($row ne 'None') ? qq~ ~ : qq~~ ; + } + + my $styling = ($col eq 'date' && $row_cnt == 1) ? qq~style="width:7%;"~ : ($col eq 'name' && $row_cnt == 2) ? qq~style="width:35%;"~ : '' ; + + $print_tbody_extra_2 .= qq~~ ; + $xlsxcol++ ; + } + $print_tbody_extra_2 .= qq~~ ; + } + + ($s_year,$s_mon,$s_day) = Add_Delta_Days($s_year,$s_mon,$s_day,1) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + + if ($nr_of_options <= $row_cnt) { + $trigger_jquery_raw .= qq~\$("#add_row_table_2_$date_cnt").css("display","none");~ ; + } + + my $plus_button_color = ($db{shift_operator_ids}{$date}{temp_calibrator_support_shifts} =~ /\|\|/ || $db{shift_operator_ids}{$date}{temp_calibrator_support_shifts} =~ /\|\:/ || $db{shift_operator_ids}{$date}{temp_calibrator_support_shifts} eq "None") ? "grey" : "blue" ; + + push @plus_btn_ids,"#add_row_table_2_$date_cnt" ; + + $plus_button = qq~ + +
    +
    + + +
    +
    +
    +
    +
    + ~ ; + + $print_tbody_extra_2 .= qq~
    $val
    $plus_button~ ; + } + + $worksheet{$ws2}->set_column('A:C',20); + + &common_min_table_update_checkbox_col_default ; + + our $trigger_jquery_raw_default_alt = qq~ + // let all_def_vals = {} ; + + // all_def_vals[row_nr] = {} ; + + // let def_name = \$("#default_name_"+row_nr ).text() ; + // let def_shift = \$("#default_shift_"+row_nr ).text() ; + + // all_def_vals[row_nr]["selectName_"+row_nr] = def_name ; + + // if (def_shift == "1") { + // all_def_vals[row_nr]["shift_1_"+row_nr ] = "true" ; + // all_def_vals[row_nr]["shift_2_"+row_nr ] = "false" ; + // } else if (def_shift == "2") { + // all_def_vals[row_nr]["shift_1_"+row_nr ] = "false" ; + // all_def_vals[row_nr]["shift_2_"+row_nr ] = "true" ; + // } + ~ ; + + my $plus_btn_ids_str = join(",",@plus_btn_ids) ; + + $trigger_jquery_raw .= qq~ + + function add_Days (date_string,num_days,as_num) { + let date = new Date(date_string) ; + date.setDate(date.getDate() + num_days) ; + let year = date.getFullYear() ; + let month = String(date.getMonth() + 1).padStart(2,'0') ; + let day = String(date.getDate()).padStart(2,'0') ; + if (as_num) { + return ""+year+"-"+month+"-"+day+"" ; + } else { + let month_names = ["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] ; + month = month_names[month] ; + return ""+day+"-"+month+"-"+year+"" ; + } + } + + function deleteTempSupport (row_cnt) { + + BootstrapDialog.confirm({ + title: 'Confirm Delete', + message: 'Are you sure you want to delete '+name+'?', + type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + callback: function(result) { + + let [cnt_for_date,table_cnt] = row_cnt.split('_').map(Number) ; + + if (result) { + // if (\$("#update_data_base_"+row_cnt).text()) { + + let curr_date = add_Days("$i{date_from}",table_cnt-1,1) ; + + let url_delete = "$useropts{scripts}/get/get_db_delete_temp_support.pl?date="+curr_date+"&row_cnt="+cnt_for_date ; + + console.log("url_delete : "+url_delete) ; + + // console.log("#select_temp_calibrators_2_"+table_cnt+" #second_table_"+cnt_for_date+"_"+table_cnt) ; + + \$("#select_temp_calibrators_2_"+table_cnt+" #second_table_"+cnt_for_date+"_"+table_cnt).remove() ; + + \$.get(url_delete) ; + // } + // $("select#selectOriginalId").attr("id", "selectNewId"); + + let table_row_cnt = \$("#select_temp_calibrators_2_"+table_cnt).find('tr').length - 2 ; + + // let start_row_nr = 2 ; let end_row_nr = table_row_cnt + 1 ; + + if (table_cnt != '1') { + table_row_cnt += 2 ; + // start_row_nr = 0 ; + // end_row_nr -= 2 ; + } + + let all_def_vals_new = {} ; + + for (let i=2;i<=table_row_cnt+1;i++) { + + let row_nr = i-1 ; + let row_val = i ; + if (table_cnt != '1') { + row_val -= 2 ; + } + + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+")").attr("id","second_table_"+row_nr+"_"+table_cnt); + + let zIndex = \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(4)").css('z-index'); + zIndex++ ; + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(4)").css('z-index',zIndex); + if (\$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(1)").html()) { + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(1)").html(" "); + } + + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+")").find("select[id^='selectName_']").each(function() { + + var oldId = \$(this).attr("id"); + let old_row_val = get_row_nr(oldId,2) ; + let new_row_val = row_nr+"_"+table_cnt ; + + if (typeof all_def_vals["2_"+old_row_val] !== 'undefined') { + + all_def_vals_new["2_"+new_row_val] = {}; + all_def_vals_new["2_"+new_row_val]["selectName_2_"+new_row_val] = all_def_vals["2_"+old_row_val]["selectName_2_"+old_row_val] ; + all_def_vals_new["2_"+new_row_val]["shift_1_2_"+new_row_val] = all_def_vals["2_"+old_row_val]["shift_1_2_"+old_row_val] ; + all_def_vals_new["2_"+new_row_val]["shift_2_2_"+new_row_val] = all_def_vals["2_"+old_row_val]["shift_2_2_"+old_row_val] ; + + } + + let old_select_val = \$("#"+oldId).val() ; + + \$(this).attr("id", "selectName_2_"+new_row_val); + \$(this).attr("name", "name_2_"+new_row_val); + \$(this).attr("data-placeholder", "Select Temp Support Name "+row_nr); + var chosenElementId = oldId + "_chosen"; + \$("#" + chosenElementId).attr("id", "selectName_2_"+row_nr+"_"+table_cnt+"_chosen"); + \$("#selectName_2_"+row_nr+"_"+table_cnt+"_chosen .chosen-single span").text("Select Temp Support Name "+row_nr); + + \$("#shift_1_2_"+old_row_val).attr("name","shift_2_"+new_row_val); + \$("#shift_1_2_"+old_row_val).attr("id","shift_1_2_"+new_row_val); + \$("#shift_2_2_"+old_row_val).attr("name","shift_2_"+new_row_val); + \$("#shift_2_2_"+old_row_val).attr("id","shift_2_2_"+new_row_val); + \$("#checkboxUpdate_2_"+old_row_val).attr("name","update_2_"+new_row_val); + \$("#checkboxUpdate_2_"+old_row_val).attr("id","checkboxUpdate_2_"+new_row_val); + + // \$("#default_name_"+old_row_nr).attr("id","default_name_"+row_nr); + // \$("#default_shift_"+old_row_nr).attr("id","default_shift_"+row_nr); + + \$("#selectName_2_"+new_row_val).val(old_select_val) ; + \$("#selectName_2_"+new_row_val).trigger("chosen:updated") ; + + if (\$("#add_row_table_2_"+table_cnt).is(":hidden")) { + \$("#add_row_table_2_"+table_cnt).css("display","") ; + } + + }) ; + + } + + all_def_vals = all_def_vals_new ; + + if (!\$("#second_table_1_"+table_cnt).html()) { + + let options = "$opts{support_users}" ; + let select = add_select("name_2_1_"+table_cnt,"selectName_2_1_"+table_cnt,"Select Temp Support Name 1","$opts{support_users}",1,90) ; + let radio_butt = "  " ; + let update_butt = "" ; + let newRow = ""+curr_date+""+select+""+radio_butt+""+update_butt+"" ; + \$("#select_temp_calibrators_2_"+table_cnt+" tbody").append(newRow) ; + \$("#selectName_2_1_"+table_cnt).chosen({allow_single_deselect:true}) ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("position","absolute") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("width","90%") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("left","5%") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("top","50%") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("transform","translateY(-50%)") ; + + let optionCount = \$("#selectName_2_1_"+table_cnt+" option").length - 1 ; + + let date_cnt = daysBetween("$i{date_from}","$i{date_to}") ; + + let z_index = (date_cnt - table_cnt + 1)*optionCount ; + + let row_val = 2 ; + if (table_cnt != '1') { + row_val = 0 ; + } + + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(4)").css("z-index",z_index) ; + + \$("#selectName_2_1_"+table_cnt+",#shift_1_2_1_"+table_cnt+",#shift_2_2_1_"+table_cnt).change( function () { + + let found_blank = 0 ; + + if ((!\$("#selectName_2_1_"+table_cnt).val() || (!\$("#shift_1_2_1_"+table_cnt).is(":checked") && !\$("#shift_2_2_1_"+table_cnt).is(":checked"))) && \$("#second_table_1_"+table_cnt).html()) { + found_blank = 1 ; + } + + if (!found_blank) { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('grey').addClass('blue'); + } else { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('blue').addClass('grey'); + } + + let tick_update = 0 ; + + if ((\$("#"+this.id).attr('type') == 'radio' && \$("#"+this.id).is(":checked")) || (\$("#"+this.id).val() && \$("#"+this.id).attr('type') != 'radio')) { + tick_update = 1 ; + } + + if (tick_update && !\$("#checkboxUpdate_2_1_"+table_cnt).is(":checked")) { + \$("#checkboxUpdate_2_1_"+table_cnt).prop("checked",true) ; + } else if (!tick_update && \$("#checkboxUpdate_2_1_"+table_cnt).is(":checked")) { + \$("#checkboxUpdate_2_1_"+table_cnt).prop("checked",false) ; + } + + }) ; + } + } + } + }); + } + + ~ ; + + $trigger_jquery_raw .= qq~ + + function daysBetween(date1,date2) { + + const oneDay = 24 * 60 * 60 * 1000 ; + const firstDate = new Date(date1) ; + const secondDate = new Date(date2) ; + const diffInTime = Math.abs(secondDate - firstDate) ; + + return Math.ceil(diffInTime/oneDay) + 1 ; + + } + + function add_select (field_name,field_id,placeholder,options,tindex,width) { + + let select_raw = "" ; + + return select_raw ; + } + + \$("$plus_btn_ids_str").click( function () { + + let table_nr = get_row_nr(this.id) ; + + let table_row_cnt = \$("#select_temp_calibrators_2_"+table_nr).find('tr').length ; + + if (table_nr == '1') { + table_row_cnt -= 2 ; + } + + let found_blank = 0 ; + // console.log("table_row_cnt : "+table_row_cnt) ; + + // let lastRowId = \$("#select_temp_calibrators_2 tr:last").attr("id"); + // let table_row_cnt = get_row_nr(lastRowId) ; + + for (i=1;i<=table_row_cnt;i++) { + if ((!\$("#selectName_2_"+i+"_"+table_nr).val() || \$("#selectName_2_"+i+"_"+table_nr).val() == null || (!\$("#shift_1_2_"+i+"_"+table_nr).is(":checked") && !\$("#shift_2_2_"+i+"_"+table_nr).is(":checked"))) && \$("#second_table_"+i+"_"+table_nr).html()) { + found_blank = 1 ; + } + } + + if (!found_blank) { + + \$('#add_row_table_2_'+table_nr).find('i').removeClass('blue').addClass('grey'); + + table_row_cnt++ ; + + let options = "$opts{support_users}" ; + + let select = add_select("name_2_"+table_row_cnt+"_"+table_nr,"selectName_2_"+table_row_cnt+"_"+table_nr,"Select Temp Support Name "+table_row_cnt,"$opts{support_users}",1,90) ; + // "Half Day (<7 hours);Full Day (7 hours+)" + let radio_butt = "  " ; + + // let delete_butt = " " ; + let delete_butt = "" ; + + let update_butt = "" ; + + let curr_date = add_Days("$i{date_from}",table_nr-1) ; + + let newRow = ""+curr_date+""+select+""+radio_butt+""+update_butt+""+delete_butt+"" ; + + \$("#select_temp_calibrators_2_"+table_nr+" tbody").append(newRow) ; + + // let optionCount = \$("#selectName_2_"+table_row_cnt+"_"+table_nr+" option").length - 1 ; + let optionCount = \$("#selectName_2_1_"+table_nr+" option").length - 1 ; + + let date_cnt = daysBetween("$i{date_from}","$i{date_to}") ; + + // my $support_users_cnt = $potential_support_users_cnt - ($day_cnt - 1)*$tot_support_users_cnt ; + + let z_index = (date_cnt - table_nr + 1)*optionCount - table_row_cnt + 1 ; + + // let optionCount = "$tot_support_users_cnt" ; + + // \$("#selectName_"+table_row_cnt).chosen({allow_single_deselect:true}) ; + + for (i=1;i 1) { + // let row_nr = get_row_nr(this.id) ; + // for (i=1;i<=table_row_cnt;i++) { + // for (j=1;j<=table_row_cnt;j++) { + + // } + // } + + } + + if (!found_blank) { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('grey').addClass('blue'); + } else { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('blue').addClass('grey'); + } + + }) ; + + ~ ; + + my $second_table_ids_str = join(",",@second_table_ids) ; + my $second_table_ids_str_2 = join(",",@second_table_ids_2) ; + my $second_table_ids_str_3 = join(",",@second_table_ids_3) ; + our $second_table_ids_str_4 = join(",",@second_table_ids_4) ; + my $second_table_ids_str_5 = join(",",@second_table_ids_5) ; + + &common_min_table_select_fixed_width_jquery("$second_table_ids_str_4") ; + + &common_min_table_select_default_values_jquery ; + + # &common_min_table_select_jquery("#select_temp_calibrators_2 td:nth-last-child(4)","") ; + + &common_min_table_update_checkbox_col_jquery("3") ; + + $trigger_jquery .= qq~ + \$("#select_temp_calibrators_2_length").css("display","none") ; + \$("#select_temp_calibrators_2_filter").css("display","none") ; + \$("#select_temp_calibrators_2_info").css("display","none") ; + \$("#select_temp_calibrators_2_paginate").css("display","none") ; + ~ ; + + $trigger_jquery .= qq~ + // \$("#select_temp_calibrators_2").css("width","66.66666%"); + \$("$second_table_ids_str_5").css("width","7%") ; + \$("$second_table_ids_str_4").css("width","40%") ; + // \$("$second_table_ids_str_4").css("position","relative") ; + // \$("$second_table_ids_str_4").css("text-align","center") ; + \$("$second_table_ids_str_3").css("width","40%") ; + \$("$second_table_ids_str_2").css("width","10%") ; + ~ ; + + +} #------------------------------------------------------------------------------------------ + +sub table_radio_button { + +my ($field,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved,$col_name,$table_id) = @_ ; + +return unless $col_name ; + +$field = "$col_name\_$table_row" unless $field ; + +my $field_cnt = $field ; +$field_cnt =~ s/$col_name\_//g ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +my @opts = ($radio_opts{$field}) ? split(/\;/,$radio_opts{$field}) : split(/\;/,$options); + +my $row = qq~~ ; + +my $cnt = 0 ; + +if ($default_val && $default_val_is_saved) { + $background_color = "#424949" unless $background_color ; + $table_with_default_ids{$background_color} .= "#$table_id tr:eq($table_row) td:nth-last-child($table_col)," ; +} + +foreach (@opts) { + $cnt++ ; + my $checked = ($cnt eq $default_val) ? 'CHECKED' : '' ; + $val_min = ($checked) ? $_ : $val_min ; + $row .= qq(  ) ; + if (!$default_val_is_saved || !$default_val) { + $default_javascript .= qq~"$col_name\_$cnt\_$field_cnt":"false",~ ; + } else { + my $default_val_boolian = ($cnt eq $default_val) ? "true" : "false" ; + $default_javascript .= qq~"$col_name\_$cnt\_$field_cnt":"$default_val_boolian",~ ; + } + push @all_radio_ids,"#shift_$cnt\_$field_cnt" ; +} + +$row = substr($row,0,-12) ; + +# my $row = qq($print_radios) ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_build_table { + + my ($table_col_name,$field_name) = @_ ; + + my $cali_cnt = 0 ; my $found_editable = 0 ; my @all_select_ids = () ; + + $format84 -> set_align("center") ; + + my $table_row = 0 ; my %default_vals = () ; + + # foreach my $id (sort {$db{$table}{$a}{date_from} cmp $db{$table}{$b}{date_from}} keys %{$db{$table}}) { + foreach my $date_ref (sort keys %sort_calibration_by_time_ref) { + + my $id = $sort_calibration_by_time_ref{$date_ref} ; + + next unless $id ; + + my $system_count = 0 ; my $system_day_cnt = 0 ; + + my %default_monitors = () ; + + my $day_cnt = 0 ; + my $sql_col = "$table_col_name" ; + my $inp_field = substr($sql_col,0,-1) ; + my $found_inp_field = 0 ; + foreach my $day_row (split(/\|/,$db{$table}{$id}{$sql_col})) { + $day_cnt++ ; $system_count = 0 ; + foreach my $system_row (split(/\;/,$day_row)) { + $system_count++ ; my $shift_cnt = 0 ; + foreach my $shift_monitor (split(/\:/,$system_row)) { + $shift_cnt++ ; + $default_monitors{$day_cnt}{$system_count}{$shift_cnt} = $shift_monitor ; + $found_inp_field = 1 if $shift_monitor eq $i{$inp_field} ; + } + } + } + $system_count = 0 ; + + my %system_has_daily_op = () ; my %default_op_ids = () ; + + foreach my $system_row (split(/\|/,$db{$table}{$id}{daily_operator_ids})) { + $system_count++ ; + next unless $system_row ; + $system_day_cnt = 0 ; + foreach my $col (split(/\;/,$system_row)) { + $system_day_cnt++ ; + next unless $col ; + $default_op_ids{$system_count}{$system_day_cnt} = $col if $col ; + $system_has_daily_op{$system_count} = 1 if $col ; + } + } + $system_count = 0 ; + + unless (&common_check_if_string_contains_an_integer($db{$table}{$id}{event_system_id_multiple})) { + $db{$table}{$id}{event_system_id_multiple} = ";none;" ; + } + + # my @system_name_ids = split(";",$db{$table}{$id}{event_system_id_multiple}) ; + + my @system_name_ids = split(/\;/,$db{$table}{$id}{event_system_id_multiple}) ; + my @club_ids = split(/\;/,$db{$table}{$id}{club_ids}) ; + my @op_ids = split(/\,/,$db{$table}{$id}{operator_ids}) ; + my @days_active = split(/\;/,$db{$table}{$id}{days_active}) ; + my @start_times = ($db{$table}{$id}{qty} eq '1' && $days_active[0]) ? () : split(/\;/,";".$db{$table}{$id}{times_from}) ; + my @end_times = ($db{$table}{$id}{qty} eq '1' && $days_active[0]) ? () : split(/\;/,$db{$table}{$id}{times_to}) ; + + my $cnt_rows = 0 ; + for (1 .. 50) { + $cnt_rows = $_ if $system_name_ids[$_ - 1] or $club_ids[$_ - 1] ; + } + + my $system_count = 0 ; my $system_day_cnt = 0 ; + + foreach my $event_sys_id (@system_name_ids) { + + $system_count++ ; + + next unless $event_sys_id ; + next if $db{event_systems}{$event_sys_id}{system_type} ne 'mobile' && !$monitoring_report && !$troubleshoot_monitoring_report ; + + # &common_debug(">>>>>>>>> 2. $system_count [$id] $db{$table}{$id}{ref} [$db{event_systems}{$event_sys_id}{system_type}]") ; + + # $event_cnt++ ; + + # foreach my $cal_date (sort {$day_of_week{$a} cmp $day_of_week{$b}} keys %day_of_week) { + + $system_day_cnt = 0 ; + + foreach my $cal_date (sort keys %day_of_week) { + + # my $srch_date_from_comp = $i{date_from} ; $srch_date_from_comp =~ s/\-//g ; + # my $srch_date_to_comp = $i{date_to} ; $srch_date_to_comp =~ s/\-//g ; + my $date_from_comp = substr($db{$table}{$id}{date_from},0,10) ; $date_from_comp =~ s/\-//g ; + my $date_to_comp = substr($db{$table}{$id}{date_to},0,10) ; $date_to_comp =~ s/\-//g ; + my $cal_date_comp = $cal_date ; # $cal_date_comp =~ s/\-//g ; + $cal_date = substr($cal_date,0,4) . '-' . substr($cal_date,4,2) . '-' . substr($cal_date,6,2) ; + my $date_from = substr($db{$table}{$id}{date_from},0,10) ; + $system_day_cnt++ ; + + # &common_debug("[$cnt{$event_sys_id}{$id}] : $event_sys_id [$id] $cal_date") ; + + # &common_debug("1. DATE >>> $cal_date_comp < $date_from_comp") if !$report ; + next if $cal_date_comp < $date_from_comp ; + # &common_debug("2. DATE >>> $cal_date_comp > $date_to_comp") if !$report ; + next if $cal_date_comp > $date_to_comp ; + + $cnt{$event_sys_id}{$id}++ ; + + next if $db{$table}{$id}{days_active} && !$days_active[$cnt{$event_sys_id}{$id}-1] ; + + my $cal_date_val = $cal_date ; my $date_from_val = $i{date_from} ; my $date_to_val = $i{date_to} ; + + $cal_date_val =~ s/\-//g ; $date_from_val =~ s/\-//g ; $date_to_val =~ s/\-//g ; + + next if $cal_date_val < $date_from_val || $cal_date_val > $date_to_val ; + + # # &common_debug("3. DATE >>> $cal_date_comp > $srch_date_to_comp") if !$report ; + # next if ($calibration_report) && $cal_date_comp > $srch_date_to_comp ; + # # &common_debug("4. DATE >>> $cal_date_comp < $srch_date_from_comp") if !$report ; + # next if ($calibration_report) && $cal_date_comp < $srch_date_from_comp ; + + # &common_debug(">>>>>>>>> 3. $system_count [$id] $db{$table}{$id}{ref} [$db{event_systems}{$event_sys_id}{system_type}]") ; + + # &common_debug("[$cnt{$event_sys_id}{$id}] : $event_sys_id [$id] $cal_date [$cal_date_comp > $srch_date_to_comp]") ; + + $cali_cnt++; + + $xlsxcol = 0 ; + $print_tbody .= qq~~ ; + $table_row++ ; + + our $default_javascript = "" ; + + foreach (@sql_col_display) { + + # &common_debug("1. XLSX >>> $_") if !$report ; + + next unless $_ ; # blank for the buttons column + + my $formatting = $format84 ; + my $val = $db{$table}{$id}{$_} ; + my $val_min = $val ; + my $align = qq~ class="dt-center"~ ; + my $nowrap = '' ; + + # &common_debug("2. XLSX >>> val_min=$val_min") if !$report ; + + my $sys_day_cnt = $cnt{$event_sys_id}{$id} ; + + if ($_ eq 'count') { + # $val = $event_cnt ; + $val = $cali_cnt ; + } elsif ($_ eq 'event_nr') { + $val = "$id" ; + } elsif ($_ eq 'event') { + $val = "$db{$table}{$id}{ref} [$id]" ; + } elsif ($_ eq 'calibration_date' || $_ eq 'date') { + # $val = "$cal_date [$day_of_week{$cal_date}]" ; + $val = &common_min_date_as_string($cal_date) ; + $nowrap = "nowrap" ; + } elsif ($_ eq 'day') { + $val = "$sys_day_cnt" ; + } elsif ($_ eq 'start_date') { + $nowrap = "nowrap" ; + $val = &common_min_date_as_string($date_from) ; + } elsif ($_ eq 'venue') { + my @oids = split(/\,/,$db{$table}{$id}{organisation_ids}) ; + foreach $_oid (@oids) { + $val .= $db{organisations}{$_oid}{name} . '
    ' ; + } + $val = substr($val,0,-4) if $val ; ; + } elsif ($_ eq 'region') { + $val = $db{regions}{$db{$table}{$id}{region_id}}{code} ; + } elsif ($_ eq 'type') { + $val = (lc $db{event_systems}{$event_sys_id}{description} =~ /cricket/) ? "C" : + ($db{event_systems}{$event_sys_id}{system_type} eq 'mobile') ? "M" : + ($db{event_systems}{$event_sys_id}{system_type} eq 'fixed') ? "F" : ""; + } elsif ($_ eq 'system') { + $val = '' ; + $val = qq~$db{event_systems}{$event_sys_id}{name}~ ; + $val .= qq~ ($db{event_systems}{$event_sys_id}{description})~ if $db{event_systems}{$event_sys_id}{description} ; + } elsif ($_ eq 'sport') { + $val = '' ; + foreach my $sport_id (split(",",$db{$table}{$id}{sport_type_ids})) { + $db{sport_types}{$sport_id}{name} = uc $db{sport_types}{$sport_id}{name} ; + $val .= qq~$db{sport_types}{$sport_id}{name}
    ~ ; + } + $val = substr($val,0,-4) if $val ; + } elsif ($_ eq 'club_name') { + $val = $db{clubs}{$club_ids[$system_count - 1]}{name} ; + } elsif ($_ eq 'operator') { + $val = '' ; + # $val = $db{users}{$table_op_ids[$system_count - 1]}{name} if $table_op_ids[$system_count - 1] ; + $val = ($default_op_ids{$system_count}{$cnt{$event_sys_id}{$id}}) ? $db{users}{$default_op_ids{$system_count}{$cnt{$event_sys_id}{$id}}}{name} : (!$default_op_ids{$system_count}{$system_day_cnt} && $system_has_daily_op{$system_count}) ? "None" : $db{users}{$op_ids[$system_count - 1]}{name} ; + # $formatting = $format92 if $event_cnt == 2 ; + $formatting = $format92 if $cali_cnt == 2 ; + } elsif ($_ eq 'start_time') { + if (!$start_times[$sys_day_cnt-1]) { + $val = substr($db{$table}{$id}{date_from},11,5) ; + } else { + $val = substr($start_times[$sys_day_cnt-1],0,5) ; + } + } elsif ($_ eq 'end_time') { + if (!$end_times[$sys_day_cnt-1]) { + $val = substr($db{$table}{$id}{date_to},11,5) ; + } else { + $val = substr($end_times[$sys_day_cnt-1],0,5) ; + } + } elsif ($_ eq 'status' || $_ eq 'fixture_check') { + push @first_table_multi_select_table_cells,"#$useropts{table_id} tr:eq($table_row) td:nth-last-child($last_child{$_})" ; + $field{$_} = "$_\_event$event_sys_id\_$sys_day_cnt\_$id" ; + $opts{$field{$_}} = $opts{$_} ; + my $background_color = qq~~ ; + if ($_ eq 'status' && $default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}) { + $val_min = $db{monitor_status}{$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}}{status} ; + if ($default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id} eq '1') { + $background_color = qq~rgb(81, 181, 41)~ ; + $formatting = $format94 ; + } elsif ($default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id} eq '2') { + $background_color = qq~rgb(246, 227, 5)~ ; + $formatting = $format95 ; + } else { + $background_color = qq~rgb(249, 13, 13)~ ; + $formatting = $format96 ; + } + } elsif ($default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}) { + $val_min = $db{users}{$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}}{name} ; + } + + $val = &common_min_table_select($field{$_},$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},'',$table_row,$last_child{$_},$background_color,$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},$_) ; + } elsif ($_ eq 'update') { + + my $field = "update_event$event_sys_id\_$sys_day_cnt\_$id" ; + $val = &common_min_form_checkbox_col($field,'') ; + + chop $default_javascript if $default_javascript ; + # 12=s:;t:|s:1;t:1|s:2;t:2-13=|s:3;t:3|s:4;t:4 + if ($default_javascript) { + push @default_javascript_by_id, qq~"event$event_sys_id\_$sys_day_cnt\_$id":{$default_javascript}~ ; + } + } + if ($_ ne 'status' && $_ ne 'calibrator' && substr($_,0,5) ne 'shift' && $_ ne 'update' && $_ ne 'status' && $_ ne 'fixture_check') { + $val_min = $val ; + $val_min =~ s/\
    /\;/g ; + } + $print_tbody .= qq~$val~ ; + + # &common_debug("XLSX >>> $event_system_calibration_ids{$id}{$event_sys_id}{$sys_day_cnt} [$id] [$event_sys_id] [$sys_day_cnt] [$field]") ; + + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$formatting) ; + $xlsxcol++ ; + } + + $print_tbody .= qq~~ ; + + $xlsxrow++ ; + } + + # next if $i{calibration_status} ne 'all' and $i{calibration_status} and $i{calibration_status} ne $db{event_systems}{$event_sys_id}{calibration_status} ; + # next if $i{calibrator_id} ne 'all' and $i{calibrator_id} and $i{calibrator_id} ne $db{event_systems}{$event_sys_id}{calibrator_id} ; + + } + } +# || $troubleshoot_monitoring_report ; + my $html_id = ($monitoring_report) ? "selectShift_monitor_" : ($troubleshoot_monitoring_report) ? "selectShift_troubleshoot_monitor_" : "selectShift_temp_calibrator_" ; + my $html_id2 = ($monitoring_report) ? "shift-monitor-id-" : ($troubleshoot_monitoring_report) ? "shift-troubleshoot-monitor-id-" : "shift-temp-calibrator-id-" ; + $row_cnt++ if $monitoring_report || $troubleshoot_monitoring_report ; + + $trigger_jquery_raw .= ($monitoring_report || $troubleshoot_monitoring_report) ? qq~ + + \$("#savebutt").click(function() { + for (let table_cnt = 1; table_cnt<= $date_cnt; table_cnt++) { + for (let i=1; i<=4; i++) { + let mon_id = \$("#$html_id"+i+"_1_1_"+table_cnt).chosen().val() ; + if (mon_id && typeof(mon_id) !== 'undefined') { + \$("#$html_id2"+i+"-"+table_cnt).val(mon_id) ; + } + } + } + \$("#$lcpage-form").submit() ; + }) ; + + ~ : qq~ + \$("#savebutt").click(function() { + + for (let table_cnt = 1; table_cnt<= $date_cnt; table_cnt++) { + + for (let i=1; i<=4; i++) { + let mon_id = \$("#$html_id"+i+"_1_1_"+table_cnt).chosen().val() ; + if (mon_id) { + \$("#$html_id2"+i+"-"+table_cnt).val(mon_id) ; + } + } + + let table_row_cnt = \$("#select_temp_calibrators_2_"+table_cnt).find('tr').length - 2 ; + + if (table_cnt > 1) { + table_row_cnt += 2 ; + } + + let seen_support = {} ; + + for (i=1;i<=table_row_cnt;i++) { + + let sel_val = \$("#selectName_2_"+i+"_"+table_cnt).val() ; + // if (!sel_val) { + // noty({text:'Please Select a Temp Support Name in all Rows',layout:"center",type:"error",timeout:3000}) ; + // return ; + // } else + if (seen_support[sel_val]) { + noty({text:'Please do not Select the same Temp Support Name in Multiple Rows for the Same Date',layout:"center",type:"error",timeout:3000}) ; + return ; + } else if (sel_val) { + seen_support[sel_val] = 1 ; + } + } + } + \$("#$lcpage-form").submit() ; + }) ; + ~ ; + + $worksheet{$ws}->set_column(0,0,10) ; + $worksheet{$ws}->set_column(1,1,30) ; + $worksheet{$ws}->set_column(2,2,15) ; + $worksheet{$ws}->set_column(3,3,5) ; + $worksheet{$ws}->set_column(4,4,15) ; + $worksheet{$ws}->set_column(5,6,10) ; + $worksheet{$ws}->set_column(7,7,30) ; + $worksheet{$ws}->set_column(8,9,10) ; + $worksheet{$ws}->set_column(10,10,30) ; + $worksheet{$ws}->set_column(11,11,15) ; + $worksheet{$ws}->set_column(12,16,20) ; + + &report_xlsx_export_footer('L',15,$xlsxdir) ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_update { + + my ($table,$table_field,$other_field,$table_field_2) = @_ ; + + unless ($table_field_2) { + $table_field_2 = "blank" ; + $ignore{$table_field_2} = 1 ; + } + + my ($s_year,$s_mon,$s_day) = split("-",$i{date_from}) ; + my ($e_year,$e_mon,$e_day) = split("-",$i{date_to}) ; + + our $date_counter = 1 ; + + while (int("$s_year$s_mon$s_day") <= int("$e_year$e_mon$e_day")) { + $date_cnt_to_date{$date_counter} = "$s_year-$s_mon-$s_day" ; + $date_counter++ ; + ($s_year,$s_mon,$s_day) = Add_Delta_Days ($s_year,$s_mon,$s_day,1) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + } + + $date_cnt_to_date{$date_counter} = "$s_year-$s_mon-$s_day" ; + $date_counter-- ; + + my %i_per_date = () ; my $temp_support_diff = 0 ; + + if ($temp_calibrator_report) { + + &db_min_ro($table,"date,temp_calibrator_support_shifts,$table_field","`date` >= '$i{date_from}' AND`date` <= '$i{date_to}'") ; + + for my $date_cnt (1 .. $date_counter) { + + my $table_pos = 0 ; my $cnt_per_date = 0 ; my $table_cnt = 0 ; + + # $db{$table}{1}{temp_calibrator_support_shifts} =~ s/\|\|/\|/g ; + # $db{$table}{1}{temp_calibrator_support_shifts} =~ s/^\|//; + # $db{$table}{1}{temp_calibrator_support_shifts} =~ s/\|$//; + + my @temp_calibrator_support_shifts_split = split(/\|/,$db{$table}{$date_cnt_to_date{$date_cnt}}{temp_calibrator_support_shifts}) ; + + foreach (sort keys %i) { + + $ignore{$_} = 1 ; + + if ($_ =~ /^name_2_.*_$date_cnt$/) { + + my @aaa = split(/\_/,$_) ; + $table_pos = $aaa[-3] ; + $cnt_per_date = $aaa[-2] ; + # $table_cnt = $aaa[-1] ; + + my $update_field = "update_$table_pos\_$cnt_per_date\_$date_cnt" ; + my $name_field = "name_$table_pos\_$cnt_per_date\_$date_cnt" ; + my $shift_field = "shift_$table_pos\_$cnt_per_date\_$date_cnt" ; + + if ($i{$update_field} && $i{$name_field} && $i{$shift_field}) { + $i_per_date{$date_cnt}{temp_calibrator_support_shifts} .= qq~$i{$name_field}:$i{$shift_field}|~ ; + } elsif ($temp_calibrator_support_shifts_split[$cnt_per_date-1]) { + my $abcde = $temp_calibrator_support_shifts_split[$cnt_per_date-1] ; + $i_per_date{$date_cnt}{temp_calibrator_support_shifts} .= qq~$abcde|~ ; + } + } + } + + chop $i_per_date{$date_cnt}{temp_calibrator_support_shifts} if $i_per_date{$date_cnt}{temp_calibrator_support_shifts} ; + # $temp_support_exists = 1 if $i_per_date{$date_cnt}{temp_calibrator_support_shifts} ; + $temp_support_diff = 1 if $i_per_date{$date_cnt}{temp_calibrator_support_shifts} && $i_per_date{$date_cnt}{temp_calibrator_support_shifts} ne $db{$table}{$date_cnt_to_date{$date_cnt}}{temp_calibrator_support_shifts} ; + } + + } else { + # return unless $i{update_table_1} ; + &db_min_ro($table,"date,$table_field,$table_field_2","`date` >= '$i{date_from}' AND `date` <= '$i{date_to}'") ; + } + + my $some_update = 0 ; + + for my $date_cnt (1 .. $date_counter) { + $some_update = 1 if $i{"update_1_1_$date_cnt"} || ($i{"update_2_1_$date_cnt"} || $temp_calibrator_report) ; + } + + + # return if !$i{update_table_1} && $temp_calibrator_report && $i{temp_calibrator_support_shifts} eq $db{$table}{1}{temp_calibrator_support_shifts} ; + return if !$some_update && !$temp_support_diff ; + + &hidden_fields ; + my %ii = %i ; + + # $ignore{blank} = 1 ; + + for my $date_cnt (1 .. $date_counter) { + + %i = () ; + + # my $date_val = $ii{"date_$date_cnt"} ; + my $date_val = $date_cnt_to_date{$date_cnt} ; + + # my $update_field = "update_1_1_$date_cnt" ; + + next if !$ii{"update_1_1_$date_cnt"} && !$ii{"update_2_1_$date_cnt"} ; + + if ($ii{"update_1_1_$date_cnt"}) { + + my $ops_exists = 0 ; my $notes_exists = 0 ; + + for my $shift_cnt (1 .. 4) { + $ii{"$other_field\_$shift_cnt\_$date_cnt"} =~ s/\,/\;/g ; + $i{$table_field} .= qq~$ii{"$other_field\_$shift_cnt\_$date_cnt"}|~ ; + $ops_exists = 1 if $ii{"$other_field\_$shift_cnt\_$date_cnt"} ; + $notes_exists = 1 if $table_field_2 && $ii{"shift_$table_field_2\_$shift_cnt\_1_1_$date_cnt"} ; + + my $field_ = "shift_$table_field_2\_$shift_cnt\_1_1_$date_cnt" ; + + $i{$table_field_2} .= qq~$ii{"shift_$table_field_2\_$shift_cnt\_1_1_$date_cnt"}:|:~ if $table_field_2 ; + } + chop $i{$table_field} ; + + $i{$table_field} = qq~~ unless $ops_exists ; + $i{$table_field_2} = qq~~ if $table_field_2 && !$notes_exists ; + + $i{$table_field_2} = substr($i{$table_field_2},0,-3) if $table_field_2 && $i{$table_field_2} ; + $ignore{$table_field} = 0 ; + $ignore{$table_field_2} = 0 if $table_field_2 && $table_field_2 ne 'blank' ; + } else { + $ignore{$table_field} = 1 ; + $ignore{$table_field_2} = 1 ; + } + # my $table_field_old = $table_field ; + + # $table_field = $table_field_old ; + + $i{temp_calibrator_support_shifts} = $i_per_date{$date_cnt}{temp_calibrator_support_shifts} if $temp_calibrator_report ; + + if (!$db{$table}{$date_val}{date}) { + + &db_min_ro($table,"1,MAX(id) + 1 AS 'max_id'","","","") ; + + $i{id} = $db{$table}{1}{max_id} ; + $i{id} = 1 unless $i{id} ; + $i{date} = $date_val ; + + $ignore{date} = 0 ; + $ignore{$table_field} = 1 unless $i{$table_field} ; + $ignore{temp_calibrator_support_shifts} = 1 if !$temp_calibrator_report || !$i{temp_calibrator_support_shifts} ; + + &db_min_insert("$table") ; + + } else { + + $ignore{$table_field} = 1 if $db{$table}{$date_val}{$table_field} eq $i{$table_field} ; + $ignore{temp_calibrator_support_shifts} = 1 if $db{$table}{$date_val}{temp_calibrator_support_shifts} eq $i{temp_calibrator_support_shifts} || !$temp_calibrator_report ; + &db_min_upd($table,"`date`='$date_val'") if !$ignore{$table_field} || !$ignore{$table_field_2}|| !$ignore{temp_calibrator_support_shifts} ; + + } + } + + %i = %ii ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_update { + + my ($field) = @_ ; + + my %iii = %i ; + my %ii = () ; + local $min_date = 0 ; local $max_date = 0 ; + foreach (sort keys %i) { + + local $cell_name = $_ ; + local @a = split("_") ; + next if $a[-2] ne int($a[-2]) ; + + if ($i{"paid_$a[-2]\_$a[-1]"} and $i{"amount_payble_$a[-2]\_$a[-1]"}) { + # my $date = substr($a[-1],0,4) . '-' . substr($a[-1],4,2) . '-' . substr($a[-1],6,2) ; + if ($a[0] eq 'amount') { + $i{$_} = sprintf("%.2f",$i{$_}) ; + $ii{$a[-1]}{"$field\_amounts_paid"} .= ($ii{$a[-1]}{"$field\_amounts_paid"}) ? qq~;$a[-2]:$i{$_}~ : qq~$a[-2]:$i{$_}~ ; + } elsif ($a[0] eq 'date') { + $ii{$a[-1]}{"$field\_dates_paid"} .= ($ii{$a[-1]}{"$field\_dates_paid"}) ? qq~;$i{$_}~ : qq~$i{$_}~ ; + } + } + $min_date = $a[-1] if ($min_id and $a[-1] < $min_id) or not $min_id ; + $max_date = $a[-1] if $a[-1] > $max_id ; + } + + $min_date = substr($min_date,0,4) . '-' . substr($min_date,4,2) . '-' . substr($min_date,6,2) ; + $max_date = substr($max_date,0,4) . '-' . substr($max_date,4,2) . '-' . substr($max_date,6,2) ; + + &db_min_ro($table,"date,$field\_dates_paid,$field\_amounts_paid","`date` <= '$max_date' AND `date` >= '$min_date'",'','') ; + + foreach my $date (sort keys %ii) { + + %i = () ; + + # $i{"$field\_dates_paid"} .= qq~$ii{$date}{"$field\_dates_paid"}~ ; + + my $date_string = substr($date,0,4) . '-' . substr($date,4,2) . '-' . substr($date,6,2) ; + + $i{"$field\_amounts_paid"} = qq~$db{$table}{$date_string}{"$field\_amounts_paid"}~ ; + $i{"$field\_amounts_paid"} .= qq~;~ if $db{$table}{$date_string}{"$field\_amounts_paid"} && $ii{$date}{"$field\_amounts_paid"} ; + $i{"$field\_amounts_paid"} .= qq~$ii{$date}{"$field\_amounts_paid"}~ ; + + $ignore{"$field\_amounts_paid"} = 1 if $i{"$field\_amounts_paid"} eq $db{$table}{$date_string}{"$field\_amounts_paid"} || !$i{"$field\_amounts_paid"} ; + + $i{"$field\_dates_paid"} = qq~$db{$table}{$date_string}{"$field\_dates_paid"}~ ; + $i{"$field\_dates_paid"} .= qq~;~ if $db{$table}{$date_string}{"$field\_dates_paid"} && $ii{$date}{"$field\_dates_paid"} ; + $i{"$field\_dates_paid"} .= qq~$ii{$date}{"$field\_dates_paid"}~ ; + + $ignore{"$field\_dates_paid"} = 1 if $i{"$field\_dates_paid"} eq $db{$table}{$date_string}{"$field\_dates_paid"} || !$i{"$field\_dates_paid"} ; + + &db_min_upd($table,"`date`='$date_string'") if $i{"$field\_dates_paid"} || $i{"$field\_amounts_paid"} ; + + } + + %i = %iii ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_report_ifields { + + my ($field) = @_ ; + + my $field2 = join(/ /, map { uc($_) } split(/\_/,$field)) ; + + if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { + $error = qq~'$i{date_from}' > '$i{date_to}'~ ; &report_screen ; + } + push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` <= '$i{date_to} 23:59:59' AND `date_to` >= '$i{date_from} 00:00:00'))" ; + push @report_results, "(BETWEEN '$i{date_from}' AND '$i{date_to}')" ; + } elsif (not $i{date_from}) { + $error = qq~PLEASE ENTER A START DATE!~ ; + } elsif (not $i{date_to}) { + $error = qq~PLEASE ENTER A END DATE!~ ; + } + + our $where_min = qq~~ ; + if ($i{"$field\_id"}) { + my $ifield = "$field\_id" ; + &db_min_ro('users','1,name',"`id` = '$i{$ifield}'",'','') ; + $where_min = " AND `$field\_ids` LIKE '%$i{$ifield}%'" ; + push @report_results,"$field2 = $db{users}{1}{name}" ; + } + + if ($i{paid_status} eq 'paid') { + push @report_results,"$field2 AMOUNTS PAID" ; + } elsif ($i{paid_status} eq 'outstanding') { + push @report_results,"$field2 PAY OUTSTANDING" ; + } + + $report_results_msg = uc join(', ', @report_results) ; + + if (not $report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); + &report_screen ; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_list_screen { + + my ($field) = @_ ; + + my $field2 = $field ; + + $field2 =~ s/\_/\-/g ; + + # &db_min_ro('event_cost_items','1,rates',"`name` LIKE '$field3%'",'','') ; + + our @sql_col_display = ($i{paid_status} eq 'paid') ? ("date","$field\_names","shifts_count","dates_paid","amounts_paid","all_paid") : ($i{paid_status} eq 'all') ? ("date","$field\_names","shifts_count","dates_paid","amounts_paid","date_payable","amount_payable","paid") : ("date","$field\_names","shifts_count","date_payable","amount_payable","paid") ; + + my $table_colspan = 0 ; + + foreach (@sql_col_display) { + $table_colspan += 1 ; + } + + local @month_arr = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + my ($year1,$month1,$day1) = split(/\-/,$i{date_from}) ; + my ($year2,$month2,$day2) = split(/\-/,$i{date_to}) ; + + my $date_string = qq~~ ; + + if ($year1 ne $year2 && $month1 ne $month2 && $day1 ne $day2) { + $date_string = qq~ $day1 $month_arr[$month1] $year1 - $day2 $month_arr[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 ne $month2) { + $date_string = qq~ $day1 $month_arr[$month1] - $month_arr[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 eq $month2 && $day1 ne $day2) { + $date_string = qq~ $day1 - $day2 $month_arr[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 eq $month2 && $day1 eq $day2) { + $date_string = qq~ $day2 $month_arr[$month2] $year2~ ; + } + + my $field_heading = join(" ", map { ucfirst($_) } split(/\_/,$field)) ; + + our $xlsxheading = "$field_heading Payments Report$xlsreportname$date_string" ; + + &report_xlsx_export_header("$field_heading Payments$xlsreportname","$field\_payments_report") ; + + &schedule_payments_load_list_vars("$where_min","$field") ; + + my @qty_work = () ; + my @amnt_usd_work = () ; + my @amnt_work = () ; + my @op_work = () ; + my @description = () ; + my @paid_work = () ; + my $row_cnt = 0 ; + my $first_id = 0 ; + my $last_id = 0 ; + my %row_cnt_to_id = () ; + + $fcol = 12 ; my $val_min = 0 ; $row_cnt = 0 ; + + my $date_pay = qq~~ ; my $quote_and_ops_ids = qq~~ ; my $op_ids = qq~~ ; + + my ($next_year,$next_month,$next_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,1) ; + + my $row_cnt = 0 ; my $quote_and_ops_ids = qq~~ ; + + my %amnt_tots = () ; + + foreach my $date (sort {$a <=> $b} keys %{$db{$table}}) { + + my @date_pay = split(/\;/,$db{$table}{$date}{"$field\_paid"}) ; + my @amount_pay = split(/\;/,$db{$table}{$date}{"$field\_amounts_paid"}) ; + my $date_val = $date ; + $date_val =~ s/\-//g ; + + foreach my $temp_id (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$operator_count{$date}}) { + + next if $i{"$field\_id"} && $i{"$field\_id"} ne $temp_id ; + + next if $temp_id eq 'none' ; + + my $amnt_owed = ($db{event_cost_items}{1}{rates}) ? $db{event_cost_items}{1}{rates} * $operator_count{$date}{$temp_id} : ($field =~ /calibrator/) ? 500 * $operator_count{$date}{$temp_id} : ($field =~ /monitor/ && $field !~ /troubleshoot/) ? 300 * $operator_count{$date}{$temp_id} : 450 * $operator_count{$date}{$temp_id} ; + $amnt_owed += $temp_support_rates{half_day}*$temp_calibrator_support{shift_count}{$date}{$temp_id}{1} ; + $amnt_owed += $temp_support_rates{full_day}*$temp_calibrator_support{shift_count}{$date}{$temp_id}{2} ; + # $temp_calibrator_support{count}{$date}{1} += ($abc[1] eq '1') ? 0.5 : 1 ; + # $temp_calibrator_support{shift_count}{$date}{1} += 1 ; + + $amnt_owed = $amnt_owed - $amounts_paid{$date}{$temp_id} ; + + $amnt_owed = 0 if $amounts_paid{$date}{$temp_id} ; + + next if $i{paid_status} eq 'outstanding' && $amnt_owed == 0 ; + next if $i{paid_status} eq 'paid' && $amounts_paid{$date}{$temp_id} == 0 ; + + $amnt_owed = sprintf("%0.2f",$amnt_owed) ; + $xlsxcol = 0 ; + + foreach my $col (@sql_col_display) { + + next unless $col ; # blank for the buttons column + $display = 1 ; + my $val = '' ; + my $align = '' ; + my $center = qq~ class="dt-center"~ ; + $align = $center ; + my $val_min = '' ; + + if ($col eq 'date') { + $val = $date ; + } elsif ($col eq "$field\_names") { + $val = $db{users}{$temp_id}{name} ; + $val .= " [Support]" if $support_user{$temp_id} ; + } elsif ($col eq 'shifts_count') { + chop $operator_shifts_string{$date}{$temp_id} if $operator_shifts_string{$date}{$temp_id} ; + my $shifts_cnt = $operator_count{$date}{$temp_id} + $temp_calibrator_support{count}{$date}{$temp_id}{1} + $temp_calibrator_support{count}{$date}{$temp_id}{2} ; + $val_min = "$shifts_cnt" ; + $val_min .= " [$operator_shifts_string{$date}{$temp_id}]" if $operator_shifts_string{$date}{$temp_id} ; + $operator_shifts_string{$date}{$temp_id} =~ s/\;/\
    /g ; + $val = ($operator_shifts_string{$date}{$temp_id}) ? qq~$shifts_cnt~ : $shifts_cnt ; + # $val = $operator_shifts{$date}{$temp_id} + } elsif ($col eq 'dates_paid') { + foreach (sort keys %{$dates_amounts_paid{$temp_id}}) { + $val .= ($val) ? qq~
    $_~ : qq~$_~ ; + } + $val = "None" unless $val ; + $val_min = $val ; + $val_min =~ s/\
    /\;/g ; + $val = qq~~ if $val =~ /
    / ; + } elsif ($col eq 'amounts_paid') { + foreach (sort keys %{$dates_amounts_paid{$temp_id}}) { + $dates_amounts_paid{$temp_id}{$_} = sprintf("%0.2f",$dates_amounts_paid{$temp_id}{$_}) ; + $val .= ($val) ? qq~
    $dates_amounts_paid{$temp_id}{$_}~ : qq~$dates_amounts_paid{$temp_id}{$_}~ ; + $amnt_tots{"amounts_paid"} += $dates_amounts_paid{$temp_id}{$_} ; + } + $val = "None" unless $val ; + $val_min = $val ; + $val_min =~ s/\
    /\;/g ; + $val = qq~~ if $val =~ /
    / ; + } elsif ($col eq 'date_payable') { + my $date_payable = "$now_year-$now_mm-$now_dd" ; + $val = ($amnt_owed != 0) ? &common_min_form_input_col("date_$temp_id\_$date_val",$date_payable) : "N/A" ; + $val_min = ($amnt_owed != 0) ? $date_payable : "N/A" ; + } elsif ($col eq 'amount_payable') { #dates_amounts_paid + $count_outstanding++ if $amnt_owed > 0 ; + $amnt_tots{"amount_payable"} += $amnt_owed ; + $val = ($amnt_owed != 0) ? &common_min_form_input_col("amount_payble_$temp_id\_$date_val",$amnt_owed) : "None" ; + $val_min = $amnt_owed ; + } elsif ($col eq 'paid') { + $val = ($amnt_owed != 0) ? &common_min_form_checkbox_col("paid_$temp_id\_$date_val",0) : '' ; + $val_min = ($amnt_owed != 0) ? "No" : "Yes" ; + } elsif ($col eq 'all_paid') { + $val = ($amnt_owed != 0) ? '' : '' ; + $val_min = ($amnt_owed != 0) ? "No" : "Yes" ; + } + $val_min = $val if $col eq 'date' || $col eq "$field\_names" ; + + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format_management_report_data) if $col ne 'shifts_count' ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format_management_report_data_ref_nr) if $col eq 'shifts_count' ; + $xlsxcol++ ; + # if ($_ eq 'ref_nr' or $_ eq 'camera_nr') { $val = &common_camera_links($tables,$id,$val) ;} + $print_tbody .= qq~$val~ ; + + } + $print_tbody .= qq~~ ; + $xlsxrow++ ; + $row_cnt++ ; + $quote_and_ops_ids .= qq~"$row_cnt\_$temp_id":"$date_val",~ ; + } + # chop $op_ids if $op_ids ; + # $quote_and_ops_ids .= qq~"$row_cnt_$id":[$op_ids],~ if $op_ids ; + } + + my $col_cnt = 0 ; + + foreach my $col (@sql_col_display) { + + if ($col eq 'date') { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$col_cnt,"TOTALS",$format_management_report_total) ; + } elsif ($col eq "amounts_paid" || $col eq "amount_payable") { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$col_cnt,"$amnt_tots{$col}",$format_management_report_totals) ; + } else { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$col_cnt,"-",$format_management_report_totals) ; + } + $col_cnt++ ; + } + + chop $quote_and_ops_ids if $quote_and_ops_ids ; + + # $print_tbody .= qq~~ ; + # $print_tbody .= qq~~ ; + $worksheet{$ws} -> set_column(0,0,15) ; + $worksheet{$ws} -> set_column(1,1,25) ; + $worksheet{$ws} -> set_column(2,7,20) if $i{paid_status} eq 'all' ; + $worksheet{$ws} -> set_column(2,5,20) if $i{paid_status} ne 'all' ; + + $box_icon .= qq~
    ~ if $i{paid_status} ne 'paid' && $count_outstanding > 0 ; + + &report_xlsx_export_footer('L',15,"$field\_payments_report") ; + + $fnsortcol = 0; + $fnsortorder = 'asc' ; + &common_min_extra_crumb("$lcpage\s","Search Screen") ; + + $trigger_jquery_raw .= qq~ + function selectAll() { + let jsObject = { + $quote_and_ops_ids + } ; + for (let key in jsObject) { + let op_id = jsObject[key] ; + let parts = key.split("_") ; + let event_id = parts[1] ; + \$(\$("#itv-table").dataTable().fnGetNodes()).find(\$("input[name=paid_"+event_id+"_"+op_id+"]")).each(function () { + // console.log("input[name=paid_"+event_id+"_"+op_id+"]") ; + if(\$(this).is(':checked')) { + \$(this).prop('checked',false) ; + } else { + \$(this).prop('checked',true) ; + } + }) ; + } + } + ~; + + my $field_id = "#$field2\-payment-form" ; + + # my $savebuttjs = ($count_outstanding > 0) ? qq~$("$field_id").submit();' : 'noty({text:"There are no calibrators to pay!",layout:"center",type:"error",timeout:3000});return;~ ; + + $trigger_jquery_raw .= qq~ + \$("#savebutt").click(function() { + // $savebuttjs + \$("$field_id").submit(); + }) ; + ~ ; + + $fcol = 2 ; + + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= &common_min_form_input_col("date_from",$i{date_from}) ; #date_from_i_field + $print_box_content_rows .= &common_min_form_input_col("date_to",$i{date_to}) ; #date_to_i_field + $print_box_content_rows .= &common_min_form_input_col("$field\_id",$i{"$field\_id"}) ; #temp_calibrator_id_i_field + $print_box_content_rows .= &common_min_form_input_col("$field\s_paid",$i{"$field\s_paid"}) ; + $print_box_content_rows .= qq~
    ~ ; + + $print_box_content_rows .= &common_min_forms_start("$field2\-payment") if $count_outstanding ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_load_list_vars { + + my ($where,$field) = @_ ; + + my $users_sql = ($field =~ /calibrator/) ? "`user_type` = 'casual_calibrator' OR `user_type` = 'support'" : "" ; + + &db_min_ro('users','id,name',"$users_sql",'','') ; + + &db_min_ro($table,"date,$field\_ids,$field\_dates_paid,$field\_amounts_paid,temp_calibrator_support_shifts","`date`>='$i{date_from}' AND `date`<='$i{date_to}' $where",'','') ; + + # &db_min_ro('shift_monitor_ids','date,monitor_ids',"`date`>='$i{date_from}' AND `date`<='$i{date_to}' $where",'','') ; + + our %operator_count = () ; our %amounts_paid = () ; our %dates_amounts_paid = () ; our %operator_shifts_string = () ; + + # my @monitor_shifts = ("","08:00-11:00","11:00-14:00","14:00-17:00","17:00-21:00") ; + my @operator_shifts = ($field =~ /calibrator/) ? ("","07:00-10:00","10:00-13:00","13:00-16:00","16:00-19:00") : ("","08:00-11:00","11:00-14:00","14:00-17:00","17:00-21:00") ; + + foreach my $date (keys %{$db{$table}}) { + my $shift_cnt = 0 ; + foreach my $shift (split(/\|/,$db{$table}{$date}{"$field\_ids"})) { + $shift_cnt++ ; + next unless $shift ; + foreach my $temp_id (split(/\;/,$shift)) { + next unless $temp_id ; + $operator_count{$date}{$temp_id} += 1 ; + $operator_shifts_string{$date}{$temp_id} .= qq~$operator_shifts[$shift_cnt];~ ; + } + } + $shift_cnt = 0 ; + # foreach my $shift (split(/\|/,$db{$table}{$date}{monitor_ids})) { + # $shift_cnt++ ; + # next unless $shift ; + # foreach my $temp_id (split(/\;/,$shift)) { + # next unless $temp_id ; + # $operator_count{$date}{$temp_id} += 1 ; + # $operator_shifts{$date}{$temp_id} .= qq~$monitor_shifts[$shift_cnt],~ ; + # } + # } + my @date_pay = split(/\;/,$db{$table}{$date}{"$field\_dates_paid"}) ; + my @amount_pay = split(/\;/,$db{$table}{$date}{"$field\_amounts_paid"}) ; + my $cnt = 0 ; + foreach my $temp_id_amnt (@amount_pay) { + my @temp_amnt = split(/\:/,$temp_id_amnt) ; + $amounts_paid{$date}{$temp_amnt[0]} += $temp_amnt[1] ; + $dates_amounts_paid{$temp_amnt[0]}{$date_pay[$cnt]} += $temp_amnt[1] ; + $cnt++ ; + } + + if ($temp_calibrator_payments_report && $db{$table}{$date}{temp_calibrator_support_shifts}) { + + foreach my $shift (split(/\|/,$db{$table}{$date}{temp_calibrator_support_shifts})) { + + $shift_cnt++ ; + next unless $shift ; + my @abc = split(/\:/,$shift) ; + next unless $abc[0] ; + + $operator_count{$date}{$abc[0]} += 0 ; + # $operator_count{$date}{$abc[0]} += ($abc[1] eq '1') ? 0.5 : 1 ; + $temp_calibrator_support{count}{$date}{$abc[0]}{$abc[1]} += ($abc[1] eq '1') ? 0.5 : 1 ; + $temp_calibrator_support{shift_count}{$date}{$abc[0]}{$abc[1]} += 1 ; + $operator_shifts_string{$date}{$abc[0]} .= ($abc[1] eq '1') ? qq~Half Day (<7 hours);~ : qq~Full Day (7 hours+);~ ; + $support_user{$abc[0]} = 1 ; + } + } + } + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_report_screen { + + my ($field) = @_ ; + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + &common_min_select_opts("$field\_id",'users',"name",$i{"$field\_id"},'','',"`name` NOT LIKE 'Rory%' AND `name` NOT LIKE 'Handre%'") ; + # &common_min_select_opts('event_quote_id','event_quotes',"ref",$i{event_quote_id},'','',"") ; + + $first_day_month = sprintf("%02d",$first_day_month) ; $first_day = sprintf("%02d",$first_day) ; + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-$now_mm-01") unless $i{date_from} ; + + my $days_in_month = Days_in_Month($now_year,$now_mm) ; + + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$days_in_month") ; + + # my ($sql_next_day) = &common_add_delta_days(1) ; + # my ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + # $print_box_content_rows .= &common_min_form_datepicker('date',"$next_year-$next_month-$next_day") ; #unless $i{date_from} ; + + $opts{paid_status} .= qq~~ ; + $opts{paid_status} .= qq~~ ; + $opts{paid_status} .= qq~~ ; + + $print_box_content_rows .= &common_min_form_select("$field\_id",'') ; + # $print_box_content_rows .= &common_min_form_select('event_quote_id','') ; + $print_box_content_rows .= &common_min_form_select('paid_status','') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------------------ + +1 ; \ No newline at end of file diff --git a/libs/modules/_FromProd/v1.0/schedule_test.pm b/libs/modules/_FromProd/v1.0/schedule_test.pm new file mode 100644 index 0000000..def5eb0 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/schedule_test.pm @@ -0,0 +1,1892 @@ +sub schedule_load_list_vars { + + my ($where) = @_ ; + + &db_min_ro('regions','*','','','') ; + + &db_min_ro('users','id,name,user_type,username,region_ids',"`name` NOT LIKE 'Rory%' AND `name` NOT LIKE 'Handre%'",'','') ; + $opts{schedule_users} .= qq~~ ; + # $opts{head_operator} .= qq~~ ; + foreach my $_uid (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + next if $useropts{it}{$db{users}{$_uid}{username}} ; + + my $regions = qq~~ ; + foreach (split(/\,/,$db{users}{$_uid}{region_ids})) { + $regions .= qq~$db{regions}{$_}{code},~ ; + } + chop $regions if $regions ; + $regions = qq~[$regions]~ if $regions ; + + # if ($db{users}{$_uid}{user_type} eq 'support' || $db{users}{$_uid}{user_type} eq 'manager' || $db{users}{$_uid}{user_type} eq 'casual_calibrator' || $monitoring_report) { + if ($db{users}{$_uid}{user_type} eq 'casual_calibrator' || (($monitoring_report || $troubleshoot_monitoring_report) && $db{users}{$_uid}{user_type} ne 'casual_c' && $db{users}{$_uid}{user_type} ne 'schools_manager' && $db{users}{$_uid}{user_type} ne 'support' && $db{users}{$_uid}{user_type} ne 'permanent')) { + $opts{schedule_users} .= qq~~ ; + } + + if (($db{users}{$_uid}{user_type} eq 'support' || $db{users}{$_uid}{user_type} eq 'casual_calibrator') && $temp_calibrator_report) { + $opts{support_users} .= qq~~ ; + $tot_support_users_cnt++; + } + + if ($db{users}{$_uid}{user_type} eq 'casual_c') { + $opts{fixture_check} .= qq~~ ; + } + } + + my $event_systems_sql_where = ($monitoring_report || $troubleshoot_monitoring_report) ? "" : "system_type = 'mobile'" ; + + &db_min_ro('event_systems','*',$event_systems_sql_where,'','') ; + + &db_min_ro($table,"id,club_ids,qty,ref,organisation_ids,quote_accepted,event_system_id_multiple,region_id,sport_type_ids,operator_ids,date_from,date_to,times_from,times_to,daily_operator_ids,days_active,monitor_ids,temp_calibrator_ids$extra_column","$where AND `quote_accepted` = '1'",'','') ; + + my $min_id = 0 ; my $max_id = 0 ; + + foreach my $id (keys %{$db{$table}}) { + + next unless $id ; my $cnt = 0 ; + + my @ed_from = &common_split_sql_time($db{$table}{$id}{date_from}) ; + my @ed_to = &common_split_sql_time($db{$table}{$id}{date_to}) ; + + &common_date_array("$ed_from[0]$ed_from[1]$ed_from[2]","$ed_to[0]$ed_to[1]$ed_to[2]") ; + + $sort_calibration_by_time_ref{"$ed_from[0]$ed_from[1]$ed_from[2]$ed_from[3]$ed_from[4]-$id"} = $id ; + + } + + &db_min_ro('sport_types','*','','','') ; + &db_min_ro('organisations','id,name','','','') ; + &db_min_ro('clubs','id,name','','','') if $monitoring_report || $troubleshoot_monitoring_report ; + + our $table_ = "shift_operator_ids" ; + my $col_ = ($monitoring_report) ? "monitor_ids" : ($troubleshoot_monitoring_report) ? "troubleshoot_monitor_ids" : "temp_calibrator_ids,temp_calibrator_support_shifts" ; + my $col2_ = ($monitoring_report) ? ",monitor_notes" : ($troubleshoot_monitoring_report) ? ",troubleshoot_monitor_notes" : "" ; + + &db_min_ro($table_,"date$col2_,$col_","`date` >= '$i{date_from}' AND `date` <= '$i{date_to}'") ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_build_extra_table { + + my ($field_name,$table_name,$table_col_name,$table_col_name_notes,$table_id) = @_ ; + + my $ws2 = join ' ', map { ucfirst $_ } split /_/, $field_name ; + $ws2 .= "s" ; + + &xlsxcreator_add_worksheet($ws2) ; + + my $col2 = 0 ; + foreach (@sql_col_display_extra) { + next if $_ eq "update" || !$_ || $_ eq 'notes' ; + my $coltitle = $_ ; + $coltitle =~ s/\_id//g ; + $coltitle =~ s/\_/ /g ; + my $ucfirst = join '', map { ucfirst lc } split /(\s+)/, $coltitle; + &xlsxcreator_write_xlsx($ws2,0,$col2,$ucfirst,$format_management_report_headings) ; + $col2++; + } + $col2=0 ; + &xlsxcreator_freeze_panes($ws2,1,0) ; # Freeze the first 3 rows + + my $uc_field_name = ucfirst $field_name ; + + # $db{$table_name}{$i{date}}{$table_col_name} = qq~147;132|||~ ; + + # for (0 .. 3) { $schedule_ids[$_] = "null" unless $schedule_ids[$_] ; } + $format84 -> set_left('1') ; + + my ($s_year,$s_mon,$s_day) = split("-",$i{date_from}) ; + my ($e_year,$e_mon,$e_day) = split("-",$i{date_to}) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + + our $date_cnt = 1 ; my $row_cnt = 0 ; + + return if int("$s_year$s_mon$s_day") > int("$e_year$e_mon$e_day") ; + + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + my %row_cnt_shifts = () ; my $max_row_cnt = 0 ; + + while (int("$s_year$s_mon$s_day") <= int("$e_year$e_mon$e_day")) { + + $db{$table_name}{"$s_year-$s_mon-$s_day"}{$table_col_name} =~ s/\;/\,/g ; + my @schedule_ids = split(/\|/,$db{$table_name}{"$s_year-$s_mon-$s_day"}{$table_col_name}) ; + + my $date = "$s_year-$s_mon-$s_day" ; + + my $date_str = &common_min_date_as_string($date) ; + + our $default_javascript = "" ; my %default_javascript_short = () ; + + my $val_notes = qq~~ ; + + foreach my $col (@sql_col_display_extra) { + + my $formatting = $format92 ; + next if substr($col,0,5) eq 'shift' && substr($col,0,7) ne 'shift_1' ; + my $val = '' ; my $nowrap = '' ; my $align = qq~~ ; my $val_min = "" ; + + my $row_span = '' ; + + if ($col eq 'date') { + + $row_cnt++ ; + $row_span = qq~rowspan="2"~ if $monitoring_report || $troubleshoot_monitoring_report ; + $val = $date_str . qq~~ ; + $nowrap = "nowrap" ; + &xlsxcreator_write_xlsx($ws2,$max_row_cnt+1,0,$date_str ,$formatting) ; + + } elsif (substr($col,0,7) eq 'shift_1') { + + $align = qq~ class="dt-center"~ ; + + local $place_holder = substr($ws2,0,-1) ; + + for (1 .. 4) { + $row_cnt_shifts{$_} = $max_row_cnt + 1 ; + } + + for my $shift_cnt (1 .. 4) { + + # $row_cnt_shifts{$shift_cnt} = ($max_row_cnt && $shift_cnt == 1) ? $max_row_cnt + 1 : 1 ; + my $field = "$field_name\_$shift_cnt\_1_1_$date_cnt" ; + $opts{$field} = $opts{schedule_users} ; + $preferred_placeholder{$field} = ($troubleshoot_monitoring_report) ? "Shift Troubleshoot Monitor $shift_cnt $date_cnt" : "$place_holder $shift_cnt $date_cnt" ; + $multiple{$field} = 1 ; + + my $table_col = 6-$shift_cnt ; + push @first_table_multi_select_table_cells,"#$table_id tr:eq($row_cnt) td:nth-last-child($table_col)" ; + + $val .= &common_min_table_select($field,$schedule_ids[$shift_cnt - 1],'',$row_cnt,$table_col,'',$schedule_ids[$shift_cnt - 1],'shift',$table_id) ; + foreach (split(/\,/,$schedule_ids[$shift_cnt - 1])) { + next unless $_ ; + $trigger_jquery_raw .= qq~\$("#select$uc_field_name\_$shift_cnt\_1_1_$date_cnt option[value='$_']").prop("selected",true);~ ; + &xlsxcreator_write_xlsx($ws2,$row_cnt_shifts{$shift_cnt},$shift_cnt,"$db{users}{$_}{name}",$formatting) ; + $row_cnt_shifts{$shift_cnt}++ ; + } + $max_row_cnt = $row_cnt_shifts{$shift_cnt} if !$max_row_cnt || $max_row_cnt < $row_cnt_shifts{$shift_cnt} ; + $val .= qq~~ if $shift_cnt < 4 ; + } + + } elsif ($col eq 'notes') { + + $row_cnt++ ; + + my @notes = split(/\:\|\:/,$db{$table_name}{$date}{$table_col_name_notes}) ; + # $max_row_cnt-- ; + # $max_row_cnt++ if $db{$table_name}{$date}{$table_col_name_notes} =~ /(\d+)/g || $db{$table_name}{$date}{$table_col_name_notes} =~ /[a-zA-Z]/ ; + + for my $shift_cnt (1 .. 4) { + + my $field = "$field_name\_notes_$shift_cnt\_1_1_$date_cnt" ; + $preferred_placeholder{$field} = ($troubleshoot_monitoring_report) ? "Shift Troubleshoot Monitor Notes $shift_cnt $date_cnt" : "Shift Monitor Notes $shift_cnt $date_cnt" ; + $val_notes .= &common_min_table_textarea($field,$notes[$shift_cnt-1],'',$row_cnt,5-$shift_cnt,'',$notes[$shift_cnt-1],'',$table_id) ; + &xlsxcreator_write_xlsx($ws2,$max_row_cnt,$shift_cnt,$notes[$shift_cnt-1],$format97) if $db{$table_name}{$date}{$table_col_name_notes} =~ /(\d+)/g || $db{$table_name}{$date}{$table_col_name_notes} =~ /[a-zA-Z]/ ; + $val_notes .= qq~~ if $shift_cnt < 4 ; + + } + + $val_notes = qq~$val_notes~ ; + + } elsif ($col eq "update") { + + $row_span = qq~rowspan="2"~ if $monitoring_report || $troubleshoot_monitoring_report ; + $align = qq~ class="dt-center"~ ; + my $field = "update_1_1_$date_cnt" ; + $val = &common_min_form_checkbox_col($field,'') ; + + chop $default_javascript if $default_javascript ; + + if ($default_javascript) { + + push @default_javascript_by_id, qq~"1_1_$date_cnt":{$default_javascript}~ ; ## ??? + + for (1 .. 4) { + my $field = "#textarea" . ucfirst "$field_name\_notes\_$_\_1_1_$date_cnt" ; + push @all_update_field_ids,"$field" if $monitoring_report || $troubleshoot_monitoring_report ; + $field = "#select" . ucfirst "$field_name\_$_\_1_1_$date_cnt" ; + push @all_update_field_ids,"$field" ; + } + } + } + + $print_tbody_extra .= qq~$val~ if $col ne 'notes' ; + + $print_tbody_extra .= qq~$val_notes~ if $col eq 'update' ; + + } + + ($s_year,$s_mon,$s_day) = Add_Delta_Days($s_year,$s_mon,$s_day,1) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + $date_cnt++ ; + } + + $date_cnt-- ; + + # &common_min_table_select_fixed_width_jquery(1) ; + # &common_min_table_select_default_values_jquery ; + + # @all_select_ids = () ; @selects_with_default_ids = () ; %col_name_select_ids = () ; %table_with_default_ids = () ; %selects_by_def_val = () ; + + @sql_col_display_extra = ("date","shift_1_(08:00-11:00)","shift_2_(11:00-14:00)","shift_3_(14:00-17:00)","shift_4_(17:00-21:00)","update") if $monitoring_report || $troubleshoot_monitoring_report ; + + $worksheet{$ws2}->set_column(0,0,10) ; + $worksheet{$ws2}->set_column(1,5,50) if $monitoring_report || $troubleshoot_monitoring_report ; + $worksheet{$ws2}->set_column(1,5,20) if $temp_calibrator_report ; + + $trigger_jquery_raw .= qq~\$("#$table_id tr:eq(0) th:nth-last-child(2),#$table_id tr th:nth-last-child(3),#$table_id tr th:nth-last-child(4),#$table_id tr th:nth-last-child(5)").css("width","23%")~ ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_build_extra_second_table { + + my ($field_name,$table_name,$table_col_name) = @_ ; + + my $ws2 = join ' ', map { ucfirst $_ } split /_/, $field_name ; + $ws2 .= "s" ; + + &xlsxcreator_add_worksheet($ws2) ; + + my $col2 = 0 ; + foreach (@sql_col_display_2) { + next if $_ eq "update" || !$_ ; + my $coltitle = $_ ; + $coltitle =~ s/\_id//g ; + $coltitle =~ s/\_/ /g ; + my $ucfirst = join '', map { ucfirst lc } split /(\s+)/, $coltitle; + &xlsxcreator_write_xlsx($ws2,0,$col2,$ucfirst,$format_management_report_headings) ; + $col2++; + } + $col2=0 ; + &xlsxcreator_freeze_panes($ws2,1,0) ; # Freeze the first 3 rows + + my ($s_year,$s_mon,$s_day) = split("-",$i{date_from}) ; + my ($e_year,$e_mon,$e_day) = split("-",$i{date_to}) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + + $opts{name} = $opts{support_users} ; + + $radio_opts{shift} = "Half Day (<7 hours);Full Day (7 hours+)" ; + + my $nr_of_options = scalar split("option> int("$e_year$e_mon$e_day") ; + + my $date1 = "$s_year-$s_mon-$s_day" ; + my $date2 = "$e_year-$e_mon-$e_day" ; + my $d1 = Time::Piece->strptime($date1, "%Y-%m-%d") ; + my $d2 = Time::Piece->strptime($date2, "%Y-%m-%d") ; + my $diff_in_days = ($d2 - $d1)->days + 1; + + my $date_cnt= 0 ; + + &common_min_thead_2 ; + + for my $day_cnt (1 .. $diff_in_days) { + + my $date = "$s_year-$s_mon-$s_day" ; + + $db{$table_name}{$date}{$table_col_name} = "None" unless $db{$table_name}{$date}{$table_col_name} ; + + $date_cnt++ ; + + push @second_table_ids,"#select_temp_calibrators_2_$date_cnt" ; + push @second_table_ids_2,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(2)" ; + push @second_table_ids_3,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(3)" ; + push @second_table_ids_4,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(4)" ; + push @second_table_ids_5,"#select_temp_calibrators_2_$date_cnt td:nth-last-child(5)" ; + + $print_tbody_extra_2 .= qq~~ ; + $print_tbody_extra_2 .= qq~$print_thead_2~ if $date_cnt == 1 ; + $print_tbody_extra_2 .= qq~~ ; + + my $row_cnt = 0 ; + + $opts{name} = $opts{support_users} ; + + my $z_index = $tot_support_users_cnt * ($diff_in_days - $day_cnt + 1) + 1 ; + + foreach my $row (split(/\|/,$db{$table_name}{$date}{$table_col_name})) { + + $z_index-- ; + + next unless $row ; + + $row_cnt++ ; + $print_tbody_extra_2 .= qq~~ ; + + our $default_javascript = qq~~ ; + + $xlsxrow++ ; $xlsxcol = 0 ; + + foreach my $col (@sql_col_display_2) { + + my $formatting = $format84 ; + my $val = '' ; my $nowrap = '' ; my $align = qq~class="dt-center"~ ; + + my $field_id = "$col\_2_$row_cnt\_$date_cnt" ; + + my $default_val_html = qq~~ ; + + if ($col eq 'date') { + my $date_str = &common_min_date_as_string($date) ; + $val = $date_str ; + $nowrap = "nowrap" ; + $align = qq~class="dt-left"~ ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow,$xlsxcol,"$date_str",$formatting) ; + } elsif ($col eq 'name') { + my @abc = split(/\:/,$row) ; + $abc[0] = "" if $abc[0] eq "None" ; + $default_val = $abc[0] ; + $default_val_is_saved = ($default_val) ? 1 : 0 ; + $preferred_placeholder{$field_id} = "Select Temp Support Name $row_cnt" ; + $opts{$field_id} = $opts{name} ; + + my $table_row_cnt = ($date_cnt == 1) ? $row_cnt + 1 : $row_cnt - 1 ; + + $val = &common_min_table_select($field_id,$default_val,'',$table_row_cnt,4,'',$default_val_is_saved,'',"select_temp_calibrators_2_$date_cnt") ; + # $default_val_html = qq~~ ; + + $trigger_jquery_raw .= qq~ + \$("#select_temp_calibrators_2_$date_cnt tr:eq($table_row_cnt) td:nth-last-child(4)").css("z-index","$z_index") ; + ~ ; + $support_users_cnt-- ; + $opts{name} =~ s/.*?<\/option>// if $default_val ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow,$xlsxcol,$db{users}{$default_val}{name},$formatting) ; + } elsif ($col eq 'shift') { + $radio_opts{$field_id} = $radio_opts{shift} ; + my @abc = split(/\:/,$row) ; + $default_val = $abc[1] ; + $default_val_is_saved = ($default_val) ? 1 : 0 ; + # $default_val_html = qq~~ ; + our $val_min = "" ; + my $table_row_cnt = ($date_cnt == 1) ? $row_cnt + 1 : $row_cnt - 1 ; + $val = &table_radio_button($field_id,$default_val,'',$table_row_cnt,3,'',$default_val_is_saved,$col,"select_temp_calibrators_2_$date_cnt") ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow,$xlsxcol,$val_min,$formatting) ; + } elsif ($col eq 'update') { + $val = &common_min_table_checkbox($field_id) ; + chop $default_javascript if $default_javascript ; + if ($default_javascript) { + push @default_javascript_by_id, qq~"2_$row_cnt\_$date_cnt":{$default_javascript}~ ; + push @all_update_field_ids, "#shift_1_2_$row_cnt\_$date_cnt,#shift_2_2_$row_cnt\_$date_cnt,#selectName_2_$row_cnt\_$date_cnt" ; + } + } elsif (!$col) { + $val = ($row ne 'None') ? qq~ ~ : qq~~ ; + } + + my $styling = ($col eq 'date' && $row_cnt == 1) ? qq~style="width:7%;"~ : ($col eq 'name' && $row_cnt == 2) ? qq~style="width:35%;"~ : '' ; + + $print_tbody_extra_2 .= qq~~ ; + $xlsxcol++ ; + } + $print_tbody_extra_2 .= qq~~ ; + } + + ($s_year,$s_mon,$s_day) = Add_Delta_Days($s_year,$s_mon,$s_day,1) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + + if ($nr_of_options <= $row_cnt) { + $trigger_jquery_raw .= qq~\$("#add_row_table_2_$date_cnt").css("display","none");~ ; + } + + my $plus_button_color = ($db{shift_operator_ids}{$date}{temp_calibrator_support_shifts} =~ /\|\|/ || $db{shift_operator_ids}{$date}{temp_calibrator_support_shifts} =~ /\|\:/ || $db{shift_operator_ids}{$date}{temp_calibrator_support_shifts} eq "None") ? "grey" : "blue" ; + + push @plus_btn_ids,"#add_row_table_2_$date_cnt" ; + + $plus_button = qq~ + +
    +
    + + +
    +
    +
    +
    +
    + ~ ; + + $print_tbody_extra_2 .= qq~
    $val
    $plus_button~ ; + } + + $worksheet{$ws2}->set_column('A:C',20); + + &common_min_table_update_checkbox_col_default ; + + our $trigger_jquery_raw_default_alt = qq~ + // let all_def_vals = {} ; + + // all_def_vals[row_nr] = {} ; + + // let def_name = \$("#default_name_"+row_nr ).text() ; + // let def_shift = \$("#default_shift_"+row_nr ).text() ; + + // all_def_vals[row_nr]["selectName_"+row_nr] = def_name ; + + // if (def_shift == "1") { + // all_def_vals[row_nr]["shift_1_"+row_nr ] = "true" ; + // all_def_vals[row_nr]["shift_2_"+row_nr ] = "false" ; + // } else if (def_shift == "2") { + // all_def_vals[row_nr]["shift_1_"+row_nr ] = "false" ; + // all_def_vals[row_nr]["shift_2_"+row_nr ] = "true" ; + // } + ~ ; + + my $plus_btn_ids_str = join(",",@plus_btn_ids) ; + + $trigger_jquery_raw .= qq~ + + function add_Days (date_string,num_days,as_num) { + let date = new Date(date_string) ; + date.setDate(date.getDate() + num_days) ; + let year = date.getFullYear() ; + let month = String(date.getMonth() + 1).padStart(2,'0') ; + let day = String(date.getDate()).padStart(2,'0') ; + if (as_num) { + return ""+year+"-"+month+"-"+day+"" ; + } else { + let month_names = ["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] ; + month = month_names[month] ; + return ""+day+"-"+month+"-"+year+"" ; + } + } + + function deleteTempSupport (row_cnt) { + + BootstrapDialog.confirm({ + title: 'Confirm Delete', + message: 'Are you sure you want to delete '+name+'?', + type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + callback: function(result) { + + let [cnt_for_date,table_cnt] = row_cnt.split('_').map(Number) ; + + if (result) { + // if (\$("#update_data_base_"+row_cnt).text()) { + + let curr_date = add_Days("$i{date_from}",table_cnt-1,1) ; + + let url_delete = "$useropts{scripts}/get/get_db_delete_temp_support.pl?date="+curr_date+"&row_cnt="+cnt_for_date ; + + console.log("url_delete : "+url_delete) ; + + // console.log("#select_temp_calibrators_2_"+table_cnt+" #second_table_"+cnt_for_date+"_"+table_cnt) ; + + \$("#select_temp_calibrators_2_"+table_cnt+" #second_table_"+cnt_for_date+"_"+table_cnt).remove() ; + + \$.get(url_delete) ; + // } + // $("select#selectOriginalId").attr("id", "selectNewId"); + + let table_row_cnt = \$("#select_temp_calibrators_2_"+table_cnt).find('tr').length - 2 ; + + // let start_row_nr = 2 ; let end_row_nr = table_row_cnt + 1 ; + + if (table_cnt != '1') { + table_row_cnt += 2 ; + // start_row_nr = 0 ; + // end_row_nr -= 2 ; + } + + let all_def_vals_new = {} ; + + for (let i=2;i<=table_row_cnt+1;i++) { + + let row_nr = i-1 ; + let row_val = i ; + if (table_cnt != '1') { + row_val -= 2 ; + } + + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+")").attr("id","second_table_"+row_nr+"_"+table_cnt); + + let zIndex = \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(4)").css('z-index'); + zIndex++ ; + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(4)").css('z-index',zIndex); + if (\$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(1)").html()) { + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(1)").html(" "); + } + + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+")").find("select[id^='selectName_']").each(function() { + + var oldId = \$(this).attr("id"); + let old_row_val = get_row_nr(oldId,2) ; + let new_row_val = row_nr+"_"+table_cnt ; + + if (typeof all_def_vals["2_"+old_row_val] !== 'undefined') { + + all_def_vals_new["2_"+new_row_val] = {}; + all_def_vals_new["2_"+new_row_val]["selectName_2_"+new_row_val] = all_def_vals["2_"+old_row_val]["selectName_2_"+old_row_val] ; + all_def_vals_new["2_"+new_row_val]["shift_1_2_"+new_row_val] = all_def_vals["2_"+old_row_val]["shift_1_2_"+old_row_val] ; + all_def_vals_new["2_"+new_row_val]["shift_2_2_"+new_row_val] = all_def_vals["2_"+old_row_val]["shift_2_2_"+old_row_val] ; + + } + + let old_select_val = \$("#"+oldId).val() ; + + \$(this).attr("id", "selectName_2_"+new_row_val); + \$(this).attr("name", "name_2_"+new_row_val); + \$(this).attr("data-placeholder", "Select Temp Support Name "+row_nr); + var chosenElementId = oldId + "_chosen"; + \$("#" + chosenElementId).attr("id", "selectName_2_"+row_nr+"_"+table_cnt+"_chosen"); + \$("#selectName_2_"+row_nr+"_"+table_cnt+"_chosen .chosen-single span").text("Select Temp Support Name "+row_nr); + + \$("#shift_1_2_"+old_row_val).attr("name","shift_2_"+new_row_val); + \$("#shift_1_2_"+old_row_val).attr("id","shift_1_2_"+new_row_val); + \$("#shift_2_2_"+old_row_val).attr("name","shift_2_"+new_row_val); + \$("#shift_2_2_"+old_row_val).attr("id","shift_2_2_"+new_row_val); + \$("#checkboxUpdate_2_"+old_row_val).attr("name","update_2_"+new_row_val); + \$("#checkboxUpdate_2_"+old_row_val).attr("id","checkboxUpdate_2_"+new_row_val); + + // \$("#default_name_"+old_row_nr).attr("id","default_name_"+row_nr); + // \$("#default_shift_"+old_row_nr).attr("id","default_shift_"+row_nr); + + \$("#selectName_2_"+new_row_val).val(old_select_val) ; + \$("#selectName_2_"+new_row_val).trigger("chosen:updated") ; + + if (\$("#add_row_table_2_"+table_cnt).is(":hidden")) { + \$("#add_row_table_2_"+table_cnt).css("display","") ; + } + + }) ; + + } + + all_def_vals = all_def_vals_new ; + + if (!\$("#second_table_1_"+table_cnt).html()) { + + let options = "$opts{support_users}" ; + let select = add_select("name_2_1_"+table_cnt,"selectName_2_1_"+table_cnt,"Select Temp Support Name 1","$opts{support_users}",1,90) ; + let radio_butt = "  " ; + let update_butt = "" ; + let newRow = ""+curr_date+""+select+""+radio_butt+""+update_butt+"" ; + \$("#select_temp_calibrators_2_"+table_cnt+" tbody").append(newRow) ; + \$("#selectName_2_1_"+table_cnt).chosen({allow_single_deselect:true}) ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("position","absolute") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("width","90%") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("left","5%") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("top","50%") ; + \$("#selectName_2_1_"+table_cnt+"_chosen").css("transform","translateY(-50%)") ; + + let optionCount = \$("#selectName_2_1_"+table_cnt+" option").length - 1 ; + + let date_cnt = daysBetween("$i{date_from}","$i{date_to}") ; + + let z_index = (date_cnt - table_cnt + 1)*optionCount ; + + let row_val = 2 ; + if (table_cnt != '1') { + row_val = 0 ; + } + + \$("#select_temp_calibrators_2_"+table_cnt+" tr:eq("+row_val+") td:nth-last-child(4)").css("z-index",z_index) ; + + \$("#selectName_2_1_"+table_cnt+",#shift_1_2_1_"+table_cnt+",#shift_2_2_1_"+table_cnt).change( function () { + + let found_blank = 0 ; + + if ((!\$("#selectName_2_1_"+table_cnt).val() || (!\$("#shift_1_2_1_"+table_cnt).is(":checked") && !\$("#shift_2_2_1_"+table_cnt).is(":checked"))) && \$("#second_table_1_"+table_cnt).html()) { + found_blank = 1 ; + } + + if (!found_blank) { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('grey').addClass('blue'); + } else { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('blue').addClass('grey'); + } + + let tick_update = 0 ; + + if ((\$("#"+this.id).attr('type') == 'radio' && \$("#"+this.id).is(":checked")) || (\$("#"+this.id).val() && \$("#"+this.id).attr('type') != 'radio')) { + tick_update = 1 ; + } + + if (tick_update && !\$("#checkboxUpdate_2_1_"+table_cnt).is(":checked")) { + \$("#checkboxUpdate_2_1_"+table_cnt).prop("checked",true) ; + } else if (!tick_update && \$("#checkboxUpdate_2_1_"+table_cnt).is(":checked")) { + \$("#checkboxUpdate_2_1_"+table_cnt).prop("checked",false) ; + } + + }) ; + } + } + } + }); + } + + ~ ; + + $trigger_jquery_raw .= qq~ + + function daysBetween(date1,date2) { + + const oneDay = 24 * 60 * 60 * 1000 ; + const firstDate = new Date(date1) ; + const secondDate = new Date(date2) ; + const diffInTime = Math.abs(secondDate - firstDate) ; + + return Math.ceil(diffInTime/oneDay) + 1 ; + + } + + function add_select (field_name,field_id,placeholder,options,tindex,width) { + + let select_raw = "" ; + + return select_raw ; + } + + \$("$plus_btn_ids_str").click( function () { + + let table_nr = get_row_nr(this.id) ; + + let table_row_cnt = \$("#select_temp_calibrators_2_"+table_nr).find('tr').length ; + + if (table_nr == '1') { + table_row_cnt -= 2 ; + } + + let found_blank = 0 ; + // console.log("table_row_cnt : "+table_row_cnt) ; + + // let lastRowId = \$("#select_temp_calibrators_2 tr:last").attr("id"); + // let table_row_cnt = get_row_nr(lastRowId) ; + + for (i=1;i<=table_row_cnt;i++) { + if ((!\$("#selectName_2_"+i+"_"+table_nr).val() || \$("#selectName_2_"+i+"_"+table_nr).val() == null || (!\$("#shift_1_2_"+i+"_"+table_nr).is(":checked") && !\$("#shift_2_2_"+i+"_"+table_nr).is(":checked"))) && \$("#second_table_"+i+"_"+table_nr).html()) { + found_blank = 1 ; + } + } + + if (!found_blank) { + + \$('#add_row_table_2_'+table_nr).find('i').removeClass('blue').addClass('grey'); + + table_row_cnt++ ; + + let options = "$opts{support_users}" ; + + let select = add_select("name_2_"+table_row_cnt+"_"+table_nr,"selectName_2_"+table_row_cnt+"_"+table_nr,"Select Temp Support Name "+table_row_cnt,"$opts{support_users}",1,90) ; + // "Half Day (<7 hours);Full Day (7 hours+)" + let radio_butt = "  " ; + + // let delete_butt = " " ; + let delete_butt = "" ; + + let update_butt = "" ; + + let curr_date = add_Days("$i{date_from}",table_nr-1) ; + + let newRow = ""+curr_date+""+select+""+radio_butt+""+update_butt+""+delete_butt+"" ; + + \$("#select_temp_calibrators_2_"+table_nr+" tbody").append(newRow) ; + + // let optionCount = \$("#selectName_2_"+table_row_cnt+"_"+table_nr+" option").length - 1 ; + let optionCount = \$("#selectName_2_1_"+table_nr+" option").length - 1 ; + + let date_cnt = daysBetween("$i{date_from}","$i{date_to}") ; + + // my $support_users_cnt = $potential_support_users_cnt - ($day_cnt - 1)*$tot_support_users_cnt ; + + let z_index = (date_cnt - table_nr + 1)*optionCount - table_row_cnt + 1 ; + + // let optionCount = "$tot_support_users_cnt" ; + + // \$("#selectName_"+table_row_cnt).chosen({allow_single_deselect:true}) ; + + for (i=1;i 1) { + // let row_nr = get_row_nr(this.id) ; + // for (i=1;i<=table_row_cnt;i++) { + // for (j=1;j<=table_row_cnt;j++) { + + // } + // } + + } + + if (!found_blank) { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('grey').addClass('blue'); + } else { + \$('#add_row_table_2_'+table_cnt).find('i').removeClass('blue').addClass('grey'); + } + + }) ; + + ~ ; + + my $second_table_ids_str = join(",",@second_table_ids) ; + my $second_table_ids_str_2 = join(",",@second_table_ids_2) ; + my $second_table_ids_str_3 = join(",",@second_table_ids_3) ; + our $second_table_ids_str_4 = join(",",@second_table_ids_4) ; + my $second_table_ids_str_5 = join(",",@second_table_ids_5) ; + + &common_min_table_select_fixed_width_jquery("$second_table_ids_str_4") ; + + &common_min_table_select_default_values_jquery ; + + # &common_min_table_select_jquery("#select_temp_calibrators_2 td:nth-last-child(4)","") ; + + &common_min_table_update_checkbox_col_jquery("3") ; + + $trigger_jquery .= qq~ + \$("#select_temp_calibrators_2_length").css("display","none") ; + \$("#select_temp_calibrators_2_filter").css("display","none") ; + \$("#select_temp_calibrators_2_info").css("display","none") ; + \$("#select_temp_calibrators_2_paginate").css("display","none") ; + ~ ; + + $trigger_jquery .= qq~ + // \$("#select_temp_calibrators_2").css("width","66.66666%"); + \$("$second_table_ids_str_5").css("width","7%") ; + \$("$second_table_ids_str_4").css("width","40%") ; + // \$("$second_table_ids_str_4").css("position","relative") ; + // \$("$second_table_ids_str_4").css("text-align","center") ; + \$("$second_table_ids_str_3").css("width","40%") ; + \$("$second_table_ids_str_2").css("width","10%") ; + ~ ; + + +} #------------------------------------------------------------------------------------------ + +sub table_radio_button { + +my ($field,$default_val,$only_display_val,$table_row,$table_col,$background_color,$default_val_is_saved,$col_name,$table_id) = @_ ; + +return unless $col_name ; + +$field = "$col_name\_$table_row" unless $field ; + +my $field_cnt = $field ; +$field_cnt =~ s/$col_name\_//g ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } + +my @opts = ($radio_opts{$field}) ? split(/\;/,$radio_opts{$field}) : split(/\;/,$options); + +my $row = qq~~ ; + +my $cnt = 0 ; + +if ($default_val && $default_val_is_saved) { + $background_color = "#424949" unless $background_color ; + $table_with_default_ids{$background_color} .= "#$table_id tr:eq($table_row) td:nth-last-child($table_col)," ; +} + +foreach (@opts) { + $cnt++ ; + my $checked = ($cnt eq $default_val) ? 'CHECKED' : '' ; + $val_min = ($checked) ? $_ : $val_min ; + $row .= qq(  ) ; + if (!$default_val_is_saved || !$default_val) { + $default_javascript .= qq~"$col_name\_$cnt\_$field_cnt":"false",~ ; + } else { + my $default_val_boolian = ($cnt eq $default_val) ? "true" : "false" ; + $default_javascript .= qq~"$col_name\_$cnt\_$field_cnt":"$default_val_boolian",~ ; + } + push @all_radio_ids,"#shift_$cnt\_$field_cnt" ; +} + +$row = substr($row,0,-12) ; + +# my $row = qq($print_radios) ; + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_build_table { + + my ($table_col_name,$field_name) = @_ ; + + my $cali_cnt = 0 ; my $found_editable = 0 ; my @all_select_ids = () ; + + $format84 -> set_align("center") ; + + my $table_row = 0 ; my %default_vals = () ; + + # foreach my $id (sort {$db{$table}{$a}{date_from} cmp $db{$table}{$b}{date_from}} keys %{$db{$table}}) { + foreach my $date_ref (sort keys %sort_calibration_by_time_ref) { + + my $id = $sort_calibration_by_time_ref{$date_ref} ; + + next unless $id ; + + my $system_count = 0 ; my $system_day_cnt = 0 ; + + my %default_monitors = () ; + + my $day_cnt = 0 ; + my $sql_col = "$table_col_name" ; + my $inp_field = substr($sql_col,0,-1) ; + my $found_inp_field = 0 ; + foreach my $day_row (split(/\|/,$db{$table}{$id}{$sql_col})) { + $day_cnt++ ; $system_count = 0 ; + foreach my $system_row (split(/\;/,$day_row)) { + $system_count++ ; my $shift_cnt = 0 ; + foreach my $shift_monitor (split(/\:/,$system_row)) { + $shift_cnt++ ; + $default_monitors{$day_cnt}{$system_count}{$shift_cnt} = $shift_monitor ; + $found_inp_field = 1 if $shift_monitor eq $i{$inp_field} ; + } + } + } + $system_count = 0 ; + + my %system_has_daily_op = () ; my %default_op_ids = () ; + + foreach my $system_row (split(/\|/,$db{$table}{$id}{daily_operator_ids})) { + $system_count++ ; + next unless $system_row ; + $system_day_cnt = 0 ; + foreach my $col (split(/\;/,$system_row)) { + $system_day_cnt++ ; + next unless $col ; + $default_op_ids{$system_count}{$system_day_cnt} = $col if $col ; + $system_has_daily_op{$system_count} = 1 if $col ; + } + } + $system_count = 0 ; + + unless (&common_check_if_string_contains_an_integer($db{$table}{$id}{event_system_id_multiple})) { + $db{$table}{$id}{event_system_id_multiple} = ";none;" ; + } + + # my @system_name_ids = split(";",$db{$table}{$id}{event_system_id_multiple}) ; + + my @system_name_ids = split(/\;/,$db{$table}{$id}{event_system_id_multiple}) ; + my @club_ids = split(/\;/,$db{$table}{$id}{club_ids}) ; + my @op_ids = split(/\,/,$db{$table}{$id}{operator_ids}) ; + my @days_active = split(/\;/,$db{$table}{$id}{days_active}) ; + my @start_times = ($db{$table}{$id}{qty} eq '1' && $days_active[0]) ? () : split(/\;/,";".$db{$table}{$id}{times_from}) ; + my @end_times = ($db{$table}{$id}{qty} eq '1' && $days_active[0]) ? () : split(/\;/,$db{$table}{$id}{times_to}) ; + + my $cnt_rows = 0 ; + for (1 .. 50) { + $cnt_rows = $_ if $system_name_ids[$_ - 1] or $club_ids[$_ - 1] ; + } + + my $system_count = 0 ; my $system_day_cnt = 0 ; + + foreach my $event_sys_id (@system_name_ids) { + + $system_count++ ; + + next unless $event_sys_id ; + next if $db{event_systems}{$event_sys_id}{system_type} ne 'mobile' && !$monitoring_report && !$troubleshoot_monitoring_report ; + + # &common_debug(">>>>>>>>> 2. $system_count [$id] $db{$table}{$id}{ref} [$db{event_systems}{$event_sys_id}{system_type}]") ; + + # $event_cnt++ ; + + # foreach my $cal_date (sort {$day_of_week{$a} cmp $day_of_week{$b}} keys %day_of_week) { + + $system_day_cnt = 0 ; + + foreach my $cal_date (sort keys %day_of_week) { + + # my $srch_date_from_comp = $i{date_from} ; $srch_date_from_comp =~ s/\-//g ; + # my $srch_date_to_comp = $i{date_to} ; $srch_date_to_comp =~ s/\-//g ; + my $date_from_comp = substr($db{$table}{$id}{date_from},0,10) ; $date_from_comp =~ s/\-//g ; + my $date_to_comp = substr($db{$table}{$id}{date_to},0,10) ; $date_to_comp =~ s/\-//g ; + my $cal_date_comp = $cal_date ; # $cal_date_comp =~ s/\-//g ; + $cal_date = substr($cal_date,0,4) . '-' . substr($cal_date,4,2) . '-' . substr($cal_date,6,2) ; + my $date_from = substr($db{$table}{$id}{date_from},0,10) ; + $system_day_cnt++ ; + + # &common_debug("[$cnt{$event_sys_id}{$id}] : $event_sys_id [$id] $cal_date") ; + + # &common_debug("1. DATE >>> $cal_date_comp < $date_from_comp") if !$report ; + next if $cal_date_comp < $date_from_comp ; + # &common_debug("2. DATE >>> $cal_date_comp > $date_to_comp") if !$report ; + next if $cal_date_comp > $date_to_comp ; + + $cnt{$event_sys_id}{$id}++ ; + + next if $db{$table}{$id}{days_active} && !$days_active[$cnt{$event_sys_id}{$id}-1] ; + + my $cal_date_val = $cal_date ; my $date_from_val = $i{date_from} ; my $date_to_val = $i{date_to} ; + + $cal_date_val =~ s/\-//g ; $date_from_val =~ s/\-//g ; $date_to_val =~ s/\-//g ; + + next if $cal_date_val < $date_from_val || $cal_date_val > $date_to_val ; + + # # &common_debug("3. DATE >>> $cal_date_comp > $srch_date_to_comp") if !$report ; + # next if ($calibration_report) && $cal_date_comp > $srch_date_to_comp ; + # # &common_debug("4. DATE >>> $cal_date_comp < $srch_date_from_comp") if !$report ; + # next if ($calibration_report) && $cal_date_comp < $srch_date_from_comp ; + + # &common_debug(">>>>>>>>> 3. $system_count [$id] $db{$table}{$id}{ref} [$db{event_systems}{$event_sys_id}{system_type}]") ; + + # &common_debug("[$cnt{$event_sys_id}{$id}] : $event_sys_id [$id] $cal_date [$cal_date_comp > $srch_date_to_comp]") ; + + $cali_cnt++; + + $xlsxcol = 0 ; + $print_tbody .= qq~~ ; + $table_row++ ; + + our $default_javascript = "" ; + + foreach (@sql_col_display) { + + # &common_debug("1. XLSX >>> $_") if !$report ; + + next unless $_ ; # blank for the buttons column + + my $formatting = $format84 ; + my $val = $db{$table}{$id}{$_} ; + my $val_min = $val ; + my $align = qq~ class="dt-center"~ ; + my $nowrap = '' ; + + # &common_debug("2. XLSX >>> val_min=$val_min") if !$report ; + + my $sys_day_cnt = $cnt{$event_sys_id}{$id} ; + + if ($_ eq 'count') { + # $val = $event_cnt ; + $val = $cali_cnt ; + } elsif ($_ eq 'event_nr') { + $val = "$id" ; + } elsif ($_ eq 'event') { + $val = "$db{$table}{$id}{ref} [$id]" ; + } elsif ($_ eq 'calibration_date' || $_ eq 'date') { + # $val = "$cal_date [$day_of_week{$cal_date}]" ; + $val = &common_min_date_as_string($cal_date) ; + $nowrap = "nowrap" ; + } elsif ($_ eq 'day') { + $val = "$sys_day_cnt" ; + } elsif ($_ eq 'start_date') { + $nowrap = "nowrap" ; + $val = &common_min_date_as_string($date_from) ; + } elsif ($_ eq 'venue') { + my @oids = split(/\,/,$db{$table}{$id}{organisation_ids}) ; + foreach $_oid (@oids) { + $val .= $db{organisations}{$_oid}{name} . '
    ' ; + } + $val = substr($val,0,-4) if $val ; ; + } elsif ($_ eq 'region') { + $val = $db{regions}{$db{$table}{$id}{region_id}}{code} ; + } elsif ($_ eq 'type') { + $val = (lc $db{event_systems}{$event_sys_id}{description} =~ /cricket/) ? "C" : + ($db{event_systems}{$event_sys_id}{system_type} eq 'mobile') ? "M" : + ($db{event_systems}{$event_sys_id}{system_type} eq 'fixed') ? "F" : ""; + } elsif ($_ eq 'system') { + $val = '' ; + $val = qq~($event_sys_id)$db{event_systems}{$event_sys_id}{name}~ ; + $val .= qq~ ($db{event_systems}{$event_sys_id}{description})~ if $db{event_systems}{$event_sys_id}{description} ; + } elsif ($_ eq 'sport') { + $val = '' ; + foreach my $sport_id (split(",",$db{$table}{$id}{sport_type_ids})) { + $db{sport_types}{$sport_id}{name} = uc $db{sport_types}{$sport_id}{name} ; + $val .= qq~$db{sport_types}{$sport_id}{name}
    ~ ; + } + $val = substr($val,0,-4) if $val ; + } elsif ($_ eq 'club_name') { + $val = $db{clubs}{$club_ids[$system_count - 1]}{name} ; + } elsif ($_ eq 'operator') { + $val = '' ; + # $val = $db{users}{$table_op_ids[$system_count - 1]}{name} if $table_op_ids[$system_count - 1] ; + $val = ($default_op_ids{$system_count}{$cnt{$event_sys_id}{$id}}) ? $db{users}{$default_op_ids{$system_count}{$cnt{$event_sys_id}{$id}}}{name} : (!$default_op_ids{$system_count}{$system_day_cnt} && $system_has_daily_op{$system_count}) ? "None" : $db{users}{$op_ids[$system_count - 1]}{name} ; + # $formatting = $format92 if $event_cnt == 2 ; + $formatting = $format92 if $cali_cnt == 2 ; + } elsif ($_ eq 'start_time') { + if (!$start_times[$sys_day_cnt-1]) { + $val = substr($db{$table}{$id}{date_from},11,5) ; + } else { + $val = substr($start_times[$sys_day_cnt-1],0,5) ; + } + } elsif ($_ eq 'end_time') { + if (!$end_times[$sys_day_cnt-1]) { + $val = substr($db{$table}{$id}{date_to},11,5) ; + } else { + $val = substr($end_times[$sys_day_cnt-1],0,5) ; + } + } elsif ($_ eq 'status' || $_ eq 'fixture_check') { + push @first_table_multi_select_table_cells,"#$useropts{table_id} tr:eq($table_row) td:nth-last-child($last_child{$_})" ; + $field{$_} = "$_\_event$event_sys_id\_$sys_day_cnt\_$id" ; + $opts{$field{$_}} = $opts{$_} ; + my $background_color = qq~~ ; + if ($_ eq 'status' && $default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}) { + $val_min = $db{monitor_status}{$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}}{status} ; + + print "\n $_ : $default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}" if $id eq '11913' || $_ eq 'status' ; + + if ($default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id} eq '1') { + $background_color = qq~rgb(81, 181, 41)~ ; + $formatting = $format94 ; + } elsif ($default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id} eq '2') { + $background_color = qq~rgb(246, 227, 5)~ ; + $formatting = $format95 ; + } else { + $background_color = qq~rgb(249, 13, 13)~ ; + $formatting = $format96 ; + } + } elsif ($default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}) { + $val_min = $db{users}{$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}}{name} ; + } + + $val = &common_min_table_select($field{$_},$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},'',$table_row,$last_child{$_},$background_color,$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},$_) ; + } elsif ($_ eq 'comments') { + $field{$_} = "$_\_event$event_sys_id\_$sys_day_cnt\_$id" ; + $val = &common_min_table_textarea($field{$_},$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},'',$table_row,$last_child{$_},$background_color,$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},$_) ; + } elsif ($_ eq 'update') { + + my $field = "update_event$event_sys_id\_$sys_day_cnt\_$id" ; + $val = &common_min_form_checkbox_col($field,'') ; + + chop $default_javascript if $default_javascript ; + + # print "\n default_javascript : $default_javascript" ; + + # 12=s:;t:|s:1;t:1|s:2;t:2-13=|s:3;t:3|s:4;t:4 + if ($default_javascript) { + push @default_javascript_by_id, qq~"event$event_sys_id\_$sys_day_cnt\_$id":{$default_javascript}~ ; + } + } + if ($_ ne 'status' && $_ ne 'calibrator' && substr($_,0,5) ne 'shift' && $_ ne 'update' && $_ ne 'status' && $_ ne 'fixture_check') { + $val_min = $val ; + $val_min =~ s/\
    /\;/g ; + } + $print_tbody .= qq~$val~ ; + + # &common_debug("XLSX >>> $event_system_calibration_ids{$id}{$event_sys_id}{$sys_day_cnt} [$id] [$event_sys_id] [$sys_day_cnt] [$field]") ; + + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$formatting) ; + $xlsxcol++ ; + } + + $print_tbody .= qq~~ ; + + $xlsxrow++ ; + } + + # next if $i{calibration_status} ne 'all' and $i{calibration_status} and $i{calibration_status} ne $db{event_systems}{$event_sys_id}{calibration_status} ; + # next if $i{calibrator_id} ne 'all' and $i{calibrator_id} and $i{calibrator_id} ne $db{event_systems}{$event_sys_id}{calibrator_id} ; + + } + } +# || $troubleshoot_monitoring_report ; + my $html_id = ($monitoring_report) ? "selectShift_monitor_" : ($troubleshoot_monitoring_report) ? "selectShift_troubleshoot_monitor_" : "selectShift_temp_calibrator_" ; + my $html_id2 = ($monitoring_report) ? "shift-monitor-id-" : ($troubleshoot_monitoring_report) ? "shift-troubleshoot-monitor-id-" : "shift-temp-calibrator-id-" ; + $row_cnt++ if $monitoring_report || $troubleshoot_monitoring_report ; + + $trigger_jquery_raw .= ($monitoring_report || $troubleshoot_monitoring_report) ? qq~ + + \$("#savebutt").click(function() { + for (let table_cnt = 1; table_cnt<= $date_cnt; table_cnt++) { + for (let i=1; i<=4; i++) { + let mon_id = \$("#$html_id"+i+"_1_1_"+table_cnt).chosen().val() ; + if (mon_id && typeof(mon_id) !== 'undefined') { + \$("#$html_id2"+i+"-"+table_cnt).val(mon_id) ; + } + } + } + \$("#$lcpage-form").submit() ; + }) ; + + ~ : qq~ + \$("#savebutt").click(function() { + + for (let table_cnt = 1; table_cnt<= $date_cnt; table_cnt++) { + + for (let i=1; i<=4; i++) { + let mon_id = \$("#$html_id"+i+"_1_1_"+table_cnt).chosen().val() ; + if (mon_id) { + \$("#$html_id2"+i+"-"+table_cnt).val(mon_id) ; + } + } + + let table_row_cnt = \$("#select_temp_calibrators_2_"+table_cnt).find('tr').length - 2 ; + + if (table_cnt > 1) { + table_row_cnt += 2 ; + } + + let seen_support = {} ; + + for (i=1;i<=table_row_cnt;i++) { + + let sel_val = \$("#selectName_2_"+i+"_"+table_cnt).val() ; + // if (!sel_val) { + // noty({text:'Please Select a Temp Support Name in all Rows',layout:"center",type:"error",timeout:3000}) ; + // return ; + // } else + if (seen_support[sel_val]) { + noty({text:'Please do not Select the same Temp Support Name in Multiple Rows for the Same Date',layout:"center",type:"error",timeout:3000}) ; + return ; + } else if (sel_val) { + seen_support[sel_val] = 1 ; + } + } + } + \$("#$lcpage-form").submit() ; + }) ; + ~ ; + + $worksheet{$ws}->set_column(0,0,10) ; + $worksheet{$ws}->set_column(1,1,30) ; + $worksheet{$ws}->set_column(2,2,15) ; + $worksheet{$ws}->set_column(3,3,5) ; + $worksheet{$ws}->set_column(4,4,15) ; + $worksheet{$ws}->set_column(5,6,10) ; + $worksheet{$ws}->set_column(7,7,30) ; + $worksheet{$ws}->set_column(8,9,10) ; + $worksheet{$ws}->set_column(10,10,30) ; + $worksheet{$ws}->set_column(11,11,15) ; + $worksheet{$ws}->set_column(12,16,20) ; + + &report_xlsx_export_footer('L',15,$xlsxdir) ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_update { + + my ($table,$table_field,$other_field,$table_field_2) = @_ ; + + unless ($table_field_2) { + $table_field_2 = "blank" ; + $ignore{$table_field_2} = 1 ; + } + + my ($s_year,$s_mon,$s_day) = split("-",$i{date_from}) ; + my ($e_year,$e_mon,$e_day) = split("-",$i{date_to}) ; + + our $date_counter = 1 ; + + while (int("$s_year$s_mon$s_day") <= int("$e_year$e_mon$e_day")) { + $date_cnt_to_date{$date_counter} = "$s_year-$s_mon-$s_day" ; + $date_counter++ ; + ($s_year,$s_mon,$s_day) = Add_Delta_Days ($s_year,$s_mon,$s_day,1) ; + $s_mon = sprintf("%02d",$s_mon) ; + $s_day = sprintf("%02d",$s_day) ; + } + + $date_cnt_to_date{$date_counter} = "$s_year-$s_mon-$s_day" ; + $date_counter-- ; + + my %i_per_date = () ; my $temp_support_diff = 0 ; + + if ($temp_calibrator_report) { + + &db_min_ro($table,"date,temp_calibrator_support_shifts,$table_field","`date` >= '$i{date_from}' AND`date` <= '$i{date_to}'") ; + + for my $date_cnt (1 .. $date_counter) { + + my $table_pos = 0 ; my $cnt_per_date = 0 ; my $table_cnt = 0 ; + + # $db{$table}{1}{temp_calibrator_support_shifts} =~ s/\|\|/\|/g ; + # $db{$table}{1}{temp_calibrator_support_shifts} =~ s/^\|//; + # $db{$table}{1}{temp_calibrator_support_shifts} =~ s/\|$//; + + my @temp_calibrator_support_shifts_split = split(/\|/,$db{$table}{$date_cnt_to_date{$date_cnt}}{temp_calibrator_support_shifts}) ; + + foreach (sort keys %i) { + + $ignore{$_} = 1 ; + + if ($_ =~ /^name_2_.*_$date_cnt$/) { + + my @aaa = split(/\_/,$_) ; + $table_pos = $aaa[-3] ; + $cnt_per_date = $aaa[-2] ; + # $table_cnt = $aaa[-1] ; + + my $update_field = "update_$table_pos\_$cnt_per_date\_$date_cnt" ; + my $name_field = "name_$table_pos\_$cnt_per_date\_$date_cnt" ; + my $shift_field = "shift_$table_pos\_$cnt_per_date\_$date_cnt" ; + + if ($i{$update_field} && $i{$name_field} && $i{$shift_field}) { + $i_per_date{$date_cnt}{temp_calibrator_support_shifts} .= qq~$i{$name_field}:$i{$shift_field}|~ ; + } elsif ($temp_calibrator_support_shifts_split[$cnt_per_date-1]) { + my $abcde = $temp_calibrator_support_shifts_split[$cnt_per_date-1] ; + $i_per_date{$date_cnt}{temp_calibrator_support_shifts} .= qq~$abcde|~ ; + } + } + } + + chop $i_per_date{$date_cnt}{temp_calibrator_support_shifts} if $i_per_date{$date_cnt}{temp_calibrator_support_shifts} ; + # $temp_support_exists = 1 if $i_per_date{$date_cnt}{temp_calibrator_support_shifts} ; + $temp_support_diff = 1 if $i_per_date{$date_cnt}{temp_calibrator_support_shifts} && $i_per_date{$date_cnt}{temp_calibrator_support_shifts} ne $db{$table}{$date_cnt_to_date{$date_cnt}}{temp_calibrator_support_shifts} ; + } + + } else { + # return unless $i{update_table_1} ; + &db_min_ro($table,"date,$table_field,$table_field_2","`date` >= '$i{date_from}' AND `date` <= '$i{date_to}'") ; + } + + my $some_update = 0 ; + + for my $date_cnt (1 .. $date_counter) { + $some_update = 1 if $i{"update_1_1_$date_cnt"} || ($i{"update_2_1_$date_cnt"} || $temp_calibrator_report) ; + } + + + # return if !$i{update_table_1} && $temp_calibrator_report && $i{temp_calibrator_support_shifts} eq $db{$table}{1}{temp_calibrator_support_shifts} ; + return if !$some_update && !$temp_support_diff ; + + &hidden_fields ; + my %ii = %i ; + + # $ignore{blank} = 1 ; + + for my $date_cnt (1 .. $date_counter) { + + %i = () ; + + # my $date_val = $ii{"date_$date_cnt"} ; + my $date_val = $date_cnt_to_date{$date_cnt} ; + + # my $update_field = "update_1_1_$date_cnt" ; + + next if !$ii{"update_1_1_$date_cnt"} && !$ii{"update_2_1_$date_cnt"} ; + + if ($ii{"update_1_1_$date_cnt"}) { + + my $ops_exists = 0 ; my $notes_exists = 0 ; + + for my $shift_cnt (1 .. 4) { + $ii{"$other_field\_$shift_cnt\_$date_cnt"} =~ s/\,/\;/g ; + $i{$table_field} .= qq~$ii{"$other_field\_$shift_cnt\_$date_cnt"}|~ ; + $ops_exists = 1 if $ii{"$other_field\_$shift_cnt\_$date_cnt"} ; + $notes_exists = 1 if $table_field_2 && $ii{"shift_$table_field_2\_$shift_cnt\_1_1_$date_cnt"} ; + + my $field_ = "shift_$table_field_2\_$shift_cnt\_1_1_$date_cnt" ; + + $i{$table_field_2} .= qq~$ii{"shift_$table_field_2\_$shift_cnt\_1_1_$date_cnt"}:|:~ if $table_field_2 ; + } + chop $i{$table_field} ; + + $i{$table_field} = qq~~ unless $ops_exists ; + $i{$table_field_2} = qq~~ if $table_field_2 && !$notes_exists ; + + $i{$table_field_2} = substr($i{$table_field_2},0,-3) if $table_field_2 && $i{$table_field_2} ; + $ignore{$table_field} = 0 ; + $ignore{$table_field_2} = 0 if $table_field_2 && $table_field_2 ne 'blank' ; + } else { + $ignore{$table_field} = 1 ; + $ignore{$table_field_2} = 1 ; + } + # my $table_field_old = $table_field ; + + # $table_field = $table_field_old ; + + $i{temp_calibrator_support_shifts} = $i_per_date{$date_cnt}{temp_calibrator_support_shifts} if $temp_calibrator_report ; + + if (!$db{$table}{$date_val}{date}) { + + &db_min_ro($table,"1,MAX(id) + 1 AS 'max_id'","","","") ; + + $i{id} = $db{$table}{1}{max_id} ; + $i{id} = 1 unless $i{id} ; + $i{date} = $date_val ; + + $ignore{date} = 0 ; + $ignore{$table_field} = 1 unless $i{$table_field} ; + $ignore{temp_calibrator_support_shifts} = 1 if !$temp_calibrator_report || !$i{temp_calibrator_support_shifts} ; + + &db_min_insert("$table") ; + + } else { + + $ignore{$table_field} = 1 if $db{$table}{$date_val}{$table_field} eq $i{$table_field} ; + $ignore{temp_calibrator_support_shifts} = 1 if $db{$table}{$date_val}{temp_calibrator_support_shifts} eq $i{temp_calibrator_support_shifts} || !$temp_calibrator_report ; + &db_min_upd($table,"`date`='$date_val'") if !$ignore{$table_field} || !$ignore{$table_field_2}|| !$ignore{temp_calibrator_support_shifts} ; + + } + } + + %i = %ii ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_update { + + my ($field) = @_ ; + + my %iii = %i ; + my %ii = () ; + local $min_date = 0 ; local $max_date = 0 ; + foreach (sort keys %i) { + + local $cell_name = $_ ; + local @a = split("_") ; + next if $a[-2] ne int($a[-2]) ; + + if ($i{"paid_$a[-2]\_$a[-1]"} and $i{"amount_payble_$a[-2]\_$a[-1]"}) { + # my $date = substr($a[-1],0,4) . '-' . substr($a[-1],4,2) . '-' . substr($a[-1],6,2) ; + if ($a[0] eq 'amount') { + $i{$_} = sprintf("%.2f",$i{$_}) ; + $ii{$a[-1]}{"$field\_amounts_paid"} .= ($ii{$a[-1]}{"$field\_amounts_paid"}) ? qq~;$a[-2]:$i{$_}~ : qq~$a[-2]:$i{$_}~ ; + } elsif ($a[0] eq 'date') { + $ii{$a[-1]}{"$field\_dates_paid"} .= ($ii{$a[-1]}{"$field\_dates_paid"}) ? qq~;$i{$_}~ : qq~$i{$_}~ ; + } + } + $min_date = $a[-1] if ($min_id and $a[-1] < $min_id) or not $min_id ; + $max_date = $a[-1] if $a[-1] > $max_id ; + } + + $min_date = substr($min_date,0,4) . '-' . substr($min_date,4,2) . '-' . substr($min_date,6,2) ; + $max_date = substr($max_date,0,4) . '-' . substr($max_date,4,2) . '-' . substr($max_date,6,2) ; + + &db_min_ro($table,"date,$field\_dates_paid,$field\_amounts_paid","`date` <= '$max_date' AND `date` >= '$min_date'",'','') ; + + foreach my $date (sort keys %ii) { + + %i = () ; + + # $i{"$field\_dates_paid"} .= qq~$ii{$date}{"$field\_dates_paid"}~ ; + + my $date_string = substr($date,0,4) . '-' . substr($date,4,2) . '-' . substr($date,6,2) ; + + $i{"$field\_amounts_paid"} = qq~$db{$table}{$date_string}{"$field\_amounts_paid"}~ ; + $i{"$field\_amounts_paid"} .= qq~;~ if $db{$table}{$date_string}{"$field\_amounts_paid"} && $ii{$date}{"$field\_amounts_paid"} ; + $i{"$field\_amounts_paid"} .= qq~$ii{$date}{"$field\_amounts_paid"}~ ; + + $ignore{"$field\_amounts_paid"} = 1 if $i{"$field\_amounts_paid"} eq $db{$table}{$date_string}{"$field\_amounts_paid"} || !$i{"$field\_amounts_paid"} ; + + $i{"$field\_dates_paid"} = qq~$db{$table}{$date_string}{"$field\_dates_paid"}~ ; + $i{"$field\_dates_paid"} .= qq~;~ if $db{$table}{$date_string}{"$field\_dates_paid"} && $ii{$date}{"$field\_dates_paid"} ; + $i{"$field\_dates_paid"} .= qq~$ii{$date}{"$field\_dates_paid"}~ ; + + $ignore{"$field\_dates_paid"} = 1 if $i{"$field\_dates_paid"} eq $db{$table}{$date_string}{"$field\_dates_paid"} || !$i{"$field\_dates_paid"} ; + + &db_min_upd($table,"`date`='$date_string'") if $i{"$field\_dates_paid"} || $i{"$field\_amounts_paid"} ; + + } + + %i = %iii ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_report_ifields { + + my ($field) = @_ ; + + my $field2 = join(/ /, map { uc($_) } split(/\_/,$field)) ; + + if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { + $error = qq~'$i{date_from}' > '$i{date_to}'~ ; &report_screen ; + } + push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` <= '$i{date_to} 23:59:59' AND `date_to` >= '$i{date_from} 00:00:00'))" ; + push @report_results, "(BETWEEN '$i{date_from}' AND '$i{date_to}')" ; + } elsif (not $i{date_from}) { + $error = qq~PLEASE ENTER A START DATE!~ ; + } elsif (not $i{date_to}) { + $error = qq~PLEASE ENTER A END DATE!~ ; + } + + our $where_min = qq~~ ; + if ($i{"$field\_id"}) { + my $ifield = "$field\_id" ; + &db_min_ro('users','1,name',"`id` = '$i{$ifield}'",'','') ; + $where_min = " AND `$field\_ids` LIKE '%$i{$ifield}%'" ; + push @report_results,"$field2 = $db{users}{1}{name}" ; + } + + if ($i{paid_status} eq 'paid') { + push @report_results,"$field2 AMOUNTS PAID" ; + } elsif ($i{paid_status} eq 'outstanding') { + push @report_results,"$field2 PAY OUTSTANDING" ; + } + + $report_results_msg = uc join(', ', @report_results) ; + + if (not $report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); + &report_screen ; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_list_screen { + + my ($field) = @_ ; + + my $field2 = $field ; + + $field2 =~ s/\_/\-/g ; + + # &db_min_ro('event_cost_items','1,rates',"`name` LIKE '$field3%'",'','') ; + + our @sql_col_display = ($i{paid_status} eq 'paid') ? ("date","$field\_names","shifts_count","dates_paid","amounts_paid","all_paid") : ($i{paid_status} eq 'all') ? ("date","$field\_names","shifts_count","dates_paid","amounts_paid","date_payable","amount_payable","paid") : ("date","$field\_names","shifts_count","date_payable","amount_payable","paid") ; + + my $table_colspan = 0 ; + + foreach (@sql_col_display) { + $table_colspan += 1 ; + } + + local @month_arr = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + my ($year1,$month1,$day1) = split(/\-/,$i{date_from}) ; + my ($year2,$month2,$day2) = split(/\-/,$i{date_to}) ; + + my $date_string = qq~~ ; + + if ($year1 ne $year2 && $month1 ne $month2 && $day1 ne $day2) { + $date_string = qq~ $day1 $month_arr[$month1] $year1 - $day2 $month_arr[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 ne $month2) { + $date_string = qq~ $day1 $month_arr[$month1] - $month_arr[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 eq $month2 && $day1 ne $day2) { + $date_string = qq~ $day1 - $day2 $month_arr[$month2] $year2~ ; + } elsif ($year1 eq $year2 && $month1 eq $month2 && $day1 eq $day2) { + $date_string = qq~ $day2 $month_arr[$month2] $year2~ ; + } + + my $field_heading = join(" ", map { ucfirst($_) } split(/\_/,$field)) ; + + our $xlsxheading = "$field_heading Payments Report$xlsreportname$date_string" ; + + &report_xlsx_export_header("$field_heading Payments$xlsreportname","$field\_payments_report") ; + + &schedule_payments_load_list_vars("$where_min","$field") ; + + my @qty_work = () ; + my @amnt_usd_work = () ; + my @amnt_work = () ; + my @op_work = () ; + my @description = () ; + my @paid_work = () ; + my $row_cnt = 0 ; + my $first_id = 0 ; + my $last_id = 0 ; + my %row_cnt_to_id = () ; + + $fcol = 12 ; my $val_min = 0 ; $row_cnt = 0 ; + + my $date_pay = qq~~ ; my $quote_and_ops_ids = qq~~ ; my $op_ids = qq~~ ; + + my ($next_year,$next_month,$next_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,1) ; + + my $row_cnt = 0 ; my $quote_and_ops_ids = qq~~ ; + + my %amnt_tots = () ; + + foreach my $date (sort {$a <=> $b} keys %{$db{$table}}) { + + my @date_pay = split(/\;/,$db{$table}{$date}{"$field\_paid"}) ; + my @amount_pay = split(/\;/,$db{$table}{$date}{"$field\_amounts_paid"}) ; + my $date_val = $date ; + $date_val =~ s/\-//g ; + + foreach my $temp_id (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$operator_count{$date}}) { + + next if $i{"$field\_id"} && $i{"$field\_id"} ne $temp_id ; + + next if $temp_id eq 'none' ; + + my $amnt_owed = ($db{event_cost_items}{1}{rates}) ? $db{event_cost_items}{1}{rates} * $operator_count{$date}{$temp_id} : ($field =~ /calibrator/) ? 500 * $operator_count{$date}{$temp_id} : ($field =~ /monitor/ && $field !~ /troubleshoot/) ? 300 * $operator_count{$date}{$temp_id} : 450 * $operator_count{$date}{$temp_id} ; + $amnt_owed += $temp_support_rates{half_day}*$temp_calibrator_support{shift_count}{$date}{$temp_id}{1} ; + $amnt_owed += $temp_support_rates{full_day}*$temp_calibrator_support{shift_count}{$date}{$temp_id}{2} ; + # $temp_calibrator_support{count}{$date}{1} += ($abc[1] eq '1') ? 0.5 : 1 ; + # $temp_calibrator_support{shift_count}{$date}{1} += 1 ; + + $amnt_owed = $amnt_owed - $amounts_paid{$date}{$temp_id} ; + + $amnt_owed = 0 if $amounts_paid{$date}{$temp_id} ; + + next if $i{paid_status} eq 'outstanding' && $amnt_owed == 0 ; + next if $i{paid_status} eq 'paid' && $amounts_paid{$date}{$temp_id} == 0 ; + + $amnt_owed = sprintf("%0.2f",$amnt_owed) ; + $xlsxcol = 0 ; + + foreach my $col (@sql_col_display) { + + next unless $col ; # blank for the buttons column + $display = 1 ; + my $val = '' ; + my $align = '' ; + my $center = qq~ class="dt-center"~ ; + $align = $center ; + my $val_min = '' ; + + if ($col eq 'date') { + $val = $date ; + } elsif ($col eq "$field\_names") { + $val = $db{users}{$temp_id}{name} ; + $val .= " [Support]" if $support_user{$temp_id} ; + } elsif ($col eq 'shifts_count') { + chop $operator_shifts_string{$date}{$temp_id} if $operator_shifts_string{$date}{$temp_id} ; + my $shifts_cnt = $operator_count{$date}{$temp_id} + $temp_calibrator_support{count}{$date}{$temp_id}{1} + $temp_calibrator_support{count}{$date}{$temp_id}{2} ; + $val_min = "$shifts_cnt" ; + $val_min .= " [$operator_shifts_string{$date}{$temp_id}]" if $operator_shifts_string{$date}{$temp_id} ; + $operator_shifts_string{$date}{$temp_id} =~ s/\;/\
    /g ; + $val = ($operator_shifts_string{$date}{$temp_id}) ? qq~$shifts_cnt~ : $shifts_cnt ; + # $val = $operator_shifts{$date}{$temp_id} + } elsif ($col eq 'dates_paid') { + foreach (sort keys %{$dates_amounts_paid{$temp_id}}) { + $val .= ($val) ? qq~
    $_~ : qq~$_~ ; + } + $val = "None" unless $val ; + $val_min = $val ; + $val_min =~ s/\
    /\;/g ; + $val = qq~~ if $val =~ /
    / ; + } elsif ($col eq 'amounts_paid') { + foreach (sort keys %{$dates_amounts_paid{$temp_id}}) { + $dates_amounts_paid{$temp_id}{$_} = sprintf("%0.2f",$dates_amounts_paid{$temp_id}{$_}) ; + $val .= ($val) ? qq~
    $dates_amounts_paid{$temp_id}{$_}~ : qq~$dates_amounts_paid{$temp_id}{$_}~ ; + $amnt_tots{"amounts_paid"} += $dates_amounts_paid{$temp_id}{$_} ; + } + $val = "None" unless $val ; + $val_min = $val ; + $val_min =~ s/\
    /\;/g ; + $val = qq~~ if $val =~ /
    / ; + } elsif ($col eq 'date_payable') { + my $date_payable = "$now_year-$now_mm-$now_dd" ; + $val = ($amnt_owed != 0) ? &common_min_form_input_col("date_$temp_id\_$date_val",$date_payable) : "N/A" ; + $val_min = ($amnt_owed != 0) ? $date_payable : "N/A" ; + } elsif ($col eq 'amount_payable') { #dates_amounts_paid + $count_outstanding++ if $amnt_owed > 0 ; + $amnt_tots{"amount_payable"} += $amnt_owed ; + $val = ($amnt_owed != 0) ? &common_min_form_input_col("amount_payble_$temp_id\_$date_val",$amnt_owed) : "None" ; + $val_min = $amnt_owed ; + } elsif ($col eq 'paid') { + $val = ($amnt_owed != 0) ? &common_min_form_checkbox_col("paid_$temp_id\_$date_val",0) : '' ; + $val_min = ($amnt_owed != 0) ? "No" : "Yes" ; + } elsif ($col eq 'all_paid') { + $val = ($amnt_owed != 0) ? '' : '' ; + $val_min = ($amnt_owed != 0) ? "No" : "Yes" ; + } + $val_min = $val if $col eq 'date' || $col eq "$field\_names" ; + + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format_management_report_data) if $col ne 'shifts_count' ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format_management_report_data_ref_nr) if $col eq 'shifts_count' ; + $xlsxcol++ ; + # if ($_ eq 'ref_nr' or $_ eq 'camera_nr') { $val = &common_camera_links($tables,$id,$val) ;} + $print_tbody .= qq~$val~ ; + + } + $print_tbody .= qq~~ ; + $xlsxrow++ ; + $row_cnt++ ; + $quote_and_ops_ids .= qq~"$row_cnt\_$temp_id":"$date_val",~ ; + } + # chop $op_ids if $op_ids ; + # $quote_and_ops_ids .= qq~"$row_cnt_$id":[$op_ids],~ if $op_ids ; + } + + my $col_cnt = 0 ; + + foreach my $col (@sql_col_display) { + + if ($col eq 'date') { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$col_cnt,"TOTALS",$format_management_report_total) ; + } elsif ($col eq "amounts_paid" || $col eq "amount_payable") { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$col_cnt,"$amnt_tots{$col}",$format_management_report_totals) ; + } else { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$col_cnt,"-",$format_management_report_totals) ; + } + $col_cnt++ ; + } + + chop $quote_and_ops_ids if $quote_and_ops_ids ; + + # $print_tbody .= qq~~ ; + # $print_tbody .= qq~~ ; + $worksheet{$ws} -> set_column(0,0,15) ; + $worksheet{$ws} -> set_column(1,1,25) ; + $worksheet{$ws} -> set_column(2,7,20) if $i{paid_status} eq 'all' ; + $worksheet{$ws} -> set_column(2,5,20) if $i{paid_status} ne 'all' ; + + $box_icon .= qq~
    ~ if $i{paid_status} ne 'paid' && $count_outstanding > 0 ; + + &report_xlsx_export_footer('L',15,"$field\_payments_report") ; + + $fnsortcol = 0; + $fnsortorder = 'asc' ; + &common_min_extra_crumb("$lcpage\s","Search Screen") ; + + $trigger_jquery_raw .= qq~ + function selectAll() { + let jsObject = { + $quote_and_ops_ids + } ; + for (let key in jsObject) { + let op_id = jsObject[key] ; + let parts = key.split("_") ; + let event_id = parts[1] ; + \$(\$("#itv-table").dataTable().fnGetNodes()).find(\$("input[name=paid_"+event_id+"_"+op_id+"]")).each(function () { + // console.log("input[name=paid_"+event_id+"_"+op_id+"]") ; + if(\$(this).is(':checked')) { + \$(this).prop('checked',false) ; + } else { + \$(this).prop('checked',true) ; + } + }) ; + } + } + ~; + + my $field_id = "#$field2\-payment-form" ; + + # my $savebuttjs = ($count_outstanding > 0) ? qq~$("$field_id").submit();' : 'noty({text:"There are no calibrators to pay!",layout:"center",type:"error",timeout:3000});return;~ ; + + $trigger_jquery_raw .= qq~ + \$("#savebutt").click(function() { + // $savebuttjs + \$("$field_id").submit(); + }) ; + ~ ; + + $fcol = 2 ; + + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= &common_min_form_input_col("date_from",$i{date_from}) ; #date_from_i_field + $print_box_content_rows .= &common_min_form_input_col("date_to",$i{date_to}) ; #date_to_i_field + $print_box_content_rows .= &common_min_form_input_col("$field\_id",$i{"$field\_id"}) ; #temp_calibrator_id_i_field + $print_box_content_rows .= &common_min_form_input_col("$field\s_paid",$i{"$field\s_paid"}) ; + $print_box_content_rows .= qq~
    ~ ; + + $print_box_content_rows .= &common_min_forms_start("$field2\-payment") if $count_outstanding ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_load_list_vars { + + my ($where,$field) = @_ ; + + my $users_sql = ($field =~ /calibrator/) ? "`user_type` = 'casual_calibrator' OR `user_type` = 'support'" : "" ; + + &db_min_ro('users','id,name',"$users_sql",'','') ; + + &db_min_ro($table,"date,$field\_ids,$field\_dates_paid,$field\_amounts_paid,temp_calibrator_support_shifts","`date`>='$i{date_from}' AND `date`<='$i{date_to}' $where",'','') ; + + # &db_min_ro('shift_monitor_ids','date,monitor_ids',"`date`>='$i{date_from}' AND `date`<='$i{date_to}' $where",'','') ; + + our %operator_count = () ; our %amounts_paid = () ; our %dates_amounts_paid = () ; our %operator_shifts_string = () ; + + # my @monitor_shifts = ("","08:00-11:00","11:00-14:00","14:00-17:00","17:00-21:00") ; + my @operator_shifts = ($field =~ /calibrator/) ? ("","07:00-10:00","10:00-13:00","13:00-16:00","16:00-19:00") : ("","08:00-11:00","11:00-14:00","14:00-17:00","17:00-21:00") ; + + foreach my $date (keys %{$db{$table}}) { + my $shift_cnt = 0 ; + foreach my $shift (split(/\|/,$db{$table}{$date}{"$field\_ids"})) { + $shift_cnt++ ; + next unless $shift ; + foreach my $temp_id (split(/\;/,$shift)) { + next unless $temp_id ; + $operator_count{$date}{$temp_id} += 1 ; + $operator_shifts_string{$date}{$temp_id} .= qq~$operator_shifts[$shift_cnt];~ ; + } + } + $shift_cnt = 0 ; + # foreach my $shift (split(/\|/,$db{$table}{$date}{monitor_ids})) { + # $shift_cnt++ ; + # next unless $shift ; + # foreach my $temp_id (split(/\;/,$shift)) { + # next unless $temp_id ; + # $operator_count{$date}{$temp_id} += 1 ; + # $operator_shifts{$date}{$temp_id} .= qq~$monitor_shifts[$shift_cnt],~ ; + # } + # } + my @date_pay = split(/\;/,$db{$table}{$date}{"$field\_dates_paid"}) ; + my @amount_pay = split(/\;/,$db{$table}{$date}{"$field\_amounts_paid"}) ; + my $cnt = 0 ; + foreach my $temp_id_amnt (@amount_pay) { + my @temp_amnt = split(/\:/,$temp_id_amnt) ; + $amounts_paid{$date}{$temp_amnt[0]} += $temp_amnt[1] ; + $dates_amounts_paid{$temp_amnt[0]}{$date_pay[$cnt]} += $temp_amnt[1] ; + $cnt++ ; + } + + if ($temp_calibrator_payments_report && $db{$table}{$date}{temp_calibrator_support_shifts}) { + + foreach my $shift (split(/\|/,$db{$table}{$date}{temp_calibrator_support_shifts})) { + + $shift_cnt++ ; + next unless $shift ; + my @abc = split(/\:/,$shift) ; + next unless $abc[0] ; + + $operator_count{$date}{$abc[0]} += 0 ; + # $operator_count{$date}{$abc[0]} += ($abc[1] eq '1') ? 0.5 : 1 ; + $temp_calibrator_support{count}{$date}{$abc[0]}{$abc[1]} += ($abc[1] eq '1') ? 0.5 : 1 ; + $temp_calibrator_support{shift_count}{$date}{$abc[0]}{$abc[1]} += 1 ; + $operator_shifts_string{$date}{$abc[0]} .= ($abc[1] eq '1') ? qq~Half Day (<7 hours);~ : qq~Full Day (7 hours+);~ ; + $support_user{$abc[0]} = 1 ; + } + } + } + +} #------------------------------------------------------------------------------------------ + +sub schedule_payments_report_screen { + + my ($field) = @_ ; + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + &common_min_select_opts("$field\_id",'users',"name",$i{"$field\_id"},'','',"`name` NOT LIKE 'Rory%' AND `name` NOT LIKE 'Handre%'") ; + # &common_min_select_opts('event_quote_id','event_quotes',"ref",$i{event_quote_id},'','',"") ; + + $first_day_month = sprintf("%02d",$first_day_month) ; $first_day = sprintf("%02d",$first_day) ; + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-$now_mm-01") unless $i{date_from} ; + + my $days_in_month = Days_in_Month($now_year,$now_mm) ; + + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$days_in_month") ; + + # my ($sql_next_day) = &common_add_delta_days(1) ; + # my ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + # $print_box_content_rows .= &common_min_form_datepicker('date',"$next_year-$next_month-$next_day") ; #unless $i{date_from} ; + + $opts{paid_status} .= qq~~ ; + $opts{paid_status} .= qq~~ ; + $opts{paid_status} .= qq~~ ; + + $print_box_content_rows .= &common_min_form_select("$field\_id",'') ; + # $print_box_content_rows .= &common_min_form_select('event_quote_id','') ; + $print_box_content_rows .= &common_min_form_select('paid_status','') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------------------ + +1 ; \ No newline at end of file diff --git a/libs/modules/_FromProd/v1.0/session.pm b/libs/modules/_FromProd/v1.0/session.pm new file mode 100644 index 0000000..3fce5fa --- /dev/null +++ b/libs/modules/_FromProd/v1.0/session.pm @@ -0,0 +1,51 @@ +sub check_session { + + use DBI; + use CGI::Session; + use CGI::Cookie; + + my %cookies = fetch CGI::Cookie ; + my $cgisessid = defined $cookies{'CGISESSID'} ? $cookies{'CGISESSID'}->value : undef; # This does + + use db ; + &db_open_ro ; + + $userid = 0 ; + $session = load CGI::Session("driver:MySQL", $cgisessid, {Handle=>$dbh}); + $userid = $session->param(-name=>'id'); + $is_logged_in = $session->param(-name=>'_IS_LOGGED_IN'); + $username = lc $session->param(-name=>'uname'); + $useremail = lc $session->param(-name=>'uemail'); + $usertype = lc $session->param(-name=>'utype'); + $orgids = $session->param(-name=>'oids'); + $regids = $session->param(-name=>'rids'); + $custids = $session->param(-name=>'cids'); + + my @orgids = split(/\,/,$orgids); + foreach (@orgids) { $glob_orgids{$userid}{$_} = 1 ; } + + my @regids = split(/\,/,$regids); + foreach (@regids) { next unless $_ > 0 ; $glob_regids{$userid}{$_} = 1 ; } + + my @custids = split(/\,/,$custids); + foreach (@custids) { next unless $_ > 0 ; $glob_custids{$userid}{$_} = 1 ; } + + $sessionid = $session->id(); + + if ($sessionid && $is_logged_in > 0 && $userid > 0) { # if $userid and $is_logged_in is -1 not allowed in + $session_state = 'active' ; + } elsif ($session->is_expired) { + $session_state = 'expired' ; + $session->delete() ; + } elsif ($session->is_empty) { + $session_state = 'empty' ; + } else { + $session_state = 'empty' ; + $session->delete() ; + } + + &db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +1 ; \ No newline at end of file diff --git a/libs/modules/_FromProd/v1.0/tabs.pm b/libs/modules/_FromProd/v1.0/tabs.pm new file mode 100644 index 0000000..771567b --- /dev/null +++ b/libs/modules/_FromProd/v1.0/tabs.pm @@ -0,0 +1,1971 @@ +our %sec_cnt = ('a_systems' => "3-Systems", 'b_software_licence' => "3-Software Licence (Monthly Fee)", 'c_game_breakdown_analytics' => "2-Game Breakdown and Analytics (Annual Fee)", 'd_installation_kits' => "7-Installation Kits", 'e_hardware_add_ons' => "7-Hardware Add Ons", 'f_additional_services' => "7-Additional Services", 'g_match_credits' => "4-Match Credits", 'h_other' => "5-Other", 'i_rental' => "2-Rental" , "j_hardware" => "1-Hardware"); + +sub tabs_get_default_totals { + + my ($id) = @_ ; + + # our %sec_cnt = ('a_systems' => "3-Systems", 'b_software_licence' => "3-Software Licence (Monthly Fee)", 'c_game_breakdown_analytics' => "2-Game Breakdown and Analytics (Annual Fee)", 'd_installation_kits' => "7-Installation Kits", 'e_hardware_add_ons' => "7-Hardware Add Ons", 'f_additional_services' => "7-Additional Services", 'g_match_credits' => "4-Match Credits", 'h_other' => "5-Other", 'i_rental' => "2-Rental" , "j_hardware" => "1-Hardware"); + # our %sec_cnt = ('a_other' => "5-Other"); + our %sec_cnt = ('a_systems' => "3-Systems", 'b_software_licence' => "3-Software Licence (Monthly Fee)", 'c_game_breakdown_analytics' => "2-Game Breakdown and Analytics (Annual Fee)", 'd_installation_kits' => "7-Installation Kits", 'e_hardware_add_ons' => "7-Hardware Add Ons", 'f_additional_services' => "7-Additional Services", 'g_match_credits' => "4-Match Credits", 'h_rental' => "2-Rental" , "j_hardware" => "1-Hardware"); + + our %default_totals = () ; + + our @ttlarr = ("one_time_fee","monthly_recurring_fee","annual_fee") ; + our @ttlarr2 = ("subtotal","vat","total") ; + + my $needs_to_update_totals = ($db{$table}{$id}{total_one_time_fee} !~ /;/ && $db{quotes_min}{$id}{item_ttl_costing_other} =~ /(?
     
    ~ ; + + +$trigger_jquery_raw .= qq~ + + if (!\$("#checkboxQuote_accepted").is(":checked") && !\$("#checkboxQuote_pending").is(":checked") && !\$("#checkboxQuote_cancelled").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked","true") ; + } + \$("#checkboxQuote_accepted,#checkboxQuote_pending,#checkboxQuote_cancelled").click( function () { + + if (this.id != 'checkboxQuote_accepted' && \$("#checkboxQuote_accepted").is(":checked")) { + \$("#checkboxQuote_accepted").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_pending' && \$("#checkboxQuote_pending").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_cancelled' && \$("#checkboxQuote_cancelled").is(":checked")) { + \$("#checkboxQuote_cancelled").prop("checked",false) ; + } + + if (!\$("#checkboxQuote_accepted").is(":checked") && !\$("#checkboxQuote_pending").is(":checked") && !\$("#checkboxQuote_cancelled").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked","true") ; + } + + }); + +~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + +if ($tab == 2) { # Costing + + # --------------- START COSTING ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + $lcol = 1 ; $fcol = 2 ; + $preferred_title{currency} = 'Currency' ; + $add_form_fields .= &common_min_form_select('currency',$db{$table}{$id}{currency},1) ; + $trigger_jquery .= qq~\$("#selectCurrency_chosen").css( "width", "96%" );~ ; + $preferred_title{roe} = ' ROE ' ; $fcol = 1 ; + $add_form_fields .= &common_min_form_label_col('roe') ; + $add_form_fields .= &common_min_form_input_col('roe',$db{$table}{$id}{roe},1) ; + $add_form_fields .= qq~
    ~ ; + my $sec = '_costing' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + return if $ret ; + + &tab_costing_select_opts('price_list','description',"`excl`<>'1'",$sec) ; + + # &db_min_ro('quotes_pdf_titles', '*', "quote_id = $id", '', '') ; + foreach (keys %{$db{quotes_pdf_titles}}){ + next unless $db{quotes_pdf_titles}{$_}{quote_id} == $id ; + $old_title_to_new_title{$db{quotes_pdf_titles}{$_}{old_name}}{$db{quotes_pdf_titles}{$_}{quote_id}} = $db{quotes_pdf_titles}{$_}{new_name} ; + } + + foreach (sort keys %sec_cnt) { + $_k = substr($_,1) ; + next if $_k eq '_hardware' ; + my @parts = split(/\-/,$sec_cnt{$_}) ; + + $add_form_fields .= qq~

    $parts[1] :

    ~ ; + # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + $fcol = 3 ; + $add_form_fields .= qq~
    PDF title :
    ~ ; + # $add_form_fields .= qq~
    PDF TITLE :
    ~ ; + if ($old_title_to_new_title{$parts[1]}{$id} and $old_title_to_new_title{$parts[1]}{$id} ne $parts[1]){ + $add_form_fields .= &common_min_form_input_col($_k, $old_title_to_new_title{$parts[1]}{$id}) ; + } + else { + $add_form_fields .= &common_min_form_input_col($_k,'') ; + } + + $add_form_fields .= qq~
    ~ ; + &tab_build_qt_col_headers("$sec$_k") ; + &build_cost_form($id,$tab,$parts[0],"$sec$_k") ; + if ($_k eq '_systems') { + $preferred_title{'systems_included'} = ' ' ; $preferred_placeholder{'systems_included'} = 'Included' ; $fcol = 3 ; + $add_form_fields .= &common_min_form_textarea('systems_included',$db{$table}{$id}{systems_included},'') ; + } + if ($_k eq '_rental') { + $preferred_title{'rental_included'} = ' ' ; $preferred_placeholder{'rental_included'} = 'Included' ; $fcol = 3 ; + $add_form_fields .= &common_min_form_textarea('rental_included',$db{$table}{$id}{rental_included},'') ; + } + if ($_k eq '_other') { + $preferred_title{'other_included'} = ' ' ; $preferred_placeholder{'other_included'} = 'Included' ; $fcol = 3 ; + $add_form_fields .= &common_min_form_textarea('other_included',$db{$table}{$id}{other_included},'') ; + } + } + + $add_form_fields .= qq~
     
    ~ ; + $add_form_fields .= qq~
    PDF total :
    ~ ; + + $lcol = 3 ; + + if ($old_title_to_new_title{"Hardware"}{$id} and $old_title_to_new_title{"Hardware"}{$id} ne "Hardware"){ + $add_form_fields .= &common_min_form_input_col('_hardware', $old_title_to_new_title{"Hardware"}{$id}) ; + } + else { + $add_form_fields .= &common_min_form_input_col('_hardware','') ; + } + + my @ttlarr_labels = ("sub_total","vat_total","grand_total") ; + $lcol = 1 ; $fcol = 1 ; + foreach (@ttlarr_labels) { + $readonly{$_} = "READONLY" ; + my $val = $db{$table}{$id}{$_} ; $val = '0.00' unless $val ; + $type = 'hidden' ; $add_form_fields .= &common_min_form_input_col($_,$val) ; $type = '' ; + $lcol = 1 ; $add_form_fields .= &common_min_form_label_col($_) ; + } + + $add_form_fields .= qq~
    ~ ; + + $lcol = 1 ; $fcol = 1 ; + + foreach my $a (@ttlarr) { + + $readonly{$a} = "READONLY" ; + + $add_form_fields .= qq~
    ~ ; + + $lcol = 2 ; + $add_form_fields .= &common_min_form_label_col($a) ; + $lcol = 1 ; + + foreach my $b (@ttlarr2) { + $field = "$b\_$a\_1" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + my $val = ($default_totals{$field}{1}) ? $default_totals{$field}{1} : '0.00' ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + } + $add_form_fields .= qq~
    ~ ; + + } + + $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col) ; + + # --------------- END COSTING ---------------------------------------------------------------------------------------------------------------- + + + # $trigger_jquery_raw .= qq~ + + # function get_tab (id) { + # let tab = "" ; + # if (id.includes("workings_event")) { + # tab = "workings_event" ; + # } else if (id.includes("costing_event")) { + # tab = "costing_event" ; + # } + # return tab ; + # } + + # function changed_vat (id) { + # let tab = get_tab (id) ; + # let row_nr = get_row_nr(id) ; + # calc_totals(row_nr,tab) ; + # } + + # function changed_others (id) { + + # let row_nr = get_row_nr(id) ; + # let firstIndex = id.indexOf('_'); + # let col = id.substring(0,firstIndex); + # let tab = get_tab (id) ; + # if (col == "inputAmount") { + # let inp = parseFloat(\$("#"+id).val()) ; + # inp = parseFloat(inp) ; + # \$("#"+id).val(inp.toFixed(2)) ; + # } else if (\$("#selectDescription_"+tab+"_"+row_nr).val() && \$("#selectDescription_"+tab+"_"+row_nr).val() != 14 && \$("#selectOperator_"+tab+"_"+row_nr).val()) { + # // \$("#selectOperator_"+tab+"_"+row_nr).val("") ; + # // \$("#selectOperator_"+tab+"_"+row_nr).trigger("chosen:updated") ; + # } + # // else if (col == "selectOperator" && \$("#selectDescription"+tab+"_"+row_nr).val() != 14) { + + # // } + + # if (col == "selectOperator") { // || (col == "selectDescription" && \$("#selectDescription_"+tab+"_"+row_nr).val( + # return ; + # } + + # calc_totals(row_nr,tab) ; + # } + + # // \$("$vat_field_ids_string").change(function() { + # \$("#content").on("change","[id^='checkboxVat_']", function () { + # const id = this.id ; + # changed_vat(id) ; + # }); + + # // \$("$excl_field_ids_string,$description_field_ids_string,$qty_field_ids_string,$amount_usd_field_ids_string,$operator_field_ids_string").change(function() { + # \$("#content").on("change","[id^='checkboxExcl_'],[id^='selectDescription_'],[id^='inputQty_'],[id^='inputAmount_usd_'],[id^='selectOperator_workings_event_']", function () { + # const id = this.id ; + # changed_others(id) ; + # }); + # ~ ; + + # $trigger_jquery_raw .= qq~ + + # \$("#content").on("click","[id^='btn_workings_event_'],[id^='btn_costing_event_']", function () { + # // \$("$btn_ids_string").click(function () { + # const id = this.id ; + # let tab = get_tab (id) ; + + # console.log("id : "+id) ; + # console.log("tab : "+tab) ; + + # add_quote_expenses_row_all(id,tab) ; + # }); + + # function add_quote_expenses_row_all (id,tab) { + + # let row_nr = get_row_nr(id) ; + # \$("#"+tab+"_"+row_nr).show(); + # let row_html = "" ; + # if (tab == "workings_event") { + # row_html = add_quote_expenses_row(row_nr,tab,"$description_options_workings","$operator_options") ; + # } else if (tab == "costing_event") { + # row_html = add_quote_expenses_row(row_nr,tab,"$description_options_costing","") ; + # } + # \$("#"+tab+"_"+row_nr).html(row_html); + # // \$("#$suffix\_"+row_nr).trigger("chosen:updated") ; + + # \$("#selectDescription_"+tab+"_"+row_nr).chosen({ allow_single_deselect:true }) ; + + # if (tab == "workings_event") { + # \$("#selectOperator_workings_event_"+row_nr).chosen({ allow_single_deselect:true }); + # \$("#inputRemarks_workings_event_"+row_nr).css("text-align","") ; + # \$("#inputSupplier_workings_event_"+row_nr).css("text-align","") ; + # \$("#inputRef_nr_workings_event_"+row_nr).css("text-align","") ; + # } + + # \$("#btn_"+tab+"_"+row_nr).hide(); + # var v = row_nr + 1 ; + + # // \$("#btn_$suffix\_"+v).css("padding-left","16px") ; + # \$("#btn_"+tab+"_"+v).html("") ; + # \$("#btn_"+tab+"_"+v).show(); + # \$("#btn_row_"+tab+"_"+v).show() ; + # \$("#2_"+tab+"_"+row_nr).show() ; + + # \$("#checkboxExcl_"+tab+"_"+row_nr).prop('checked',false) ; + + # // \$("#"+tab+"_"+row_nr).on("change","#checkboxVat_"+tab+"_"+row_nr+"", function() { + # // const id = this.id ; + # // changed_vat(id) ; + # // }); + + # // \$("#"+tab+"_"+row_nr).on("change","#checkboxExcl_"+tab+"_"+row_nr+",#selectDescription_"+tab+"_"+row_nr+",#selectOperator_"+tab+"_"+row_nr+",#inputQty_"+tab+"_"+row_nr+",#inputAmount_usd_"+tab+"_"+row_nr+"", function() { + # // const id = this.id ; + # // changed_others(id) ; + # // }); + + # } + + # ~ if $btn_ids_string ; + + # $trigger_jquery_raw .= qq~ + + # \$("#selectCurrency").change(function () { + + # }) ; + + # \$("input[name='roe']").change(function () { + + # let roe = \$(this).val() ; + # if (roe < 0 || !roe) { + # roe = 1 ; + # } + # \$(this).val(parseFloat(roe).toFixed(2)) ; + + # var sub_total = 0 ; var vat_total = 0 ; var sub_total_quote = 0 ; var vat_total_quote = 0 ; + + # [sub_total,vat_total] = add_up_totals("workings_event",50,roe,1) ; + # [sub_total_quote,vat_total_quote] = add_up_totals("costing_event",30,roe,1) ; + + # // // // \$("input[name='income']").val((sub_total_quote+vat_total_quote).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # \$("input[name='income']").val((sub_total_quote+vat_total_quote).toFixed(2)) ; + # \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + # update_overall_totals(sub_total,vat_total,"workings_event") ; + # update_overall_totals(sub_total_quote,vat_total_quote,"costing_event") ; + + # }) ; + + # function add_up_totals (tab,nr_of_rows,roe,recalc_totals) { + + # let sub_total = 0 ; let vat_total = 0 ; + # for (let i=1; i<=nr_of_rows; i++) { + # if (!\$("#"+tab+"_"+i).html()) { break ; } + # if (\$("#selectDescription_"+tab+"_"+i).val()) { + # if (\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { continue ; } + # let ttl = 0 ; + # if (recalc_totals) { + # ttl = parseFloat(\$("#inputAmount_usd_"+tab+"_"+i).val()) * parseFloat(\$("#inputQty_"+tab+"_"+i).val()) * parseFloat(roe) ; + # } else { + # ttl = parseFloat(\$("#inputAmount_ttl_"+tab+"_"+i).val().replace(/,/g, '')) + # } + # // // // // \$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # \$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toFixed(2)) ; + # if (!\$("#inputAmount_ttl_"+tab+"_"+i).val() || \$("#inputAmount_ttl_"+tab+"_"+i).val() == "NaN") { + # \$("#inputAmount_ttl_"+tab+"_"+i).val("0.00") ; + # ttl = 0 ; + # } + # sub_total += ttl ; + # if (\$("#checkboxVat_"+tab+"_"+i).is(":checked")) { + # vat_total += ttl*0.15 ; + # } + # } else if (!\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { + # \$("#checkboxExcl_"+tab+"_"+i).prop('checked',true) ; + # } + # } + # return [sub_total,vat_total] ; + # } + + # // function getNum(val) { + + # // if (isNaN(val)) { + # // return 0; + # // } + # // return val; + # // } + + # function calc_totals (row_cnt,tab) { + + # var qty = \$("#inputQty_"+tab+"_"+row_cnt) ; + # var usd = \$("#inputAmount_usd_"+tab+"_"+row_cnt) ; + # var conv = \$("#inputAmount_ttl_"+tab+"_"+row_cnt) ; + # var excl = \$("#checkboxExcl_"+tab+"_"+row_cnt) ; + # var item = \$("#selectDescription_"+tab+"_"+row_cnt) ; + + # if (!usd.val() && !conv.val() && !usd.val()) { + # // console.log("skip calc_totals_workings") ; + # if (!item.val()) { + # excl.prop("checked",true) ; + # } + # return ; + # } + + # var vat = \$("#checkboxVat_"+tab+"_"+row_cnt) ; + + # if (!item.val()) { + + # excl.prop("checked",true) ; + # vat.prop("checked",true) ; + # qty.val("") ; + # usd.val("") ; + # conv.val(""); + # if (tab == "workings_event") { + # var rem = \$("#inputRemarks_"+tab+"_"+row_cnt) ; + # var sup = \$("#inputSupplier_"+tab+"_"+row_cnt) ; + # var ref = \$("#inputRef_nr_"+tab+"_"+row_cnt) ; + # var op = \$("#selectOperator_"+tab+"_"+row_cnt) ; + # rem.val("") ; + # sup.val("") ; + # ref.val("") ; + # op.val("") ; + # op.trigger("chosen:updated") ; + # } + # } else if (excl.is(":checked") && item.val() && conv.val() == "0.00") { + # excl.prop("checked",false) ; + # } + + # if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) ; } + + # let roe = parseFloat(\$("#inputRoe").val()) ; + + # let ttl = usd.val() * qty.val() * roe ; + + # // // // conv.val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # conv.val(ttl.toFixed(2)) ; + + # let sub_total = 0 ; let vat_total = 0 ; + + # let nr_of_rows = 50 ; + # if (tab == "costing_event") { + # nr_of_rows = 30 ; + # } + + # [sub_total,vat_total] = add_up_totals (tab,nr_of_rows,roe,0) ; + + # if (tab == "workings_event") { + # // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + # update_overall_totals(sub_total,vat_total,tab) ; + # } else { + # // // // \$("input[name='income']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # \$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; + # update_overall_totals(sub_total,vat_total,tab) ; + # // update_overall_totals_costings(sub_total,vat_total) ; + # } + # } + + # function update_overall_totals (sub_total,vat_total,tab) { + + # let profit_loss = parseFloat(\$("input[name='income']").val().replace(/,/g, '')) - parseFloat(\$("input[name='expenses']").val().replace(/,/g, '')) ; + + # // // // \$("input[name='profit_loss']").val(profit_loss.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # // // // \$("input[name='sub_total_"+tab+"']").val(sub_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # // // // \$("input[name='vat_total_"+tab+"']").val(vat_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # // // // \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + + # \$("input[name='profit_loss']").val(profit_loss.toFixed(2)) ; + # \$("input[name='sub_total_"+tab+"']").val(sub_total.toFixed(2)) ; + # \$("input[name='vat_total_"+tab+"']").val(vat_total.toFixed(2)) ; + # \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toFixed(2)) ; + # } + + # function add_quote_expenses_row (row_nr,tab,options1,options2) { + + # let tindex = $tindex ; + # tindex = parseInt(tindex) ; + # row_nr = parseInt(row_nr) ; + # tindex = tindex - 10*(1+50-row_nr) ; + + # let row = add_checkbox(row_nr,"excl_"+tab+"_"+row_nr,"checkboxExcl_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + + # row = row+""+add_select(row_nr,"description_"+tab+"_"+row_nr,"selectDescription_"+tab+"_"+row_nr,"Select Description "+row_nr,options1,tindex,2,90,'','') ; tindex++ ; + # if (tab == "workings_event") { + # row = row+add_select(row_nr,"operator_workings_event_"+row_nr,"selectOperator_workings_event_"+row_nr,"Select Operator "+row_nr,options2,tindex,2,90,'','') ; tindex++ ; + # row = row+add_input(row_nr,"remarks_workings_event_"+row_nr,"inputRemarks_workings_event_"+row_nr,"Remarks "+row_nr,tindex,'',1) ; tindex++ ; + # row = row+add_input(row_nr,"supplier_workings_event_"+row_nr,"inputSupplier_workings_event_"+row_nr,"Supplier "+row_nr,tindex,'',1) ; tindex++ ; + # row = row+add_input(row_nr,"ref_nr_workings_event_"+row_nr,"inputRef_nr_workings_event_"+row_nr,"Ref Nr "+row_nr,tindex,'',1) ; tindex++ ; + # } + # row = row+add_input(row_nr,"qty_"+tab+"_"+row_nr,"inputQty_"+tab+"_"+row_nr,"Qty "+row_nr,tindex,'',1) ; tindex++ ; + # row = row+add_input(row_nr,"amount_usd_"+tab+"_"+row_nr,"inputAmount_usd_"+tab+"_"+row_nr,"Amount "+row_nr,tindex,'',1) ; tindex++ ; + # row = row+add_input(row_nr,"amount_ttl_"+tab+"_"+row_nr,"inputAmount_ttl_"+tab+"_"+row_nr,"Total Amount "+row_nr,tindex,"readonly",1) ; tindex++ ; + # row = row+add_checkbox(row_nr,"vat_"+tab+"_"+row_nr,"checkboxVat_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + # return row ; + # } + # ~ ; + +} + +if ($tab==3) { # Costing + + # --------------- START COSTING ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + $lcol=1; $fcol=2; + + my $sec = '_costing' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + %sec_cnt = ('a_other' => "5-Other"); + + foreach (sort keys %sec_cnt) { + $_k = substr($_,1) ; + next if $_k eq '_hardware' ; + my @parts = split(/\-/,$sec_cnt{$_}) ; + $add_form_fields .= qq~

    $parts[1] :

    ~ ; + # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + $fcol = 3 ; + $add_form_fields .= qq~
    PDF title :
    ~ ; + # $add_form_fields .= qq~
    PDF TITLE :
    ~ ; + if ($old_title_to_new_title{$parts[1]}{$id} and $old_title_to_new_title{$parts[1]}{$id} ne $parts[1]){ + $add_form_fields .= &common_min_form_input_col($_k, $old_title_to_new_title{$parts[1]}{$id}) ; + } + else { + $add_form_fields .= &common_min_form_input_col($_k,'') ; + } + + $add_form_fields .= qq~
    ~ ; + &tab_build_qt_col_headers("$sec$_k") ; + &build_cost_form($id,$tab,$parts[0],"$sec$_k") ; + if ($_k eq '_systems') { + $preferred_title{'systems_included'} = ' ' ; $preferred_placeholder{'systems_included'} = 'Included' ; $fcol = 3 ; + $add_form_fields .= &common_min_form_textarea('systems_included',$db{$table}{$id}{systems_included},'') ; + } + if ($_k eq '_rental') { + $preferred_title{'rental_included'} = ' ' ; $preferred_placeholder{'rental_included'} = 'Included' ; $fcol = 3 ; + $add_form_fields .= &common_min_form_textarea('rental_included',$db{$table}{$id}{rental_included},'') ; + } + if ($_k eq '_other') { + $preferred_title{'other_included'} = ' ' ; $preferred_placeholder{'other_included'} = 'Included' ; $fcol = 3 ; + $add_form_fields .= &common_min_form_textarea('other_included',$db{$table}{$id}{other_included},'') ; + } + } + + $add_form_fields .= qq~
     
    ~ ; + + # $add_form_fields .= qq~
     
    ~ ; + + $add_form_fields .= qq~
    PDF total :
    ~ ; + $lcol = 3 ; + # if ($old_title_to_new_title{"Hardware"}{$id} and $old_title_to_new_title{"Hardware"}{$id} ne "Hardware") { + # $add_form_fields .= &common_min_form_input_col('_hardware', $old_title_to_new_title{"Hardware"}{$id}) ; + # } else { + # $add_form_fields .= &common_min_form_input_col('_hardware','') ; + # } + + # my @ttlarr = ("sub_total","vat_total","grand_total") ; + + # @ttlarr2 = ("subtotal","vat","total") ; + + $lcol = 1 ; $fcol = 1 ; + + print "\n Other Costing Tab " ; + + foreach (@ttlarr) { + print "\n 1 ttlarr : $_ " ; + $readonly{$_} = "READONLY" ; + my $val = $db{$table}{$id}{$_} ; $val = '0.00' unless $val ; + # $add_form_fields .= qq~
    ~ ; $lcol=2; + # $add_form_fields .= &common_min_form_label_col($_) ; $lcol = 1 ; + $type = 'hidden' ; $add_form_fields .= &common_min_form_input_col($_,$val) ; $type = '' ; + # $add_form_fields .= qq~
    ~ ; + + $lcol = 1 ; $add_form_fields .= &common_min_form_label_col($_) ; + # $add_form_fields .= qq~
    ~ ; + } + + $add_form_fields .= qq~
    ~ ; + + # $add_form_fields .= qq~
     
    ~ ; + + # my @ttlarr = ("one_time_fee","monthly_recurring_fee","annual_fee") ; + $lcol = 1 ; $fcol = 1 ; + + foreach my $a (@ttlarr) { + + $readonly{$a} = "READONLY" ; + + # if ($_ eq 'one_time_fee') { + + # $add_form_fields .= qq~
    PDF total :
    ~ ; + # $lcol = 1 ; + # if ($old_title_to_new_title{"Hardware"}{$id} and $old_title_to_new_title{"Hardware"}{$id} ne "Hardware"){ + # $add_form_fields .= &common_min_form_input_col('_hardware', $old_title_to_new_title{"Hardware"}{$id}) ; + # } + # else { + # $add_form_fields .= &common_min_form_input_col('_hardware','') ; + # } + # } + + # else { + $add_form_fields .= qq~
    ~ ; + # } + + $lcol = 2 ; + $add_form_fields .= &common_min_form_label_col($a) ; + $lcol = 1 ; + + foreach my $b (@ttlarr2) { + + $field = "$b\_$a\_2" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + my $val = $default_totals{$field}{2} ? $default_totals{$field}{2} : '0.00' ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + } + + # $field = "2_subtotal_$_" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + # my $val = $db{$table}{$id}{$field} ? $db{$table}{$id}{$field} : '0.00' ; + # $add_form_fields .= &common_min_form_input_col($field,$val) ; + + # $field = "2_vat_$_" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + # my $val = $db{$table}{$id}{$field} ? $db{$table}{$id}{$field} : '0.00' ; + # $add_form_fields .= &common_min_form_input_col($field,$val) ; + + # $field = "2_total_$_" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + # my $val = $db{$table}{$id}{$field} ? $db{$table}{$id}{$field} : '0.00' ; + # $add_form_fields .= &common_min_form_input_col($field,$val) ; + $add_form_fields .= qq~
    ~ ; + + } + + $add_form_fields .= qq~
     
    ~ ; + + # $print_box_content_rows .= qq~
    ~ ; + # $print_box_content_rows .= $add_form_fields ; + # $print_box_content_rows .= &common_min_box_foot; + + &tab_content_box($sec_name,$sec_col) ; + + # --------------- END COSTING ---------------------------------------------------------------------------------------------------------------- + + + $trigger_jquery_raw .= qq~ + + + + ~ ; + +} + +if ($tab==4) { # Purchase Summary + + # --------------- START PURCHASE SUMMARY ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + my $sec = '_purchase_summary' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + my $style_vat = '' ; if ($no_vat{$sec}) { $style_vat = 'style="display:none;"' ; } + + $add_form_fields .= qq~
     
    ~ ; + + my $field = "excl$sec" ; + if ($db{$table}{$id}{$field} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + $label{$field} = 1 ; + $add_form_fields .= qq~
    ~ ;$fcol=1 ; + $add_form_fields .= &common_min_form_checkbox_col($field,$db{$table}{$id}{$field},$checked) ; + $add_form_fields .= qq~

    Purchase Summary

    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + my $suffix = $sec ; my $rcnt = 3 ; + + # &set_check_boxes_checked($id,$rcnt,"excl",$suffix); + + $default_desc{1} = 'Hardware Purchase' ; + $default_desc{2} = 'Monthly Fees' ; + $default_desc{3} = 'Annual Fees' ; + + my @prefexes = ("excl", "item") ; + + foreach my $prefex (@prefexes) { + + $col_name = "$prefex" . "$suffix" ; + $cnt = 0 ; + # if($db{quotes_min}{$id}{$col_name}){ + for my $col_input (split(";", $db{quotes_min}{$id}{$col_name})){ + $cnt++ ; + $saved_field{$prefex}{$suffix}{$cnt} = $col_input ; + } + # } + } + for (1 .. $rcnt) { + $add_form_fields .= qq~
    ~ ; + #---------------------------------------------------------------------------------------------------- + $field = "excl_$_$suffix" ; $fcol=1 ; + # if ($checkit{$field} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + # if ($db{$table}{$id}{$field} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + if ($saved_field{"excl"}{$suffix}{$_} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + $label{$field} = 1 ; + # $add_form_fields .= &common_min_form_checkbox_col($field,$db{$table}{$id}{$field},$checked) ; + $add_form_fields .= &common_min_form_checkbox_col($field,$saved_field{"excl"}{$suffix}{$_},$checked) ; + #---------------------------------------------------------------------------------------------------- + my $field = "item_$_$suffix" ; $fcol=2 ; + $preferred_placeholder{$field} = "Item $_" ; + # my $val = $db{$table}{$id}{$field} ; + my $val = $saved_field{"item"}{$suffix}{$_} ; + $val = $default_desc{$_} unless $val ; + # $readonly{$field} = 'READONLY' ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + for my $year (1 .. 5) { + $field = "year_$year\_$_$suffix" ; $input_style{$field} = qq~style="text-align:right;"~; + + unless ($year==1 and $_==3) { + $readonly{$field} = 'READONLY' ; + } else { + $trigger_jquery_raw .= qq~\$("#inputYear_1_$_$suffix").change(function() { + calcAnnual$field() ; + }); + ~; + $trigger_jquery_raw .= qq~function calcAnnual$field() + { + var annual_ttl = getNum(parseFloat(\$("#inputYear_1_$_$suffix").val())) + getNum(parseFloat(\$("#inputYear_2_$_$suffix").val())) + getNum(parseFloat(\$("#inputYear_3_$_$suffix").val())) ; + \$("#inputTotal_$_$suffix").val(annual_ttl.toFixed(2)); + }~; + } + $preferred_placeholder{$field} = "Year $year Total $_" ; + # my $val = &q_get_val($db{$table}{$id}{$field}) ; + $excl_on_change{$field} = 1 ; + $year_totals{"yearly_totals_$year"} += $db{$table}{$id}{$field} ; + + $fcol = 12 ; + $add_form_fields .= qq~
    ~ if $year <= 3 ; + $add_form_fields .= qq~~ ; + } + $fcol = 2 ; + #---------------------------------------------------------------------------------------------------- + + $field = "total_$_$suffix" ; $input_style{$field} = qq~style="text-align:right;"~; $readonly{$field} = 'READONLY' ; # $fcol=2 ; + $preferred_placeholder{$field} = "Total $_" ; + # my $val = &q_get_val($db{$table}{$id}{$field}) ; + $add_form_fields .= &common_min_form_input_col($field,$db{$table}{$id}{$field},1) ; + #---------------------------------------------------------------------------------------------------- + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + } + $add_form_fields .= qq~
    ~ ; + for my $y (1 .. 5) { + $grand_tot += $year_totals{"yearly_totals_$y"} ; + $field ="yearly_totals_$y" ; + $readonly{$field} = 'READONLY' ; + # $year_totals{"yearly_totals_$y"} = &common_commify($year_totals{"yearly_totals_$y"}) ; + $input_style{$field} = qq~style="text-align:right;"~ ; + $fcol = 12 ; + $add_form_fields .= qq~
    ~ if $y <= 3 ; + $add_form_fields .= qq~~ ; + } + + $trigger_jquery_raw .= qq~ + // console.log("suffix : "+$suffix) ;console.log("1") ; + + if (\$("#selectPeriod").val() == 60) { + + for (let ii = 1; ii <= 5; ii++) { + + if (ii <= 3) { + \$("#year_"+ii+"_sum").removeClass("col-md-2").addClass("col-md-1") ; + \$("#total_"+ii+"").removeClass("col-md-2").addClass("col-md-1") + } + else if (ii <= 5 && ii > 3) { + \$("#year_"+ii+"_sum").removeClass("col-md-0").addClass("col-md-1") ; + \$("#total_"+ii+"").removeClass("col-md-0").addClass("col-md-1") ; + \$("#year_"+ii+"_sum").show() ; + \$("#total_"+ii+"").show() ; + } + for (let jj = 1; jj <= 3; jj++) { + + if (ii <= 3) { + \$("#b_year_"+ii+"_"+jj+"").removeClass("col-md-2").addClass("col-md-1") ; + } + else if (ii <= 5 && ii > 3) { + \$("#b_year_"+ii+"_"+jj+"").removeClass("col-md-0").addClass("col-md-1") ; + \$("#b_year_"+ii+"_"+jj+"").show() ; + } + } + } + } + + \$("#selectPeriod").on("change", function() { + + for (let i = 1; i <= 5; i++) { + + if (i <= 3 && \$(this).val() == 36) { + \$("#year_"+i+"_sum").removeClass("col-md-1").addClass("col-md-2") ; + \$("#total_"+i+"").removeClass("col-md-1").addClass("col-md-2") ; + } + else if (i <= 3 && \$(this).val() == 60) { + \$("#year_"+i+"_sum").removeClass("col-md-2").addClass("col-md-1") ; + \$("#total_"+i+"").removeClass("col-md-2").addClass("col-md-1") + } + else if (i <= 5 && i > 3 && \$(this).val() == 36) { + \$("#year_"+i+"_sum").removeClass("col-md-1").addClass("col-md-0") ; + \$("#total_"+i+"").removeClass("col-md-1").addClass("col-md-0") ; + \$("#year_"+i+"_sum").hide() ; + \$("#total_"+i+"").hide() ; + } + else if (i <= 5 && i > 3 && \$(this).val() == 60) { + \$("#year_"+i+"_sum").removeClass("col-md-0").addClass("col-md-1") ; + \$("#total_"+i+"").removeClass("col-md-0").addClass("col-md-1") ; + \$("#year_"+i+"_sum").show() ; + \$("#total_"+i+"").show() ; + } + for (let j = 1; j <= 3; j++) { + + if (i <= 3 && \$(this).val() == 36) { + \$("#b_year_"+i+"_"+j+"").removeClass("col-md-1").addClass("col-md-2") ; + } + else if (i <= 5 && i > 3 && \$(this).val() == 36) { + \$("#b_year_"+i+"_"+j+"").removeClass("col-md-1").addClass("col-md-0") ; + \$("#b_year_"+i+"_"+j+"").hide() ; + } + + else if (i <= 3 && \$(this).val() == 60) { + \$("#b_year_"+i+"_"+j+"").removeClass("col-md-2").addClass("col-md-1") ; + } + else if (i <= 5 && i > 3 && \$(this).val() == 60) { + \$("#b_year_"+i+"_"+j+"").removeClass("col-md-0").addClass("col-md-1") ; + \$("#b_year_"+i+"_"+j+"").show() ; + // if (\$("#b_year_"+i+"_"+j+"").text().trim() === '') { + // \$("#b_year_"+i+"_"+j+"").text("0.00") ; + // } + } + } + } + }); + ~ ; + + $fcol = 2 ; + $field ="yearly_total" ; + $readonly{$field} = 'READONLY' ; + # $grand_tot = &common_commify($grand_tot) ; + $input_style{$field} = qq~style="text-align:right;"~ ; + $add_form_fields .= &common_min_form_input_col($field,$grand_tot,1) ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END PURCHASE SUMMARY ---------------------------------------------------------------------------------------------------------------- + } + +if ($tab==5) { # Notes + + # --------------- START NOTES ---------------------------------------------------------------------------------------------------------------- + + my $sec = '_notes' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $add_form_fields = '' ; + + # &set_check_boxes_checked($id,$sec_cnt,"excl",$sec); + + + &db_min_ro('quote_notes','*',"id='1'",'','') ; + + $add_form_fields .= qq~

    Notes:

    ~ ; + &tab_build_terms_headers; + + $cntnoteloop=1; for (1 .. 12) { &tab_build_terms_fields('note',$_,$id) ; } + + $add_form_fields .= qq~

    Payment Terms:

    ~ ; + &tab_build_terms_headers; + + $cntnoteloop=1; for (1 .. 6) { &tab_build_terms_fields('payment_term',$_,$id) ; } + + $add_form_fields .= qq~

    ROE:

    ~ ; + &tab_build_terms_headers; + + $cntnoteloop=1; for (1 .. 6) { &tab_build_terms_fields('roe',$_,$id) ; } + + $add_form_fields .= qq~

    Delivery Time:

    ~ ; + &tab_build_terms_headers; + + $cntnoteloop=1; for (1 .. 4) { &tab_build_terms_fields('delivery_time',$_,$id) ; } + + $add_form_fields .= qq~

    Terms and Conditions:

    ~ ; + &tab_build_terms_headers; + + $cntnoteloop=1; for (1 .. 1) { &tab_build_terms_fields_terms_and_conditions('terms',$_,$id) ; } + + $trigger_jquery .= qq~\$("#selectTerms_chosen").css( "width", "100%" );~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END NOTES ---------------------------------------------------------------------------------------------------------------- + } + +if ($tab==6) { # Camera Details + + # --------------- START CAMERA DETAILS ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + my $sec = '_camera_details' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $add_form_fields = '' ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + # my $suffix = $sec ; my $rcnt = 11 ; + # my $suffix = $sec ; my $rcnt = 20 ; + my $suffix = $sec ; my $rcnt = $max_cams ; # set in quotes.pl + # our %linked_vpu = () ; our %vpu_serial_nr = () ; our %vpu_camera_nr = () ; + &tab_camera_details_select_opts('cameras','camera_nr',"camera_nr NOT LIKE 'vpu%'",$suffix,$rcnt) ; + + $rcnt = $max_cams ; # reset in tab_camera_details_select_opts + + # &tab_camera_details_select_opts('cameras','camera_nr',"event_system_id < 1",$suffix,$rcnt) ; + + my $cam_qtys = '' ; + + # &common_debug("cam_qtys : quote_nr=$db{$table}{$id}{quote_nr}") ; + + foreach (keys %{$camera_system_count{$db{$table}{$id}{quote_nr}}}) { + # &common_debug("cam_qtys : cam=$_, qty=$camera_system_count{$db{$table}{$id}{quote_nr}}{$_}") ; + $cam_qtys .= qq~$_ : $camera_system_count{$db{$table}{$id}{quote_nr}}{$_}
    ~ ; + } + + # our $cam_box_icon = qq~ ~ if $cam_qtys ; + our $cam_box_icon = qq~ ~ if $cam_qtys ; + + # foreach (sort keys %sec_cnt) { + # $_k = substr($_,1) ; + # my @parts = split(/\-/,$sec_cnt{$_}) ; + # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + # &tab_build_qt_col_headers("$sec$_k"); + # &build_cost_form($id,$tab,$parts[0],"$sec$_k"); + # } + + # unless ($db{quote_notes}{1}{$inpfield}) { $checkit{$exfield} = 1 ; } + + # $add_form_fields .= qq~
    ~ ; + # if ($checkit{$exfield} == 1) { $checked = 'CHECKED'; } elsif (($excl_tick{$cnt}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } + + # &set_check_boxes_checked($id,$rcnt,"excl",$suffix); + + my $cntcamloop=1; + + for (1 .. $rcnt) { + + my $q_nr = $db{$table}{$id}{quote_nr} ; + + + # next if substr($sel_cam_nr{$camera_details{$q_nr}{$_}{"$_$suffix"}{id}},0,3) eq 'VPU' ; + my $a = "$_$suffix" ; + # &common_debug("rcnt : $_ , q_nr : $q_nr , camera_details : $camera_details{$q_nr}{$_}{$a}{id}") ; + + $cam_display_style = '' ; $cam_display_plus_btn = '' ; + # unless ($_==1 or $db{$table}{$id}{"camera_nr_$_$suffix"}) { + unless ($_==1 or $camera_details{$q_nr}{$_}{"$_$suffix"}{id}) { + $cam_display_style = qq~style='display:none;'~ ; + $trigger_jquery_raw .= qq~ \$("#btn_$_$suffix").click(function () { + \$("#$_$suffix").toggle(); + \$("#btn_$_$suffix").hide(); + var v = $_ + 1 ; + \$("#btn_"+v+"$suffix").show(); + });~ ; + if ($_>$cntcamloop) { $cam_display_butt = qq~display:none;~ ; } else { $cam_display_butt = '' ; } + $cam_display_plus_btn = qq~~; + } else { $cntcamloop++ ; } + + + + $add_form_fields .= qq~
    ~ ; + + # my $cam_id = $db{$table}{$id}{"camera_nr_$_$suffix"} ; + + # $add_form_fields .= qq~
    ~ ; + #---------------------------------------------------------------------------------------------------- + $field = "excl_$_$suffix" ; $fcol=1 ; + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_cam_excl} ; + # if ($checkit{$field} == 1) { $checked = 'CHECKED'; } elsif ($_!=1 and $iaction eq 'add') { $checked = 'CHECKED'; } else { $checked = ''; } + if ($val==1) { $checked = 'CHECKED'; } elsif ($iaction eq 'add') { $checked = 'CHECKED'; } elsif ($val eq '0') { $checked = ''; } else { $checked = 'CHECKED'; } + # &common_debug("$field : [$val] [$checked] [$_$suffix]") ; + $label{$field} = 1 ; + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_checkbox_col($field,$val,$checked) ; + #---------------------------------------------------------------------------------------------------- + my $field = "camera_nr_$_$suffix" ; $fcol=2 ; + $allow_deselect{$field} = 1 ; + $preferred_placeholder{$field} = "Camera Nr $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{id} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + # $add_form_fields .= &common_min_form_input_col($field,$val) ; + $excl_on_change{$field} = 1 ; + + $opts{$field} = $opts_on_edit{$field} if $opts_on_edit{$field} and $db{quotes}{$i{id}}{max_cams} > 50 ; #and $username eq 'rory' ; # overwrite if selected and max_cams exceeded + + $add_form_fields .= &common_min_form_select_col($field,$val) ; + + my $abrv_cam_system = substr($sel_cam_nr{$val},0,3); + # next if $abrv_cam_system eq 'VPU' ; + # &common_debug("abrv_cam_system=$abrv_cam_system, abrv_prev_cam_system=$abrv_prev_cam_system, prev_cam_nr=$prev_cam_nr, link to: c_excl_$_\_camera_details") ; + # if ($abrv_cam_system eq 'VPU' and ($abrv_prev_cam_system eq 'S1' or $abrv_prev_cam_system_other eq 'Prime' or $abrv_prev_cam_system_other eq 'Coach')) { + + # if ($abrv_cam_system eq 'VPU' and ($abrv_prev_cam_system eq 'S1' or $abrv_prev_cam_system eq 'S2' or $abrv_prev_cam_system_other eq 'Prime' or $abrv_prev_cam_system_other eq 'Coach')) { + + if ($linked_vpu{$val}) { + $trigger_jquery .= qq~\$("#c_excl_$_\_camera_details").append("");\$('[data-toggle="tooltip"]').tooltip({html:true}) ;~; + } + # } + $abrv_prev_cam_system = substr($abrv_cam_system,0,2); + $abrv_prev_cam_system_other = substr($abrv_cam_system,0,5); + $prev_cam_nr = $sel_cam_nr{$val} ; + #---------------------------------------------------------------------------------------------------- + # # my $field = "item_code_$_$suffix" ; $fcol=1 ; + # # $preferred_placeholder{$field} = "Item Code $_" ; + # # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + # # $add_form_fields .= &common_min_form_input_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + my $field = "description_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "Description $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_cam_desc} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + # my $field = "qty_$_$suffix" ; $fcol=1 ; + # $preferred_placeholder{$field} = "Qty $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + # $type = 'hidden' ; $add_form_fields .= &common_min_form_input_col($field,$val) ; $type = '' ; + #---------------------------------------------------------------------------------------------------- + my $field = "serial_nr_$_$suffix" ; $fcol=2 ; + $preferred_placeholder{$field} = "Serial Nr $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{serial_nr} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + my $field = "ref_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "Ref $_" ; + # my $val = $db{$table}{$id}{$field} ; + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ref} ; + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + # &common_debug("2. $field : [$q_nr] [$_] [$_$suffix] [$val]") if $val; + #---------------------------------------------------------------------------------------------------- + my $field = "delivery_date_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "Delivery Date $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_delivery_date} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_datepicker_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + my $field = "active_date_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "Active Date $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_active_date} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $add_form_fields .= &common_min_form_datepicker_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + my $field = "ew_date_from_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "E/W Date From $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_from} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_datepicker_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + my $field = "ew_date_to_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "E/W Date To $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_to} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_datepicker_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + # my $ew_pdf_butt = '' ; if ($username eq 'rory' or $username eq 'handre') { $ew_pdf_butt = qq~ ~; } + # my $ew_pdf_butt = '' ; if ($camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_from} and $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_to} and uc substr($camera_details{$q_nr}{$_}{"$_$suffix"}{camera_nr},0,3) ne 'VPU') { $ew_pdf_butt = qq~ ~; } + my $ew_pdf_butt = '' ; if ($camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_from} and $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_to} and (uc substr($camera_details{$q_nr}{$_}{"$_$suffix"}{camera_nr},0,2) eq 'S1' or uc substr($camera_details{$q_nr}{$_}{"$_$suffix"}{camera_nr},0,5) eq 'SCORE')) { $ew_pdf_butt = qq~ ~; } + #---------------------------------------------------------------------------------------------------- + $add_form_fields .= qq~
    $ew_pdf_butt
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    $cam_display_plus_btn
    ~ ; + $add_form_fields .= qq~
    ~ ; + } + + $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + $cam_box_icon = '' ; + + # --------------- END CAMERA DETAILS ---------------------------------------------------------------------------------------------------------------- +} + +if ($tab==7) { # Invoice Details + + # --------------- START INVOICE DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_invoice_details' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $lcol = 2 ; + $fcol = 5 ; + + $add_form_fields = '' ; + + $add_form_fields .= &common_min_form_input('invoice_nr',$db{$table}{$id}{invoice_nr},'') ; + my $checked = 'CHECKED' if $db{$table}{$id}{annual_invoice} ; + $add_form_fields .= &common_min_form_checkbox('annual_invoice',$db{$table}{$id}{annual_invoice},$checked) ; + # if ($db{$table}{$id}{invoice_date} eq '' or $db{$table}{$id}{invoice_date} eq '0000-00-00') { $db{$table}{$id}{invoice_date} = $now_ccyy_mm_dd ; } + $add_form_fields .= &common_min_form_datepicker('invoice_date',$db{$table}{$id}{invoice_date}) ; + $add_form_fields .= &common_min_form_input('annual_invoice_2',$db{$table}{$id}{annual_invoice_2},'') ; + $add_form_fields .= &common_min_form_input('annual_invoice_3',$db{$table}{$id}{annual_invoice_3},'') ; + # $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END INVOICE DETAILS ---------------------------------------------------------------------------------------------------------- + } + +# if ($tab==7) { # Extended Warranty + + # # --------------- START EXTENDED WARRANTY -------------------------------------------------------------------------------------------------------- + + # my $sec = '_extended_warranty' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # if ($ret) { return ; } + + # $lcol = 2 ; + # $fcol = 3 ; + + # $add_form_fields = '' ; + + # if (($db{$table}{$id}{date_from} eq '') or ($db{$table}{$id}{date_from} eq '0000-00-00')) { $db{$table}{$id}{date_from} = $now_ccyy_mm_dd ; } + # $add_form_fields .= &common_min_form_datepicker('date_from',$db{$table}{$id}{date_from}) ; + # if (($db{$table}{$id}{date_to} eq '') or ($db{$table}{$id}{date_to} eq '0000-00-00')) { $db{$table}{$id}{date_to} = $now_ccyy_mm_dd ; } + # $add_form_fields .= &common_min_form_datepicker('date_to',$db{$table}{$id}{date_to}) ; + + # &tab_content_box($sec_name,$sec_col); + + # # --------------- END EXTENDED WARRANTY ---------------------------------------------------------------------------------------------------------- + # } + +# if ($tab==8) { # Rental + + # # --------------- START RENTAL -------------------------------------------------------------------------------------------------------- + + # my $sec = '_rental' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # if ($ret) { return ; } + + # $lcol = 2 ; + # $fcol = 3 ; + + # $add_form_fields = '' ; + + # # our %sec_cnt = ('_cost' => "1-Cost"); + + # # my $sec = '_rental' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + # # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # # if ($ret) { return ; } + + # # foreach (sort keys %sec_cnt) { + # # my @parts = split(/\-/,$sec_cnt{$_}) ; + # # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + # # &tab_build_qt_col_headers("$sec$_"); + # # &build_cost_form($id,$tab,$parts[0],"$sec$_"); + # # } + + # &tab_content_box($sec_name,$sec_col); + + # # --------------- END RENTAL ---------------------------------------------------------------------------------------------------------- + # } + +if ($tab==8) { # Document Uploads + + # --------------- START DOCUMENT UPLOADS ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + my $sec = '_document_uploads' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $add_form_fields = '' ; + + my @docs = ('Signed Quote','PO','Other 1','SLA','T&Cs','Other 2','Photos','Delivery Note','Other 3'); + + $add_form_fields .= qq~
    ~ ; + + foreach (@docs) { + my $doc = lc $_ ; $doc =~ s/ /\_/ ; $doc =~ s/&/\_/ ; + $costing_uploads = &common_get_field_uploads($id,"costing_$doc",'id') ; + if ($costing_uploads) { + $add_form_fields .= qq~
    $costing_uploads
    ~; + } else { + $add_form_fields .= qq~ +
    +
    + + +

    Upload file from PC.

    +
    +
    + ~; + } + } + + $add_form_fields .= qq~
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END DOCUMENT UPLOADS ---------------------------------------------------------------------------------------------------------------- + } + +} #------------------------------------------------------------------------------------ + +sub tab_costing_select_opts { + +my ($table,$dispfield,$where,$sec_) = @_ ; + +&db_min_ro($table,'*',$where,'','') ; +my @b = ( +"_costing_additional_services", +"_costing_game_breakdown_analytics", +"_costing_hardware_add_ons", +"_costing_installation_kits", +"_costing_match_credits", +"_costing_other", +"_costing_rental", +"_costing_software_licence", +"_costing_systems" ) ; + +foreach my $suf (@b){ + $col_name = "item" . "$suf" ; + $cnt = 0 ; + if($db{quotes_min}{$i{id}}{$col_name}){ + foreach my $col_input (split(";", $db{quotes_min}{$i{id}}{$col_name})){ + $cnt++ ; + $saved_field{"item"}{$suf}{$cnt} = $col_input ; + # &common_debug("$aa/$suffix : $cc") ; + } + } +} + +foreach my $id (keys %{$db{$table}}) { + foreach (sort keys %sec_cnt) { + $_k = substr($_,1) ; $k = substr($_,2) ; + # &common_debug("tab_select_opts : $db{$table}{$id}{type} ne $k") ; + unless ($db{$table}{$id}{type} eq $k) { next ; } + my @parts = split(/\-/,$sec_cnt{$_}) ; + for my $p_ (1 .. $parts[0]) { # item_1_costing_systems + my $field = "$p_$sec_$_k" ; #my $ucf_field = ucfirst $field ; my $chosen_field = ucfirst $field . '_chosen' ; + # $opts{"item_$p_$sec_$_k"} .= qq~~ ; + my $field_2 = "$sec_$_k" ; + # my $saved_val = $db{quotes}{$i{id}}{"item_$field"} ; + my $saved_val = $saved_field{"item"}{$field_2}{$p_} ; + + if ($saved_val) { my @valarr = split(/\:/,$saved_val) ; $saved_val = $valarr[0] ; } + + if ($saved_val eq $id) { $selected = 'SELECTED' ; } else { $selected = '' ; } + + # $opts{"item_$field"} .= qq~~ ; + $opts{"item_$field"} .= qq~~ ; + + # if ($field eq '3_costing_software_licence' or $field eq '2_costing_game_breakdown_analytics') { + if ($field eq '2_costing_systems' or $field eq '3_costing_systems' or $field eq '3_costing_software_licence' or $field eq '2_costing_game_breakdown_analytics') { + $item_type = 'input' ; + } else { + $item_type = 'select' ; + } + + unless ($got{$field}) { + $preferred_title{"item_$field"} = &common_min_print_field("item_$p_$_k") ; + if ($item_type eq 'select') { $trigger_jquery .= qq~\$("#selectItem_$field\_chosen").css( "width", "96%" ) +~ ; } $got{$field} = 1 ; + $trigger_jquery_raw .= qq~\$("#$item_type\Item_$field, #selectDiscount").change(function() { + calcCosting$field(1) ; + }); + ~; + $trigger_jquery_raw .= qq~\$("#inputQty_$field, #inputUsd_amnt_$field").change(function() { + calcCosting$field(0) ; + }); + ~;$trigger_jquery_raw .= qq~function calcCosting$field(b) + { + if (b==1) { \$("#inputUsd_amnt_$field").val(''); } + + var excl = \$("#checkboxExcl_$field"); + var item = \$("#$item_type\Item_$field"); + var usd = \$("#inputUsd_amnt_$field"); + var conv = \$("#inputCurr_amnt_$field"); + var qty = \$("#inputQty_$field"); + var ttl = \$("#inputItem_ttl_$field"); + var vat = \$("#checkboxVat_$field"); + + // console.log('DISCOUNT - item: '+item.val()+', usd: '+usd.val()) ; + + if (!item.val()) { + excl.prop("checked", true); + usd.val(""); + conv.val(""); + qty.val(""); + ttl.val(""); + vat.val(""); + // return ; + } + + calcCosting(excl,item,qty,usd,conv,vat,ttl) ; + }~; + + } + } + } + } +} #------------------------------------------------------------------------------------------ + +sub tab_camera_details_select_opts { + +my ($table,$dispfield,$where,$suffix,$rcnt) = @_ ; + +&db_min_ro('customers','id,name','','','') ; +foreach my $id (keys %{$db{customers}}) { $customers_name{$id} = $db{customers}{$id}{name} ; } + +&db_min_ro('camera_systems','id,name','','','') ; +foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + +# my $add_quote_fields = '' ; my $sql_or_where = '' ; my @sqlorwhere = () ; +# for (1 .. $rcnt) { + # $add_quote_fields .= ",quotes.camera_nr_$_$suffix" ; + # push @sqlorwhere, "quotes.camera_nr_$_$suffix>0" ; +# } +# $sql_or_where = join(" OR ",@sqlorwhere) ; + +# &db_min_ro("$table,quotes","quotes.id,$table.id$add_quote_fields",$sql_or_where,'','') ; + +# foreach my $id (keys %{$db{"$table,quotes"}}) { + # # $db{quotes}{$i{id}}{"camera_nr_$field"} + # for (1 .. 10) { + # my $field = $db{"$table,quotes"}{$id}{"camera_nr_$_$suffix"} ; + # if ($field) { + # # $camera_exists_on_quote{$field} = $id ; + # $exclude_camera_from_list{$field} = 1 ; + # # &common_debug("exclude_camera_from_list : $field") ; + # } + # } + +# } + +our %linked_vpu = () ; our %vpu_serial_nr = () ; our %vpu_camera_nr = () ; my $cnt_sel=0; my %done_quote_cam_num = () ; my %done_field = () ; +&db_min_ro($table,'id,camera_nr,serial_nr,quote_nr',"camera_nr LIKE 'vpu%'",'','') ; +foreach (keys %{$db{$table}}) { + $vpu_serial_nr{$_} = $db{$table}{$_}{serial_nr} ; + $vpu_camera_nr{$_} = $db{$table}{$_}{camera_nr} ; + + my $qnr = $db{$table}{$_}{quote_nr} ; + + if ($qnr eq $db{quotes}{$i{id}}{quote_nr}) { + $cnt_cams{$qnr}++; + # &common_debug("$cnt_cams{$qnr}. $qnr eq $db{quotes}{$i{id}}{quote_nr} ") if $qnr == 1261 ; + } + +} +&db_min_ro($table,'*',$where,'','') ; + +LOOP1: foreach my $id (sort keys %{$db{$table}}) { + + # &common_debug("1. LOOP1 $db{$table}{$id}{quote_nr} and $db{$table}{$id}{quote_nr} ne $db{quotes}{$i{id}}{quote_nr}") if $db{$table}{$id}{quote_nr} == 1261 ; + if ($db{$table}{$id}{quote_nr} and $db{$table}{$id}{quote_nr} ne $db{quotes}{$i{id}}{quote_nr}) { next ; } + + # &common_debug("2. LOOP1 event_system_id=$db{$table}{$id}{event_system_id} ") if $db{$table}{$id}{quote_nr} == 1261 ; + if ($db{$table}{$id}{event_system_id}) { $skip_event_linked_vpu{$db{$table}{$id}{event_linked_vpu}} = 1 ; next ; } # skip as it's being used for events + + # &common_debug("3. LOOP1 skip_event_linked_vpu=$skip_event_linked_vpu{$db{$table}{$id}{serial_nr}}") if $db{$table}{$id}{quote_nr} == 1261 ; + if ($skip_event_linked_vpu{$db{$table}{$id}{serial_nr}}) { next ; } # skip as it's being used for events + + # &common_debug("LOOP1 rcnt=$rcnt") if $db{$table}{$id}{quote_nr} == 1261 ; + + my $qnr = $db{$table}{$id}{quote_nr} ; + + if ($qnr eq $db{quotes}{$i{id}}{quote_nr}) { + $cnt_cams{$qnr}++; + # &common_debug("$cnt_cams{$qnr}. $qnr eq $db{quotes}{$i{id}}{quote_nr} ") if $qnr == 1261 ; + } + + # LOOP2: for (1 .. $rcnt) { + + # if ($qnr eq $db{quotes}{$i{id}}{quote_nr} and $db{$table}{$id}{quote_cam_num} eq $_) { + # $cnt_sel++ ; + # # &common_debug("$cnt_sel. $qnr eq $db{quotes}{$i{id}}{quote_nr} and $db{$table}{$id}{quote_cam_num} eq $_") if $qnr == 1261 ; + # } + # } +} + +$max_cams = $cnt_cams{$db{quotes}{$i{id}}{quote_nr}} if $cnt_cams{$db{quotes}{$i{id}}{quote_nr}} > $max_cams && $db{quotes}{$i{id}}{quote_nr} ; + +&common_debug("$cnt_cams{$db{quotes}{$i{id}}{quote_nr}} [max_cams = $max_cams]") ; + +# print "\n cnt_sel : $cnt_sel \n" ; +LOOP1: foreach my $id (sort keys %{$db{$table}}) { + + # &common_debug("exclude_camera_from_list [$exclude_camera_from_list{$id}] : [$table] : $id") ; + + if ($db{$table}{$id}{quote_nr} and $db{$table}{$id}{quote_nr} ne $db{quotes}{$i{id}}{quote_nr}) { next ; } + + if ($db{$table}{$id}{event_system_id}) { $skip_event_linked_vpu{$db{$table}{$id}{event_linked_vpu}} = 1 ; next ; } # skip as it's being used for events + if ($skip_event_linked_vpu{$db{$table}{$id}{serial_nr}}) { next ; } # skip as it's being used for events + + my ($camtype,$camcnt) = split(/\-/,$db{$table}{$id}{$dispfield}) ; + $camera_system_count{$db{$table}{$id}{quote_nr}}{$camtype}++ if $db{$table}{$id}{quote_nr} and $camtype ; + $linked_vpu{$id} = $db{$table}{$id}{linked_vpu_id} ; + + # &common_debug("[cam_qtys] quote_nr : [$db{$table}{$id}{quote_nr}] [$db{$table}{$id}{$dispfield}] [$camera_system_count{$db{$table}{$id}{quote_nr}}{$db{$table}{$id}{$dispfield}}]") if $db{$table}{$id}{quote_nr} ; + + my $qnr = $db{$table}{$id}{quote_nr} ; + + # LOOP2: for (1 .. $rcnt) { + LOOP2: for (1 .. $max_cams) { + my $field = "$_$suffix" ; + + # if ($exclude_camera_from_list{$id} and $db{quotes}{$i{id}}{"camera_nr_$_$suffix"} ne $id) { next LOOP2; ; } + # if ($exclude_camera_from_list{$id} and $db{quotes}{$i{id}}{"camera_nr_$_$suffix"} ne $id) { next LOOP1; ; } + + # my $quote_camera_id = $db{quotes}{$i{id}}{"camera_nr_$field"} ; if ($quote_camera_id) { my @valarr = split(/\:/,$quote_camera_id) ; $quote_camera_id = $valarr[0] ; } + + # # my $abrv_cam_system = substr($db{$table}{$id}{camera_nr},0,3); + # next if $seen_cnt{$_} ; + # $seen_cnt{$_} = 1 ; + + # next unless $qnr ; + my $selected = '' ; + + # if ($saved_val eq $id) { $selected = 'SELECTED' ; $sel_cam_nr{$id} = $db{$table}{$id}{camera_nr}; } else { $selected = '' ; } + # if ($db{$table}{$id}{quote_nr} eq $db{quotes}{$i{id}}{quote_nr} and $quote_camera_id eq $id) { + + # if ($qnr == 1261) { + # &common_debug("if ($qnr eq $db{quotes}{$i{id}}{quote_nr} and $_ <= $cnt_sel and not $done_quote_cam_num{$db{$table}{$id}{quote_cam_num}} and not $done_field{$field}) { ") ; + # } + + # if ($qnr eq $db{quotes}{$i{id}}{quote_nr} and $_ <= $cnt_sel and not $done_quote_cam_num{$db{$table}{$id}{quote_cam_num}} and not $done_field{$field}) { + if ($qnr eq $db{quotes}{$i{id}}{quote_nr} and $_ <= $max_cams and not $done_quote_cam_num{$db{$table}{$id}{quote_cam_num}} and not $done_field{$field}) { + $done_quote_cam_num{$db{$table}{$id}{quote_cam_num}} = 1 ; $done_field{$field} = 1 ; + $selected = 'SELECTED' ; $sel_cam_nr{$id} = $db{$table}{$id}{camera_nr}; + # &common_debug("1. quote_ref : [$db{$table}{$id}{quote_cam_num}] [$field] [$db{$table}{$id}{quote_ref}] [$_. max_cams=$max_cams]"); + $camera_details{$qnr}{$_}{$field}{quote_delivery_date} = $db{$table}{$id}{quote_delivery_date} ; + $camera_details{$qnr}{$_}{$field}{quote_active_date} = $db{$table}{$id}{quote_active_date} ; + $camera_details{$qnr}{$_}{$field}{quote_ew_date_from} = $db{$table}{$id}{quote_ew_date_from} ; + $camera_details{$qnr}{$_}{$field}{quote_ew_date_to} = $db{$table}{$id}{quote_ew_date_to} ; + $camera_details{$qnr}{$_}{$field}{quote_cam_desc} = $db{$table}{$id}{quote_cam_desc} ; + $camera_details{$qnr}{$_}{$field}{quote_cam_excl} = $db{$table}{$id}{quote_cam_excl} ; + $camera_details{$qnr}{$_}{$field}{quote_cam_num} = $db{$table}{$id}{quote_cam_num} ; + $camera_details{$qnr}{$_}{$field}{quote_nr} = $qnr ; + $camera_details{$qnr}{$_}{$field}{quote_ref} = $db{$table}{$id}{quote_ref} ; + $camera_details{$qnr}{$_}{$field}{serial_nr} = $db{$table}{$id}{serial_nr} ; + $camera_details{$qnr}{$_}{$field}{camera_nr} = $db{$table}{$id}{camera_nr} ; + $camera_details{$qnr}{$_}{$field}{id} = $id ; + } elsif ($qnr and $db{$table}{$id}{quote_cam_num}) { # camera alread linked to a quote + next ; + } + + # print "\n $qnr eq $db{quotes}{$i{id}}{quote_nr} and $db{$table}{$id}{quote_cam_num} and $_ <= $cnt_sel , field : $field" ; + # &common_debug("tab_camera_details_select_opts [$field] : [$saved_val eq $id] : $selected") ; + + my $display_field = $db{$table}{$id}{$dispfield} ; my ($system,$camcnt) = split(/\-/,$display_field) ; $camcnt+=0; $display_field .= " [$camcnt] [$db{$table}{$id}{serial_nr}]" ; # $display_field =~ s/-//g ; + + # my $opts = qq~~ ; + my $opts = qq~~ ; + + $opts_on_edit{"camera_nr_$field"} = $opts if $selected ; + + $opts{"camera_nr_$field"} .= $opts ; + + # $debugcnt++ ; &common_debug("$debugcnt. camera_nr_$field [$display_field] : [$iaction eq 'edit' and $camera_details{$q_nr}{$_}{$field}{id}] : $selected : cam camera_nr=$db{$table}{$id}{camera_nr} [max_cams=$db{quotes}{$i{id}}{max_cams}]") ; + + # # if ($username eq 'rory' and $iaction eq 'edit' and $db{quotes}{$i{id}}{quote_nr} and $db{quotes}{$i{id}}{max_cams} > 25) { + # if ($username eq 'rory' and $iaction eq 'edit' and $camera_details{$q_nr}{$_}{$field}{id} and $db{quotes}{$i{id}}{max_cams} > 25) { + # $opts_single{"camera_nr_$field"} = $opts if $selected ; + # $debugcnt++ ; &common_debug("$debugcnt. camera_nr_$field [$display_field] : [$username eq 'rory' and $iaction eq 'edit' and $camera_details{$q_nr}{$_}{$field}{id}] : $selected : cam camera_nr=$db{$table}{$id}{camera_nr} [max_cams=$db{quotes}{$i{id}}{max_cams}]") if $selected ; + # } else { + # $opts{"camera_nr_$field"} .= $opts ; + # $debugcnt++ ; &common_debug("NO *** $debugcnt. *** camera_nr_$field [$display_field] : [$username eq 'rory' and $iaction eq 'edit' and $camera_details{$q_nr}{$_}{$field}{id}] : $selected : cam camera_nr=$db{$table}{$id}{camera_nr} [max_cams=$db{quotes}{$i{id}}{max_cams}]") ; + # } + + unless ($got{$field}) { + # $preferred_title{"item_$field"} = &common_min_print_field("item_$p_$_k") ; + $trigger_jquery .= qq~\$("#selectCamera_nr_$field\_chosen").css( "width", "96%" ); +~ ; $got{$field} = 1 ; + + $trigger_jquery_raw .= qq~\$("#selectCamera_nr_$field").change(function() { + dispCamDetails$field('$_') ; + }); + ~; + + $trigger_jquery_raw .= qq~function dispCamDetails$field(f) + { + var excl = \$("#checkboxExcl_$field"); + var camnr = \$("#selectCamera_nr_$field"); + var itcode = '' ; // var itcode = \$("#inputItem_code_$field"); + var desc = \$("#inputDescription_$field"); + var qty = \$("#inputQty_$field"); + var snr = \$("#inputSerial_nr_$field"); + var ddate = \$("#datepickDelivery_date_$field"); + var adate = \$("#datepickActive_date_$field"); + + dispCamDetails(excl,camnr,qty,itcode,desc,snr,ddate,adate,f) ; + }~; + } + } +} + +} #------------------------------------------------------------------------------------------ + +sub tab_customer_select_opts { + +my ($table,$dispfield,$where,$field) = @_ ; + +&db_min_ro($table,'*',$where,'','') ; + +foreach my $id (keys %{$db{$table}}) { + + my $saved_val = $db{quotes}{$i{id}}{$field} ; + + if ($saved_val) { my @valarr = split(/\:/,$saved_val) ; $saved_val = $valarr[0] ; } + + if ($saved_val eq $id) { $selected = 'SELECTED' ; } else { $selected = '' ; } + + $opts{$field} .= qq~~ ; + unless ($got{$field}) { + # $trigger_jquery .= qq~\$("#selectQuote_to_chosen").css( "width", "96%" ); + $trigger_jquery .= qq~\$("#selectQuote_to_chosen").css( "width", "100%" ); +~ ; $got{$field} = 1 ; + + $trigger_jquery_raw .= qq~\$("#selectQuote_to").change(function() { + dispCustomer() ; + }); + ~; + + $trigger_jquery_raw .= qq~function dispCustomer() + { + var custval = \$("#selectQuote_to").val(); + var arrP = custval.split(":"); + \$("#inputContact_name").val(arrP[1]); + \$("#inputAddress").val(arrP[4]); + \$("#inputEmail").val(arrP[2]); + \$("#inputTel").val(arrP[3]); + }~; + } +} + +} #------------------------------------------------------------------------------------------ + +sub tab_build_terms_headers { + +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; + +} #------------------------------------------------------------------------------------ + +sub tab_build_terms_fields { + +my ($sec,$cnt,$id) = @_ ; + +my $exfield = "excl_$cnt\_$sec\s" ; +my $inpfield = "$sec\_$cnt" ; + +unless ($db{quote_notes}{1}{$inpfield}) { $checkit{$exfield} = 1 ; } + +my $val = ($db{$table}{$id}{$inpfield} && $db{$table}{$id}{$inpfield} ne "-1") ? $db{$table}{$id}{$inpfield} : (($db{$table}{$id}{$inpfield} && $db{$table}{$id}{$inpfield} eq "-1")) ? "" : $db{quote_notes}{1}{$inpfield} ; + +$note_display_style = '' ; $note_display_plus_btn = '' ; +# unless ($cnt==1 or $db{quote_notes}{1}{$inpfield}) { +unless ($cnt==1 || $val) { + $note_display_style = qq~style='display:none;'~ ; + $trigger_jquery_raw .= qq~ \$("#btn_$cnt\_$sec").click(function () { + \$("#$cnt\_$sec").toggle(); + \$("#btn_$cnt\_$sec").hide(); + var v = $cnt + 1 ; + \$("#btn_"+v+"\_$sec").show(); + });~ ; + if ($cnt>$cntnoteloop) { $note_display_butt = qq~display:none;~ ; } else { $note_display_butt = '' ; } + $note_display_plus_btn = qq~~; +} else { $cntnoteloop++ ; } + +$add_form_fields .= qq~
    ~ ; + +# $add_form_fields .= qq~
    ~ ; +# if ($checkit{$exfield} == 1) { $checked = 'CHECKED'; } elsif (($excl_tick{$cnt}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } + +# if ($db{$table}{$id}{$exfield} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } +$sec = "_" . $sec . "s" ; +$col_name = "excl" . "$sec" ; +$counter = 0 ; +# &db_min_ro('quotes_min', "id, excl$sec", "id = $id", '', '') ; + +foreach my $col_input (split(/\;/,$db{quotes_min}{$id}{$col_name})) { + $counter++ ; + $saved_field{"excl"}{$sec}{$counter} = $col_input ; +} + +if ($saved_field{"excl"}{$sec}{$cnt}) { $checked = 'CHECKED'; } else { $checked = '' ; } + +$label{$exfield} = 1 ; +$fcol=1 ; +$add_form_fields .= &common_min_form_checkbox_col($exfield,$checkit{$exfield},$checked) ; +$fcol=6 ; +$input_style{$inpfield} = qq~style='margin-bottom:4px;margin-top:-2px;'~ ; # add spaces between boxes +$add_form_fields .= &common_min_form_input_col($inpfield,$val,'') ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    $note_display_plus_btn
    ~ ; + +} #------------------------------------------------------------------------------------ + +sub tab_build_terms_fields_terms_and_conditions { + + my ($sec,$cnt,$id) = @_ ; + + my $exfield = "excl_$cnt\_$sec" ; + my $inpfield = "$sec" ; + my $quote_notes_field = "$sec\_$cnt" ; + + unless ($db{$table}{$id}{$inpfield}) { $checkit{$exfield} = 1 ; } + + if ($db{$table}{$id}{$inpfield}) { $selected{$db{$table}{$id}{$inpfield}} = 'SELECTED';} + + $note_display_style = '' ; + unless ($cnt==1 or $db{$table}{$id}{$inpfield}) { + $note_display_style = qq~style='display:none;'~ ; + $trigger_jquery_raw .= qq~ \$("#btn_$cnt\_$sec").click(function () { + \$("#$cnt\_$sec").toggle(); + \$("#btn_$cnt\_$sec").hide(); + var v = $cnt + 1 ; + \$("#btn_"+v+"\_$sec").show(); + });~ ; + if ($cnt>$cntnoteloop) { $note_display_butt = qq~display:none;~ ; } else { $note_display_butt = '' ; } + } else { $cntnoteloop++ ; } + + $add_form_fields .= qq~
    ~ ; + + + + # $add_form_fields .= qq~
    ~ ; + # if ($checkit{$exfield} == 1) { $checked = 'CHECKED'; } elsif (($excl_tick{$cnt}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } + $sec_2 = "_" . $sec ; + $col_name = "excl" . "$sec_2" ; + $counter = 0 ; + # &db_min_ro('quotes_min', "id, excl$sec", "id = $id", '', '') ; + + foreach my $col_input (split(";", $db{quotes_min}{$id}{$col_name})){ + $counter++ ; + $saved_field{"excl"}{$sec_2}{$counter} = $col_input ; + } + + if ($saved_field{"excl"}{$sec_2}{$cnt}) { $checked = 'CHECKED'; } else { $checked = ''; } + + # if ($db{$table}{$id}{$exfield} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + + $label{$exfield} = 1 ; + $fcol=1 ; + $add_form_fields .= &common_min_form_checkbox_col($exfield,$checkit{$exfield},$checked) ; + $fcol=6 ; + $input_style{$inpfield} = qq~style='margin-bottom:4px;margin-top:-2px;'~ ; # add spaces between boxes + $opts{$inpfield} = "" ; + for (1 .. 5){ + $quote_notes_field = "$sec\_$_" ; + next unless $db{quote_notes}{1}{$quote_notes_field} ; + $opts{$inpfield} .= qq() ; + } + $allow_deselect{$inpfield} = 1; + $add_form_fields .= &common_min_form_select_col($inpfield,$db{$table}{$id}{$inpfield},'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    $note_display_plus_btn
    ~ ; + +} #------------------------------------------------------------------------------------ + +sub tab_build_qt_right { + +my ($id,$tab,$ret) = @_ ; + +if ($tab==1) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_office_details' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $lcol = 2 ; + + $add_form_fields = '' ; + + $fcol = 9 ; + $textarea_height{notes} = 80 ; + $add_form_fields .= &common_min_form_textarea('notes',$db{$table}{$id}{notes},'') ; + $add_form_fields .= qq~
     
    ~ ; + $textarea_height{office_notes} = 80 ; + $add_form_fields .= &common_min_form_textarea('office_notes',$db{$table}{$id}{office_notes},'') ; + $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + +if ($tab==7) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_invoice_notes' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $lcol = 2 ; + + $add_form_fields = '' ; + + $fcol = 9 ; + # $add_form_fields .= qq~
     
    ~ ; + $add_form_fields .= &common_min_form_input('po_nr',$db{$table}{$id}{po_nr},'') ; + $add_form_fields .= &common_min_form_textarea('invoice_notes',$db{$table}{$id}{invoice_notes},'') ; + $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + +} #------------------------------------------------------------------------------------ + +sub tab_curr_symbols { + +$curr_symb{ZAR} = 'R'; +$curr_symb{USD} = '$'; +# $curr_symb{GBP} = '£'; +$curr_symb{GBP} = 'GBP'; +# $curr_symb{EUR} = '€'; +$curr_symb{EUR} = 'EUR'; + +our $js_curr_arr = '' ; + +foreach (keys %curr_symb) { + $js_curr_arr .= qq(currArr['$_'] = "$curr_symb{$_}";) ; + } + +} #------------------------------------------------------------------------------------ + +sub tab_build_qt_col_headers { + +my ($sec) = @_ ; + +my $style_vat = '' ; if ($no_vat{$sec}) { $style_vat = 'style="display:none;"' ; } + +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +# $add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; + +%cost_desc = () ; %def_qty = () ; %def_zar = () ; %min_zar = () ; %vat_tick = () ; %excl_tick = () ; + +} #---------------------------------------------------------------------------------------- + +sub tab_content_box { + +my ($sec_name,$sec_col) = @_ ; + +$fcol=9 ; +$print_box_content_rows .= &common_min_box_top('indent-left',$sec_name,$sec_col,$cam_box_icon); +# $print_box_content_rows .= qq~
    ~ ; +$print_box_content_rows .= qq~$add_form_fields~; +$print_box_content_rows .= &common_min_box_foot; + +} #---------------------------------------------------------------------------------------- + +sub tab_cnt { + +our %cntxt = () ; + +$cntxt{1} = 'one' ; +$cntxt{2} = 'two' ; +$cntxt{3} = 'three' ; +$cntxt{4} = 'four' ; +$cntxt{5} = 'five' ; +$cntxt{6} = 'six' ; +$cntxt{7} = 'seven' ; +$cntxt{8} = 'eight' ; +# $cntxt{9} = 'nine' ; + +} #---------------------------------------------------------------------------------------- + +sub tab_names { + +my ($tab) = @_ ; + +my $tabname = '' ; + + if ($tab==1) { $tabname = 'Quote Details' ; } +elsif ($tab==2) { $tabname = 'Costing' ; } +elsif ($tab==3) { $tabname = 'Costing Other' ; } +elsif ($tab==4) { $tabname = 'Purchase Summary' ; } +elsif ($tab==5) { $tabname = 'Notes' ; } +elsif ($tab==6) { $tabname = 'Camera Details' ; } +elsif ($tab==7) { $tabname = 'Invoice Details' ; } +# elsif ($tab==7) { $tabname = 'Extended Warranty' ; } +# elsif ($tab==8) { $tabname = 'Rental' ; } +elsif ($tab==8) { $tabname = 'Document Uploads' ; } + +return ($tabname) ; + +} #------------------------------------------------------------------------------------ + +sub tab_hash { + +# &tabs_get_default_totals ; + +# for (1 .. 8) { + # my $tname = &tab_names($_) ; + + # our $ret_pdf_link_sec = '' ; # _sa_out+16|_cl_del+13|_sa_in+17|_des_sa+13| + + # &tab_build_qt_left('',$_,1) ; + # &tab_build_qt_right('',$_,1) ; + + # $tabcnt{$tname} = $_ ; + # $tabsec{$tname} = $ret_pdf_link_sec ; + # } + +} #------------------------------------------------------------------------------------ + +sub tab_sec_det { + +my ($sec) = @_ ; + +my ($sec_nam,$sec_cnt,$sec_col) ; + +$sec_col = '71919b' ; # '85acb8' ; +$sec_cnt = 20 ; +$sec_nam = substr($sec,1) ; +@array = split(/\_/,$sec_nam); my @sec_nam = map ucfirst, @array; +$sec_nam = join(" ", @sec_nam) ; + +if ($sec eq '_costing') { + $sec_nam = 'Camera System Costing' ; + for (1 .. 20) { $vat_tick{$_} = 1 ; } + } + +return ($sec_nam,$sec_cnt,$sec_col) ; + +} #------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/_FromProd/v1.0/tabs_test.pm b/libs/modules/_FromProd/v1.0/tabs_test.pm new file mode 100644 index 0000000..6d7cbc3 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/tabs_test.pm @@ -0,0 +1,2266 @@ +our %sec_cnt = ('a_systems' => "3-Systems", 'b_software_licence' => "3-Software Licence (Monthly Fee)", 'c_game_breakdown_analytics' => "2-Game Breakdown and Analytics (Annual Fee)", 'd_installation_kits' => "7-Installation Kits", 'e_hardware_add_ons' => "7-Hardware Add Ons", 'f_additional_services' => "7-Additional Services", 'g_match_credits' => "4-Match Credits", 'h_other' => "5-Other", 'i_rental' => "2-Rental" , "j_hardware" => "1-Hardware"); + +sub tabs_costings_forms_jquery { + + $onload .= qq~onload="add_up_totals('costing',\$('#inputRoe').val(),1);"~ if $iaction ne 'add' ; + + $trigger_jquery_raw .= qq~ + + let prev_currency = \$("#selectCurrency").val() ; + + \$("#selectCurrency").change(function () { + + if ((\$(this).val() == 'USD' && \$("input[name='roe']").val() == '20.00' && prev_currency != 'ZAR') || (prev_currency != 'ZAR' && \$(this).val() != 'ZAR' && prev_currency != 'USD' && \$(this).val() != 'USD')) { + return ; + } + let roe = 1 ; + if (\$(this).val() == 'USD') { + roe = 20 ; + } + + \$("input[name='roe']").val(roe.toFixed(2)) ; + + let j = 1 ; + + let tab = "costing" ; + + if (\$(this).val() == 'ZAR') { + while (\$("#"+tab+"_"+j).html()) { + if (!\$("#checkboxVat_"+tab+"_"+j).is(":checked")) { + \$("#checkboxVat_"+tab+"_"+j).prop('checked',true) ; + } + j++ ; + } + } else if (\$(this).val() != 'ZAR' && prev_currency == 'ZAR') { + while (\$("#"+tab+"_"+j).html()) { + if (\$("#checkboxVat_"+tab+"_"+j).is(":checked")) { + \$("#checkboxVat_"+tab+"_"+j).prop('checked',false) ; + } + j++ ; + } + } + + prev_currency = \$(this).val() ; + + add_up_totals("costing",roe,1) ; + + }) ; + + \$("input[name='roe']").change(function () { + if (\$("#selectCurrency").val() == 'ZAR' && \$(this).val() != '1.00') { + \$("input[name='roe']").val("1.00") ; + return ; + } + update_with_roe(\$(this).val()) ; + }) ; + + function update_with_roe (roe="") { + if (roe < 0 || !roe || roe == "") { + roe = 1 ; + } + \$("input[name='roe']").val(parseFloat(roe).toFixed(2)) ; + let sub_total = 0 ; let vat_total = 0 ; + add_up_totals("costing",roe,1) ; + } + + function add_up_totals (tab,roe,recalc_totals) { + + let sub_total = 0 ; let vat_total = 0 ; + + let i = 1 ; + + while (\$("#"+tab+"_"+i).html()) { + + if (\$("#inputDescription_"+tab+"_"+i).val()) { + if (\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { i++ ; continue ; } + let ttl = 0 ; + if (recalc_totals) { + ttl = parseFloat(\$("#inputZar_amount_"+tab+"_"+i).val()) * parseFloat(\$("#inputQty_"+tab+"_"+i).val()) * parseFloat(roe) ; + } else { + ttl = parseFloat(\$("#inputTotal_"+tab+"_"+i).val().replace(/,/g, '')) + } + \$("#inputTotal_"+tab+"_"+i).val(ttl.toFixed(2)) ; + if (!\$("#inputTotal_"+tab+"_"+i).val() || \$("#inputTotal_"+tab+"_"+i).val() == "NaN") { + \$("#inputTotal_"+tab+"_"+i).val("0.00") ; + ttl = 0 ; + } + sub_total += ttl ; + if (\$("#checkboxVat_"+tab+"_"+i).is(":checked")) { + vat_total += ttl*0.15 ; + } + } else if (!\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { + \$("#checkboxExcl_"+tab+"_"+i).prop('checked',true) ; + } + i++ ; + } + + \$("input[name='subtotal']").val(sub_total.toFixed(2)) ; + \$("input[name='vat']").val(vat_total.toFixed(2)) ; + \$("input[name='total']").val((sub_total+vat_total).toFixed(2)) ; + + } + + \$("#two").on("click","[id^='checkboxVat_']", function () { + changed_vat(this.id) ; + }) ; + + \$("#two").on("click","[id^='checkboxExcl_']", function () { + changed_others(this.id) ; + }) ; + + \$("#two").on("change","[id^='inputDescription_'],[id^='inputQty_'],[id^='inputZar_amount_']", function () { + changed_others(this.id) ; + }) ; + + function get_tab (id) { + let tab = "" ; + if (id.includes("costing")) { + tab = "costing" ; + } + return tab ; + } + + function changed_vat (id) { + let tab = get_tab (id) ; + let row_nr = get_row_nr(id) ; + calc_totals(row_nr,tab) ; + } + + function changed_others (id) { + + let row_nr = get_row_nr(id) ; + let firstIndex = id.indexOf('_'); + let col = id.substring(0,firstIndex); + let tab = get_tab (id) ; + + if (col == "inputZar") { + let inp = parseFloat(\$("#"+id).val()) ; + inp = parseFloat(inp) ; + \$("#"+id).val(inp.toFixed(2)) ; + } + + calc_totals(row_nr,tab) ; + } + + function calc_totals (row_cnt,tab) { + + var qty = \$("#inputQty_"+tab+"_"+row_cnt) ; + var usd = \$("#inputZar_amount_"+tab+"_"+row_cnt) ; + var conv = \$("#inputTotal_"+tab+"_"+row_cnt) ; + var excl = \$("#checkboxExcl_"+tab+"_"+row_cnt) ; + var item = \$("#inputDescription_"+tab+"_"+row_cnt) ; + + if (!usd.val() && !qty.val()) { + if (!item.val()) { + excl.prop("checked",true) ; + } else if (item.val() && excl.is(":checked")) { + excl.prop("checked",false) ; + } + return ; + } + + var vat = \$("#checkboxVat_"+tab+"_"+row_cnt) ; + + if (!item.val()) { + excl.prop("checked",true) ; + vat.prop("checked",true) ; + qty.val("") ; + usd.val("") ; + conv.val("") ; + } else if (item.val() && excl.is(":checked")) { + // excl.prop("checked",false) ; + } + + if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) ; } + + let roe = parseFloat(\$("#inputRoe").val()) ; + + let ttl = usd.val() * qty.val() * roe ; + + conv.val(ttl.toFixed(2)) ; + + let sub_total = 0 ; let vat_total = 0 ; + + let nr_of_rows = 50 ; + + add_up_totals (tab,roe,0) ; + + } + + function add_costing_row (row_nr,tab,options1,options2) { + + let tindex = "$tindex" ; + tindex = parseInt(tindex) ; + row_nr = parseInt(row_nr) ; + tindex = tindex - 10*(1+50-row_nr) ; + + row_nr = row_nr + 1 ; + + let row = "
    " ; + + row = row+add_checkbox(row_nr,"excl_"+tab+"_"+row_nr,"checkboxExcl_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + // row = row+add_select(row_nr,"description_"+tab+"_"+row_nr,"selectDescription_"+tab+"_"+row_nr,"Select Description "+row_nr,options1,tindex,2,90,'','') ; tindex++ ; + row = row+add_input(row_nr,"description_"+tab+"_"+row_nr,"inputDescription_"+tab+"_"+row_nr,"Description "+row_nr,tindex,'',2) ; tindex++ ; + row = row+add_input(row_nr,"qty_"+tab+"_"+row_nr,"inputQty_"+tab+"_"+row_nr,"Qty "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"amount_usd_"+tab+"_"+row_nr,"inputZar_amount_"+tab+"_"+row_nr,"ZAR Amount "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"amount_ttl_"+tab+"_"+row_nr,"inputTotal_"+tab+"_"+row_nr,"Total Amount "+row_nr,tindex,"readonly",1) ; tindex++ ; + row = row+add_checkbox(row_nr,"vat_"+tab+"_"+row_nr,"checkboxVat_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + + row = row+"
    " ; + row = row+"
    " ; + + return row ; + } + + function get_row_nr (id) { + let lastIndex = id.lastIndexOf('_'); + lastIndex = parseInt(lastIndex) ; + let row_nr = id.substring(1+lastIndex); + row_nr = parseInt(row_nr) ; + return row_nr ; + } + + function add_checkbox (row_nr,field_name,field_id,tindex,fcol) { + let checkbox = "
    " ; + return checkbox ; + } + + function add_input (row_nr,field_name,field_id,placeholder,tindex,readonly,fcol) { + let input = "
    " ; + return input ; + } + + function add_select (row_nr,field_name,field_id,placeholder,options,tindex,fcol,width,div_id,hide_div) { + let select = "
    " ; + select = select + add_select_raw(row_nr,field_name,field_id,placeholder,options,tindex,width) ; + select = select + "
    " ; + return select ; + } + + function add_select_raw (row_nr,field_name,field_id,placeholder,options,tindex,width) { + let select_raw = "
    " ; + return select_raw ; + } + + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub tabs_get_default_totals { + + my ($id) = @_ ; + + # our %sec_cnt = ('a_systems' => "3-Systems", 'b_software_licence' => "3-Software Licence (Monthly Fee)", 'c_game_breakdown_analytics' => "2-Game Breakdown and Analytics (Annual Fee)", 'd_installation_kits' => "7-Installation Kits", 'e_hardware_add_ons' => "7-Hardware Add Ons", 'f_additional_services' => "7-Additional Services", 'g_match_credits' => "4-Match Credits", 'h_other' => "5-Other", 'i_rental' => "2-Rental" , "j_hardware" => "1-Hardware"); + # our %sec_cnt = ('a_other' => "5-Other"); + our %sec_cnt = ('a_systems' => "3-Systems", 'b_software_licence' => "3-Software Licence (Monthly Fee)", 'c_game_breakdown_analytics' => "2-Game Breakdown and Analytics (Annual Fee)", 'd_installation_kits' => "7-Installation Kits", 'e_hardware_add_ons' => "7-Hardware Add Ons", 'f_additional_services' => "7-Additional Services", 'g_match_credits' => "4-Match Credits", 'h_rental' => "2-Rental" , "j_hardware" => "1-Hardware"); + + our %default_totals = () ; + + our @ttlarr = ("one_time_fee","monthly_recurring_fee","annual_fee") ; + our @ttlarr2 = ("subtotal","vat","total") ; + + my $needs_to_update_totals = ($db{$table}{$id}{total_one_time_fee} !~ /;/ && $db{quotes_min}{$id}{item_ttl_costing_other} =~ /(?
     
    ~ ; + + +$trigger_jquery_raw .= qq~ + + if (!\$("#checkboxQuote_accepted").is(":checked") && !\$("#checkboxQuote_pending").is(":checked") && !\$("#checkboxQuote_cancelled").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked","true") ; + } + \$("#checkboxQuote_accepted,#checkboxQuote_pending,#checkboxQuote_cancelled").click( function () { + + if (this.id != 'checkboxQuote_accepted' && \$("#checkboxQuote_accepted").is(":checked")) { + \$("#checkboxQuote_accepted").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_pending' && \$("#checkboxQuote_pending").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked",false) ; + } + + if (this.id != 'checkboxQuote_cancelled' && \$("#checkboxQuote_cancelled").is(":checked")) { + \$("#checkboxQuote_cancelled").prop("checked",false) ; + } + + if (!\$("#checkboxQuote_accepted").is(":checked") && !\$("#checkboxQuote_pending").is(":checked") && !\$("#checkboxQuote_cancelled").is(":checked")) { + \$("#checkboxQuote_pending").prop("checked","true") ; + } + + }); + +~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + +# if ($tab == 2) { # Costing + + # # --------------- START COSTING ---------------------------------------------------------------------------------------------------------------- + + # $add_form_fields = '' ; + + # $lcol = 1 ; $fcol = 2 ; + # $preferred_title{currency} = 'Currency' ; + # $add_form_fields .= &common_min_form_select('currency',$db{$table}{$id}{currency},1) ; + # $trigger_jquery .= qq~\$("#selectCurrency_chosen").css( "width", "96%" );~ ; + # $preferred_title{roe} = ' ROE ' ; $fcol = 1 ; + # $add_form_fields .= &common_min_form_label_col('roe') ; + # $add_form_fields .= &common_min_form_input_col('roe',$db{$table}{$id}{roe},1) ; + # $add_form_fields .= qq~
    ~ ; + # my $sec = '_costing' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # return if $ret ; + + # &tab_costing_select_opts('price_list','description',"`excl`<>'1'",$sec) ; + + # # &db_min_ro('quotes_pdf_titles', '*', "quote_id = $id", '', '') ; + # foreach (keys %{$db{quotes_pdf_titles}}){ + # next unless $db{quotes_pdf_titles}{$_}{quote_id} == $id ; + # $old_title_to_new_title{$db{quotes_pdf_titles}{$_}{old_name}}{$db{quotes_pdf_titles}{$_}{quote_id}} = $db{quotes_pdf_titles}{$_}{new_name} ; + # } + + # foreach (sort keys %sec_cnt) { + # $_k = substr($_,1) ; + # next if $_k eq '_hardware' ; + # my @parts = split(/\-/,$sec_cnt{$_}) ; + + # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + # # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + # $fcol = 3 ; + # $add_form_fields .= qq~
    PDF title :
    ~ ; + # # $add_form_fields .= qq~
    PDF TITLE :
    ~ ; + # if ($old_title_to_new_title{$parts[1]}{$id} and $old_title_to_new_title{$parts[1]}{$id} ne $parts[1]){ + # $add_form_fields .= &common_min_form_input_col($_k, $old_title_to_new_title{$parts[1]}{$id}) ; + # } + # else { + # $add_form_fields .= &common_min_form_input_col($_k,'') ; + # } + + # $add_form_fields .= qq~
    ~ ; + # &tab_build_qt_col_headers("$sec$_k") ; + # &build_cost_form($id,$tab,$parts[0],"$sec$_k") ; + # if ($_k eq '_systems') { + # $preferred_title{'systems_included'} = ' ' ; $preferred_placeholder{'systems_included'} = 'Included' ; $fcol = 3 ; + # $add_form_fields .= &common_min_form_textarea('systems_included',$db{$table}{$id}{systems_included},'') ; + # } + # if ($_k eq '_rental') { + # $preferred_title{'rental_included'} = ' ' ; $preferred_placeholder{'rental_included'} = 'Included' ; $fcol = 3 ; + # $add_form_fields .= &common_min_form_textarea('rental_included',$db{$table}{$id}{rental_included},'') ; + # } + # if ($_k eq '_other') { + # $preferred_title{'other_included'} = ' ' ; $preferred_placeholder{'other_included'} = 'Included' ; $fcol = 3 ; + # $add_form_fields .= &common_min_form_textarea('other_included',$db{$table}{$id}{other_included},'') ; + # } + # } + + # $add_form_fields .= qq~
     
    ~ ; + # $add_form_fields .= qq~
    PDF total :
    ~ ; + + # $lcol = 3 ; + + # if ($old_title_to_new_title{"Hardware"}{$id} and $old_title_to_new_title{"Hardware"}{$id} ne "Hardware"){ + # $add_form_fields .= &common_min_form_input_col('_hardware', $old_title_to_new_title{"Hardware"}{$id}) ; + # } + # else { + # $add_form_fields .= &common_min_form_input_col('_hardware','') ; + # } + + # my @ttlarr_labels = ("sub_total","vat_total","grand_total") ; + # $lcol = 1 ; $fcol = 1 ; + # foreach (@ttlarr_labels) { + # $readonly{$_} = "READONLY" ; + # my $val = $db{$table}{$id}{$_} ; $val = '0.00' unless $val ; + # $type = 'hidden' ; $add_form_fields .= &common_min_form_input_col($_,$val) ; $type = '' ; + # $lcol = 1 ; $add_form_fields .= &common_min_form_label_col($_) ; + # } + + # $add_form_fields .= qq~
    ~ ; + + # $lcol = 1 ; $fcol = 1 ; + + # foreach my $a (@ttlarr) { + + # $readonly{$a} = "READONLY" ; + + # $add_form_fields .= qq~
    ~ ; + + # $lcol = 2 ; + # $add_form_fields .= &common_min_form_label_col($a) ; + # $lcol = 1 ; + + # foreach my $b (@ttlarr2) { + # $field = "$b\_$a\_1" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # my $val = ($default_totals{$field}{1}) ? $default_totals{$field}{1} : '0.00' ; + # $add_form_fields .= &common_min_form_input_col($field,$val) ; + # } + # $add_form_fields .= qq~
    ~ ; + + # } + + # $add_form_fields .= qq~
     
    ~ ; + + # &tab_content_box($sec_name,$sec_col) ; + + # # --------------- END COSTING ---------------------------------------------------------------------------------------------------------------- + + + # # $trigger_jquery_raw .= qq~ + + # # function get_tab (id) { + # # let tab = "" ; + # # if (id.includes("workings_event")) { + # # tab = "workings_event" ; + # # } else if (id.includes("costing_event")) { + # # tab = "costing_event" ; + # # } + # # return tab ; + # # } + + # # function changed_vat (id) { + # # let tab = get_tab (id) ; + # # let row_nr = get_row_nr(id) ; + # # calc_totals(row_nr,tab) ; + # # } + + # # function changed_others (id) { + + # # let row_nr = get_row_nr(id) ; + # # let firstIndex = id.indexOf('_'); + # # let col = id.substring(0,firstIndex); + # # let tab = get_tab (id) ; + # # if (col == "inputAmount") { + # # let inp = parseFloat(\$("#"+id).val()) ; + # # inp = parseFloat(inp) ; + # # \$("#"+id).val(inp.toFixed(2)) ; + # # } else if (\$("#selectDescription_"+tab+"_"+row_nr).val() && \$("#selectDescription_"+tab+"_"+row_nr).val() != 14 && \$("#selectOperator_"+tab+"_"+row_nr).val()) { + # # // \$("#selectOperator_"+tab+"_"+row_nr).val("") ; + # # // \$("#selectOperator_"+tab+"_"+row_nr).trigger("chosen:updated") ; + # # } + # # // else if (col == "selectOperator" && \$("#selectDescription"+tab+"_"+row_nr).val() != 14) { + + # # // } + + # # if (col == "selectOperator") { // || (col == "selectDescription" && \$("#selectDescription_"+tab+"_"+row_nr).val( + # # return ; + # # } + + # # calc_totals(row_nr,tab) ; + # # } + + # # // \$("$vat_field_ids_string").change(function() { + # # \$("#content").on("change","[id^='checkboxVat_']", function () { + # # const id = this.id ; + # # changed_vat(id) ; + # # }); + + # # // \$("$excl_field_ids_string,$description_field_ids_string,$qty_field_ids_string,$amount_usd_field_ids_string,$operator_field_ids_string").change(function() { + # # \$("#content").on("change","[id^='checkboxExcl_'],[id^='selectDescription_'],[id^='inputQty_'],[id^='inputZar_amount_'],[id^='selectOperator_workings_event_']", function () { + # # const id = this.id ; + # # changed_others(id) ; + # # }); + # # ~ ; + + # # $trigger_jquery_raw .= qq~ + + # # \$("#content").on("click","[id^='btn_workings_event_'],[id^='btn_costing_event_']", function () { + # # // \$("$btn_ids_string").click(function () { + # # const id = this.id ; + # # let tab = get_tab (id) ; + + # # console.log("id : "+id) ; + # # console.log("tab : "+tab) ; + + # # add_quote_expenses_row_all(id,tab) ; + # # }); + + # # function add_quote_expenses_row_all (id,tab) { + + # # let row_nr = get_row_nr(id) ; + # # \$("#"+tab+"_"+row_nr).show(); + # # let row_html = "" ; + # # if (tab == "workings_event") { + # # row_html = add_quote_expenses_row(row_nr,tab,"$description_options_workings","$operator_options") ; + # # } else if (tab == "costing_event") { + # # row_html = add_quote_expenses_row(row_nr,tab,"$description_options_costing","") ; + # # } + # # \$("#"+tab+"_"+row_nr).html(row_html); + # # // \$("#$suffix\_"+row_nr).trigger("chosen:updated") ; + + # # \$("#selectDescription_"+tab+"_"+row_nr).chosen({ allow_single_deselect:true }) ; + + # # if (tab == "workings_event") { + # # \$("#selectOperator_workings_event_"+row_nr).chosen({ allow_single_deselect:true }); + # # \$("#inputRemarks_workings_event_"+row_nr).css("text-align","") ; + # # \$("#inputSupplier_workings_event_"+row_nr).css("text-align","") ; + # # \$("#inputRef_nr_workings_event_"+row_nr).css("text-align","") ; + # # } + + # # \$("#btn_"+tab+"_"+row_nr).hide(); + # # var v = row_nr + 1 ; + + # # // \$("#btn_$suffix\_"+v).css("padding-left","16px") ; + # # \$("#btn_"+tab+"_"+v).html("") ; + # # \$("#btn_"+tab+"_"+v).show(); + # # \$("#btn_row_"+tab+"_"+v).show() ; + # # \$("#2_"+tab+"_"+row_nr).show() ; + + # # \$("#checkboxExcl_"+tab+"_"+row_nr).prop('checked',false) ; + + # # // \$("#"+tab+"_"+row_nr).on("change","#checkboxVat_"+tab+"_"+row_nr+"", function() { + # # // const id = this.id ; + # # // changed_vat(id) ; + # # // }); + + # # // \$("#"+tab+"_"+row_nr).on("change","#checkboxExcl_"+tab+"_"+row_nr+",#selectDescription_"+tab+"_"+row_nr+",#selectOperator_"+tab+"_"+row_nr+",#inputQty_"+tab+"_"+row_nr+",#inputZar_amount_"+tab+"_"+row_nr+"", function() { + # # // const id = this.id ; + # # // changed_others(id) ; + # # // }); + + # # } + + # # ~ if $btn_ids_string ; + + # # $trigger_jquery_raw .= qq~ + + # # \$("#selectCurrency").change(function () { + + # # }) ; + + # # \$("input[name='roe']").change(function () { + + # # let roe = \$(this).val() ; + # # if (roe < 0 || !roe) { + # # roe = 1 ; + # # } + # # \$(this).val(parseFloat(roe).toFixed(2)) ; + + # # var sub_total = 0 ; var vat_total = 0 ; var sub_total_quote = 0 ; var vat_total_quote = 0 ; + + # # [sub_total,vat_total] = add_up_totals("workings_event",50,roe,1) ; + # # [sub_total_quote,vat_total_quote] = add_up_totals("costing_event",30,roe,1) ; + + # # // // // \$("input[name='income']").val((sub_total_quote+vat_total_quote).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # \$("input[name='income']").val((sub_total_quote+vat_total_quote).toFixed(2)) ; + # # \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + # # update_overall_totals(sub_total,vat_total,"workings_event") ; + # # update_overall_totals(sub_total_quote,vat_total_quote,"costing_event") ; + + # # }) ; + + # # function add_up_totals (tab,nr_of_rows,roe,recalc_totals) { + + # # let sub_total = 0 ; let vat_total = 0 ; + # # for (let i=1; i<=nr_of_rows; i++) { + # # if (!\$("#"+tab+"_"+i).html()) { break ; } + # # if (\$("#selectDescription_"+tab+"_"+i).val()) { + # # if (\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { continue ; } + # # let ttl = 0 ; + # # if (recalc_totals) { + # # ttl = parseFloat(\$("#inputZar_amount_"+tab+"_"+i).val()) * parseFloat(\$("#inputQty_"+tab+"_"+i).val()) * parseFloat(roe) ; + # # } else { + # # ttl = parseFloat(\$("#inputTotal_"+tab+"_"+i).val().replace(/,/g, '')) + # # } + # # // // // // \$("#inputTotal_"+tab+"_"+i).val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # \$("#inputTotal_"+tab+"_"+i).val(ttl.toFixed(2)) ; + # # if (!\$("#inputTotal_"+tab+"_"+i).val() || \$("#inputTotal_"+tab+"_"+i).val() == "NaN") { + # # \$("#inputTotal_"+tab+"_"+i).val("0.00") ; + # # ttl = 0 ; + # # } + # # sub_total += ttl ; + # # if (\$("#checkboxVat_"+tab+"_"+i).is(":checked")) { + # # vat_total += ttl*0.15 ; + # # } + # # } else if (!\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { + # # \$("#checkboxExcl_"+tab+"_"+i).prop('checked',true) ; + # # } + # # } + # # return [sub_total,vat_total] ; + # # } + + # # // function getNum(val) { + + # # // if (isNaN(val)) { + # # // return 0; + # # // } + # # // return val; + # # // } + + # # function calc_totals (row_cnt,tab) { + + # # var qty = \$("#inputQty_"+tab+"_"+row_cnt) ; + # # var usd = \$("#inputZar_amount_"+tab+"_"+row_cnt) ; + # # var conv = \$("#inputTotal_"+tab+"_"+row_cnt) ; + # # var excl = \$("#checkboxExcl_"+tab+"_"+row_cnt) ; + # # var item = \$("#selectDescription_"+tab+"_"+row_cnt) ; + + # # if (!usd.val() && !conv.val() && !usd.val()) { + # # // console.log("skip calc_totals_workings") ; + # # if (!item.val()) { + # # excl.prop("checked",true) ; + # # } + # # return ; + # # } + + # # var vat = \$("#checkboxVat_"+tab+"_"+row_cnt) ; + + # # if (!item.val()) { + + # # excl.prop("checked",true) ; + # # vat.prop("checked",true) ; + # # qty.val("") ; + # # usd.val("") ; + # # conv.val(""); + # # if (tab == "workings_event") { + # # var rem = \$("#inputRemarks_"+tab+"_"+row_cnt) ; + # # var sup = \$("#inputSupplier_"+tab+"_"+row_cnt) ; + # # var ref = \$("#inputRef_nr_"+tab+"_"+row_cnt) ; + # # var op = \$("#selectOperator_"+tab+"_"+row_cnt) ; + # # rem.val("") ; + # # sup.val("") ; + # # ref.val("") ; + # # op.val("") ; + # # op.trigger("chosen:updated") ; + # # } + # # } else if (excl.is(":checked") && item.val() && conv.val() == "0.00") { + # # excl.prop("checked",false) ; + # # } + + # # if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) ; } + + # # let roe = parseFloat(\$("#inputRoe").val()) ; + + # # let ttl = usd.val() * qty.val() * roe ; + + # # // // // conv.val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # conv.val(ttl.toFixed(2)) ; + + # # let sub_total = 0 ; let vat_total = 0 ; + + # # let nr_of_rows = 50 ; + # # if (tab == "costing_event") { + # # nr_of_rows = 30 ; + # # } + + # # [sub_total,vat_total] = add_up_totals (tab,nr_of_rows,roe,0) ; + + # # if (tab == "workings_event") { + # # // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + # # update_overall_totals(sub_total,vat_total,tab) ; + # # } else { + # # // // // \$("input[name='income']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # \$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; + # # update_overall_totals(sub_total,vat_total,tab) ; + # # // update_overall_totals_costings(sub_total,vat_total) ; + # # } + # # } + + # # function update_overall_totals (sub_total,vat_total,tab) { + + # # let profit_loss = parseFloat(\$("input[name='income']").val().replace(/,/g, '')) - parseFloat(\$("input[name='expenses']").val().replace(/,/g, '')) ; + + # # // // // \$("input[name='profit_loss']").val(profit_loss.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # // // // \$("input[name='sub_total_"+tab+"']").val(sub_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # // // // \$("input[name='vat_total_"+tab+"']").val(vat_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # // // // \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + + # # \$("input[name='profit_loss']").val(profit_loss.toFixed(2)) ; + # # \$("input[name='sub_total_"+tab+"']").val(sub_total.toFixed(2)) ; + # # \$("input[name='vat_total_"+tab+"']").val(vat_total.toFixed(2)) ; + # # \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toFixed(2)) ; + # # } + + # # function add_quote_expenses_row (row_nr,tab,options1,options2) { + + # # let tindex = $tindex ; + # # tindex = parseInt(tindex) ; + # # row_nr = parseInt(row_nr) ; + # # tindex = tindex - 10*(1+50-row_nr) ; + + # # let row = add_checkbox(row_nr,"excl_"+tab+"_"+row_nr,"checkboxExcl_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + + # # row = row+""+add_select(row_nr,"description_"+tab+"_"+row_nr,"selectDescription_"+tab+"_"+row_nr,"Select Description "+row_nr,options1,tindex,2,90,'','') ; tindex++ ; + # # if (tab == "workings_event") { + # # row = row+add_select(row_nr,"operator_workings_event_"+row_nr,"selectOperator_workings_event_"+row_nr,"Select Operator "+row_nr,options2,tindex,2,90,'','') ; tindex++ ; + # # row = row+add_input(row_nr,"remarks_workings_event_"+row_nr,"inputRemarks_workings_event_"+row_nr,"Remarks "+row_nr,tindex,'',1) ; tindex++ ; + # # row = row+add_input(row_nr,"supplier_workings_event_"+row_nr,"inputSupplier_workings_event_"+row_nr,"Supplier "+row_nr,tindex,'',1) ; tindex++ ; + # # row = row+add_input(row_nr,"ref_nr_workings_event_"+row_nr,"inputRef_nr_workings_event_"+row_nr,"Ref Nr "+row_nr,tindex,'',1) ; tindex++ ; + # # } + # # row = row+add_input(row_nr,"qty_"+tab+"_"+row_nr,"inputQty_"+tab+"_"+row_nr,"Qty "+row_nr,tindex,'',1) ; tindex++ ; + # # row = row+add_input(row_nr,"amount_usd_"+tab+"_"+row_nr,"inputZar_amount_"+tab+"_"+row_nr,"Amount "+row_nr,tindex,'',1) ; tindex++ ; + # # row = row+add_input(row_nr,"amount_ttl_"+tab+"_"+row_nr,"inputTotal_"+tab+"_"+row_nr,"Total Amount "+row_nr,tindex,"readonly",1) ; tindex++ ; + # # row = row+add_checkbox(row_nr,"vat_"+tab+"_"+row_nr,"checkboxVat_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + # # return row ; + # # } + # # ~ ; + +# } + +if ($tab==2) { # Costing + + # --------------- START COSTING ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + $lcol = 1 ; $fcol = 2 ; + + $db{$table}{$id}{currency} = "ZAR" unless $db{$table}{$id}{currency} ; + + $opts{currency} = qq~~ ; + $opts{currency} =~ s/value="\Q$db{$table}{$id}{currency}\E"/value="$db{$table}{$id}{currency}" SELECTED/g ; + + $add_form_fields .= &common_min_form_select('currency',$db{$table}{$id}{currency},1) ; + $trigger_jquery .= qq~\$("#selectCurrency_chosen").css( "width", "96%" );~ ; + $preferred_title{roe} = ' ROE ' ; $fcol = 1 ; + $add_form_fields .= &common_min_form_label_col('roe') ; + + $db{$table}{$id}{roe} = "1.00" unless $db{$table}{$id}{roe} ; + + $add_form_fields .= &common_min_form_input_col('roe',$db{$table}{$id}{roe},1) ; + $add_form_fields .= qq~
    ~ ; + + my $sec = 'costing' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + %sec_cnt = ('a' => "10-Other"); + + foreach (sort keys %sec_cnt) { + + $_k = substr($_,1) ; + next if $_k eq '_hardware' ; + my @parts = split(/\-/,$sec_cnt{$_}) ; + # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + $fcol = 3 ; + # $add_form_fields .= qq~
    PDF title :
    ~ ; + + # if ($old_title_to_new_title{$parts[1]}{$id} and $old_title_to_new_title{$parts[1]}{$id} ne $parts[1]) { + # $add_form_fields .= &common_min_form_input_col($_k, $old_title_to_new_title{$parts[1]}{$id}) ; + # } else { + # $add_form_fields .= &common_min_form_input_col($_k,'') ; + # } + + # $add_form_fields .= qq~
    ~ ; + &tab_build_qt_col_headers("$sec$_k") ; + &build_cost_form($id,$tab,$parts[0],"$sec$_k") ; + + # if ($_k eq '_systems') { + # $preferred_title{'systems_included'} = ' ' ; $preferred_placeholder{'systems_included'} = 'Included' ; $fcol = 3 ; + # $add_form_fields .= &common_min_form_textarea('systems_included',$db{$table}{$id}{systems_included},'') ; + # } + + # if ($_k eq '_rental') { + # $preferred_title{'rental_included'} = ' ' ; $preferred_placeholder{'rental_included'} = 'Included' ; $fcol = 3 ; + # $add_form_fields .= &common_min_form_textarea('rental_included',$db{$table}{$id}{rental_included},'') ; + # } + + # if ($_k eq '_other') { + # $preferred_title{'other_included'} = ' ' ; $preferred_placeholder{'other_included'} = 'Included' ; $fcol = 3 ; + # $add_form_fields .= &common_min_form_textarea('other_included',$db{$table}{$id}{other_included},'') ; + # } + + } + + # $add_form_fields .= qq~
     
    ~ ; + + # $add_form_fields .= qq~
     
    ~ ; + + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    PDF total :
    ~ ; + $add_form_fields .= qq~
    ~ ; + $lcol = 3 ; + # if ($old_title_to_new_title{"Hardware"}{$id} and $old_title_to_new_title{"Hardware"}{$id} ne "Hardware") { + # $add_form_fields .= &common_min_form_input_col('_hardware', $old_title_to_new_title{"Hardware"}{$id}) ; + # } else { + # $add_form_fields .= &common_min_form_input_col('_hardware','') ; + # } + + # my @ttlarr = ("sub_total","vat_total","grand_total") ; + + # @ttlarr2 = ("subtotal","vat","total") ; + + $lcol = 1 ; $fcol = 1 ; + + foreach (@ttlarr2) { + $readonly{$_} = "READONLY" ; + my $val = $db{$table}{$id}{$_} ; $val = '0.00' unless $val ; + # $add_form_fields .= qq~
    ~ ; $lcol=2; + # $add_form_fields .= &common_min_form_label_col($_) ; $lcol = 1 ; + $type = 'hidden' ; $add_form_fields .= &common_min_form_input_col($_,$val) ; $type = '' ; + # $add_form_fields .= qq~
    ~ ; + + $lcol = 1 ; $add_form_fields .= &common_min_form_label_col($_) ; + # $add_form_fields .= qq~
    ~ ; + } + + $add_form_fields .= qq~
    ~ ; + + # $add_form_fields .= qq~
     
    ~ ; + + # my @ttlarr = ("one_time_fee","monthly_recurring_fee","annual_fee") ; + $lcol = 1 ; $fcol = 1 ; + + # foreach my $a (@ttlarr) { + + # $readonly{$a} = "READONLY" ; + + # # if ($_ eq 'one_time_fee') { + + # # $add_form_fields .= qq~
    PDF total :
    ~ ; + # # $lcol = 1 ; + # # if ($old_title_to_new_title{"Hardware"}{$id} and $old_title_to_new_title{"Hardware"}{$id} ne "Hardware"){ + # # $add_form_fields .= &common_min_form_input_col('_hardware', $old_title_to_new_title{"Hardware"}{$id}) ; + # # } + # # else { + # # $add_form_fields .= &common_min_form_input_col('_hardware','') ; + # # } + # # } + + # # else { + # $add_form_fields .= qq~
    ~ ; + # # } + + # $lcol = 2 ; + # $add_form_fields .= &common_min_form_label_col($a) ; + # $lcol = 1 ; + + # foreach my $b (@ttlarr2) { + + # $field = "$b\_$a\_2" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + # my $val = $default_totals{$field}{2} ? $default_totals{$field}{2} : '0.00' ; + # $add_form_fields .= &common_min_form_input_col($field,$val) ; + # } + + # # $field = "2_subtotal_$_" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + # # my $val = $db{$table}{$id}{$field} ? $db{$table}{$id}{$field} : '0.00' ; + # # $add_form_fields .= &common_min_form_input_col($field,$val) ; + + # # $field = "2_vat_$_" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + # # my $val = $db{$table}{$id}{$field} ? $db{$table}{$id}{$field} : '0.00' ; + # # $add_form_fields .= &common_min_form_input_col($field,$val) ; + + # # $field = "2_total_$_" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + # # my $val = $db{$table}{$id}{$field} ? $db{$table}{$id}{$field} : '0.00' ; + # # $add_form_fields .= &common_min_form_input_col($field,$val) ; + # $add_form_fields .= qq~
    ~ ; + + # } + + $add_form_fields .= qq~
    ~ ; + + foreach my $a (@ttlarr2) { + $readonly{$a} = "READONLY" ; + $lcol = 1 ; + $field = "$a" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + my $val = $default_totals{$field}{2} ? $default_totals{$field}{2} : '0.00' ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + } + + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= qq~
     
    ~ ; + + $preferred_title{'include_exclude'} = 'Include/Exclude' ; $preferred_placeholder{'include_exclude'} = 'Include/Exclude' ; $fcol = 5 ; + $add_form_fields .= &common_min_form_textarea('include_exclude',$db{$table}{$id}{include_exclude},'') ; + + $add_form_fields .= qq~
     
    ~ ; + + $add_form_fields .= qq~
    ~ ; + + my @docs = ("1","2","3") ; + + ($db{$table}{$id}{costing_1},$db{$table}{$id}{costing_2},$db{$table}{$id}{costing_3}) = split(/\:;:/,$db{$table}{$id}{costing_uploads}) ; + + foreach (@docs) { + my $doc = lc $_ ; $doc =~ s/ /\_/ ; $doc =~ s/&/\_/ ; + $costing_uploads = &common_get_field_uploads($id,"costing_$doc",'id') ; + if ($costing_uploads) { + $add_form_fields .= qq~
    $costing_uploads
    ~; + } else { + $add_form_fields .= qq~ +
    +
    + + +

    Upload file from PC.

    +
    +
    + ~; + } + } + + $add_form_fields .= qq~
    ~ ; + + # $print_box_content_rows .= qq~
    ~ ; + # $print_box_content_rows .= $add_form_fields ; + # $print_box_content_rows .= &common_min_box_foot; + + &tab_content_box($sec_name,$sec_col) ; + + # --------------- END COSTING ---------------------------------------------------------------------------------------------------------------- + +} + +# if ($tab==4) { # Purchase Summary + + # # --------------- START PURCHASE SUMMARY ---------------------------------------------------------------------------------------------------------------- + + # $add_form_fields = '' ; + + # my $sec = '_purchase_summary' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # if ($ret) { return ; } + + # my $style_vat = '' ; if ($no_vat{$sec}) { $style_vat = 'style="display:none;"' ; } + + # $add_form_fields .= qq~
     
    ~ ; + + # my $field = "excl$sec" ; + # if ($db{$table}{$id}{$field} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + # $label{$field} = 1 ; + # $add_form_fields .= qq~
    ~ ;$fcol=1 ; + # $add_form_fields .= &common_min_form_checkbox_col($field,$db{$table}{$id}{$field},$checked) ; + # $add_form_fields .= qq~

    Purchase Summary

    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~~ ; + # $add_form_fields .= qq~~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + + # my $suffix = $sec ; my $rcnt = 3 ; + + # # &set_check_boxes_checked($id,$rcnt,"excl",$suffix); + + # $default_desc{1} = 'Hardware Purchase' ; + # $default_desc{2} = 'Monthly Fees' ; + # $default_desc{3} = 'Annual Fees' ; + + # my @prefexes = ("excl", "item") ; + + # foreach my $prefex (@prefexes) { + + # $col_name = "$prefex" . "$suffix" ; + # $cnt = 0 ; + # # if($db{quotes_min}{$id}{$col_name}){ + # for my $col_input (split(";", $db{quotes_min}{$id}{$col_name})){ + # $cnt++ ; + # $saved_field{$prefex}{$suffix}{$cnt} = $col_input ; + # } + # # } + # } + # for (1 .. $rcnt) { + # $add_form_fields .= qq~
    ~ ; + # #---------------------------------------------------------------------------------------------------- + # $field = "excl_$_$suffix" ; $fcol=1 ; + # # if ($checkit{$field} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + # # if ($db{$table}{$id}{$field} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + # if ($saved_field{"excl"}{$suffix}{$_} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + # $label{$field} = 1 ; + # # $add_form_fields .= &common_min_form_checkbox_col($field,$db{$table}{$id}{$field},$checked) ; + # $add_form_fields .= &common_min_form_checkbox_col($field,$saved_field{"excl"}{$suffix}{$_},$checked) ; + # #---------------------------------------------------------------------------------------------------- + # my $field = "item_$_$suffix" ; $fcol=2 ; + # $preferred_placeholder{$field} = "Item $_" ; + # # my $val = $db{$table}{$id}{$field} ; + # my $val = $saved_field{"item"}{$suffix}{$_} ; + # $val = $default_desc{$_} unless $val ; + # # $readonly{$field} = 'READONLY' ; + # $add_form_fields .= &common_min_form_input_col($field,$val) ; + # #---------------------------------------------------------------------------------------------------- + # for my $year (1 .. 5) { + # $field = "year_$year\_$_$suffix" ; $input_style{$field} = qq~style="text-align:right;"~; + + # unless ($year==1 and $_==3) { + # $readonly{$field} = 'READONLY' ; + # } else { + # $trigger_jquery_raw .= qq~\$("#inputYear_1_$_$suffix").change(function() { + # calcAnnual$field() ; + # }); + # ~; + # $trigger_jquery_raw .= qq~function calcAnnual$field() + # { + # var annual_ttl = getNum(parseFloat(\$("#inputYear_1_$_$suffix").val())) + getNum(parseFloat(\$("#inputYear_2_$_$suffix").val())) + getNum(parseFloat(\$("#inputYear_3_$_$suffix").val())) ; + # \$("#inputTotal_$_$suffix").val(annual_ttl.toFixed(2)); + # }~; + # } + # $preferred_placeholder{$field} = "Year $year Total $_" ; + # # my $val = &q_get_val($db{$table}{$id}{$field}) ; + # $excl_on_change{$field} = 1 ; + # $year_totals{"yearly_totals_$year"} += $db{$table}{$id}{$field} ; + + # $fcol = 12 ; + # $add_form_fields .= qq~
    ~ if $year <= 3 ; + # $add_form_fields .= qq~~ ; + # } + # $fcol = 2 ; + # #---------------------------------------------------------------------------------------------------- + + # $field = "total_$_$suffix" ; $input_style{$field} = qq~style="text-align:right;"~; $readonly{$field} = 'READONLY' ; # $fcol=2 ; + # $preferred_placeholder{$field} = "Total $_" ; + # # my $val = &q_get_val($db{$table}{$id}{$field}) ; + # $add_form_fields .= &common_min_form_input_col($field,$db{$table}{$id}{$field},1) ; + # #---------------------------------------------------------------------------------------------------- + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # } + # $add_form_fields .= qq~
    ~ ; + # for my $y (1 .. 5) { + # $grand_tot += $year_totals{"yearly_totals_$y"} ; + # $field ="yearly_totals_$y" ; + # $readonly{$field} = 'READONLY' ; + # # $year_totals{"yearly_totals_$y"} = &common_commify($year_totals{"yearly_totals_$y"}) ; + # $input_style{$field} = qq~style="text-align:right;"~ ; + # $fcol = 12 ; + # $add_form_fields .= qq~
    ~ if $y <= 3 ; + # $add_form_fields .= qq~~ ; + # } + + # $trigger_jquery_raw .= qq~ + # // console.log("suffix : "+$suffix) ;console.log("1") ; + + # if (\$("#selectPeriod").val() == 60) { + + # for (let ii = 1; ii <= 5; ii++) { + + # if (ii <= 3) { + # \$("#year_"+ii+"_sum").removeClass("col-md-2").addClass("col-md-1") ; + # \$("#total_"+ii+"").removeClass("col-md-2").addClass("col-md-1") + # } + # else if (ii <= 5 && ii > 3) { + # \$("#year_"+ii+"_sum").removeClass("col-md-0").addClass("col-md-1") ; + # \$("#total_"+ii+"").removeClass("col-md-0").addClass("col-md-1") ; + # \$("#year_"+ii+"_sum").show() ; + # \$("#total_"+ii+"").show() ; + # } + # for (let jj = 1; jj <= 3; jj++) { + + # if (ii <= 3) { + # \$("#b_year_"+ii+"_"+jj+"").removeClass("col-md-2").addClass("col-md-1") ; + # } + # else if (ii <= 5 && ii > 3) { + # \$("#b_year_"+ii+"_"+jj+"").removeClass("col-md-0").addClass("col-md-1") ; + # \$("#b_year_"+ii+"_"+jj+"").show() ; + # } + # } + # } + # } + + # \$("#selectPeriod").on("change", function() { + + # for (let i = 1; i <= 5; i++) { + + # if (i <= 3 && \$(this).val() == 36) { + # \$("#year_"+i+"_sum").removeClass("col-md-1").addClass("col-md-2") ; + # \$("#total_"+i+"").removeClass("col-md-1").addClass("col-md-2") ; + # } + # else if (i <= 3 && \$(this).val() == 60) { + # \$("#year_"+i+"_sum").removeClass("col-md-2").addClass("col-md-1") ; + # \$("#total_"+i+"").removeClass("col-md-2").addClass("col-md-1") + # } + # else if (i <= 5 && i > 3 && \$(this).val() == 36) { + # \$("#year_"+i+"_sum").removeClass("col-md-1").addClass("col-md-0") ; + # \$("#total_"+i+"").removeClass("col-md-1").addClass("col-md-0") ; + # \$("#year_"+i+"_sum").hide() ; + # \$("#total_"+i+"").hide() ; + # } + # else if (i <= 5 && i > 3 && \$(this).val() == 60) { + # \$("#year_"+i+"_sum").removeClass("col-md-0").addClass("col-md-1") ; + # \$("#total_"+i+"").removeClass("col-md-0").addClass("col-md-1") ; + # \$("#year_"+i+"_sum").show() ; + # \$("#total_"+i+"").show() ; + # } + # for (let j = 1; j <= 3; j++) { + + # if (i <= 3 && \$(this).val() == 36) { + # \$("#b_year_"+i+"_"+j+"").removeClass("col-md-1").addClass("col-md-2") ; + # } + # else if (i <= 5 && i > 3 && \$(this).val() == 36) { + # \$("#b_year_"+i+"_"+j+"").removeClass("col-md-1").addClass("col-md-0") ; + # \$("#b_year_"+i+"_"+j+"").hide() ; + # } + + # else if (i <= 3 && \$(this).val() == 60) { + # \$("#b_year_"+i+"_"+j+"").removeClass("col-md-2").addClass("col-md-1") ; + # } + # else if (i <= 5 && i > 3 && \$(this).val() == 60) { + # \$("#b_year_"+i+"_"+j+"").removeClass("col-md-0").addClass("col-md-1") ; + # \$("#b_year_"+i+"_"+j+"").show() ; + # // if (\$("#b_year_"+i+"_"+j+"").text().trim() === '') { + # // \$("#b_year_"+i+"_"+j+"").text("0.00") ; + # // } + # } + # } + # } + # }); + # ~ ; + + # $fcol = 2 ; + # $field ="yearly_total" ; + # $readonly{$field} = 'READONLY' ; + # # $grand_tot = &common_commify($grand_tot) ; + # $input_style{$field} = qq~style="text-align:right;"~ ; + # $add_form_fields .= &common_min_form_input_col($field,$grand_tot,1) ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
     
    ~ ; + + # &tab_content_box($sec_name,$sec_col); + + # # --------------- END PURCHASE SUMMARY ---------------------------------------------------------------------------------------------------------------- + # } + +# if ($tab==5) { # Notes + + # # --------------- START NOTES ---------------------------------------------------------------------------------------------------------------- + + # my $sec = '_notes' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # if ($ret) { return ; } + + # $add_form_fields = '' ; + + # # &set_check_boxes_checked($id,$sec_cnt,"excl",$sec); + + + # &db_min_ro('quote_notes','*',"id='1'",'','') ; + + # $add_form_fields .= qq~

    Notes:

    ~ ; + # &tab_build_terms_headers; + + # $cntnoteloop=1; for (1 .. 12) { &tab_build_terms_fields('note',$_,$id) ; } + + # $add_form_fields .= qq~

    Payment Terms:

    ~ ; + # &tab_build_terms_headers; + + # $cntnoteloop=1; for (1 .. 6) { &tab_build_terms_fields('payment_term',$_,$id) ; } + + # $add_form_fields .= qq~

    ROE:

    ~ ; + # &tab_build_terms_headers; + + # $cntnoteloop=1; for (1 .. 6) { &tab_build_terms_fields('roe',$_,$id) ; } + + # $add_form_fields .= qq~

    Delivery Time:

    ~ ; + # &tab_build_terms_headers; + + # $cntnoteloop=1; for (1 .. 4) { &tab_build_terms_fields('delivery_time',$_,$id) ; } + + # $add_form_fields .= qq~

    Terms and Conditions:

    ~ ; + # &tab_build_terms_headers; + + # $cntnoteloop=1; for (1 .. 1) { &tab_build_terms_fields_terms_and_conditions('terms',$_,$id) ; } + + # $trigger_jquery .= qq~\$("#selectTerms_chosen").css( "width", "100%" );~ ; + + # &tab_content_box($sec_name,$sec_col); + + # # --------------- END NOTES ---------------------------------------------------------------------------------------------------------------- + # } + +if ($tab==3) { # Camera Details + + # --------------- START CAMERA DETAILS ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + my $sec = '_camera_details' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $add_form_fields = '' ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + # my $suffix = $sec ; my $rcnt = 11 ; + # my $suffix = $sec ; my $rcnt = 20 ; + my $suffix = $sec ; my $rcnt = $max_cams ; # set in quotes.pl + # our %linked_vpu = () ; our %vpu_serial_nr = () ; our %vpu_camera_nr = () ; + &tab_camera_details_select_opts('cameras','camera_nr',"camera_nr NOT LIKE 'vpu%'",$suffix,$rcnt) ; + + $rcnt = $max_cams ; # reset in tab_camera_details_select_opts + + # &tab_camera_details_select_opts('cameras','camera_nr',"event_system_id < 1",$suffix,$rcnt) ; + + my $cam_qtys = '' ; + + # &common_debug("cam_qtys : quote_nr=$db{$table}{$id}{quote_nr}") ; + + foreach (keys %{$camera_system_count{$db{$table}{$id}{quote_nr}}}) { + # &common_debug("cam_qtys : cam=$_, qty=$camera_system_count{$db{$table}{$id}{quote_nr}}{$_}") ; + $cam_qtys .= qq~$_ : $camera_system_count{$db{$table}{$id}{quote_nr}}{$_}
    ~ ; + } + + # our $cam_box_icon = qq~ ~ if $cam_qtys ; + our $cam_box_icon = qq~ ~ if $cam_qtys ; + + # foreach (sort keys %sec_cnt) { + # $_k = substr($_,1) ; + # my @parts = split(/\-/,$sec_cnt{$_}) ; + # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + # &tab_build_qt_col_headers("$sec$_k"); + # &build_cost_form($id,$tab,$parts[0],"$sec$_k"); + # } + + # unless ($db{quote_notes}{1}{$inpfield}) { $checkit{$exfield} = 1 ; } + + # $add_form_fields .= qq~
    ~ ; + # if ($checkit{$exfield} == 1) { $checked = 'CHECKED'; } elsif (($excl_tick{$cnt}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } + + # &set_check_boxes_checked($id,$rcnt,"excl",$suffix); + + my $cntcamloop=1; + + for (1 .. $rcnt) { + + my $q_nr = $db{$table}{$id}{quote_nr} ; + + + # next if substr($sel_cam_nr{$camera_details{$q_nr}{$_}{"$_$suffix"}{id}},0,3) eq 'VPU' ; + my $a = "$_$suffix" ; + # &common_debug("rcnt : $_ , q_nr : $q_nr , camera_details : $camera_details{$q_nr}{$_}{$a}{id}") ; + + $cam_display_style = '' ; $cam_display_plus_btn = '' ; + # unless ($_==1 or $db{$table}{$id}{"camera_nr_$_$suffix"}) { + unless ($_==1 or $camera_details{$q_nr}{$_}{"$_$suffix"}{id}) { + $cam_display_style = qq~style='display:none;'~ ; + $trigger_jquery_raw .= qq~ \$("#btn_$_$suffix").click(function () { + \$("#$_$suffix").toggle(); + \$("#btn_$_$suffix").hide(); + var v = $_ + 1 ; + \$("#btn_"+v+"$suffix").show(); + });~ ; + if ($_>$cntcamloop) { $cam_display_butt = qq~display:none;~ ; } else { $cam_display_butt = '' ; } + $cam_display_plus_btn = qq~~; + } else { $cntcamloop++ ; } + + + + $add_form_fields .= qq~
    ~ ; + + # my $cam_id = $db{$table}{$id}{"camera_nr_$_$suffix"} ; + + # $add_form_fields .= qq~
    ~ ; + #---------------------------------------------------------------------------------------------------- + $field = "excl_$_$suffix" ; $fcol=1 ; + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_cam_excl} ; + # if ($checkit{$field} == 1) { $checked = 'CHECKED'; } elsif ($_!=1 and $iaction eq 'add') { $checked = 'CHECKED'; } else { $checked = ''; } + if ($val==1) { $checked = 'CHECKED'; } elsif ($iaction eq 'add') { $checked = 'CHECKED'; } elsif ($val eq '0') { $checked = ''; } else { $checked = 'CHECKED'; } + # &common_debug("$field : [$val] [$checked] [$_$suffix]") ; + $label{$field} = 1 ; + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_checkbox_col($field,$val,$checked) ; + #---------------------------------------------------------------------------------------------------- + my $field = "camera_nr_$_$suffix" ; $fcol=2 ; + $allow_deselect{$field} = 1 ; + $preferred_placeholder{$field} = "Camera Nr $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{id} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + # $add_form_fields .= &common_min_form_input_col($field,$val) ; + $excl_on_change{$field} = 1 ; + + $opts{$field} = $opts_on_edit{$field} if $opts_on_edit{$field} and $db{quotes}{$i{id}}{max_cams} > 50 ; #and $username eq 'rory' ; # overwrite if selected and max_cams exceeded + + $add_form_fields .= &common_min_form_select_col($field,$val) ; + + my $abrv_cam_system = substr($sel_cam_nr{$val},0,3); + # next if $abrv_cam_system eq 'VPU' ; + # &common_debug("abrv_cam_system=$abrv_cam_system, abrv_prev_cam_system=$abrv_prev_cam_system, prev_cam_nr=$prev_cam_nr, link to: c_excl_$_\_camera_details") ; + # if ($abrv_cam_system eq 'VPU' and ($abrv_prev_cam_system eq 'S1' or $abrv_prev_cam_system_other eq 'Prime' or $abrv_prev_cam_system_other eq 'Coach')) { + + # if ($abrv_cam_system eq 'VPU' and ($abrv_prev_cam_system eq 'S1' or $abrv_prev_cam_system eq 'S2' or $abrv_prev_cam_system_other eq 'Prime' or $abrv_prev_cam_system_other eq 'Coach')) { + + if ($linked_vpu{$val}) { + $trigger_jquery .= qq~\$("#c_excl_$_\_camera_details").append("");\$('[data-toggle="tooltip"]').tooltip({html:true}) ;~; + } + # } + $abrv_prev_cam_system = substr($abrv_cam_system,0,2); + $abrv_prev_cam_system_other = substr($abrv_cam_system,0,5); + $prev_cam_nr = $sel_cam_nr{$val} ; + #---------------------------------------------------------------------------------------------------- + # # my $field = "item_code_$_$suffix" ; $fcol=1 ; + # # $preferred_placeholder{$field} = "Item Code $_" ; + # # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + # # $add_form_fields .= &common_min_form_input_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + my $field = "description_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "Description $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_cam_desc} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + # my $field = "qty_$_$suffix" ; $fcol=1 ; + # $preferred_placeholder{$field} = "Qty $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + # $type = 'hidden' ; $add_form_fields .= &common_min_form_input_col($field,$val) ; $type = '' ; + #---------------------------------------------------------------------------------------------------- + my $field = "serial_nr_$_$suffix" ; $fcol=2 ; + $preferred_placeholder{$field} = "Serial Nr $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{serial_nr} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + my $field = "ref_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "Ref $_" ; + # my $val = $db{$table}{$id}{$field} ; + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ref} ; + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + # &common_debug("2. $field : [$q_nr] [$_] [$_$suffix] [$val]") if $val; + #---------------------------------------------------------------------------------------------------- + my $field = "delivery_date_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "Delivery Date $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_delivery_date} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_datepicker_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + my $field = "active_date_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "Active Date $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_active_date} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $add_form_fields .= &common_min_form_datepicker_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + my $field = "ew_date_from_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "E/W Date From $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_from} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_datepicker_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + my $field = "ew_date_to_$_$suffix" ; $fcol=1 ; + $preferred_placeholder{$field} = "E/W Date To $_" ; + # my $val = $db{$table}{$id}{$field} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + my $val = $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_to} ; # if ($_==1) { $readonly{$field} = 'READONLY' ; } + $excl_on_change{$field} = 1 ; + $add_form_fields .= &common_min_form_datepicker_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + # my $ew_pdf_butt = '' ; if ($username eq 'rory' or $username eq 'handre') { $ew_pdf_butt = qq~ ~; } + # my $ew_pdf_butt = '' ; if ($camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_from} and $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_to} and uc substr($camera_details{$q_nr}{$_}{"$_$suffix"}{camera_nr},0,3) ne 'VPU') { $ew_pdf_butt = qq~ ~; } + my $ew_pdf_butt = '' ; if ($camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_from} and $camera_details{$q_nr}{$_}{"$_$suffix"}{quote_ew_date_to} and (uc substr($camera_details{$q_nr}{$_}{"$_$suffix"}{camera_nr},0,2) eq 'S1' or uc substr($camera_details{$q_nr}{$_}{"$_$suffix"}{camera_nr},0,5) eq 'SCORE')) { $ew_pdf_butt = qq~ ~; } + #---------------------------------------------------------------------------------------------------- + $add_form_fields .= qq~
    $ew_pdf_butt
    ~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    $cam_display_plus_btn
    ~ ; + $add_form_fields .= qq~
    ~ ; + } + + $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + $cam_box_icon = '' ; + + # --------------- END CAMERA DETAILS ---------------------------------------------------------------------------------------------------------------- +} + +if ($tab==4) { # Invoice Details + + # --------------- START INVOICE DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_invoice_details' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $lcol = 2 ; + $fcol = 5 ; + + $add_form_fields = '' ; + + $add_form_fields .= &common_min_form_input('invoice_nr',$db{$table}{$id}{invoice_nr},'') ; + my $checked = 'CHECKED' if $db{$table}{$id}{annual_invoice} ; + $add_form_fields .= &common_min_form_checkbox('annual_invoice',$db{$table}{$id}{annual_invoice},$checked) ; + # if ($db{$table}{$id}{invoice_date} eq '' or $db{$table}{$id}{invoice_date} eq '0000-00-00') { $db{$table}{$id}{invoice_date} = $now_ccyy_mm_dd ; } + $add_form_fields .= &common_min_form_datepicker('invoice_date',$db{$table}{$id}{invoice_date}) ; + $add_form_fields .= &common_min_form_input('annual_invoice_2',$db{$table}{$id}{annual_invoice_2},'') ; + $add_form_fields .= &common_min_form_input('annual_invoice_3',$db{$table}{$id}{annual_invoice_3},'') ; + # $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END INVOICE DETAILS ---------------------------------------------------------------------------------------------------------- + } + +# if ($tab==7) { # Extended Warranty + + # # --------------- START EXTENDED WARRANTY -------------------------------------------------------------------------------------------------------- + + # my $sec = '_extended_warranty' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # if ($ret) { return ; } + + # $lcol = 2 ; + # $fcol = 3 ; + + # $add_form_fields = '' ; + + # if (($db{$table}{$id}{date_from} eq '') or ($db{$table}{$id}{date_from} eq '0000-00-00')) { $db{$table}{$id}{date_from} = $now_ccyy_mm_dd ; } + # $add_form_fields .= &common_min_form_datepicker('date_from',$db{$table}{$id}{date_from}) ; + # if (($db{$table}{$id}{date_to} eq '') or ($db{$table}{$id}{date_to} eq '0000-00-00')) { $db{$table}{$id}{date_to} = $now_ccyy_mm_dd ; } + # $add_form_fields .= &common_min_form_datepicker('date_to',$db{$table}{$id}{date_to}) ; + + # &tab_content_box($sec_name,$sec_col); + + # # --------------- END EXTENDED WARRANTY ---------------------------------------------------------------------------------------------------------- + # } + +# if ($tab==8) { # Rental + + # # --------------- START RENTAL -------------------------------------------------------------------------------------------------------- + + # my $sec = '_rental' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # if ($ret) { return ; } + + # $lcol = 2 ; + # $fcol = 3 ; + + # $add_form_fields = '' ; + + # # our %sec_cnt = ('_cost' => "1-Cost"); + + # # my $sec = '_rental' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + # # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # # if ($ret) { return ; } + + # # foreach (sort keys %sec_cnt) { + # # my @parts = split(/\-/,$sec_cnt{$_}) ; + # # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + # # &tab_build_qt_col_headers("$sec$_"); + # # &build_cost_form($id,$tab,$parts[0],"$sec$_"); + # # } + + # &tab_content_box($sec_name,$sec_col); + + # # --------------- END RENTAL ---------------------------------------------------------------------------------------------------------- + # } + +if ($tab==5) { # Document Uploads + + # --------------- START DOCUMENT UPLOADS ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + my $sec = '_document_uploads' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $add_form_fields = '' ; + + my @docs = ('Signed Quote','PO','Other 1','SLA','T&Cs','Other 2','Photos','Delivery Note','Other 3'); + + $add_form_fields .= qq~
    ~ ; + + foreach (@docs) { + my $doc = lc $_ ; $doc =~ s/ /\_/ ; $doc =~ s/&/\_/ ; + $costing_uploads = &common_get_field_uploads($id,"costing_$doc",'id') ; + if ($costing_uploads) { + $add_form_fields .= qq~
    $costing_uploads
    ~; + } else { + $add_form_fields .= qq~ +
    +
    + + +

    Upload file from PC.

    +
    +
    + ~; + } + } + + $add_form_fields .= qq~
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END DOCUMENT UPLOADS ---------------------------------------------------------------------------------------------------------------- + } + +} #------------------------------------------------------------------------------------ + +# sub tab_costing_select_opts { + +# my ($table,$dispfield,$where,$sec_) = @_ ; + +# &db_min_ro($table,'*',$where,'','') ; +# my @b = ( +# "_costing_additional_services", +# "_costing_game_breakdown_analytics", +# "_costing_hardware_add_ons", +# "_costing_installation_kits", +# "_costing_match_credits", +# "_costing_other", +# "_costing_rental", +# "_costing_software_licence", +# "_costing_systems" ) ; + +# foreach my $suf (@b){ + # $col_name = "item" . "$suf" ; + # $cnt = 0 ; + # if($db{quotes_min}{$i{id}}{$col_name}){ + # foreach my $col_input (split(";", $db{quotes_min}{$i{id}}{$col_name})){ + # $cnt++ ; + # $saved_field{"item"}{$suf}{$cnt} = $col_input ; + # # &common_debug("$aa/$suffix : $cc") ; + # } + # } +# } + +# foreach my $id (keys %{$db{$table}}) { + # foreach (sort keys %sec_cnt) { + # $_k = substr($_,1) ; $k = substr($_,2) ; + # # &common_debug("tab_select_opts : $db{$table}{$id}{type} ne $k") ; + # unless ($db{$table}{$id}{type} eq $k) { next ; } + # my @parts = split(/\-/,$sec_cnt{$_}) ; + # for my $p_ (1 .. $parts[0]) { # item_1_costing_systems + # my $field = "$p_$sec_$_k" ; #my $ucf_field = ucfirst $field ; my $chosen_field = ucfirst $field . '_chosen' ; + # # $opts{"item_$p_$sec_$_k"} .= qq~~ ; + # my $field_2 = "$sec_$_k" ; + # # my $saved_val = $db{quotes}{$i{id}}{"item_$field"} ; + # my $saved_val = $saved_field{"item"}{$field_2}{$p_} ; + + # if ($saved_val) { my @valarr = split(/\:/,$saved_val) ; $saved_val = $valarr[0] ; } + + # if ($saved_val eq $id) { $selected = 'SELECTED' ; } else { $selected = '' ; } + + # # $opts{"item_$field"} .= qq~~ ; + # $opts{"item_$field"} .= qq~~ ; + + # # if ($field eq '3_costing_software_licence' or $field eq '2_costing_game_breakdown_analytics') { + # if ($field eq '2_costing_systems' or $field eq '3_costing_systems' or $field eq '3_costing_software_licence' or $field eq '2_costing_game_breakdown_analytics') { + # $item_type = 'input' ; + # } else { + # $item_type = 'select' ; + # } + + # unless ($got{$field}) { + # $preferred_title{"item_$field"} = &common_min_print_field("item_$p_$_k") ; + # if ($item_type eq 'select') { $trigger_jquery .= qq~\$("#selectItem_$field\_chosen").css( "width", "96%" ) +# ~ ; } $got{$field} = 1 ; + # # $trigger_jquery_raw .= qq~\$("#$item_type\Item_$field, #selectDiscount").change(function() { + # # calcCosting$field(1) ; + # # }); + # # ~; + # # $trigger_jquery_raw .= qq~\$("#inputQty_$field, #inputUsd_amnt_$field").change(function() { + # # calcCosting$field(0) ; + # # }); + # # ~;$trigger_jquery_raw .= qq~function calcCosting$field(b) + # # { + # # if (b==1) { \$("#inputUsd_amnt_$field").val(''); } + + # # var excl = \$("#checkboxExcl_$field"); + # # var item = \$("#$item_type\Item_$field"); + # # var usd = \$("#inputUsd_amnt_$field"); + # # var conv = \$("#inputCurr_amnt_$field"); + # # var qty = \$("#inputQty_$field"); + # # var ttl = \$("#inputItem_ttl_$field"); + # # var vat = \$("#checkboxVat_$field"); + + # # // console.log('DISCOUNT - item: '+item.val()+', usd: '+usd.val()) ; + + # # if (!item.val()) { + # # excl.prop("checked", true); + # # usd.val(""); + # # conv.val(""); + # # qty.val(""); + # # ttl.val(""); + # # vat.val(""); + # # // return ; + # # } + + # # calcCosting(excl,item,qty,usd,conv,vat,ttl) ; + # # }~; + + # } + # } + # } + # } +# } #------------------------------------------------------------------------------------------ + +sub tab_camera_details_select_opts { + +my ($table,$dispfield,$where,$suffix,$rcnt) = @_ ; + +&db_min_ro('customers','id,name','','','') ; +foreach my $id (keys %{$db{customers}}) { $customers_name{$id} = $db{customers}{$id}{name} ; } + +&db_min_ro('camera_systems','id,name','','','') ; +foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + +# my $add_quote_fields = '' ; my $sql_or_where = '' ; my @sqlorwhere = () ; +# for (1 .. $rcnt) { + # $add_quote_fields .= ",quotes.camera_nr_$_$suffix" ; + # push @sqlorwhere, "quotes.camera_nr_$_$suffix>0" ; +# } +# $sql_or_where = join(" OR ",@sqlorwhere) ; + +# &db_min_ro("$table,quotes","quotes.id,$table.id$add_quote_fields",$sql_or_where,'','') ; + +# foreach my $id (keys %{$db{"$table,quotes"}}) { + # # $db{quotes}{$i{id}}{"camera_nr_$field"} + # for (1 .. 10) { + # my $field = $db{"$table,quotes"}{$id}{"camera_nr_$_$suffix"} ; + # if ($field) { + # # $camera_exists_on_quote{$field} = $id ; + # $exclude_camera_from_list{$field} = 1 ; + # # &common_debug("exclude_camera_from_list : $field") ; + # } + # } + +# } + +our %linked_vpu = () ; our %vpu_serial_nr = () ; our %vpu_camera_nr = () ; my $cnt_sel=0; my %done_quote_cam_num = () ; my %done_field = () ; +&db_min_ro($table,'id,camera_nr,serial_nr,quote_nr',"camera_nr LIKE 'vpu%'",'','') ; +foreach (keys %{$db{$table}}) { + $vpu_serial_nr{$_} = $db{$table}{$_}{serial_nr} ; + $vpu_camera_nr{$_} = $db{$table}{$_}{camera_nr} ; + + my $qnr = $db{$table}{$_}{quote_nr} ; + + if ($qnr eq $db{quotes}{$i{id}}{quote_nr}) { + $cnt_cams{$qnr}++; + # &common_debug("$cnt_cams{$qnr}. $qnr eq $db{quotes}{$i{id}}{quote_nr} ") if $qnr == 1261 ; + } + +} +&db_min_ro($table,'*',$where,'','') ; + +LOOP1: foreach my $id (sort keys %{$db{$table}}) { + + # &common_debug("1. LOOP1 $db{$table}{$id}{quote_nr} and $db{$table}{$id}{quote_nr} ne $db{quotes}{$i{id}}{quote_nr}") if $db{$table}{$id}{quote_nr} == 1261 ; + if ($db{$table}{$id}{quote_nr} and $db{$table}{$id}{quote_nr} ne $db{quotes}{$i{id}}{quote_nr}) { next ; } + + # &common_debug("2. LOOP1 event_system_id=$db{$table}{$id}{event_system_id} ") if $db{$table}{$id}{quote_nr} == 1261 ; + if ($db{$table}{$id}{event_system_id}) { $skip_event_linked_vpu{$db{$table}{$id}{event_linked_vpu}} = 1 ; next ; } # skip as it's being used for events + + # &common_debug("3. LOOP1 skip_event_linked_vpu=$skip_event_linked_vpu{$db{$table}{$id}{serial_nr}}") if $db{$table}{$id}{quote_nr} == 1261 ; + if ($skip_event_linked_vpu{$db{$table}{$id}{serial_nr}}) { next ; } # skip as it's being used for events + + # &common_debug("LOOP1 rcnt=$rcnt") if $db{$table}{$id}{quote_nr} == 1261 ; + + my $qnr = $db{$table}{$id}{quote_nr} ; + + if ($qnr eq $db{quotes}{$i{id}}{quote_nr}) { + $cnt_cams{$qnr}++; + # &common_debug("$cnt_cams{$qnr}. $qnr eq $db{quotes}{$i{id}}{quote_nr} ") if $qnr == 1261 ; + } + + # LOOP2: for (1 .. $rcnt) { + + # if ($qnr eq $db{quotes}{$i{id}}{quote_nr} and $db{$table}{$id}{quote_cam_num} eq $_) { + # $cnt_sel++ ; + # # &common_debug("$cnt_sel. $qnr eq $db{quotes}{$i{id}}{quote_nr} and $db{$table}{$id}{quote_cam_num} eq $_") if $qnr == 1261 ; + # } + # } +} + +$max_cams = $cnt_cams{$db{quotes}{$i{id}}{quote_nr}} if $cnt_cams{$db{quotes}{$i{id}}{quote_nr}} > $max_cams && $db{quotes}{$i{id}}{quote_nr} ; + +&common_debug("$cnt_cams{$db{quotes}{$i{id}}{quote_nr}} [max_cams = $max_cams]") ; + +LOOP1: foreach my $id (sort keys %{$db{$table}}) { + + # &common_debug("exclude_camera_from_list [$exclude_camera_from_list{$id}] : [$table] : $id") ; + + if ($db{$table}{$id}{quote_nr} and $db{$table}{$id}{quote_nr} ne $db{quotes}{$i{id}}{quote_nr}) { next ; } + + if ($db{$table}{$id}{event_system_id}) { $skip_event_linked_vpu{$db{$table}{$id}{event_linked_vpu}} = 1 ; next ; } # skip as it's being used for events + if ($skip_event_linked_vpu{$db{$table}{$id}{serial_nr}}) { next ; } # skip as it's being used for events + + my ($camtype,$camcnt) = split(/\-/,$db{$table}{$id}{$dispfield}) ; + $camera_system_count{$db{$table}{$id}{quote_nr}}{$camtype}++ if $db{$table}{$id}{quote_nr} and $camtype ; + $linked_vpu{$id} = $db{$table}{$id}{linked_vpu_id} ; + + # &common_debug("[cam_qtys] quote_nr : [$db{$table}{$id}{quote_nr}] [$db{$table}{$id}{$dispfield}] [$camera_system_count{$db{$table}{$id}{quote_nr}}{$db{$table}{$id}{$dispfield}}]") if $db{$table}{$id}{quote_nr} ; + + my $qnr = $db{$table}{$id}{quote_nr} ; + + # LOOP2: for (1 .. $rcnt) { + LOOP2: for (1 .. $max_cams) { + my $field = "$_$suffix" ; + + # if ($exclude_camera_from_list{$id} and $db{quotes}{$i{id}}{"camera_nr_$_$suffix"} ne $id) { next LOOP2; ; } + # if ($exclude_camera_from_list{$id} and $db{quotes}{$i{id}}{"camera_nr_$_$suffix"} ne $id) { next LOOP1; ; } + + # my $quote_camera_id = $db{quotes}{$i{id}}{"camera_nr_$field"} ; if ($quote_camera_id) { my @valarr = split(/\:/,$quote_camera_id) ; $quote_camera_id = $valarr[0] ; } + + # # my $abrv_cam_system = substr($db{$table}{$id}{camera_nr},0,3); + # next if $seen_cnt{$_} ; + # $seen_cnt{$_} = 1 ; + + # next unless $qnr ; + my $selected = '' ; + + # if ($saved_val eq $id) { $selected = 'SELECTED' ; $sel_cam_nr{$id} = $db{$table}{$id}{camera_nr}; } else { $selected = '' ; } + # if ($db{$table}{$id}{quote_nr} eq $db{quotes}{$i{id}}{quote_nr} and $quote_camera_id eq $id) { + + # if ($qnr == 1261) { + # &common_debug("if ($qnr eq $db{quotes}{$i{id}}{quote_nr} and $_ <= $cnt_sel and not $done_quote_cam_num{$db{$table}{$id}{quote_cam_num}} and not $done_field{$field}) { ") ; + # } + + # if ($qnr eq $db{quotes}{$i{id}}{quote_nr} and $_ <= $cnt_sel and not $done_quote_cam_num{$db{$table}{$id}{quote_cam_num}} and not $done_field{$field}) { + if ($qnr eq $db{quotes}{$i{id}}{quote_nr} and $_ <= $max_cams and not $done_quote_cam_num{$db{$table}{$id}{quote_cam_num}} and not $done_field{$field}) { + $done_quote_cam_num{$db{$table}{$id}{quote_cam_num}} = 1 ; $done_field{$field} = 1 ; + $selected = 'SELECTED' ; $sel_cam_nr{$id} = $db{$table}{$id}{camera_nr}; + # &common_debug("1. quote_ref : [$db{$table}{$id}{quote_cam_num}] [$field] [$db{$table}{$id}{quote_ref}] [$_. max_cams=$max_cams]"); + $camera_details{$qnr}{$_}{$field}{quote_delivery_date} = $db{$table}{$id}{quote_delivery_date} ; + $camera_details{$qnr}{$_}{$field}{quote_active_date} = $db{$table}{$id}{quote_active_date} ; + $camera_details{$qnr}{$_}{$field}{quote_ew_date_from} = $db{$table}{$id}{quote_ew_date_from} ; + $camera_details{$qnr}{$_}{$field}{quote_ew_date_to} = $db{$table}{$id}{quote_ew_date_to} ; + $camera_details{$qnr}{$_}{$field}{quote_cam_desc} = $db{$table}{$id}{quote_cam_desc} ; + $camera_details{$qnr}{$_}{$field}{quote_cam_excl} = $db{$table}{$id}{quote_cam_excl} ; + $camera_details{$qnr}{$_}{$field}{quote_cam_num} = $db{$table}{$id}{quote_cam_num} ; + $camera_details{$qnr}{$_}{$field}{quote_nr} = $qnr ; + $camera_details{$qnr}{$_}{$field}{quote_ref} = $db{$table}{$id}{quote_ref} ; + $camera_details{$qnr}{$_}{$field}{serial_nr} = $db{$table}{$id}{serial_nr} ; + $camera_details{$qnr}{$_}{$field}{camera_nr} = $db{$table}{$id}{camera_nr} ; + $camera_details{$qnr}{$_}{$field}{id} = $id ; + } elsif ($qnr and $db{$table}{$id}{quote_cam_num}) { # camera alread linked to a quote + next ; + } + + # &common_debug("tab_camera_details_select_opts [$field] : [$saved_val eq $id] : $selected") ; + + my $display_field = $db{$table}{$id}{$dispfield} ; my ($system,$camcnt) = split(/\-/,$display_field) ; $camcnt+=0; $display_field .= " [$camcnt] [$db{$table}{$id}{serial_nr}]" ; # $display_field =~ s/-//g ; + + # my $opts = qq~~ ; + my $opts = qq~~ ; + + $opts_on_edit{"camera_nr_$field"} = $opts if $selected ; + + $opts{"camera_nr_$field"} .= $opts ; + + # $debugcnt++ ; &common_debug("$debugcnt. camera_nr_$field [$display_field] : [$iaction eq 'edit' and $camera_details{$q_nr}{$_}{$field}{id}] : $selected : cam camera_nr=$db{$table}{$id}{camera_nr} [max_cams=$db{quotes}{$i{id}}{max_cams}]") ; + + # # if ($username eq 'rory' and $iaction eq 'edit' and $db{quotes}{$i{id}}{quote_nr} and $db{quotes}{$i{id}}{max_cams} > 25) { + # if ($username eq 'rory' and $iaction eq 'edit' and $camera_details{$q_nr}{$_}{$field}{id} and $db{quotes}{$i{id}}{max_cams} > 25) { + # $opts_single{"camera_nr_$field"} = $opts if $selected ; + # $debugcnt++ ; &common_debug("$debugcnt. camera_nr_$field [$display_field] : [$username eq 'rory' and $iaction eq 'edit' and $camera_details{$q_nr}{$_}{$field}{id}] : $selected : cam camera_nr=$db{$table}{$id}{camera_nr} [max_cams=$db{quotes}{$i{id}}{max_cams}]") if $selected ; + # } else { + # $opts{"camera_nr_$field"} .= $opts ; + # $debugcnt++ ; &common_debug("NO *** $debugcnt. *** camera_nr_$field [$display_field] : [$username eq 'rory' and $iaction eq 'edit' and $camera_details{$q_nr}{$_}{$field}{id}] : $selected : cam camera_nr=$db{$table}{$id}{camera_nr} [max_cams=$db{quotes}{$i{id}}{max_cams}]") ; + # } + + unless ($got{$field}) { + # $preferred_title{"item_$field"} = &common_min_print_field("item_$p_$_k") ; + $trigger_jquery .= qq~\$("#selectCamera_nr_$field\_chosen").css( "width", "96%" ); +~ ; $got{$field} = 1 ; + + $trigger_jquery_raw .= qq~\$("#selectCamera_nr_$field").change(function() { + dispCamDetails$field('$_') ; + }); + ~; + + $trigger_jquery_raw .= qq~function dispCamDetails$field(f) + { + var excl = \$("#checkboxExcl_$field"); + var camnr = \$("#selectCamera_nr_$field"); + var itcode = '' ; // var itcode = \$("#inputItem_code_$field"); + var desc = \$("#inputDescription_$field"); + var qty = \$("#inputQty_$field"); + var snr = \$("#inputSerial_nr_$field"); + var ddate = \$("#datepickDelivery_date_$field"); + var adate = \$("#datepickActive_date_$field"); + + dispCamDetails(excl,camnr,qty,itcode,desc,snr,ddate,adate,f) ; + }~; + } + } +} + +} #------------------------------------------------------------------------------------------ + +sub tab_customer_select_opts { + +my ($table,$dispfield,$where,$field) = @_ ; + +&db_min_ro($table,'*',$where,'','') ; + +foreach my $id (keys %{$db{$table}}) { + + my $saved_val = $db{quotes}{$i{id}}{$field} ; + + if ($saved_val) { my @valarr = split(/\:/,$saved_val) ; $saved_val = $valarr[0] ; } + + if ($saved_val eq $id) { $selected = 'SELECTED' ; } else { $selected = '' ; } + + $opts{$field} .= qq~~ ; + unless ($got{$field}) { + # $trigger_jquery .= qq~\$("#selectQuote_to_chosen").css( "width", "96%" ); + $trigger_jquery .= qq~\$("#selectQuote_to_chosen").css( "width", "100%" ); +~ ; $got{$field} = 1 ; + + $trigger_jquery_raw .= qq~\$("#selectQuote_to").change(function() { + dispCustomer() ; + }); + ~; + + $trigger_jquery_raw .= qq~function dispCustomer() + { + var custval = \$("#selectQuote_to").val(); + var arrP = custval.split(":"); + \$("#inputContact_name").val(arrP[1]); + \$("#inputAddress").val(arrP[4]); + \$("#inputEmail").val(arrP[2]); + \$("#inputTel").val(arrP[3]); + }~; + } +} + +} #------------------------------------------------------------------------------------------ + +# sub tab_build_terms_headers { + +# $add_form_fields .= qq~
    ~ ; +# $add_form_fields .= qq~
    ~ ; +# $add_form_fields .= qq~
    ~ ; +# $add_form_fields .= qq~
    ~ ; + +# } #------------------------------------------------------------------------------------ + +# sub tab_build_terms_fields { + +# my ($sec,$cnt,$id) = @_ ; + +# my $exfield = "excl_$cnt\_$sec\s" ; +# my $inpfield = "$sec\_$cnt" ; + +# unless ($db{quote_notes}{1}{$inpfield}) { $checkit{$exfield} = 1 ; } + +# my $val = ($db{$table}{$id}{$inpfield} && $db{$table}{$id}{$inpfield} ne "-1") ? $db{$table}{$id}{$inpfield} : (($db{$table}{$id}{$inpfield} && $db{$table}{$id}{$inpfield} eq "-1")) ? "" : $db{quote_notes}{1}{$inpfield} ; + +# $note_display_style = '' ; $note_display_plus_btn = '' ; +# # unless ($cnt==1 or $db{quote_notes}{1}{$inpfield}) { +# unless ($cnt==1 || $val) { + # $note_display_style = qq~style='display:none;'~ ; + # $trigger_jquery_raw .= qq~ \$("#btn_$cnt\_$sec").click(function () { + # \$("#$cnt\_$sec").toggle(); + # \$("#btn_$cnt\_$sec").hide(); + # var v = $cnt + 1 ; + # \$("#btn_"+v+"\_$sec").show(); + # });~ ; + # if ($cnt>$cntnoteloop) { $note_display_butt = qq~display:none;~ ; } else { $note_display_butt = '' ; } + # $note_display_plus_btn = qq~~; +# } else { $cntnoteloop++ ; } + +# $add_form_fields .= qq~
    ~ ; + +# # $add_form_fields .= qq~
    ~ ; +# # if ($checkit{$exfield} == 1) { $checked = 'CHECKED'; } elsif (($excl_tick{$cnt}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } + +# # if ($db{$table}{$id}{$exfield} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } +# $sec = "_" . $sec . "s" ; +# $col_name = "excl" . "$sec" ; +# $counter = 0 ; +# # &db_min_ro('quotes_min', "id, excl$sec", "id = $id", '', '') ; + +# foreach my $col_input (split(/\;/,$db{quotes_min}{$id}{$col_name})) { + # $counter++ ; + # $saved_field{"excl"}{$sec}{$counter} = $col_input ; +# } + +# if ($saved_field{"excl"}{$sec}{$cnt}) { $checked = 'CHECKED'; } else { $checked = '' ; } + +# $label{$exfield} = 1 ; +# $fcol=1 ; +# $add_form_fields .= &common_min_form_checkbox_col($exfield,$checkit{$exfield},$checked) ; +# $fcol=6 ; +# $input_style{$inpfield} = qq~style='margin-bottom:4px;margin-top:-2px;'~ ; # add spaces between boxes +# $add_form_fields .= &common_min_form_input_col($inpfield,$val,'') ; +# $add_form_fields .= qq~
    ~ ; +# $add_form_fields .= qq~
    $note_display_plus_btn
    ~ ; + +# } #------------------------------------------------------------------------------------ + +# sub tab_build_terms_fields_terms_and_conditions { + + # my ($sec,$cnt,$id) = @_ ; + + # my $exfield = "excl_$cnt\_$sec" ; + # my $inpfield = "$sec" ; + # my $quote_notes_field = "$sec\_$cnt" ; + + # unless ($db{$table}{$id}{$inpfield}) { $checkit{$exfield} = 1 ; } + + # if ($db{$table}{$id}{$inpfield}) { $selected{$db{$table}{$id}{$inpfield}} = 'SELECTED';} + + # $note_display_style = '' ; + # unless ($cnt==1 or $db{$table}{$id}{$inpfield}) { + # $note_display_style = qq~style='display:none;'~ ; + # $trigger_jquery_raw .= qq~ \$("#btn_$cnt\_$sec").click(function () { + # \$("#$cnt\_$sec").toggle(); + # \$("#btn_$cnt\_$sec").hide(); + # var v = $cnt + 1 ; + # \$("#btn_"+v+"\_$sec").show(); + # });~ ; + # if ($cnt>$cntnoteloop) { $note_display_butt = qq~display:none;~ ; } else { $note_display_butt = '' ; } + # } else { $cntnoteloop++ ; } + + # $add_form_fields .= qq~
    ~ ; + + + + # # $add_form_fields .= qq~
    ~ ; + # # if ($checkit{$exfield} == 1) { $checked = 'CHECKED'; } elsif (($excl_tick{$cnt}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } + # $sec_2 = "_" . $sec ; + # $col_name = "excl" . "$sec_2" ; + # $counter = 0 ; + # # &db_min_ro('quotes_min', "id, excl$sec", "id = $id", '', '') ; + + # foreach my $col_input (split(";", $db{quotes_min}{$id}{$col_name})){ + # $counter++ ; + # $saved_field{"excl"}{$sec_2}{$counter} = $col_input ; + # } + + # if ($saved_field{"excl"}{$sec_2}{$cnt}) { $checked = 'CHECKED'; } else { $checked = ''; } + + # # if ($db{$table}{$id}{$exfield} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + + # $label{$exfield} = 1 ; + # $fcol=1 ; + # $add_form_fields .= &common_min_form_checkbox_col($exfield,$checkit{$exfield},$checked) ; + # $fcol=6 ; + # $input_style{$inpfield} = qq~style='margin-bottom:4px;margin-top:-2px;'~ ; # add spaces between boxes + # $opts{$inpfield} = "" ; + # for (1 .. 5){ + # $quote_notes_field = "$sec\_$_" ; + # next unless $db{quote_notes}{1}{$quote_notes_field} ; + # $opts{$inpfield} .= qq() ; + # } + # $allow_deselect{$inpfield} = 1; + # $add_form_fields .= &common_min_form_select_col($inpfield,$db{$table}{$id}{$inpfield},'') ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    $note_display_plus_btn
    ~ ; + +# } #------------------------------------------------------------------------------------ + +sub tab_build_qt_right { + +my ($id,$tab,$ret) = @_ ; + +if ($tab==1) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_office_details' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $lcol = 2 ; + + $add_form_fields = '' ; + + $fcol = 9 ; + $textarea_height{notes} = 80 ; + $add_form_fields .= &common_min_form_textarea('notes',$db{$table}{$id}{notes},'') ; + $add_form_fields .= qq~
     
    ~ ; + $textarea_height{office_notes} = 80 ; + $add_form_fields .= &common_min_form_textarea('office_notes',$db{$table}{$id}{office_notes},'') ; + $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + +if ($tab==4) { # Cusotmer Details + + # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- + + my $sec = '_invoice_notes' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + if ($ret) { return ; } + + $lcol = 2 ; + + $add_form_fields = '' ; + + $fcol = 9 ; + # $add_form_fields .= qq~
     
    ~ ; + $add_form_fields .= &common_min_form_input('po_nr',$db{$table}{$id}{po_nr},'') ; + $add_form_fields .= &common_min_form_textarea('invoice_notes',$db{$table}{$id}{invoice_notes},'') ; + $add_form_fields .= qq~
     
    ~ ; + + &tab_content_box($sec_name,$sec_col); + + # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- + } + +} #------------------------------------------------------------------------------------ + +sub tab_curr_symbols { + +$curr_symb{ZAR} = 'R'; +$curr_symb{USD} = '$'; +# $curr_symb{GBP} = '£'; +$curr_symb{GBP} = 'GBP'; +# $curr_symb{EUR} = '€'; +$curr_symb{EUR} = 'EUR'; + +our $js_curr_arr = '' ; + +foreach (keys %curr_symb) { + $js_curr_arr .= qq(currArr['$_'] = "$curr_symb{$_}";) ; + } + +} #------------------------------------------------------------------------------------ + +sub tab_build_qt_col_headers { + +my ($sec) = @_ ; + +my $style_vat = '' ; if ($no_vat{$sec}) { $style_vat = 'style="display:none;"' ; } + +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +# $add_form_fields .= qq~
    ~ ; +# $add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; + +%cost_desc = () ; %def_qty = () ; %def_zar = () ; %min_zar = () ; %vat_tick = () ; %excl_tick = () ; + +} #---------------------------------------------------------------------------------------- + +sub tab_content_box { + +my ($sec_name,$sec_col) = @_ ; + +$fcol=9 ; +$print_box_content_rows .= &common_min_box_top('indent-left',$sec_name,$sec_col,$cam_box_icon); +# $print_box_content_rows .= qq~
    ~ ; +$print_box_content_rows .= qq~$add_form_fields~; +$print_box_content_rows .= &common_min_box_foot; + +} #---------------------------------------------------------------------------------------- + +sub tab_cnt { + +our %cntxt = () ; + +$cntxt{1} = 'one' ; +$cntxt{2} = 'two' ; +$cntxt{3} = 'three' ; +$cntxt{4} = 'four' ; +$cntxt{5} = 'five' ; + +# $cntxt{6} = 'six' ; +# $cntxt{7} = 'seven' ; +# $cntxt{9} = 'nine' ; +# $cntxt{9} = 'nine' ; + +} #---------------------------------------------------------------------------------------- + +sub tab_names { + +my ($tab) = @_ ; + +my $tabname = '' ; + + if ($tab==1) { $tabname = 'Quote Details' ; } +elsif ($tab==2) { $tabname = 'Costing' ; } +elsif ($tab==3) { $tabname = 'Camera Details' ; } +elsif ($tab==4) { $tabname = 'Invoice Details' ; } +# elsif ($tab==7) { $tabname = 'Extended Warranty' ; } +# elsif ($tab==8) { $tabname = 'Rental' ; } +elsif ($tab==5) { $tabname = 'Document Uploads' ; } + +return ($tabname) ; + +} #------------------------------------------------------------------------------------ + +sub tab_hash { + +# &tabs_get_default_totals ; + +# for (1 .. 8) { + # my $tname = &tab_names($_) ; + + # our $ret_pdf_link_sec = '' ; # _sa_out+16|_cl_del+13|_sa_in+17|_des_sa+13| + + # &tab_build_qt_left('',$_,1) ; + # &tab_build_qt_right('',$_,1) ; + + # $tabcnt{$tname} = $_ ; + # $tabsec{$tname} = $ret_pdf_link_sec ; + # } + +} #------------------------------------------------------------------------------------ + +sub tab_sec_det { + +my ($sec) = @_ ; + +my ($sec_nam,$sec_cnt,$sec_col) ; + +$sec_col = '71919b' ; # '85acb8' ; +$sec_cnt = 20 ; +$sec_nam = substr($sec,1) ; +@array = split(/\_/,$sec_nam); my @sec_nam = map ucfirst, @array; +$sec_nam = join(" ", @sec_nam) ; + +if ($sec eq '_costing') { + $sec_nam = 'Camera System Costing' ; + for (1 .. 20) { $vat_tick{$_} = 1 ; } + } + +return ($sec_nam,$sec_cnt,$sec_col) ; + +} #------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/_FromProd/v1.0/today.pm b/libs/modules/_FromProd/v1.0/today.pm new file mode 100644 index 0000000..44374f2 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/today.pm @@ -0,0 +1,42 @@ +sub today { + +our ($now_sec,$now_min,$now_hour,$now_dd,$now_mm,$now_year,$now_wday,$now_yday,$isdst)=localtime(); + +$now_sec = sprintf("%02d", $now_sec) ; +$now_min = sprintf("%02d", $now_min) ; +$now_hour = sprintf("%02d", $now_hour) ; + +$now_year += 1900; + +$now_dd = sprintf("%02s", $now_dd) ; +$now_mm = sprintf("%02s", $now_mm + 1) ; +$now_yy = sprintf("%02s", $now_year - 2000) ; + +use Date::Calc qw(:all); + +our ($sayear,$samonth,$saday,$sahour,$samin,$sasec) = Add_Delta_DHMS($now_year,$now_mm,$now_dd,$now_hour,$now_min,$now_sec,0,2,0,0); # add 2 hours for server time + +$samonth = sprintf("%02s", $samonth) ; +$saday = sprintf("%02s", $saday) ; +$sahour = sprintf("%02s", $sahour) ; +$samin = sprintf("%02s", $samin) ; +$sasec = sprintf("%02s", $sasec) ; + +$now_year = $sayear ; +$now_mm = $samonth ; +$now_dd = $saday ; +$now_sec = $sasec ; +$now_min = $samin ; +$now_hour = $sahour ; + +$now_hh_min_sec = $sahour . ':' . $samin . ':' . $sasec ; + +$now_ccyymmdd = $now_year . $now_mm . $now_dd ; +$now_ccyymmddhrmnsc = $now_year . $now_mm . $now_dd . $now_hour . $now_min . $now_sec ; +$now_dd_mm_ccyy = $now_dd . '-' . $now_mm . '-' . $now_year ; +$now_ccyy_mm_dd = $now_year . '-' . $now_mm . '-' . $now_dd ; +$nowsddsmmsccyy = $now_dd . '/' . $now_mm . '/' . $now_year ; + +} #------------------------------------------------------------------------------------------ + +1; \ No newline at end of file diff --git a/libs/modules/_FromProd/v1.0/uploader.pm b/libs/modules/_FromProd/v1.0/uploader.pm new file mode 100644 index 0000000..2dd2df9 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/uploader.pm @@ -0,0 +1,30 @@ + +sub uploader_filmfreight { + +my ($file_to_upload,$ftp_dir,$ftp_file_name,$delete_file_to_upload) = @_ ; + +use Net::FTP; + +my $host = "154.0.175.152"; # filmfreight.co.za +my $user = "filmfree"; +my $password = "h0lNH8fMzrrWUC"; + +my $ftp = Net::FTP->new($host) or die "Can't open $host : $!\n" ; +$ftp->login($user, $password) or die "Can't log $user in : $!\n" ; + +$ftp->cwd($ftp_dir) or die "Can't cwd to $ftp_dir\n"; + +$ftp->binary() or die "Can't change to binary mode"; # Unix and Windows switch $ftp->ascii(); + +$ftp->put($file_to_upload, "$ftp_dir/$ftp_file_name") or die "Can't put $file_to_upload into $ftp_dir\n" ; + +$ftp->quit; + +# if ($delete_file_to_upload eq 'y') { + # unlink ("$file_to_upload") ; + # } + +} #------------------------------------------------------------------------------------------------------------- + +1; + diff --git a/libs/modules/_FromProd/v1.0/users.pm b/libs/modules/_FromProd/v1.0/users.pm new file mode 100644 index 0000000..ad80925 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/users.pm @@ -0,0 +1,426 @@ + +sub users_list_screen { + + &db_open_ro; + $db_ignore_open_close=1; + &users_list_vars ; + $db_ignore_open_close=0 ; + &db_close_conn ; + + foreach my $id (keys %{$db{$table}}) { + + $delete_button = ($seen_operator{$id}) ? qq~~ : qq~~ ; + + my $disp_blocked = qq~~; + if ($db{$table}{$id}{block} || $db{$table}{$id}{inactive} ) { $disp_blocked = qq~~; } + + # if (!$useropts{it}{$username} && (substr($db{$table}{$id}{username},0,4) eq 'rory' || substr($db{$table}{$id}{username},0,6) eq 'handre')) { next ; } + + my $it_username_subs_4 = substr($db{$table}{$id}{username},0,4) ; # rory / jean + my $it_username_subs_6 = substr($db{$table}{$id}{username},0,6) ; # handre + + if (($useropts{it}{$it_username_subs_4} || $useropts{it}{$it_username_subs_6}) && !$useropts{it}{$username} && $useremail =~ /re8it/g) { next ; } + + next if $glod_user_level < 4 && $level{$db{$table}{$id}{user_type}} > 1 && $user_type eq 'casual' ; + + $opts{$lcpage} .= qq~~ ; + $print_tbody .= qq~ + $id + $db{$table}{$id}{username} + $db{$table}{$id}{name} + $db{$table}{$id}{email} + $disp_blocked + $db{$table}{$id}{based_in}~ ; + + $print_tbody .= qq~ + $level{$db{$table}{$id}{user_type}}~ if $user_type eq 'casual' ; + + $print_tbody .= qq~ + $db{$table}{$id}{lastupdate} + $db{$table}{$id}{lastvisitdate} + +   +  $delete_button + + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub users_list_vars { + + our %seen = () ; our %seen_operator = () ; our $delete_button = '' ; + + &db_min_ro('events','id, user_id','','','') ; + + foreach my $id (keys %{$db{'events'}}) { + next if $seen{$db{'events'}{$id}{user_id}} ; + $seen{$db{'events'}{$id}{user_id}} = 1 ; + } + + &db_min_ro('event_quotes','id,user_id,operator_ids,daily_operator_ids','','','') ; + + foreach my $id (keys %{$db{event_quotes}}) { + # next if $seen{$db{event_quotes}{$id}{user_id}} ; + $seen{$db{event_quotes}{$id}{user_id}} = 1 ; + my $op_ids = $db{event_quotes}{$id}{operator_ids} ; + next unless $op_ids ; + my @op_ids = ($op_ids =~ /;/) ? split(/;/,$op_ids) : split(/,/,$op_ids) ; + for my $op_id (@op_ids) { + next if $seen_operator{$op_id} || !$op_id ; + $seen_operator{$op_id} = 1 ; + } + foreach my $op_ids_list (split(/\|/,$db{event_quotes}{$id}{daily_operator_ids})) { + next unless $op_ids_list ; + foreach my $op_id (split(/\;/,$op_ids_list)) { + next if $seen_operator{$op_id} || !$op_id ; + $seen_operator{$op_id} = 1 if $op_id ; + } + } + } + + &db_min_ro('quotes','id,user_id','','','') ; + + foreach my $id (keys %{$db{quotes}}) { + next if $seen{$db{quotes}{$id}{user_id}} ; + $seen{$db{quotes}{$id}{user_id}} = 1 ; + } + + $level{casual_a} = 1 ; + $level{casual_b} = 2 ; + $level{casual_c} = 3 ; + + if ($user_type eq 'coding_provider') { + &db_min_ro('analytics_event_bookings','id,fixtures_saved_values','','','') ; + foreach my $id (keys %{$db{analytics_event_bookings}}) { + my @split1 = split(/\|/,$db{analytics_event_bookings}{$id}{fixtures_saved_values}) ; + foreach my $row (@split1) { + my @split2 = split(/\;/,$row) ; + $seen{$split2[-2]} = 1 ; + } + } + } + + if ($user_type eq 'analytics_client') { + &db_min_ro('analytics_event_bookings','id,client_id','','','') ; + foreach (keys %{$db{analytics_event_bookings}}) { + $seen{$db{analytics_event_bookings}{$_}{client_id}} = 1 ; + } + } + + # my $cust_sql_where = "user_type = '$user_type'" if $user_type ; + my $cust_sql_where = ($user_type) ? "user_type LIKE '$user_type%'" : "user_type NOT LIKE 'casual%' AND user_type <> 'schools_manager' AND user_type <> 'installation_partner'" ; + + &db_min_ro($table,'*',$cust_sql_where,'username','') ; + +} #------------------------------------------------------------------------------------------ + +sub users_sort_fields { + + my $fcnt = 1 ; + + $sort_field{$fcnt} = 'name' ; $fcnt++ ; + $sort_field{$fcnt} = 'email' ; $fcnt++ ; + $sort_field{$fcnt} = 'phone' ; $fcnt++ ; + + if ($user_type eq 'casual') { + $sort_field{$fcnt} = 'bank' ; $fcnt++ ; + $sort_field{$fcnt} = 'bank_acc_no' ; $fcnt++ ; + } + + $sort_field{$fcnt} = 'based_in' ; $fcnt++ ; + $sort_field{$fcnt} = 'user_type' ; $fcnt++ ; + # $sort_field{$fcnt} = 'organisation_ids' ; $fcnt++ ; + + if ($user_type eq 'schools_manager' || $user_type eq 'installation_partner' || $user_type eq 'casual') { + $sort_field{$fcnt} = 'region_ids' ; + $fcnt++ ; + } + + if ($user_type eq 'installation_partner') { + $sort_field{$fcnt} = 'customer_ids' ; + $fcnt++ ; + } + + $sort_field{$fcnt} = 'block' ; $fcnt++ ; + $sort_field{$fcnt} = 'inactive' ; $fcnt++ ; + + # if ($dialog) { + # $sort_field{$fcnt} = 'sel_field' ; $fcnt++ ; + # } + + $sort_field{$fcnt} = 'username' ; $fcnt++ ; + $sort_field{$fcnt} = 'password' if $iaction eq 'add' ; + +} #------------------------------------------------------------------------------- + +sub users_add_db_fields { + + $ignore{lastvisitdate} = 1 ; + $ignore{iaction} = 1 ; + $ignore{block} = 1 ; + $ignore{inactive} = 1 ; + # $ignore{id} = 1 ; + $hidden{lastupdate} = 2 ; + $required{email} = 1 ; + $required{username} = 1 ; + $required{name} = 1 ; + $required{password} = 1 ; + + &sort_fields ; + +} #------------------------------------------------------------------------------------------ + +sub users_edit_db_fields { + + $ignore{lastvisitdate} = 1 ; + $ignore{password} = 1 ; + $ignore{iaction} = 1 ; + $hidden{id} = 1 ; # 1 = bypass for db update + $hidden{username} = 1 ; # 1 = bypass for db update + $hidden{lastupdate} = 2 ; # 2 = update db + # $readonly{username} = 'READONLY' ; + $checkbox{block} = 1 ; + $checkbox{inactive} = 1 ; + # $required{username} = 1 ; + $required{email} = 1 ; + + &sort_fields ; + +} #------------------------------------------------------------------------------------------ + +sub users_add_screen { + + # called from common_add_screen + + $selected{user_type}{$user_type} = "SELECTED" if $user_type ; + + &users_select_opts ; + + our $savjqy = 1 if $user_type ; # incorporate jquery into the save event to accommodate the multiple chosen options + +} #------------------------------------------------------------------------------------------ + +sub users_edit_screen { + + our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + + $selected{based_in}{$db{$table}{$i{id}}{based_in}} = "SELECTED" ; + $selected{user_type}{$db{$table}{$i{id}}{user_type}} = "SELECTED" ; + + $extra_form_fields .= &common_min_form_input('new_password','','password') ; + + &users_select_opts ; + + our $savjqy = 1 if $user_type ; # incorporate jquery into the save event to accommodate the multiple chosen options + +} #------------------------------------------------------------------------------------------ + +sub users_thead { + + $print_thead = qq~IDUSERNAMENAMEEMAILACTIVEBASE~; + + $print_thead .= qq~LEVEL~ if $user_type eq 'casual' ; + + $print_thead .= qq~LASTUPDATELASTVISITDATE ~ ; + +} #------------------------------------------------------------------------------- + +sub users_process_multi_select { + + # local @organisationids = split(/\,/,$i{organisationids}) ; + # my $organisationids = join(",",@organisationids) ; + # $organisationids =~ s/\s//g; # remove white space + # $ignore{organisationids} = 1 ; + # $i{organisation_ids} = $organisationids ; + + $i{organisation_ids} = '0' ; + + local @regionids = split(/\,/,$i{regionids}) ; + my $regionids = join(",",@regionids) ; + $regionids =~ s/\s//g; # remove white space + $ignore{regionids} = 1 ; + $i{region_ids} = $regionids || '0' ; + + if ($user_type eq 'installation_partner' || $user_type eq 'coding_provider' || $user_type eq 'analytics_client') { + local @customerids = split(/\,/,$i{customerids}) ; + my $customerids = join(",",@customerids) ; + $customerids =~ s/\s//g; # remove white space + $ignore{customerids} = 1 ; + $i{customer_ids} = $customerids ; + } else { + $i{customer_ids} = '0' ; + } + +} #------------------------------------------------------------------------------------------ + +sub users_select_opts { + + # $multiple{organisation_ids} = 1; + # my @organisation_ids = split(/\,/,$db{$table}{$i{id}}{organisation_ids}); + # foreach (@organisation_ids) { $selected_multi{$_} = 'SELECTED' ; } + # $preferred_title{organisation_ids} = "Venue" ; + # &common_min_select_opts('organisation_ids','organisations','name',$db{$table}{$i{id}}{organisation_ids},'') ; + # $extra_form_fields .= qq~~; + + # $trigger_jquery_raw .= qq~ + # \$("#savebutt").click(function() { + # let st_val = \$("#selectOrganisation_ids").chosen().val() ; + # \$('#organisation-ids').val(st_val); + # \$('#users-form').submit(); + # });~; + + if ($user_type eq 'installation_partner' || $user_type eq 'coding_provider' || $user_type eq 'analytics_client') { + $multiple{customer_ids} = 1; + my @customer_ids = split(/\,/,$db{$table}{$i{id}}{customer_ids}); + foreach (@customer_ids) { $selected_multi{$_} = 'SELECTED' ; } + $preferred_title{customer_ids} = "Customers" ; + &common_min_select_opts('customer_ids','customers','name','','') ; + $extra_form_fields .= qq~~; + $add_to_trigger_jquery_raw = qq~ + let cust_val = \$("#selectCustomer_ids").chosen().val() ; + \$('#customer-ids').val(cust_val); + ~; + } + + if ($user_type eq 'schools_manager' || $user_type eq 'installation_partner' || $user_type eq 'casual' || $user_type eq 'coding_provider' || $user_type eq 'analytics_client') { + $multiple{region_ids} = 1; + my @region_ids = split(/\,/,$db{$table}{$i{id}}{region_ids}); + foreach (@region_ids) { $selected_multi{$_} = 'SELECTED' ; } + $preferred_title{region_ids} = "Regions" ; + &common_min_select_opts('region_ids','regions','name','','') ; + $extra_form_fields .= qq~~; + + $trigger_jquery_raw .= qq~ + \$("#savebutt").click(function() { + let st_val = \$("#selectRegion_ids").chosen().val() ; + \$('#region-ids').val(st_val); + $add_to_trigger_jquery_raw + \$('#users-form').submit(); + });~; + } + + # &common_min_select_opts('organisation_ids','organisations','name',$db{$table}{$i{id}}{organisation_ids},1,'',''); + + &common_min_select_opts('based_in','regions','name',$db{$table}{$i{id}}{based_in},1,'','','code') ; + + # $required{based_in} = 1 ; + # $select{based_in} = 1 ; + # # $opts{based_in} = qq~~ ; + # $opts{based_in} = qq~~ ; + + $required{user_type} = 1 ; + $select{user_type} = 1 ; + if ($user_type eq 'casual') { + if ($glod_user_level > 2) { + $opts{user_type} = qq~~; + } + if ($glod_user_level > 3) { + $opts{user_type} .= qq~~; + } + $opts{user_type} .= qq~~; + } elsif ($user_type) { + my $user_type_name = join(" ", map { ucfirst lc } split /_/, $user_type); + $opts{user_type} = qq~ + + ~ ; + } else { + $opts{user_type} = qq~ + + + + + + + + + + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub users_insert { + + &add_db_fields ; + + my $crypted_password = apache_md5_crypt($i{password},$useropts{salt}) ; + $i{password} = $crypted_password ; + $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{email} = lc $i{email} ; + + $i{id} = &db_min_get_max($table,'id') ; + + &process_multi_select if $user_type ; + + &db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub users_update { + + unless ($i{id}) { $error = qq(NO ID) ; return ; } + + &edit_db_fields ; + + unless ($i{block}) { $i{block} = '0' ; } + unless ($i{inactive}) { $i{inactive} = '0' ; } + + if ($i{new_password}) { + my $crypted_password = apache_md5_crypt($i{new_password},$useropts{salt}) ; + $i{password} = $crypted_password ; + $ignore{password} = 0 ; + $hidden{password} = 2 ; + } + + $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + + &process_multi_select if $user_type ; + + &db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub users_validate { + + my $user_exists = '' ; my $email_exists = '' ; + + $i{username} = lc $i{username} ; + $i{username} =~ s/ //gi ; + + $i{email} = lc $i{email} ; + $i{email} =~ s/ //gi ; + + &db_min_ro($table,'*',"username='$i{username}' OR email='$i{email}'",'username','') ; + + foreach my $id (keys %{$db{$table}}) { + if ($db{$table}{$id}{username} eq $i{username}) { + $user_exists = 1 ; + last; + } + + if ($i{email} && $db{$table}{$id}{email} eq $i{email}) { + $email_exists = 1 ; + last; + } + } + + if ($user_exists) { + $alert = &common_min_alert('warning',"USERNAME ALREADY EXISTS!",'ok') ; + %col_name = (); + &common_min_add_screen; + &common_min_screen1 unless $dialog ; + &screen1 if $dialog ; + } + + if ($email_exists) { + $alert = &common_min_alert('warning',"EMAIL ALREADY EXISTS!",'ok') ; + %col_name = (); + &common_min_add_screen; + &common_min_screen1 unless $dialog ; + &screen1 if $dialog ; + } + +} #------------------------------------------------------------------------------------------ + +1 ; \ No newline at end of file diff --git a/libs/modules/_FromProd/v1.0/xlscreator.pm b/libs/modules/_FromProd/v1.0/xlscreator.pm new file mode 100644 index 0000000..dd1e5d7 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/xlscreator.pm @@ -0,0 +1,619 @@ +sub xlscreator_delete_previous_xls { + +my ($path) = @_ ; + +opendir(DIR, "$path") or die "cant open Directory $path: $!\n"; + +while(defined($folder = readdir(DIR))) { + if (length $folder > 2) { + my ($file,$type) = split(/\./,$folder) ; + + # if ($match) { unless ($file =~ /$match/gi) { next ; } } + + # my ($j1,$j2,$accid,$date) = split(/\-/,$file) ; + # if ($match) { unless ($accid eq $match) { next ; } } + + if (-e "$path/$file.xls"){ + unlink ("$path/$file.xls") or print "unable to unlink - $path/$file.xls : $!"; + } + } + } + +closedir(DIR) ; + +} #------------------------------------------------------------------------------------ + +sub xlscreator_create_xls { + +my ($file) = @_; + +$workbook = Spreadsheet::WriteExcel->new($file) or die "ERROR : $file : $!"; + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_close_xls { + +$workbook->close(); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_hide_gridlines_xls { + +($worksheet_name) = @_; + +$worksheet{$worksheet_name}->hide_gridlines(1); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_set_margins_xls { + +($worksheet_name,$margin_width) = @_; + +$worksheet{$worksheet_name}->set_margins($margin_width); # Set all margins to the same value in inches + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_add_worksheet { + +my ($worksheet_name) = @_; + +$worksheet{$worksheet_name} = $workbook->add_worksheet($worksheet_name); + +#$worksheet{$worksheet_name}->add_write_handler(qr[\w], \&xlscreator_store_string_widths); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_add_pie_chart { + +my ($worksheet_name) = @_; + +$chart{$worksheet_name} = $workbook->add_chart( type => 'pie', embedded => 1 ); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_write_xls { + +my ($worksheet_name,$row,$col,$token,$cellformat) = @_; + +$token =~ s/\,//g; + +$worksheet{$worksheet_name}->write($row,$col,$token,$cellformat); + +#&xlscreator_autofit_columns($worksheet{$worksheet_name}); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_write_formula { + +my ($worksheet_name,$row,$col,$formula,$cellformat) = @_; + +$worksheet{$worksheet_name}->write_formula($row,$col,$formula,$cellformat); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_freeze_panes { + +my ($worksheet_name,$rows,$cols) = @_; + +$worksheet{$worksheet_name}->freeze_panes($rows,$cols); # Freeze the first 5 rows + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_insert_image { + +my ($worksheet_name,$row,$col,$file,$margin_right, $margin_bottom) = @_; + +$worksheet{$worksheet_name}->insert_image($row,$col,$file,$margin_right,$margin_bottom); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_xls_format { + +$format1 = $workbook->add_format(); +$format1->set_font('Verdana'); +$format1->set_size(8); + +$format2 = $workbook->add_format(); +$format2->copy($format1); +$format2->set_bold(); # Turns bold on +$format2->set_num_format('#,##0.00'); # 1,234.56 + +$format3 = $workbook->add_format(); +$format3->copy($format1); +$format3->set_num_format('#,##0.00'); # 1,234.56 + +$format4 = $workbook->add_format(); +$format4->copy($format1); +$format4->set_bold(); # Turns bold on +$format4->set_num_format('#,##0.00'); # 1,234.56 +$format4->set_top('6'); +$format4->set_bottom('6'); + +$format5 = $workbook->add_format(); +$format5->copy($format1); +$format5->set_underline(); # Single underline + +$format6 = $workbook->add_format(); +$format6->copy($format1); +$format6->set_underline(); # Single underline +$format6->set_align('right'); + +$format7 = $workbook->add_format(); +$format7->copy($format1); +$format7->set_align('right'); +$format7->set_num_format('#,##0.00'); # 1,234.56 + +$format8 = $workbook->add_format(); +$format8->copy($format1); +$format8->set_bold(); # Turns bold on +$format8->set_align('left'); +$format8->set_num_format('#,##0.00'); # 1,234.56 + +$format9 = $workbook->add_format(); +$format9->copy($format1); +$format9->set_bold(); # Turns bold on +$format9->set_align('right'); +$format9->set_num_format('#,##0.00'); # 1,234.56 + +$format10 = $workbook->add_format(); +$format10->copy($format1); +$format10->set_align('left'); + +$format11 = $workbook->add_format(); +$format11->copy($format1); +$format11->set_align('center'); +$format11->set_bg_color(0x16); #0x08 = 'black' ; #0x0C = 'blue' ; #0x10 = 'brown' ; #0x0F = 'cyan' ; #0x17 = 'gray' ; #0x11 = 'green' ; #0x0B = 'lime' ; #0x0E = 'magenta' ; #0x12 = 'navy' ; #0x35 = 'orange' ; #0x21 = 'pink' ; #0x14 = 'purple' ; #0x0A = 'red' ; #0x16 = 'silver' ; #0x09 = 'white' ; #0x0D = 'yellow' ; +$format11->set_top('1'); +$format11->set_bottom('1'); +$format11->set_left('1'); +$format11->set_right('1'); + +$format12 = $workbook->add_format(); +$format12->set_bg_color(0x16); +$format12->set_top('1'); +$format12->set_bottom('1'); +$format12->set_left('1'); +$format12->set_right('1'); + +$format13 = $workbook->add_format(); +$format13->copy($format1); +$format13->set_bg_color(0x16); +$format13->set_num_format('#,##0.00'); # 1,234.56 +$format13->set_top('1'); +$format13->set_bottom('1'); +$format13->set_left('1'); +$format13->set_right('1'); + +$format14 = $workbook->add_format(); +$format14->copy($format1); +$format14->set_bold(); # Turns bold on +$format14->set_bg_color(0x16); +$format14->set_top('1'); +$format14->set_bottom('1'); +$format14->set_left('1'); +$format14->set_right('1'); + +$format15 = $workbook->add_format(); +$format15->copy($format1); +$format15->set_align('right'); +$format15->set_num_format('#,##0.00'); # 1,234.56 +$format15->set_top('1'); +$format15->set_bottom('1'); +$format15->set_left('1'); +$format15->set_right('1'); + +$format16 = $workbook->add_format(); +$format16->copy($format1); +$format16->set_bg_color(0x16); +$format16->set_num_format('#,##0.0000'); # 1,234.56 +$format16->set_top('1'); +$format16->set_bottom('1'); +$format16->set_left('1'); +$format16->set_right('1'); + +$format17 = $workbook->add_format(); +$format17->copy($format1); +$format17->set_align('right'); +$format17->set_bg_color(0x16); +$format17->set_num_format('#,##0.00'); # 1,234.56 +$format17->set_top('1'); +$format17->set_bottom('1'); +$format17->set_left('1'); +$format17->set_right('1'); + +$format18 = $workbook->add_format(); +$format18->copy($format1); +$format18->set_bold(); +$format18->set_align('center'); + +$format19 = $workbook->add_format(); +$format19->copy($format1); +$format19->set_num_format('#,##0.00'); # 1,234.56 +$format19->set_top('1'); +$format19->set_bottom('6'); + +$format20 = $workbook->add_format(); +$format20->copy($format1); +$format20->set_align('center'); +$format20->set_num_format(0x0a); #0.00% (0x09 = 0%) + +$format21 = $workbook->add_format(); +$format21->copy($format1); +$format21->set_align('right'); + +$format22 = $workbook->add_format(); +$format22->copy($format1); +$format22->set_bold(); # Turns bold on +$format22->set_align('right'); +$format22->set_bg_color(0x16); +$format22->set_num_format('#,##0.00'); # 1,234.56 + +$format23 = $workbook->add_format(); +$format23->copy($format1); +$format23->set_bold(); # Turns bold on +$format23->set_color(0x0A); # red + +$format24 = $workbook->add_format(); +$format24->copy($format1); +$format24->set_top('2'); + +$format25 = $workbook->add_format(); +$format25->copy($format1); +$format25->set_bottom('3'); + +$format26 = $workbook->add_format(); +$format26->copy($format1); +$format26->set_bold(); # Turns bold on +$format26->set_align('left'); + +$format27 = $workbook->add_format(); +$format27->copy($format1); +$format27->set_bold(); # Turns bold on +$format27->set_align('right'); + +$format28 = $workbook->add_format(); +$format28->set_underline(2); # Single underline + +$format29 = $workbook->add_format(); +$format29->set_font('Verdana'); +$format29->set_size(5); + +$format30 = $workbook->add_format(); +$format30->set_font('Verdana'); +$format30->set_size(7); + +$format31 = $workbook->add_format(); +$format31->set_font('Verdana'); +$format31->set_size(4); +$format31->set_align('right'); + +$format32 = $workbook->add_format(); +$format32->set_font('Verdana'); +$format32->set_size(6); + +$format33 = $workbook->add_format(); +$format33->copy($format10); + +$format34 = $workbook->add_format(); +$format34->copy($format1); +$format34->set_border(1); + +$format35 = $workbook->add_format(); +$format35->copy($format10); +$format35->set_text_wrap(); +$format35->set_border(1); + +my $light_blue = $workbook->set_custom_color(40,'#D5FFFF'); + +$format36 = $workbook->add_format(); +$format36->copy($format8); +$format36->set_bg_color($light_blue); + +$format37 = $workbook->add_format(); +$format37->copy($format10); +$format37->set_bg_color($light_blue); + +$format38 = $workbook->add_format(); +$format38->copy($format1); +$format38->set_align('center'); +$format38->set_bg_color($light_blue); + +$format39 = $workbook->add_format(); +$format39->copy($format1); +$format39->set_bg_color($light_blue); + +my $light_grey = $workbook->set_custom_color(41,'#c6c6c6'); + +$format40 = $workbook->add_format(); +$format40->copy($format1); +$format40->set_align('center'); +$format40->set_bg_color($light_grey); +$format40->set_border(1); + +my $very_light_grey = $workbook->set_custom_color(42,'#EEEEEE'); + +$format41 = $workbook->add_format(); +$format41->copy($format10); +$format41->set_bg_color($very_light_grey); +$format41->set_border(1); +$format41->set_italic(); + +# merged +$format42 = $workbook->add_format(); +$format42->copy($format40); + +$format43 = $workbook->add_format(); +$format43->copy($format38); +$format43->set_border(1); + +$format44 = $workbook->add_format(); +$format44->copy($format41); +$format44->set_bg_color(0x09); + +$format45 = $workbook->add_format(); +$format45->set_font('Verdana'); +$format45->set_size(10); + +my $green = $workbook->set_custom_color(43,'#00b050'); + +$format46 = $workbook->add_format(); +$format46->set_align('center'); +$format46->copy($format45); +$format46->set_bg_color($green); + +my $light_blue_1 = $workbook->set_custom_color(44,'#b8cce4'); + +$format47 = $workbook->add_format(); +$format47->copy($format45); +$format47->set_bg_color($light_blue_1); +$format47->set_border(1); +$format47->set_border_color(0x09); + +my $very_light_blue = $workbook->set_custom_color(45,'#dce6f1'); + +$format48 = $workbook->add_format(); +$format48->copy($format47); +$format48->set_bg_color($very_light_blue); + +$format49 = $workbook->add_format(); +$format49->set_font('Arial'); +$format49->set_size(12); +$format49->set_bold(); + +$format50 = $workbook->add_format(); +$format50->set_font('Arial'); +$format50->set_size(10); +$format50->set_bold(); + +$format51 = $workbook->add_format(); +$format51->set_font('Arial'); +$format51->set_size(9); + +#-------------------------------------------------------- red highlighting + +my $hred = $workbook->set_custom_color(46,'#ff0000'); + +#40 +$format52 = $workbook->add_format(); +$format52->copy($format1); +$format52->set_align('center'); +$format52->set_bg_color($light_grey); +$format52->set_border(1); +$format52->set_color($hred); # red + +#42 +$format53 = $workbook->add_format(); +$format53->copy($format52); +$format53->set_color($hred); # red + +#35 +$format54 = $workbook->add_format(); +$format54->copy($format10); +$format54->set_text_wrap(); +$format54->set_border(1); +$format54->set_color($hred); # red + +#41 +$format55 = $workbook->add_format(); +$format55->copy($format10); +$format55->set_bg_color($very_light_grey); +$format55->set_border(1); +$format55->set_italic(); +$format55->set_color($hred); # red + +#34 +$format56 = $workbook->add_format(); +$format56->copy($format1); +$format56->set_border(1); +$format56->set_color($hred); # red + +#--------------------------------------------------- + +$format57 = $workbook->add_format(); +$format57->copy($format1); +$format57->set_top('1'); +$format57->set_bottom('6'); + +$format58 = $workbook->add_format(); +$format58->copy($format1); +$format58->set_top('1'); +$format58->set_bottom('6'); +$format58->set_bold(); +$format58->set_align('center'); + +my $ttl_light_blue = $workbook->set_custom_color(47,'#DAEEF3'); + +$format59 = $workbook->add_format(); +$format59->copy($format40); +$format59->set_bg_color($ttl_light_blue); +$format59->set_bold(); + +$format60 = $workbook->add_format(); +$format60->copy($format18); +$format60->set_bg_color($ttl_light_blue); +$format60->set_border(1); + +my $ttl_light_green = $workbook->set_custom_color(48,'#EBF1DE'); + +$format61 = $workbook->add_format(); +$format61->copy($format40); +$format61->set_bg_color($ttl_light_green); +$format61->set_bold(); + +$format62 = $workbook->add_format(); +$format62->copy($format18); +$format62->set_bg_color($ttl_light_green); +$format62->set_border(1); + +my $ttl_light_orange = $workbook->set_custom_color(49,'#FDE9D9'); + +$format63 = $workbook->add_format(); +$format63->copy($format40); +$format63->set_bg_color($ttl_light_orange); +$format63->set_bold(); + +$format64 = $workbook->add_format(); +$format64->copy($format18); +$format64->set_bg_color($ttl_light_orange); +$format64->set_border(1); + +$format65 = $workbook->add_format(); +$format65->copy($format40); +$format65->set_align('vcenter'); + +$format66 = $workbook->add_format(); +$format66->copy($format42); +$format66->set_align('vcenter'); + +$format67 = $workbook->add_format(); +$format67->copy($format19); +$format67->set_bold(); + +$format68 = $workbook->add_format(); +$format68->copy($format49); +$format68->set_bold(); +$format68->set_text_wrap() ; +$format68->set_align('vcenter'); +$format68->set_align('center'); + +my $ttl_light_yellow = $workbook->set_custom_color(50,'#FFFFB7'); + +$format69 = $workbook->add_format(); +$format69->copy($format40); +$format69->set_bg_color($ttl_light_yellow); +$format69->set_bold(); + +$format70 = $workbook->add_format(); +$format70->copy($format18); +$format70->set_bg_color($ttl_light_yellow); +$format70->set_border(1); + +$format71 = $workbook->add_format(); +$format71->copy($format23); +$format71->set_bg_color($ttl_light_yellow); + +$format72 = $workbook->add_format(); +$format72->copy($format3); +$format72->set_bg_color($ttl_light_yellow); + +$format73 = $workbook->add_format(); +$format73->copy($format1); +$format73->set_bg_color($ttl_light_yellow); + +$format74 = $workbook->add_format(); +$format74->copy($format69); +$format74->set_bold(); +$format74->set_text_wrap() ; +$format74->set_align('vcenter'); +$format74->set_align('center'); + +$format75 = $workbook->add_format(); +$format75->copy($format40); +$format75->set_bold(); +$format75->set_text_wrap() ; +$format75->set_align('vcenter'); +$format75->set_align('center'); + +$format76 = $workbook->add_format(); +$format76->copy($format1); +$format76->set_text_wrap() ; +# $format76->set_bold(); +$format76->set_align('right'); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_set_column_width { + +my ($worksheet_name,$from,$to,$width) = @_; + +$worksheet{$worksheet_name}->set_column("$from".":"."$to", $width); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_autofit_columns { + +my $worksheet = shift; +my $col = 0; + +for my $width (@{$worksheet->{__col_widths}}) { + + $worksheet->set_column($col, $col, $width) if $width; + $col++; + } + +} #------------------------------------------------------------------------------------------ + +# The following function is a callback that was added via add_write_handler() +# above. It modifies the write() function so that it stores the maximum +# unwrapped width of a string in a column. + +sub xlscreator_store_string_widths { + + my $worksheet = shift; + my $col = $_[1]; + my $token = $_[2]; + + # Ignore some tokens that we aren't interested in. + return if not defined $token; # Ignore undefs. + return if $token eq ''; # Ignore blank cells. + return if ref $token eq 'ARRAY'; # Ignore array refs. + return if $token =~ /^=/; # Ignore formula + + # Ignore numbers + #return if $token =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/; + + # Ignore various internal and external hyperlinks. In a real scenario + # you may wish to track the length of the optional strings used with + # urls. + return if $token =~ m{^[fh]tt?ps?://}; + return if $token =~ m{^mailto:}; + return if $token =~ m{^(?:in|ex)ternal:}; + + # We store the string width as data in the Worksheet object. We use + # a double underscore key name to avoid conflicts with future names. + # + my $old_width = $worksheet->{__col_widths}->[$col]; + my $string_width = xlscreator_string_width($token); + + if (not defined $old_width or $string_width > $old_width) { + # You may wish to set a minimum column width as follows. + #return undef if $string_width < 10; + + $worksheet->{__col_widths}->[$col] = $string_width; + } + + + # Return control to write(); + return undef; +} #------------------------------------------------------------------------------------------ + +# Very simple conversion between string length and string width for Arial 10. +# See below for a more sophisticated method. + +sub xlscreator_string_width { + +return 1.2 * length $_[0]; + +} #------------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/_FromProd/v1.0/xlsxcreator.pm b/libs/modules/_FromProd/v1.0/xlsxcreator.pm new file mode 100644 index 0000000..858b178 --- /dev/null +++ b/libs/modules/_FromProd/v1.0/xlsxcreator.pm @@ -0,0 +1,997 @@ +sub xlsxcreator_delete_previous_xlsx { + +my ($path) = @_ ; + +opendir(DIR, "$path") or die "cant open Directory $path: $!\n"; + +while(defined($folder = readdir(DIR))) { + if (length $folder > 2) { + my ($file,$type) = split(/\./,$folder) ; + + # if ($match) { unless ($file =~ /$match/gi) { next ; } } + + # my ($j1,$j2,$accid,$date) = split(/\-/,$file) ; + # if ($match) { unless ($accid eq $match) { next ; } } + + if (-e "$path/$file.xlsx"){ + unlink ("$path/$file.xlsx") or print "unable to unlink - $path/$file.xlsx : $!"; + } + } + } + +closedir(DIR) ; + +} #------------------------------------------------------------------------------------ + +sub xlsxcreator_create_xlsx { + +my ($file) = @_; + +our $workbook = Excel::Writer::XLSX->new($file) or die "ERROR : $file : $!"; + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_close_xlsx { + +$workbook->close(); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_hide_gridlines_xlsx { + +($worksheet_name) = @_; + +$worksheet{$worksheet_name}->hide_gridlines(1); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_set_margins_xlsx { + +($worksheet_name,$margin_width) = @_; + +$worksheet{$worksheet_name}->set_margins($margin_width); # Set all margins to the same value in inches + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_add_worksheet { + +my ($worksheet_name) = @_; + +$worksheet{$worksheet_name} = $workbook->add_worksheet($worksheet_name); + +#$worksheet{$worksheet_name}->add_write_handler(qr[\w], \&xlsxcreator_store_string_widths); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_add_pie_chart { + +my ($worksheet_name) = @_; + +$chart{$worksheet_name} = $workbook->add_chart( type => 'pie', embedded => 1 ); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_merge_xlsx { + +my ($worksheet_name,$merge_range,$token,$format) = @_ ; + +$worksheet{$worksheet_name}->merge_range($merge_range,$token,$format) ; + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_write_xlsx { + +my ($worksheet_name,$row,$col,$token,$cellformat) = @_; + +$token =~ s/\,//g; + +$worksheet{$worksheet_name}->write($row,$col,$token,$cellformat); + +#&xlsxcreator_autofit_columns($worksheet{$worksheet_name}); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_write_formula { + +my ($worksheet_name,$row,$col,$formula,$cellformat) = @_; + +$worksheet{$worksheet_name}->write_formula($row,$col,$formula,$cellformat); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_freeze_panes { + +my ($worksheet_name,$rows,$cols) = @_; + +$worksheet{$worksheet_name}->freeze_panes($rows,$cols); # Freeze the first 5 rows + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_insert_image { + +my ($worksheet_name,$row,$col,$file,$margin_right,$margin_bottom,$width_scale,$height_scale) = @_; + +$height_scale = $width_scale if $width_scale & !$height_scale ; + +$worksheet{$worksheet_name}->insert_image($row,$col,$file,$margin_right,$margin_bottom,$width_scale,$height_scale) ; + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_write_url { + + my ($worksheet_name,$row,$col,$url,$name) = @_; + + $worksheet{$worksheet_name}->write_url($row, $col, $url,$name, undef, 'URL') ; + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_xlsx_format { + +$format1 = $workbook->add_format(); +$format1->set_font('Verdana'); +$format1->set_size(8); + +$format2 = $workbook->add_format(); +$format2->copy($format1); +$format2->set_bold(); # Turns bold on +$format2->set_num_format('#,##0.00'); # 1,234.56 + +$format3 = $workbook->add_format(); +$format3->copy($format1); +$format3->set_num_format('#,##0.00'); # 1,234.56 + +$format4 = $workbook->add_format(); +$format4->copy($format1); +$format4->set_bold(); # Turns bold on +$format4->set_num_format('#,##0.00'); # 1,234.56 +$format4->set_top('6'); +$format4->set_bottom('6'); + +$format5 = $workbook->add_format(); +$format5->copy($format1); +$format5->set_underline(); # Single underline + +$format6 = $workbook->add_format(); +$format6->copy($format1); +$format6->set_underline(); # Single underline +$format6->set_align('right'); + +$format7 = $workbook->add_format(); +$format7->copy($format1); +$format7->set_align('right'); +$format7->set_num_format('#,##0.00'); # 1,234.56 + +$format8 = $workbook->add_format(); +$format8->copy($format1); +$format8->set_bold(); # Turns bold on +$format8->set_align('left'); +$format8->set_num_format('#,##0.00'); # 1,234.56 + +$format9 = $workbook->add_format(); +$format9->copy($format1); +$format9->set_bold(); # Turns bold on +$format9->set_align('right'); +$format9->set_num_format('#,##0.00'); # 1,234.56 + +$format10 = $workbook->add_format(); +$format10->copy($format1); +$format10->set_align('left'); + +$format11 = $workbook->add_format(); +$format11->copy($format1); +$format11->set_align('center'); +$format11->set_bg_color(0x16); #0x08 = 'black' ; #0x0C = 'blue' ; #0x10 = 'brown' ; #0x0F = 'cyan' ; #0x17 = 'gray' ; #0x11 = 'green' ; #0x0B = 'lime' ; #0x0E = 'magenta' ; #0x12 = 'navy' ; #0x35 = 'orange' ; #0x21 = 'pink' ; #0x14 = 'purple' ; #0x0A = 'red' ; #0x16 = 'silver' ; #0x09 = 'white' ; #0x0D = 'yellow' ; +$format11->set_top('1'); +$format11->set_bottom('1'); +$format11->set_left('1'); +$format11->set_right('1'); + +$format12 = $workbook->add_format(); +$format12->set_bg_color(0x16); +$format12->set_top('1'); +$format12->set_bottom('1'); +$format12->set_left('1'); +$format12->set_right('1'); + +$format13 = $workbook->add_format(); +$format13->copy($format1); +$format13->set_bg_color(0x16); +$format13->set_num_format('#,##0.00'); # 1,234.56 +$format13->set_top('1'); +$format13->set_bottom('1'); +$format13->set_left('1'); +$format13->set_right('1'); + +$format14 = $workbook->add_format(); +$format14->copy($format1); +$format14->set_bold(); # Turns bold on +$format14->set_bg_color(0x16); +$format14->set_top('1'); +$format14->set_bottom('1'); +$format14->set_left('1'); +$format14->set_right('1'); + +$format15 = $workbook->add_format(); +$format15->copy($format1); +$format15->set_align('right'); +$format15->set_num_format('#,##0.00'); # 1,234.56 +$format15->set_top('1'); +$format15->set_bottom('1'); +$format15->set_left('1'); +$format15->set_right('1'); + +$format16 = $workbook->add_format(); +$format16->copy($format1); +$format16->set_bg_color(0x16); +$format16->set_num_format('#,##0.0000'); # 1,234.56 +$format16->set_top('1'); +$format16->set_bottom('1'); +$format16->set_left('1'); +$format16->set_right('1'); + +$format17 = $workbook->add_format(); +$format17->copy($format1); +$format17->set_align('right'); +$format17->set_bg_color(0x16); +$format17->set_num_format('#,##0.00'); # 1,234.56 +$format17->set_top('1'); +$format17->set_bottom('1'); +$format17->set_left('1'); +$format17->set_right('1'); + +$format18 = $workbook->add_format(); +$format18->copy($format1); +$format18->set_bold(); +$format18->set_align('center'); + +$format19 = $workbook->add_format(); +$format19->copy($format1); +$format19->set_num_format('#,##0.00'); # 1,234.56 +$format19->set_top('1'); +$format19->set_bottom('6'); + +$format20 = $workbook->add_format(); +$format20->copy($format1); +$format20->set_align('center'); +$format20->set_num_format(0x0a); #0.00% (0x09 = 0%) + +$format21 = $workbook->add_format(); +$format21->copy($format1); +$format21->set_align('right'); + +$format22 = $workbook->add_format(); +$format22->copy($format1); +$format22->set_bold(); # Turns bold on +$format22->set_align('right'); +$format22->set_bg_color(0x16); +$format22->set_num_format('#,##0.00'); # 1,234.56 + +$format23 = $workbook->add_format(); +$format23->copy($format1); +$format23->set_bold(); # Turns bold on +$format23->set_color(0x0A); # red + +$format24 = $workbook->add_format(); +$format24->copy($format1); +$format24->set_top('2'); + +$format25 = $workbook->add_format(); +$format25->copy($format1); +$format25->set_bottom('3'); + +$format26 = $workbook->add_format(); +$format26->copy($format1); +$format26->set_bold(); # Turns bold on +$format26->set_align('left'); + +$format27 = $workbook->add_format(); +$format27->copy($format1); +$format27->set_bold(); # Turns bold on +$format27->set_align('right'); + +$format28 = $workbook->add_format(); +$format28->set_underline(2); # Single underline + +$format29 = $workbook->add_format(); +$format29->set_font('Verdana'); +$format29->set_size(5); + +$format30 = $workbook->add_format(); +$format30->set_font('Verdana'); +$format30->set_size(7); + +$format31 = $workbook->add_format(); +$format31->set_font('Verdana'); +$format31->set_size(4); +$format31->set_align('right'); + +$format32 = $workbook->add_format(); +$format32->set_font('Verdana'); +$format32->set_size(6); + +$format33 = $workbook->add_format(); +$format33->copy($format10); + +$format34 = $workbook->add_format(); +$format34->copy($format1); +$format34->set_border(1); + +$format35 = $workbook->add_format(); +$format35->copy($format10); +$format35->set_text_wrap(); +$format35->set_border(1); + +my $light_blue = $workbook->set_custom_color(40,'#D5FFFF'); + +$format36 = $workbook->add_format(); +$format36->copy($format8); +$format36->set_bg_color($light_blue); + +$format37 = $workbook->add_format(); +$format37->copy($format10); +$format37->set_bg_color($light_blue); + +$format38 = $workbook->add_format(); +$format38->copy($format1); +$format38->set_align('center'); +$format38->set_bg_color($light_blue); + +$format39 = $workbook->add_format(); +$format39->copy($format1); +$format39->set_bg_color($light_blue); + +my $light_grey = $workbook->set_custom_color(41,'#c6c6c6'); + +$format40 = $workbook->add_format(); +$format40->copy($format1); +$format40->set_align('center'); +$format40->set_bg_color($light_grey); +$format40->set_border(1); + +my $very_light_grey = $workbook->set_custom_color(42,'#EEEEEE'); + +$format41 = $workbook->add_format(); +$format41->copy($format10); +$format41->set_bg_color($very_light_grey); +$format41->set_border(1); +$format41->set_italic(); + +# merged +$format42 = $workbook->add_format(); +$format42->copy($format40); + +$format43 = $workbook->add_format(); +$format43->copy($format38); +$format43->set_border(1); + +$format44 = $workbook->add_format(); +$format44->copy($format41); +$format44->set_bg_color(0x09); + +$format45 = $workbook->add_format(); +$format45->set_font('Verdana'); +$format45->set_size(10); + +my $green = $workbook->set_custom_color(43,'#00b050'); + +$format46 = $workbook->add_format(); +$format46->set_align('center'); +$format46->copy($format45); +$format46->set_bg_color($green); + +my $light_blue_1 = $workbook->set_custom_color(44,'#b8cce4'); + +$format47 = $workbook->add_format(); +$format47->copy($format45); +$format47->set_bg_color($light_blue_1); +$format47->set_border(1); +$format47->set_border_color(0x09); + +my $very_light_blue = $workbook->set_custom_color(45,'#dce6f1'); + +$format48 = $workbook->add_format(); +$format48->copy($format47); +$format48->set_bg_color($very_light_blue); + +$format49 = $workbook->add_format(); +$format49->set_font('Arial'); +$format49->set_size(12); +$format49->set_bold(); + +$format50 = $workbook->add_format(); +$format50->set_font('Arial'); +$format50->set_size(10); +$format50->set_bold(); + +$format51 = $workbook->add_format(); +$format51->set_font('Arial'); +$format51->set_size(9); + +#-------------------------------------------------------- red highlighting + +my $hred = $workbook->set_custom_color(46,'#ff0000'); + +#40 +$format52 = $workbook->add_format(); +$format52->copy($format1); +$format52->set_align('center'); +$format52->set_bg_color($light_grey); +$format52->set_border(1); +$format52->set_color($hred); # red + +#42 +$format53 = $workbook->add_format(); +$format53->copy($format52); +$format53->set_color($hred); # red + +#35 +$format54 = $workbook->add_format(); +$format54->copy($format10); +$format54->set_text_wrap(); +$format54->set_border(1); +$format54->set_color($hred); # red + +#41 +$format55 = $workbook->add_format(); +$format55->copy($format10); +$format55->set_bg_color($very_light_grey); +$format55->set_border(1); +$format55->set_italic(); +$format55->set_color($hred); # red + +#34 +$format56 = $workbook->add_format(); +$format56->copy($format1); +$format56->set_border(1); +$format56->set_color($hred); # red + +#--------------------------------------------------- + +$format57 = $workbook->add_format(); +$format57->copy($format1); +$format57->set_top('1'); +$format57->set_bottom('6'); + +$format58 = $workbook->add_format(); +$format58->copy($format1); +$format58->set_top('1'); +$format58->set_bottom('6'); +$format58->set_bold(); +$format58->set_align('center'); + +my $ttl_light_blue = $workbook->set_custom_color(47,'#DAEEF3'); + +$format59 = $workbook->add_format(); +$format59->copy($format40); +$format59->set_bg_color($ttl_light_blue); +$format59->set_bold(); + +$format60 = $workbook->add_format(); +$format60->copy($format18); +$format60->set_bg_color($ttl_light_blue); +$format60->set_border(1); + +my $ttl_light_green = $workbook->set_custom_color(48,'#EBF1DE'); + +$format61 = $workbook->add_format(); +$format61->copy($format40); +$format61->set_bg_color($ttl_light_green); +$format61->set_bold(); + +$format62 = $workbook->add_format(); +$format62->copy($format18); +$format62->set_bg_color($ttl_light_green); +$format62->set_border(1); + +my $ttl_light_orange = $workbook->set_custom_color(49,'#FDE9D9'); + +$format63 = $workbook->add_format(); +$format63->copy($format40); +$format63->set_bg_color($ttl_light_orange); +$format63->set_bold(); + +$format64 = $workbook->add_format(); +$format64->copy($format18); +$format64->set_bg_color($ttl_light_orange); +$format64->set_border(1); + +$format65 = $workbook->add_format(); +$format65->copy($format40); +$format65->set_align('vcenter'); + +$format66 = $workbook->add_format(); +$format66->copy($format42); +$format66->set_align('vcenter'); + +$format67 = $workbook->add_format(); +$format67->copy($format19); +$format67->set_bold(); + +$format68 = $workbook->add_format(); +$format68->copy($format49); +$format68->set_bold(); +$format68->set_text_wrap() ; +$format68->set_align('vcenter'); +$format68->set_align('center'); + +my $ttl_light_yellow = $workbook->set_custom_color(50,'#FFFFB7'); + +$format69 = $workbook->add_format(); +$format69->copy($format40); +$format69->set_bg_color($ttl_light_yellow); +$format69->set_bold(); + +$format70 = $workbook->add_format(); +$format70->copy($format18); +$format70->set_bg_color($ttl_light_yellow); +$format70->set_border(1); + +$format71 = $workbook->add_format(); +$format71->copy($format23); +$format71->set_bg_color($ttl_light_yellow); + +$format72 = $workbook->add_format(); +$format72->copy($format3); +$format72->set_bg_color($ttl_light_yellow); + +$format73 = $workbook->add_format(); +$format73->copy($format1); +$format73->set_bg_color($ttl_light_yellow); + +$format74 = $workbook->add_format(); +$format74->copy($format69); +$format74->set_bold(); +$format74->set_text_wrap() ; +$format74->set_align('vcenter'); +$format74->set_align('center'); + +$format75 = $workbook->add_format(); +$format75->copy($format40); +$format75->set_bold(); +$format75->set_text_wrap() ; +$format75->set_align('vcenter'); +$format75->set_align('center'); + +$format76 = $workbook->add_format(); +$format76->copy($format1); +$format76->set_text_wrap() ; +# $format76->set_bold(); +$format76->set_align('right'); + +our $format_event_heading = $workbook -> add_format() ; +$format_event_heading -> set_size(20) ; +$format_event_heading -> set_align('center') ; +$format_event_heading -> set_valign('vcenter') ; +$format_event_heading -> set_bottom('2') ; +$format_event_heading -> set_bold() ; + +our $format_event_heading_2 = $workbook -> add_format() ; +$format_event_heading_2 -> set_size(12) ; +$format_event_heading_2 -> set_align('center') ; +$format_event_heading_2 -> set_valign('vcenter') ; +$format_event_heading_2 -> set_bottom('2') ; +$format_event_heading_2 -> set_underline() ; +$format_event_heading_2 -> set_bold() ; + +our $format_event_data = $workbook -> add_format() ; +$format_event_data -> set_size(11) ; +$format_event_data -> set_align('center') ; +$format_event_data -> set_valign('vcenter') ; + +our $format_event_data_2 = $workbook -> add_format() ; +$format_event_data_2 -> copy($format_event_data) ; +$format_event_data_2 -> set_bottom('1') ; + +our $format_empty_row = $workbook -> add_format() ; +$format_empty_row -> set_bottom('1') ; + +our $format_management_report_totals = $workbook -> add_format() ; +$format_management_report_totals -> set_size(11) ; +$format_management_report_totals -> set_align('center') ; +$format_management_report_totals -> set_valign('vcenter') ; +$format_management_report_totals -> set_top(6) ; +$format_management_report_totals -> set_num_format('#,##0.00'); +$format_management_report_totals -> set_bold() ; + +our $format_management_report_totals_2 = $workbook -> add_format() ; +$format_management_report_totals_2 -> copy($format_management_report_totals); +$format_management_report_totals_2 -> set_num_format('#,##0'); + +our $format_management_report_total = $workbook -> add_format() ; +$format_management_report_total -> set_size(11) ; +$format_management_report_total -> set_bold() ; +$format_management_report_total -> set_align('right') ; +$format_management_report_total -> set_valign('vcenter') ; + +our $format_management_report_data = $workbook -> add_format() ; +$format_management_report_data -> set_size(10) ; +$format_management_report_data -> set_num_format('#,##0.00'); +$format_management_report_data -> set_align('center') ; +$format_management_report_data -> set_valign('vcenter') ; + +our $format_management_report_data_ref_nr = $workbook -> add_format() ; +$format_management_report_data_ref_nr -> set_size(10) ; +$format_management_report_data_ref_nr -> set_align('center') ; +$format_management_report_data_ref_nr -> set_valign('vcenter') ; + +our $format_management_report_months= $workbook -> add_format() ; +$format_management_report_months -> set_size(10) ; +$format_management_report_months -> set_align('right') ; +$format_management_report_months -> set_valign('vcenter') ; + +our $format_management_report_months_2 = $workbook -> add_format() ; +$format_management_report_months_2 -> set_size(10) ; +$format_management_report_months_2 -> set_align('left') ; +$format_management_report_months_2 -> set_valign('vcenter') ; + + + +our $format_management_report_headings = $workbook -> add_format() ; +$format_management_report_headings -> set_size(11) ; +$format_management_report_headings -> set_align('center') ; +$format_management_report_headings -> set_valign('vcenter') ; +$format_management_report_headings -> set_bold() ; +$format_management_report_headings -> set_border(1) ; +$format_management_report_headings -> set_bg_color('#B6D7A8') ; +$format_management_report_headings -> set_text_wrap() ; + +our $format_management_report_title = $workbook -> add_format() ; +$format_management_report_title -> set_bold() ; +$format_management_report_title -> set_size(16) ; +$format_management_report_title -> set_align('left') ; +$format_management_report_title -> set_valign('vcenter') ; + +my $light_blue_bg = $workbook -> set_custom_color(51,'#51CBF2'); +$format77 = $workbook -> add_format() ; +$format77 -> copy($format_event_data) ; +$format77 -> set_bottom('1') ; +$format77 -> set_left('1') ; +$format77 -> set_right('1') ; +$format77 -> set_bg_color($light_blue_bg) ; + +my $yellow_bg = $workbook -> set_custom_color(52,'#F6E305'); +$format78 = $workbook -> add_format() ; +$format78 -> copy($format77) ; +$format78 -> set_bg_color($yellow_bg) ; + +my $green_bg = $workbook -> set_custom_color(53,'#51B529'); +$format80 = $workbook -> add_format() ; +$format80 -> copy($format77) ; +$format80 -> set_bg_color($green_bg) ; + +my $orange_bg = $workbook -> set_custom_color(54,'#F4BC14'); +$format79 = $workbook -> add_format() ; +$format79 -> copy($format77) ; +$format79 -> set_bg_color($orange_bg) ; + +my $red_bg = $workbook -> set_custom_color(55,'#F90D0D'); +$format81 = $workbook -> add_format() ; +$format81 -> copy($format77) ; +$format81 -> set_bg_color($red_bg) ; + +$format82 = $workbook -> add_format() ; +$format82 -> copy($format_event_data) ; +$format82 -> set_align('left') ; + +my $slight_green = $workbook -> set_custom_color(56,'#E4EDD8'); + +# $format_management_report_headings -> set_bg_color($slight_green) ; + +$format83 = $workbook -> add_format() ; +$format83 -> set_bg_color($slight_green) ; +$format83 -> set_bottom('1') ; +$format83 -> set_right('1') ; +$format83 -> set_bold() ; +$format83 -> set_size(12) ; +$format83 -> set_align('left') ; +$format83 -> set_valign('vcenter') ; + +$format84 = $workbook -> add_format() ; +$format84 -> set_bottom('1') ; +$format84 -> set_right('1') ; +$format84 -> set_size(10) ; +$format84 -> set_align('left') ; +$format84 -> set_valign('vcenter') ; + +$format85 = $workbook -> add_format() ; +$format85 -> copy($format84) ; +$format85 -> set_align('right') ; + +$format86 = $workbook -> add_format() ; +$format86 -> copy($format85) ; + +$format87 = $workbook -> add_format() ; +$format87 -> copy($format85) ; + +my $dark_green_font = $workbook -> set_custom_color(57,'#2D6F4B'); +# my $light_green_bg = $workbook -> set_custom_color(58,'#D5EDBB'); +my $light_green_bg = $workbook -> set_custom_color(58,'#51B529'); + +my $dark_blue_font = $workbook -> set_custom_color(59,'#1D4D7E'); +# my $light_blue_bg = $workbook -> set_custom_color(60,'#C0E0F5'); +my $light_blue_bg = $workbook -> set_custom_color(60,'#FFA500'); + + +# my $dark_reb_bg = $workbook -> set_custom_color(61,'#AD0502'); +my $dark_reb_bg = $workbook -> set_custom_color(61,'#F90D0D'); +my $light_red_font = $workbook -> set_custom_color(62,'#E1B5B4'); + +my $light_grey_bg = $workbook -> set_custom_color(63,'#E9EAEC'); + +# my $pubple_border_color = $workbook -> set_custom_color(64,'#8B1D5F'); + + +# my $dark_green_font = $workbook -> set_custom_color(57,'#2D6F4B'); +# my $light_green_bg = $workbook -> set_custom_color(58,'#D5EDBB'); +# my $dark_blue_font = $workbook -> set_custom_color(59,'#1D4D7E'); +# my $light_blue_bg = $workbook -> set_custom_color(60,'#C0E0F5'); +# my $dark_reb_bg = $workbook -> set_custom_color(61,'#AD0502'); +# my $light_red_font = $workbook -> set_custom_color(62,'#E1B5B4'); +# my $light_grey_bg = $workbook -> set_custom_color(63,'#E9EAEC'); +# my $pubple_border_color = $workbook -> set_custom_color(64,'#8B1D5F'); + + + +$format88 = $workbook -> add_format() ; +$format88 -> copy($format84) ; +$format88 -> set_bg_color($light_green_bg) ; +# $format88 -> set_custom_color('#2D6F4B') ; + +$format89 = $workbook -> add_format() ; +$format89 -> copy($format84) ; +$format89 -> set_bg_color($light_blue_bg) ; + +$format90 = $workbook -> add_format() ; +$format90 -> copy($format84) ; +$format90 -> set_bg_color($dark_reb_bg) ; + +$format91 = $workbook -> add_format() ; +$format91 -> copy($format84) ; +$format91 -> set_bg_color($light_grey_bg) ; + +$format92 = $workbook -> add_format() ; +$format92 -> copy($format84) ; +$format92 -> set_border(1); + +my $lgreen_heading_bg = $workbook -> set_custom_color(64,'#E2EEDA'); + +$format93 = $workbook -> add_format() ; +$format93 -> copy($format84) ; +$format93 -> set_top('1') ; +$format93 -> set_bold() ; +$format93 -> set_size(12) ; +$format93 -> set_bg_color($light_green_bg) ; + +# my $green_bg = $workbook -> set_custom_color(65,'#009624'); +# my $yellow_bg = $workbook -> set_custom_color(66,'#FFF000'); +# my $red_bg = $workbook -> set_custom_color(67,'#AD0502'); + +$format94 = $workbook -> add_format() ; +$format94 -> copy($format84) ; +$format94 -> set_bg_color($green_bg) ; + +$format95 = $workbook -> add_format() ; +$format95 -> copy($format84) ; +$format95 -> set_bg_color($yellow_bg) ; + +$format96 = $workbook -> add_format() ; +$format96 -> copy($format84) ; +$format96 -> set_bg_color($red_bg) ; + +$format97 = $workbook -> add_format() ; +$format97 -> copy($format84) ; +$format97 -> set_top(6) ; +$format97 -> set_bottom(6) ; +$format97 -> set_italic() ; + +$format98 = $workbook->add_format() ; +$format98 -> copy($format8) ; +$format98 -> set_align('vcenter') ; + +$format99 = $workbook->add_format(); +$format99 -> copy($format7); +$format99 -> set_num_format('#,##0'); # 1,234.56 + +$format100 = $workbook->add_format(); +$format100 -> copy($format_management_report_headings); +$format100 -> set_bg_color('#FFFF00') ; + +$format101 = $workbook -> add_format(); +$format101 -> copy($format_management_report_headings); +$format101 -> set_bg_color('#F9CB9C') ; + +# my $purple_bg = $workbook -> set_custom_color(66,'#CA0AD3'); +$format102 = $workbook -> add_format() ; +$format102 -> copy($format77) ; +$format102 -> set_bg_color('#CA0AD3') ; + +$format103 = $workbook -> add_format() ; +$format103 -> copy($format77) ; +$format103 -> set_bg_color('#164473') ; + +$format104 = $workbook -> add_format() ; +$format104 -> copy($format77) ; +$format104 -> set_bg_color('#A349A4') ; + +$format105 = $workbook -> add_format() ; +$format105 -> copy($format77) ; +$format105 -> set_bg_color('#5D09D3') ; + +$format106 = $workbook -> add_format() ; +$format106 -> copy($format77) ; +$format106 -> set_bg_color('#5D092C') ; + +$format107 = $workbook -> add_format() ; #ANALYTICS EVENT +$format107 -> copy($format77) ; +$format107 -> set_bg_color('#A05000') ; + +$format108 = $workbook -> add_format() ; #DEMO EVENT +$format108 -> copy($format77) ; +$format108 -> set_bg_color('#FF40FF') ; + +$format109 = $workbook->add_format() ; +$format109 -> copy($format1) ; +$format109 -> set_bold() ; +$format109 -> set_size(12) ; + +$format110 = $workbook->add_format() ; +$format110 -> copy($format1) ; +$format110 -> set_bold() ; +$format110 -> set_size(10) ; +$format110 -> set_bg_color('#DEECFF') ; #blue +$format110 -> set_color('#037AFE') ; #blue + +$format111 = $workbook->add_format() ; +$format111 -> copy($format110) ; +$format111 -> set_bg_color('#FFE1E6') ; #red +$format111 -> set_color('#FE2D55') ; #red + +$format112 = $workbook->add_format() ; +$format112 -> copy($format110) ; +$format112 -> set_bg_color('#E3F8F6') ; #lightbluie +$format112 -> set_color('#00C8BE') ; #lightbluie + +$format113 = $workbook->add_format() ; +$format113 -> copy($format110) ; +$format113 -> set_bg_color('#FFF0E0') ; #orange +$format113 -> set_color('#FF9502') ; #orange +$format113 -> set_size(8) ; + +$format114 = $workbook->add_format() ; +$format114 -> copy($format113) ; +$format114 -> set_bold('0') ; + +$format115 = $workbook->add_format() ; +$format115 -> copy($format1) ; +$format115 -> set_bold() ; +# FF9502 +$format116 = $workbook->add_format() ; +$format116 -> copy($format113) ; +$format116 -> set_bold() ; +$format116 -> set_size(10) ; + +$format117 = $workbook->add_format() ; +$format117 -> copy($format1) ; +$format117 -> set_bold() ; +$format117 -> set_size(12) ; + +$format118 = $workbook->add_format() ; +$format118 -> copy($format117) ; +$format118 -> set_size(10) ; + +$format119 = $workbook->add_format() ; +$format119 -> copy($format1) ; +$format119 -> set_size(10) ; +$format119 -> set_top(1) ; +$format119 -> set_bottom(6) ; +$format119 -> set_num_format('#,##0.00'); + +$format120 = $workbook->add_format() ; +$format120 -> copy($format1) ; +$format120 -> set_size(8) ; +$format120 -> set_num_format('#,##0.00'); + +$format121 = $workbook->add_format() ; +$format121 -> copy($format1) ; +$format121 -> set_bottom(1) ; + +$format122 = $workbook->add_format() ; +$format122 -> copy($format1) ; +$format122 -> set_left(1) ; + +# my $other_green = $workbook -> set_custom_color(100,'#B6D7A8'); + +# $format_management_report_headings -> set_bg_color($lgreen_heading_bg) ; + + +# $format92 -> set_border_color(0x0A) ; +# $format92 -> set_border_color($pubple_border_color) ; + +# set_font_strikethrough +# $format86 -> strikeout('1'); + +# $format87 = $workbook -> add_format() ; +# $format87 -> set_bottom('1') ; +# $format87 -> set_right('1') ; +# $format87 -> set_size(10) ; +# $format87 -> set_align('right') ; +# $format87 -> set_valign('vcenter') ; +# $format87 -> set_font_strikethrough('1'); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_set_column_width { + +my ($worksheet_name,$from,$to,$width) = @_; + +$worksheet{$worksheet_name}->set_column("$from".":"."$to", $width); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_autofit_columns { + +my $worksheet = shift; +my $col = 0; + +for my $width (@{$worksheet->{__col_widths}}) { + + $worksheet->set_column($col, $col, $width) if $width; + $col++; + } + +} #------------------------------------------------------------------------------------------ + +# The following function is a callback that was added via add_write_handler() +# above. It modifies the write() function so that it stores the maximum +# unwrapped width of a string in a column. + +sub xlsxcreator_store_string_widths { + + my $worksheet = shift; + my $col = $_[1]; + my $token = $_[2]; + + # Ignore some tokens that we aren't interested in. + return if not defined $token; # Ignore undefs. + return if $token eq ''; # Ignore blank cells. + return if ref $token eq 'ARRAY'; # Ignore array refs. + return if $token =~ /^=/; # Ignore formula + + # Ignore numbers + #return if $token =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/; + + # Ignore various internal and external hyperlinks. In a real scenario + # you may wish to track the length of the optional strings used with + # urls. + return if $token =~ m{^[fh]tt?ps?://}; + return if $token =~ m{^mailto:}; + return if $token =~ m{^(?:in|ex)ternal:}; + + # We store the string width as data in the Worksheet object. We use + # a double underscore key name to avoid conflicts with future names. + # + my $old_width = $worksheet->{__col_widths}->[$col]; + my $string_width = xlsxcreator_string_width($token); + + if (not defined $old_width or $string_width > $old_width) { + # You may wish to set a minimum column width as follows. + #return undef if $string_width < 10; + + $worksheet->{__col_widths}->[$col] = $string_width; + } + + + # Return control to write(); + return undef; +} #------------------------------------------------------------------------------------------ + +# Very simple conversion between string length and string width for Arial 10. +# See below for a more sophisticated method. + +sub xlsxcreator_string_width { + +return 1.2 * length $_[0]; + +} #------------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/_FromProd/xlscreator.pm b/libs/modules/_FromProd/xlscreator.pm new file mode 100644 index 0000000..dd1e5d7 --- /dev/null +++ b/libs/modules/_FromProd/xlscreator.pm @@ -0,0 +1,619 @@ +sub xlscreator_delete_previous_xls { + +my ($path) = @_ ; + +opendir(DIR, "$path") or die "cant open Directory $path: $!\n"; + +while(defined($folder = readdir(DIR))) { + if (length $folder > 2) { + my ($file,$type) = split(/\./,$folder) ; + + # if ($match) { unless ($file =~ /$match/gi) { next ; } } + + # my ($j1,$j2,$accid,$date) = split(/\-/,$file) ; + # if ($match) { unless ($accid eq $match) { next ; } } + + if (-e "$path/$file.xls"){ + unlink ("$path/$file.xls") or print "unable to unlink - $path/$file.xls : $!"; + } + } + } + +closedir(DIR) ; + +} #------------------------------------------------------------------------------------ + +sub xlscreator_create_xls { + +my ($file) = @_; + +$workbook = Spreadsheet::WriteExcel->new($file) or die "ERROR : $file : $!"; + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_close_xls { + +$workbook->close(); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_hide_gridlines_xls { + +($worksheet_name) = @_; + +$worksheet{$worksheet_name}->hide_gridlines(1); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_set_margins_xls { + +($worksheet_name,$margin_width) = @_; + +$worksheet{$worksheet_name}->set_margins($margin_width); # Set all margins to the same value in inches + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_add_worksheet { + +my ($worksheet_name) = @_; + +$worksheet{$worksheet_name} = $workbook->add_worksheet($worksheet_name); + +#$worksheet{$worksheet_name}->add_write_handler(qr[\w], \&xlscreator_store_string_widths); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_add_pie_chart { + +my ($worksheet_name) = @_; + +$chart{$worksheet_name} = $workbook->add_chart( type => 'pie', embedded => 1 ); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_write_xls { + +my ($worksheet_name,$row,$col,$token,$cellformat) = @_; + +$token =~ s/\,//g; + +$worksheet{$worksheet_name}->write($row,$col,$token,$cellformat); + +#&xlscreator_autofit_columns($worksheet{$worksheet_name}); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_write_formula { + +my ($worksheet_name,$row,$col,$formula,$cellformat) = @_; + +$worksheet{$worksheet_name}->write_formula($row,$col,$formula,$cellformat); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_freeze_panes { + +my ($worksheet_name,$rows,$cols) = @_; + +$worksheet{$worksheet_name}->freeze_panes($rows,$cols); # Freeze the first 5 rows + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_insert_image { + +my ($worksheet_name,$row,$col,$file,$margin_right, $margin_bottom) = @_; + +$worksheet{$worksheet_name}->insert_image($row,$col,$file,$margin_right,$margin_bottom); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_xls_format { + +$format1 = $workbook->add_format(); +$format1->set_font('Verdana'); +$format1->set_size(8); + +$format2 = $workbook->add_format(); +$format2->copy($format1); +$format2->set_bold(); # Turns bold on +$format2->set_num_format('#,##0.00'); # 1,234.56 + +$format3 = $workbook->add_format(); +$format3->copy($format1); +$format3->set_num_format('#,##0.00'); # 1,234.56 + +$format4 = $workbook->add_format(); +$format4->copy($format1); +$format4->set_bold(); # Turns bold on +$format4->set_num_format('#,##0.00'); # 1,234.56 +$format4->set_top('6'); +$format4->set_bottom('6'); + +$format5 = $workbook->add_format(); +$format5->copy($format1); +$format5->set_underline(); # Single underline + +$format6 = $workbook->add_format(); +$format6->copy($format1); +$format6->set_underline(); # Single underline +$format6->set_align('right'); + +$format7 = $workbook->add_format(); +$format7->copy($format1); +$format7->set_align('right'); +$format7->set_num_format('#,##0.00'); # 1,234.56 + +$format8 = $workbook->add_format(); +$format8->copy($format1); +$format8->set_bold(); # Turns bold on +$format8->set_align('left'); +$format8->set_num_format('#,##0.00'); # 1,234.56 + +$format9 = $workbook->add_format(); +$format9->copy($format1); +$format9->set_bold(); # Turns bold on +$format9->set_align('right'); +$format9->set_num_format('#,##0.00'); # 1,234.56 + +$format10 = $workbook->add_format(); +$format10->copy($format1); +$format10->set_align('left'); + +$format11 = $workbook->add_format(); +$format11->copy($format1); +$format11->set_align('center'); +$format11->set_bg_color(0x16); #0x08 = 'black' ; #0x0C = 'blue' ; #0x10 = 'brown' ; #0x0F = 'cyan' ; #0x17 = 'gray' ; #0x11 = 'green' ; #0x0B = 'lime' ; #0x0E = 'magenta' ; #0x12 = 'navy' ; #0x35 = 'orange' ; #0x21 = 'pink' ; #0x14 = 'purple' ; #0x0A = 'red' ; #0x16 = 'silver' ; #0x09 = 'white' ; #0x0D = 'yellow' ; +$format11->set_top('1'); +$format11->set_bottom('1'); +$format11->set_left('1'); +$format11->set_right('1'); + +$format12 = $workbook->add_format(); +$format12->set_bg_color(0x16); +$format12->set_top('1'); +$format12->set_bottom('1'); +$format12->set_left('1'); +$format12->set_right('1'); + +$format13 = $workbook->add_format(); +$format13->copy($format1); +$format13->set_bg_color(0x16); +$format13->set_num_format('#,##0.00'); # 1,234.56 +$format13->set_top('1'); +$format13->set_bottom('1'); +$format13->set_left('1'); +$format13->set_right('1'); + +$format14 = $workbook->add_format(); +$format14->copy($format1); +$format14->set_bold(); # Turns bold on +$format14->set_bg_color(0x16); +$format14->set_top('1'); +$format14->set_bottom('1'); +$format14->set_left('1'); +$format14->set_right('1'); + +$format15 = $workbook->add_format(); +$format15->copy($format1); +$format15->set_align('right'); +$format15->set_num_format('#,##0.00'); # 1,234.56 +$format15->set_top('1'); +$format15->set_bottom('1'); +$format15->set_left('1'); +$format15->set_right('1'); + +$format16 = $workbook->add_format(); +$format16->copy($format1); +$format16->set_bg_color(0x16); +$format16->set_num_format('#,##0.0000'); # 1,234.56 +$format16->set_top('1'); +$format16->set_bottom('1'); +$format16->set_left('1'); +$format16->set_right('1'); + +$format17 = $workbook->add_format(); +$format17->copy($format1); +$format17->set_align('right'); +$format17->set_bg_color(0x16); +$format17->set_num_format('#,##0.00'); # 1,234.56 +$format17->set_top('1'); +$format17->set_bottom('1'); +$format17->set_left('1'); +$format17->set_right('1'); + +$format18 = $workbook->add_format(); +$format18->copy($format1); +$format18->set_bold(); +$format18->set_align('center'); + +$format19 = $workbook->add_format(); +$format19->copy($format1); +$format19->set_num_format('#,##0.00'); # 1,234.56 +$format19->set_top('1'); +$format19->set_bottom('6'); + +$format20 = $workbook->add_format(); +$format20->copy($format1); +$format20->set_align('center'); +$format20->set_num_format(0x0a); #0.00% (0x09 = 0%) + +$format21 = $workbook->add_format(); +$format21->copy($format1); +$format21->set_align('right'); + +$format22 = $workbook->add_format(); +$format22->copy($format1); +$format22->set_bold(); # Turns bold on +$format22->set_align('right'); +$format22->set_bg_color(0x16); +$format22->set_num_format('#,##0.00'); # 1,234.56 + +$format23 = $workbook->add_format(); +$format23->copy($format1); +$format23->set_bold(); # Turns bold on +$format23->set_color(0x0A); # red + +$format24 = $workbook->add_format(); +$format24->copy($format1); +$format24->set_top('2'); + +$format25 = $workbook->add_format(); +$format25->copy($format1); +$format25->set_bottom('3'); + +$format26 = $workbook->add_format(); +$format26->copy($format1); +$format26->set_bold(); # Turns bold on +$format26->set_align('left'); + +$format27 = $workbook->add_format(); +$format27->copy($format1); +$format27->set_bold(); # Turns bold on +$format27->set_align('right'); + +$format28 = $workbook->add_format(); +$format28->set_underline(2); # Single underline + +$format29 = $workbook->add_format(); +$format29->set_font('Verdana'); +$format29->set_size(5); + +$format30 = $workbook->add_format(); +$format30->set_font('Verdana'); +$format30->set_size(7); + +$format31 = $workbook->add_format(); +$format31->set_font('Verdana'); +$format31->set_size(4); +$format31->set_align('right'); + +$format32 = $workbook->add_format(); +$format32->set_font('Verdana'); +$format32->set_size(6); + +$format33 = $workbook->add_format(); +$format33->copy($format10); + +$format34 = $workbook->add_format(); +$format34->copy($format1); +$format34->set_border(1); + +$format35 = $workbook->add_format(); +$format35->copy($format10); +$format35->set_text_wrap(); +$format35->set_border(1); + +my $light_blue = $workbook->set_custom_color(40,'#D5FFFF'); + +$format36 = $workbook->add_format(); +$format36->copy($format8); +$format36->set_bg_color($light_blue); + +$format37 = $workbook->add_format(); +$format37->copy($format10); +$format37->set_bg_color($light_blue); + +$format38 = $workbook->add_format(); +$format38->copy($format1); +$format38->set_align('center'); +$format38->set_bg_color($light_blue); + +$format39 = $workbook->add_format(); +$format39->copy($format1); +$format39->set_bg_color($light_blue); + +my $light_grey = $workbook->set_custom_color(41,'#c6c6c6'); + +$format40 = $workbook->add_format(); +$format40->copy($format1); +$format40->set_align('center'); +$format40->set_bg_color($light_grey); +$format40->set_border(1); + +my $very_light_grey = $workbook->set_custom_color(42,'#EEEEEE'); + +$format41 = $workbook->add_format(); +$format41->copy($format10); +$format41->set_bg_color($very_light_grey); +$format41->set_border(1); +$format41->set_italic(); + +# merged +$format42 = $workbook->add_format(); +$format42->copy($format40); + +$format43 = $workbook->add_format(); +$format43->copy($format38); +$format43->set_border(1); + +$format44 = $workbook->add_format(); +$format44->copy($format41); +$format44->set_bg_color(0x09); + +$format45 = $workbook->add_format(); +$format45->set_font('Verdana'); +$format45->set_size(10); + +my $green = $workbook->set_custom_color(43,'#00b050'); + +$format46 = $workbook->add_format(); +$format46->set_align('center'); +$format46->copy($format45); +$format46->set_bg_color($green); + +my $light_blue_1 = $workbook->set_custom_color(44,'#b8cce4'); + +$format47 = $workbook->add_format(); +$format47->copy($format45); +$format47->set_bg_color($light_blue_1); +$format47->set_border(1); +$format47->set_border_color(0x09); + +my $very_light_blue = $workbook->set_custom_color(45,'#dce6f1'); + +$format48 = $workbook->add_format(); +$format48->copy($format47); +$format48->set_bg_color($very_light_blue); + +$format49 = $workbook->add_format(); +$format49->set_font('Arial'); +$format49->set_size(12); +$format49->set_bold(); + +$format50 = $workbook->add_format(); +$format50->set_font('Arial'); +$format50->set_size(10); +$format50->set_bold(); + +$format51 = $workbook->add_format(); +$format51->set_font('Arial'); +$format51->set_size(9); + +#-------------------------------------------------------- red highlighting + +my $hred = $workbook->set_custom_color(46,'#ff0000'); + +#40 +$format52 = $workbook->add_format(); +$format52->copy($format1); +$format52->set_align('center'); +$format52->set_bg_color($light_grey); +$format52->set_border(1); +$format52->set_color($hred); # red + +#42 +$format53 = $workbook->add_format(); +$format53->copy($format52); +$format53->set_color($hred); # red + +#35 +$format54 = $workbook->add_format(); +$format54->copy($format10); +$format54->set_text_wrap(); +$format54->set_border(1); +$format54->set_color($hred); # red + +#41 +$format55 = $workbook->add_format(); +$format55->copy($format10); +$format55->set_bg_color($very_light_grey); +$format55->set_border(1); +$format55->set_italic(); +$format55->set_color($hred); # red + +#34 +$format56 = $workbook->add_format(); +$format56->copy($format1); +$format56->set_border(1); +$format56->set_color($hred); # red + +#--------------------------------------------------- + +$format57 = $workbook->add_format(); +$format57->copy($format1); +$format57->set_top('1'); +$format57->set_bottom('6'); + +$format58 = $workbook->add_format(); +$format58->copy($format1); +$format58->set_top('1'); +$format58->set_bottom('6'); +$format58->set_bold(); +$format58->set_align('center'); + +my $ttl_light_blue = $workbook->set_custom_color(47,'#DAEEF3'); + +$format59 = $workbook->add_format(); +$format59->copy($format40); +$format59->set_bg_color($ttl_light_blue); +$format59->set_bold(); + +$format60 = $workbook->add_format(); +$format60->copy($format18); +$format60->set_bg_color($ttl_light_blue); +$format60->set_border(1); + +my $ttl_light_green = $workbook->set_custom_color(48,'#EBF1DE'); + +$format61 = $workbook->add_format(); +$format61->copy($format40); +$format61->set_bg_color($ttl_light_green); +$format61->set_bold(); + +$format62 = $workbook->add_format(); +$format62->copy($format18); +$format62->set_bg_color($ttl_light_green); +$format62->set_border(1); + +my $ttl_light_orange = $workbook->set_custom_color(49,'#FDE9D9'); + +$format63 = $workbook->add_format(); +$format63->copy($format40); +$format63->set_bg_color($ttl_light_orange); +$format63->set_bold(); + +$format64 = $workbook->add_format(); +$format64->copy($format18); +$format64->set_bg_color($ttl_light_orange); +$format64->set_border(1); + +$format65 = $workbook->add_format(); +$format65->copy($format40); +$format65->set_align('vcenter'); + +$format66 = $workbook->add_format(); +$format66->copy($format42); +$format66->set_align('vcenter'); + +$format67 = $workbook->add_format(); +$format67->copy($format19); +$format67->set_bold(); + +$format68 = $workbook->add_format(); +$format68->copy($format49); +$format68->set_bold(); +$format68->set_text_wrap() ; +$format68->set_align('vcenter'); +$format68->set_align('center'); + +my $ttl_light_yellow = $workbook->set_custom_color(50,'#FFFFB7'); + +$format69 = $workbook->add_format(); +$format69->copy($format40); +$format69->set_bg_color($ttl_light_yellow); +$format69->set_bold(); + +$format70 = $workbook->add_format(); +$format70->copy($format18); +$format70->set_bg_color($ttl_light_yellow); +$format70->set_border(1); + +$format71 = $workbook->add_format(); +$format71->copy($format23); +$format71->set_bg_color($ttl_light_yellow); + +$format72 = $workbook->add_format(); +$format72->copy($format3); +$format72->set_bg_color($ttl_light_yellow); + +$format73 = $workbook->add_format(); +$format73->copy($format1); +$format73->set_bg_color($ttl_light_yellow); + +$format74 = $workbook->add_format(); +$format74->copy($format69); +$format74->set_bold(); +$format74->set_text_wrap() ; +$format74->set_align('vcenter'); +$format74->set_align('center'); + +$format75 = $workbook->add_format(); +$format75->copy($format40); +$format75->set_bold(); +$format75->set_text_wrap() ; +$format75->set_align('vcenter'); +$format75->set_align('center'); + +$format76 = $workbook->add_format(); +$format76->copy($format1); +$format76->set_text_wrap() ; +# $format76->set_bold(); +$format76->set_align('right'); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_set_column_width { + +my ($worksheet_name,$from,$to,$width) = @_; + +$worksheet{$worksheet_name}->set_column("$from".":"."$to", $width); + +} #------------------------------------------------------------------------------------------ + +sub xlscreator_autofit_columns { + +my $worksheet = shift; +my $col = 0; + +for my $width (@{$worksheet->{__col_widths}}) { + + $worksheet->set_column($col, $col, $width) if $width; + $col++; + } + +} #------------------------------------------------------------------------------------------ + +# The following function is a callback that was added via add_write_handler() +# above. It modifies the write() function so that it stores the maximum +# unwrapped width of a string in a column. + +sub xlscreator_store_string_widths { + + my $worksheet = shift; + my $col = $_[1]; + my $token = $_[2]; + + # Ignore some tokens that we aren't interested in. + return if not defined $token; # Ignore undefs. + return if $token eq ''; # Ignore blank cells. + return if ref $token eq 'ARRAY'; # Ignore array refs. + return if $token =~ /^=/; # Ignore formula + + # Ignore numbers + #return if $token =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/; + + # Ignore various internal and external hyperlinks. In a real scenario + # you may wish to track the length of the optional strings used with + # urls. + return if $token =~ m{^[fh]tt?ps?://}; + return if $token =~ m{^mailto:}; + return if $token =~ m{^(?:in|ex)ternal:}; + + # We store the string width as data in the Worksheet object. We use + # a double underscore key name to avoid conflicts with future names. + # + my $old_width = $worksheet->{__col_widths}->[$col]; + my $string_width = xlscreator_string_width($token); + + if (not defined $old_width or $string_width > $old_width) { + # You may wish to set a minimum column width as follows. + #return undef if $string_width < 10; + + $worksheet->{__col_widths}->[$col] = $string_width; + } + + + # Return control to write(); + return undef; +} #------------------------------------------------------------------------------------------ + +# Very simple conversion between string length and string width for Arial 10. +# See below for a more sophisticated method. + +sub xlscreator_string_width { + +return 1.2 * length $_[0]; + +} #------------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/_FromProd/xlsxcreator.pm b/libs/modules/_FromProd/xlsxcreator.pm new file mode 100644 index 0000000..858b178 --- /dev/null +++ b/libs/modules/_FromProd/xlsxcreator.pm @@ -0,0 +1,997 @@ +sub xlsxcreator_delete_previous_xlsx { + +my ($path) = @_ ; + +opendir(DIR, "$path") or die "cant open Directory $path: $!\n"; + +while(defined($folder = readdir(DIR))) { + if (length $folder > 2) { + my ($file,$type) = split(/\./,$folder) ; + + # if ($match) { unless ($file =~ /$match/gi) { next ; } } + + # my ($j1,$j2,$accid,$date) = split(/\-/,$file) ; + # if ($match) { unless ($accid eq $match) { next ; } } + + if (-e "$path/$file.xlsx"){ + unlink ("$path/$file.xlsx") or print "unable to unlink - $path/$file.xlsx : $!"; + } + } + } + +closedir(DIR) ; + +} #------------------------------------------------------------------------------------ + +sub xlsxcreator_create_xlsx { + +my ($file) = @_; + +our $workbook = Excel::Writer::XLSX->new($file) or die "ERROR : $file : $!"; + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_close_xlsx { + +$workbook->close(); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_hide_gridlines_xlsx { + +($worksheet_name) = @_; + +$worksheet{$worksheet_name}->hide_gridlines(1); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_set_margins_xlsx { + +($worksheet_name,$margin_width) = @_; + +$worksheet{$worksheet_name}->set_margins($margin_width); # Set all margins to the same value in inches + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_add_worksheet { + +my ($worksheet_name) = @_; + +$worksheet{$worksheet_name} = $workbook->add_worksheet($worksheet_name); + +#$worksheet{$worksheet_name}->add_write_handler(qr[\w], \&xlsxcreator_store_string_widths); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_add_pie_chart { + +my ($worksheet_name) = @_; + +$chart{$worksheet_name} = $workbook->add_chart( type => 'pie', embedded => 1 ); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_merge_xlsx { + +my ($worksheet_name,$merge_range,$token,$format) = @_ ; + +$worksheet{$worksheet_name}->merge_range($merge_range,$token,$format) ; + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_write_xlsx { + +my ($worksheet_name,$row,$col,$token,$cellformat) = @_; + +$token =~ s/\,//g; + +$worksheet{$worksheet_name}->write($row,$col,$token,$cellformat); + +#&xlsxcreator_autofit_columns($worksheet{$worksheet_name}); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_write_formula { + +my ($worksheet_name,$row,$col,$formula,$cellformat) = @_; + +$worksheet{$worksheet_name}->write_formula($row,$col,$formula,$cellformat); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_freeze_panes { + +my ($worksheet_name,$rows,$cols) = @_; + +$worksheet{$worksheet_name}->freeze_panes($rows,$cols); # Freeze the first 5 rows + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_insert_image { + +my ($worksheet_name,$row,$col,$file,$margin_right,$margin_bottom,$width_scale,$height_scale) = @_; + +$height_scale = $width_scale if $width_scale & !$height_scale ; + +$worksheet{$worksheet_name}->insert_image($row,$col,$file,$margin_right,$margin_bottom,$width_scale,$height_scale) ; + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_write_url { + + my ($worksheet_name,$row,$col,$url,$name) = @_; + + $worksheet{$worksheet_name}->write_url($row, $col, $url,$name, undef, 'URL') ; + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_xlsx_format { + +$format1 = $workbook->add_format(); +$format1->set_font('Verdana'); +$format1->set_size(8); + +$format2 = $workbook->add_format(); +$format2->copy($format1); +$format2->set_bold(); # Turns bold on +$format2->set_num_format('#,##0.00'); # 1,234.56 + +$format3 = $workbook->add_format(); +$format3->copy($format1); +$format3->set_num_format('#,##0.00'); # 1,234.56 + +$format4 = $workbook->add_format(); +$format4->copy($format1); +$format4->set_bold(); # Turns bold on +$format4->set_num_format('#,##0.00'); # 1,234.56 +$format4->set_top('6'); +$format4->set_bottom('6'); + +$format5 = $workbook->add_format(); +$format5->copy($format1); +$format5->set_underline(); # Single underline + +$format6 = $workbook->add_format(); +$format6->copy($format1); +$format6->set_underline(); # Single underline +$format6->set_align('right'); + +$format7 = $workbook->add_format(); +$format7->copy($format1); +$format7->set_align('right'); +$format7->set_num_format('#,##0.00'); # 1,234.56 + +$format8 = $workbook->add_format(); +$format8->copy($format1); +$format8->set_bold(); # Turns bold on +$format8->set_align('left'); +$format8->set_num_format('#,##0.00'); # 1,234.56 + +$format9 = $workbook->add_format(); +$format9->copy($format1); +$format9->set_bold(); # Turns bold on +$format9->set_align('right'); +$format9->set_num_format('#,##0.00'); # 1,234.56 + +$format10 = $workbook->add_format(); +$format10->copy($format1); +$format10->set_align('left'); + +$format11 = $workbook->add_format(); +$format11->copy($format1); +$format11->set_align('center'); +$format11->set_bg_color(0x16); #0x08 = 'black' ; #0x0C = 'blue' ; #0x10 = 'brown' ; #0x0F = 'cyan' ; #0x17 = 'gray' ; #0x11 = 'green' ; #0x0B = 'lime' ; #0x0E = 'magenta' ; #0x12 = 'navy' ; #0x35 = 'orange' ; #0x21 = 'pink' ; #0x14 = 'purple' ; #0x0A = 'red' ; #0x16 = 'silver' ; #0x09 = 'white' ; #0x0D = 'yellow' ; +$format11->set_top('1'); +$format11->set_bottom('1'); +$format11->set_left('1'); +$format11->set_right('1'); + +$format12 = $workbook->add_format(); +$format12->set_bg_color(0x16); +$format12->set_top('1'); +$format12->set_bottom('1'); +$format12->set_left('1'); +$format12->set_right('1'); + +$format13 = $workbook->add_format(); +$format13->copy($format1); +$format13->set_bg_color(0x16); +$format13->set_num_format('#,##0.00'); # 1,234.56 +$format13->set_top('1'); +$format13->set_bottom('1'); +$format13->set_left('1'); +$format13->set_right('1'); + +$format14 = $workbook->add_format(); +$format14->copy($format1); +$format14->set_bold(); # Turns bold on +$format14->set_bg_color(0x16); +$format14->set_top('1'); +$format14->set_bottom('1'); +$format14->set_left('1'); +$format14->set_right('1'); + +$format15 = $workbook->add_format(); +$format15->copy($format1); +$format15->set_align('right'); +$format15->set_num_format('#,##0.00'); # 1,234.56 +$format15->set_top('1'); +$format15->set_bottom('1'); +$format15->set_left('1'); +$format15->set_right('1'); + +$format16 = $workbook->add_format(); +$format16->copy($format1); +$format16->set_bg_color(0x16); +$format16->set_num_format('#,##0.0000'); # 1,234.56 +$format16->set_top('1'); +$format16->set_bottom('1'); +$format16->set_left('1'); +$format16->set_right('1'); + +$format17 = $workbook->add_format(); +$format17->copy($format1); +$format17->set_align('right'); +$format17->set_bg_color(0x16); +$format17->set_num_format('#,##0.00'); # 1,234.56 +$format17->set_top('1'); +$format17->set_bottom('1'); +$format17->set_left('1'); +$format17->set_right('1'); + +$format18 = $workbook->add_format(); +$format18->copy($format1); +$format18->set_bold(); +$format18->set_align('center'); + +$format19 = $workbook->add_format(); +$format19->copy($format1); +$format19->set_num_format('#,##0.00'); # 1,234.56 +$format19->set_top('1'); +$format19->set_bottom('6'); + +$format20 = $workbook->add_format(); +$format20->copy($format1); +$format20->set_align('center'); +$format20->set_num_format(0x0a); #0.00% (0x09 = 0%) + +$format21 = $workbook->add_format(); +$format21->copy($format1); +$format21->set_align('right'); + +$format22 = $workbook->add_format(); +$format22->copy($format1); +$format22->set_bold(); # Turns bold on +$format22->set_align('right'); +$format22->set_bg_color(0x16); +$format22->set_num_format('#,##0.00'); # 1,234.56 + +$format23 = $workbook->add_format(); +$format23->copy($format1); +$format23->set_bold(); # Turns bold on +$format23->set_color(0x0A); # red + +$format24 = $workbook->add_format(); +$format24->copy($format1); +$format24->set_top('2'); + +$format25 = $workbook->add_format(); +$format25->copy($format1); +$format25->set_bottom('3'); + +$format26 = $workbook->add_format(); +$format26->copy($format1); +$format26->set_bold(); # Turns bold on +$format26->set_align('left'); + +$format27 = $workbook->add_format(); +$format27->copy($format1); +$format27->set_bold(); # Turns bold on +$format27->set_align('right'); + +$format28 = $workbook->add_format(); +$format28->set_underline(2); # Single underline + +$format29 = $workbook->add_format(); +$format29->set_font('Verdana'); +$format29->set_size(5); + +$format30 = $workbook->add_format(); +$format30->set_font('Verdana'); +$format30->set_size(7); + +$format31 = $workbook->add_format(); +$format31->set_font('Verdana'); +$format31->set_size(4); +$format31->set_align('right'); + +$format32 = $workbook->add_format(); +$format32->set_font('Verdana'); +$format32->set_size(6); + +$format33 = $workbook->add_format(); +$format33->copy($format10); + +$format34 = $workbook->add_format(); +$format34->copy($format1); +$format34->set_border(1); + +$format35 = $workbook->add_format(); +$format35->copy($format10); +$format35->set_text_wrap(); +$format35->set_border(1); + +my $light_blue = $workbook->set_custom_color(40,'#D5FFFF'); + +$format36 = $workbook->add_format(); +$format36->copy($format8); +$format36->set_bg_color($light_blue); + +$format37 = $workbook->add_format(); +$format37->copy($format10); +$format37->set_bg_color($light_blue); + +$format38 = $workbook->add_format(); +$format38->copy($format1); +$format38->set_align('center'); +$format38->set_bg_color($light_blue); + +$format39 = $workbook->add_format(); +$format39->copy($format1); +$format39->set_bg_color($light_blue); + +my $light_grey = $workbook->set_custom_color(41,'#c6c6c6'); + +$format40 = $workbook->add_format(); +$format40->copy($format1); +$format40->set_align('center'); +$format40->set_bg_color($light_grey); +$format40->set_border(1); + +my $very_light_grey = $workbook->set_custom_color(42,'#EEEEEE'); + +$format41 = $workbook->add_format(); +$format41->copy($format10); +$format41->set_bg_color($very_light_grey); +$format41->set_border(1); +$format41->set_italic(); + +# merged +$format42 = $workbook->add_format(); +$format42->copy($format40); + +$format43 = $workbook->add_format(); +$format43->copy($format38); +$format43->set_border(1); + +$format44 = $workbook->add_format(); +$format44->copy($format41); +$format44->set_bg_color(0x09); + +$format45 = $workbook->add_format(); +$format45->set_font('Verdana'); +$format45->set_size(10); + +my $green = $workbook->set_custom_color(43,'#00b050'); + +$format46 = $workbook->add_format(); +$format46->set_align('center'); +$format46->copy($format45); +$format46->set_bg_color($green); + +my $light_blue_1 = $workbook->set_custom_color(44,'#b8cce4'); + +$format47 = $workbook->add_format(); +$format47->copy($format45); +$format47->set_bg_color($light_blue_1); +$format47->set_border(1); +$format47->set_border_color(0x09); + +my $very_light_blue = $workbook->set_custom_color(45,'#dce6f1'); + +$format48 = $workbook->add_format(); +$format48->copy($format47); +$format48->set_bg_color($very_light_blue); + +$format49 = $workbook->add_format(); +$format49->set_font('Arial'); +$format49->set_size(12); +$format49->set_bold(); + +$format50 = $workbook->add_format(); +$format50->set_font('Arial'); +$format50->set_size(10); +$format50->set_bold(); + +$format51 = $workbook->add_format(); +$format51->set_font('Arial'); +$format51->set_size(9); + +#-------------------------------------------------------- red highlighting + +my $hred = $workbook->set_custom_color(46,'#ff0000'); + +#40 +$format52 = $workbook->add_format(); +$format52->copy($format1); +$format52->set_align('center'); +$format52->set_bg_color($light_grey); +$format52->set_border(1); +$format52->set_color($hred); # red + +#42 +$format53 = $workbook->add_format(); +$format53->copy($format52); +$format53->set_color($hred); # red + +#35 +$format54 = $workbook->add_format(); +$format54->copy($format10); +$format54->set_text_wrap(); +$format54->set_border(1); +$format54->set_color($hred); # red + +#41 +$format55 = $workbook->add_format(); +$format55->copy($format10); +$format55->set_bg_color($very_light_grey); +$format55->set_border(1); +$format55->set_italic(); +$format55->set_color($hred); # red + +#34 +$format56 = $workbook->add_format(); +$format56->copy($format1); +$format56->set_border(1); +$format56->set_color($hred); # red + +#--------------------------------------------------- + +$format57 = $workbook->add_format(); +$format57->copy($format1); +$format57->set_top('1'); +$format57->set_bottom('6'); + +$format58 = $workbook->add_format(); +$format58->copy($format1); +$format58->set_top('1'); +$format58->set_bottom('6'); +$format58->set_bold(); +$format58->set_align('center'); + +my $ttl_light_blue = $workbook->set_custom_color(47,'#DAEEF3'); + +$format59 = $workbook->add_format(); +$format59->copy($format40); +$format59->set_bg_color($ttl_light_blue); +$format59->set_bold(); + +$format60 = $workbook->add_format(); +$format60->copy($format18); +$format60->set_bg_color($ttl_light_blue); +$format60->set_border(1); + +my $ttl_light_green = $workbook->set_custom_color(48,'#EBF1DE'); + +$format61 = $workbook->add_format(); +$format61->copy($format40); +$format61->set_bg_color($ttl_light_green); +$format61->set_bold(); + +$format62 = $workbook->add_format(); +$format62->copy($format18); +$format62->set_bg_color($ttl_light_green); +$format62->set_border(1); + +my $ttl_light_orange = $workbook->set_custom_color(49,'#FDE9D9'); + +$format63 = $workbook->add_format(); +$format63->copy($format40); +$format63->set_bg_color($ttl_light_orange); +$format63->set_bold(); + +$format64 = $workbook->add_format(); +$format64->copy($format18); +$format64->set_bg_color($ttl_light_orange); +$format64->set_border(1); + +$format65 = $workbook->add_format(); +$format65->copy($format40); +$format65->set_align('vcenter'); + +$format66 = $workbook->add_format(); +$format66->copy($format42); +$format66->set_align('vcenter'); + +$format67 = $workbook->add_format(); +$format67->copy($format19); +$format67->set_bold(); + +$format68 = $workbook->add_format(); +$format68->copy($format49); +$format68->set_bold(); +$format68->set_text_wrap() ; +$format68->set_align('vcenter'); +$format68->set_align('center'); + +my $ttl_light_yellow = $workbook->set_custom_color(50,'#FFFFB7'); + +$format69 = $workbook->add_format(); +$format69->copy($format40); +$format69->set_bg_color($ttl_light_yellow); +$format69->set_bold(); + +$format70 = $workbook->add_format(); +$format70->copy($format18); +$format70->set_bg_color($ttl_light_yellow); +$format70->set_border(1); + +$format71 = $workbook->add_format(); +$format71->copy($format23); +$format71->set_bg_color($ttl_light_yellow); + +$format72 = $workbook->add_format(); +$format72->copy($format3); +$format72->set_bg_color($ttl_light_yellow); + +$format73 = $workbook->add_format(); +$format73->copy($format1); +$format73->set_bg_color($ttl_light_yellow); + +$format74 = $workbook->add_format(); +$format74->copy($format69); +$format74->set_bold(); +$format74->set_text_wrap() ; +$format74->set_align('vcenter'); +$format74->set_align('center'); + +$format75 = $workbook->add_format(); +$format75->copy($format40); +$format75->set_bold(); +$format75->set_text_wrap() ; +$format75->set_align('vcenter'); +$format75->set_align('center'); + +$format76 = $workbook->add_format(); +$format76->copy($format1); +$format76->set_text_wrap() ; +# $format76->set_bold(); +$format76->set_align('right'); + +our $format_event_heading = $workbook -> add_format() ; +$format_event_heading -> set_size(20) ; +$format_event_heading -> set_align('center') ; +$format_event_heading -> set_valign('vcenter') ; +$format_event_heading -> set_bottom('2') ; +$format_event_heading -> set_bold() ; + +our $format_event_heading_2 = $workbook -> add_format() ; +$format_event_heading_2 -> set_size(12) ; +$format_event_heading_2 -> set_align('center') ; +$format_event_heading_2 -> set_valign('vcenter') ; +$format_event_heading_2 -> set_bottom('2') ; +$format_event_heading_2 -> set_underline() ; +$format_event_heading_2 -> set_bold() ; + +our $format_event_data = $workbook -> add_format() ; +$format_event_data -> set_size(11) ; +$format_event_data -> set_align('center') ; +$format_event_data -> set_valign('vcenter') ; + +our $format_event_data_2 = $workbook -> add_format() ; +$format_event_data_2 -> copy($format_event_data) ; +$format_event_data_2 -> set_bottom('1') ; + +our $format_empty_row = $workbook -> add_format() ; +$format_empty_row -> set_bottom('1') ; + +our $format_management_report_totals = $workbook -> add_format() ; +$format_management_report_totals -> set_size(11) ; +$format_management_report_totals -> set_align('center') ; +$format_management_report_totals -> set_valign('vcenter') ; +$format_management_report_totals -> set_top(6) ; +$format_management_report_totals -> set_num_format('#,##0.00'); +$format_management_report_totals -> set_bold() ; + +our $format_management_report_totals_2 = $workbook -> add_format() ; +$format_management_report_totals_2 -> copy($format_management_report_totals); +$format_management_report_totals_2 -> set_num_format('#,##0'); + +our $format_management_report_total = $workbook -> add_format() ; +$format_management_report_total -> set_size(11) ; +$format_management_report_total -> set_bold() ; +$format_management_report_total -> set_align('right') ; +$format_management_report_total -> set_valign('vcenter') ; + +our $format_management_report_data = $workbook -> add_format() ; +$format_management_report_data -> set_size(10) ; +$format_management_report_data -> set_num_format('#,##0.00'); +$format_management_report_data -> set_align('center') ; +$format_management_report_data -> set_valign('vcenter') ; + +our $format_management_report_data_ref_nr = $workbook -> add_format() ; +$format_management_report_data_ref_nr -> set_size(10) ; +$format_management_report_data_ref_nr -> set_align('center') ; +$format_management_report_data_ref_nr -> set_valign('vcenter') ; + +our $format_management_report_months= $workbook -> add_format() ; +$format_management_report_months -> set_size(10) ; +$format_management_report_months -> set_align('right') ; +$format_management_report_months -> set_valign('vcenter') ; + +our $format_management_report_months_2 = $workbook -> add_format() ; +$format_management_report_months_2 -> set_size(10) ; +$format_management_report_months_2 -> set_align('left') ; +$format_management_report_months_2 -> set_valign('vcenter') ; + + + +our $format_management_report_headings = $workbook -> add_format() ; +$format_management_report_headings -> set_size(11) ; +$format_management_report_headings -> set_align('center') ; +$format_management_report_headings -> set_valign('vcenter') ; +$format_management_report_headings -> set_bold() ; +$format_management_report_headings -> set_border(1) ; +$format_management_report_headings -> set_bg_color('#B6D7A8') ; +$format_management_report_headings -> set_text_wrap() ; + +our $format_management_report_title = $workbook -> add_format() ; +$format_management_report_title -> set_bold() ; +$format_management_report_title -> set_size(16) ; +$format_management_report_title -> set_align('left') ; +$format_management_report_title -> set_valign('vcenter') ; + +my $light_blue_bg = $workbook -> set_custom_color(51,'#51CBF2'); +$format77 = $workbook -> add_format() ; +$format77 -> copy($format_event_data) ; +$format77 -> set_bottom('1') ; +$format77 -> set_left('1') ; +$format77 -> set_right('1') ; +$format77 -> set_bg_color($light_blue_bg) ; + +my $yellow_bg = $workbook -> set_custom_color(52,'#F6E305'); +$format78 = $workbook -> add_format() ; +$format78 -> copy($format77) ; +$format78 -> set_bg_color($yellow_bg) ; + +my $green_bg = $workbook -> set_custom_color(53,'#51B529'); +$format80 = $workbook -> add_format() ; +$format80 -> copy($format77) ; +$format80 -> set_bg_color($green_bg) ; + +my $orange_bg = $workbook -> set_custom_color(54,'#F4BC14'); +$format79 = $workbook -> add_format() ; +$format79 -> copy($format77) ; +$format79 -> set_bg_color($orange_bg) ; + +my $red_bg = $workbook -> set_custom_color(55,'#F90D0D'); +$format81 = $workbook -> add_format() ; +$format81 -> copy($format77) ; +$format81 -> set_bg_color($red_bg) ; + +$format82 = $workbook -> add_format() ; +$format82 -> copy($format_event_data) ; +$format82 -> set_align('left') ; + +my $slight_green = $workbook -> set_custom_color(56,'#E4EDD8'); + +# $format_management_report_headings -> set_bg_color($slight_green) ; + +$format83 = $workbook -> add_format() ; +$format83 -> set_bg_color($slight_green) ; +$format83 -> set_bottom('1') ; +$format83 -> set_right('1') ; +$format83 -> set_bold() ; +$format83 -> set_size(12) ; +$format83 -> set_align('left') ; +$format83 -> set_valign('vcenter') ; + +$format84 = $workbook -> add_format() ; +$format84 -> set_bottom('1') ; +$format84 -> set_right('1') ; +$format84 -> set_size(10) ; +$format84 -> set_align('left') ; +$format84 -> set_valign('vcenter') ; + +$format85 = $workbook -> add_format() ; +$format85 -> copy($format84) ; +$format85 -> set_align('right') ; + +$format86 = $workbook -> add_format() ; +$format86 -> copy($format85) ; + +$format87 = $workbook -> add_format() ; +$format87 -> copy($format85) ; + +my $dark_green_font = $workbook -> set_custom_color(57,'#2D6F4B'); +# my $light_green_bg = $workbook -> set_custom_color(58,'#D5EDBB'); +my $light_green_bg = $workbook -> set_custom_color(58,'#51B529'); + +my $dark_blue_font = $workbook -> set_custom_color(59,'#1D4D7E'); +# my $light_blue_bg = $workbook -> set_custom_color(60,'#C0E0F5'); +my $light_blue_bg = $workbook -> set_custom_color(60,'#FFA500'); + + +# my $dark_reb_bg = $workbook -> set_custom_color(61,'#AD0502'); +my $dark_reb_bg = $workbook -> set_custom_color(61,'#F90D0D'); +my $light_red_font = $workbook -> set_custom_color(62,'#E1B5B4'); + +my $light_grey_bg = $workbook -> set_custom_color(63,'#E9EAEC'); + +# my $pubple_border_color = $workbook -> set_custom_color(64,'#8B1D5F'); + + +# my $dark_green_font = $workbook -> set_custom_color(57,'#2D6F4B'); +# my $light_green_bg = $workbook -> set_custom_color(58,'#D5EDBB'); +# my $dark_blue_font = $workbook -> set_custom_color(59,'#1D4D7E'); +# my $light_blue_bg = $workbook -> set_custom_color(60,'#C0E0F5'); +# my $dark_reb_bg = $workbook -> set_custom_color(61,'#AD0502'); +# my $light_red_font = $workbook -> set_custom_color(62,'#E1B5B4'); +# my $light_grey_bg = $workbook -> set_custom_color(63,'#E9EAEC'); +# my $pubple_border_color = $workbook -> set_custom_color(64,'#8B1D5F'); + + + +$format88 = $workbook -> add_format() ; +$format88 -> copy($format84) ; +$format88 -> set_bg_color($light_green_bg) ; +# $format88 -> set_custom_color('#2D6F4B') ; + +$format89 = $workbook -> add_format() ; +$format89 -> copy($format84) ; +$format89 -> set_bg_color($light_blue_bg) ; + +$format90 = $workbook -> add_format() ; +$format90 -> copy($format84) ; +$format90 -> set_bg_color($dark_reb_bg) ; + +$format91 = $workbook -> add_format() ; +$format91 -> copy($format84) ; +$format91 -> set_bg_color($light_grey_bg) ; + +$format92 = $workbook -> add_format() ; +$format92 -> copy($format84) ; +$format92 -> set_border(1); + +my $lgreen_heading_bg = $workbook -> set_custom_color(64,'#E2EEDA'); + +$format93 = $workbook -> add_format() ; +$format93 -> copy($format84) ; +$format93 -> set_top('1') ; +$format93 -> set_bold() ; +$format93 -> set_size(12) ; +$format93 -> set_bg_color($light_green_bg) ; + +# my $green_bg = $workbook -> set_custom_color(65,'#009624'); +# my $yellow_bg = $workbook -> set_custom_color(66,'#FFF000'); +# my $red_bg = $workbook -> set_custom_color(67,'#AD0502'); + +$format94 = $workbook -> add_format() ; +$format94 -> copy($format84) ; +$format94 -> set_bg_color($green_bg) ; + +$format95 = $workbook -> add_format() ; +$format95 -> copy($format84) ; +$format95 -> set_bg_color($yellow_bg) ; + +$format96 = $workbook -> add_format() ; +$format96 -> copy($format84) ; +$format96 -> set_bg_color($red_bg) ; + +$format97 = $workbook -> add_format() ; +$format97 -> copy($format84) ; +$format97 -> set_top(6) ; +$format97 -> set_bottom(6) ; +$format97 -> set_italic() ; + +$format98 = $workbook->add_format() ; +$format98 -> copy($format8) ; +$format98 -> set_align('vcenter') ; + +$format99 = $workbook->add_format(); +$format99 -> copy($format7); +$format99 -> set_num_format('#,##0'); # 1,234.56 + +$format100 = $workbook->add_format(); +$format100 -> copy($format_management_report_headings); +$format100 -> set_bg_color('#FFFF00') ; + +$format101 = $workbook -> add_format(); +$format101 -> copy($format_management_report_headings); +$format101 -> set_bg_color('#F9CB9C') ; + +# my $purple_bg = $workbook -> set_custom_color(66,'#CA0AD3'); +$format102 = $workbook -> add_format() ; +$format102 -> copy($format77) ; +$format102 -> set_bg_color('#CA0AD3') ; + +$format103 = $workbook -> add_format() ; +$format103 -> copy($format77) ; +$format103 -> set_bg_color('#164473') ; + +$format104 = $workbook -> add_format() ; +$format104 -> copy($format77) ; +$format104 -> set_bg_color('#A349A4') ; + +$format105 = $workbook -> add_format() ; +$format105 -> copy($format77) ; +$format105 -> set_bg_color('#5D09D3') ; + +$format106 = $workbook -> add_format() ; +$format106 -> copy($format77) ; +$format106 -> set_bg_color('#5D092C') ; + +$format107 = $workbook -> add_format() ; #ANALYTICS EVENT +$format107 -> copy($format77) ; +$format107 -> set_bg_color('#A05000') ; + +$format108 = $workbook -> add_format() ; #DEMO EVENT +$format108 -> copy($format77) ; +$format108 -> set_bg_color('#FF40FF') ; + +$format109 = $workbook->add_format() ; +$format109 -> copy($format1) ; +$format109 -> set_bold() ; +$format109 -> set_size(12) ; + +$format110 = $workbook->add_format() ; +$format110 -> copy($format1) ; +$format110 -> set_bold() ; +$format110 -> set_size(10) ; +$format110 -> set_bg_color('#DEECFF') ; #blue +$format110 -> set_color('#037AFE') ; #blue + +$format111 = $workbook->add_format() ; +$format111 -> copy($format110) ; +$format111 -> set_bg_color('#FFE1E6') ; #red +$format111 -> set_color('#FE2D55') ; #red + +$format112 = $workbook->add_format() ; +$format112 -> copy($format110) ; +$format112 -> set_bg_color('#E3F8F6') ; #lightbluie +$format112 -> set_color('#00C8BE') ; #lightbluie + +$format113 = $workbook->add_format() ; +$format113 -> copy($format110) ; +$format113 -> set_bg_color('#FFF0E0') ; #orange +$format113 -> set_color('#FF9502') ; #orange +$format113 -> set_size(8) ; + +$format114 = $workbook->add_format() ; +$format114 -> copy($format113) ; +$format114 -> set_bold('0') ; + +$format115 = $workbook->add_format() ; +$format115 -> copy($format1) ; +$format115 -> set_bold() ; +# FF9502 +$format116 = $workbook->add_format() ; +$format116 -> copy($format113) ; +$format116 -> set_bold() ; +$format116 -> set_size(10) ; + +$format117 = $workbook->add_format() ; +$format117 -> copy($format1) ; +$format117 -> set_bold() ; +$format117 -> set_size(12) ; + +$format118 = $workbook->add_format() ; +$format118 -> copy($format117) ; +$format118 -> set_size(10) ; + +$format119 = $workbook->add_format() ; +$format119 -> copy($format1) ; +$format119 -> set_size(10) ; +$format119 -> set_top(1) ; +$format119 -> set_bottom(6) ; +$format119 -> set_num_format('#,##0.00'); + +$format120 = $workbook->add_format() ; +$format120 -> copy($format1) ; +$format120 -> set_size(8) ; +$format120 -> set_num_format('#,##0.00'); + +$format121 = $workbook->add_format() ; +$format121 -> copy($format1) ; +$format121 -> set_bottom(1) ; + +$format122 = $workbook->add_format() ; +$format122 -> copy($format1) ; +$format122 -> set_left(1) ; + +# my $other_green = $workbook -> set_custom_color(100,'#B6D7A8'); + +# $format_management_report_headings -> set_bg_color($lgreen_heading_bg) ; + + +# $format92 -> set_border_color(0x0A) ; +# $format92 -> set_border_color($pubple_border_color) ; + +# set_font_strikethrough +# $format86 -> strikeout('1'); + +# $format87 = $workbook -> add_format() ; +# $format87 -> set_bottom('1') ; +# $format87 -> set_right('1') ; +# $format87 -> set_size(10) ; +# $format87 -> set_align('right') ; +# $format87 -> set_valign('vcenter') ; +# $format87 -> set_font_strikethrough('1'); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_set_column_width { + +my ($worksheet_name,$from,$to,$width) = @_; + +$worksheet{$worksheet_name}->set_column("$from".":"."$to", $width); + +} #------------------------------------------------------------------------------------------ + +sub xlsxcreator_autofit_columns { + +my $worksheet = shift; +my $col = 0; + +for my $width (@{$worksheet->{__col_widths}}) { + + $worksheet->set_column($col, $col, $width) if $width; + $col++; + } + +} #------------------------------------------------------------------------------------------ + +# The following function is a callback that was added via add_write_handler() +# above. It modifies the write() function so that it stores the maximum +# unwrapped width of a string in a column. + +sub xlsxcreator_store_string_widths { + + my $worksheet = shift; + my $col = $_[1]; + my $token = $_[2]; + + # Ignore some tokens that we aren't interested in. + return if not defined $token; # Ignore undefs. + return if $token eq ''; # Ignore blank cells. + return if ref $token eq 'ARRAY'; # Ignore array refs. + return if $token =~ /^=/; # Ignore formula + + # Ignore numbers + #return if $token =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/; + + # Ignore various internal and external hyperlinks. In a real scenario + # you may wish to track the length of the optional strings used with + # urls. + return if $token =~ m{^[fh]tt?ps?://}; + return if $token =~ m{^mailto:}; + return if $token =~ m{^(?:in|ex)ternal:}; + + # We store the string width as data in the Worksheet object. We use + # a double underscore key name to avoid conflicts with future names. + # + my $old_width = $worksheet->{__col_widths}->[$col]; + my $string_width = xlsxcreator_string_width($token); + + if (not defined $old_width or $string_width > $old_width) { + # You may wish to set a minimum column width as follows. + #return undef if $string_width < 10; + + $worksheet->{__col_widths}->[$col] = $string_width; + } + + + # Return control to write(); + return undef; +} #------------------------------------------------------------------------------------------ + +# Very simple conversion between string length and string width for Arial 10. +# See below for a more sophisticated method. + +sub xlsxcreator_string_width { + +return 1.2 * length $_[0]; + +} #------------------------------------------------------------------------------------------ + +1; diff --git a/libs/modules/analytics_event_booking_tabs.pm b/libs/modules/analytics_event_booking_tabs.pm index 05ca4b2..73d3c94 100644 --- a/libs/modules/analytics_event_booking_tabs.pm +++ b/libs/modules/analytics_event_booking_tabs.pm @@ -17,7 +17,7 @@ sub analytics_event_bookings_tabs_build_qt_left { $lcol = 2 ; $fcol = 1 ; $add_form_fields = '' ; # $add_form_fields .= qq~
    ~ if $is_schools_manager ; - $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 && $usertype ne 'analytics_client' ; my $checked = ($db{$table}{$id}{event_completed}) ? 'CHECKED' : '' ; $preferred_title{event_completed} = "Event Completed" ; @@ -43,10 +43,10 @@ sub analytics_event_bookings_tabs_build_qt_left { $add_form_fields .= &common_min_form_checkbox('event_cancelled',$db{$table}{$id}{event_cancelled},$checked) ; # $add_form_fields .= qq~
    ~ if $is_schools_manager ; - $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 && $usertype ne 'analytics_client' ; # $add_form_fields .= qq~
    ~ if $is_schools_manager ; - $add_form_fields .= qq~
    ~ if $glod_user_level < 3 ; + $add_form_fields .= qq~
    ~ if $glod_user_level < 3 && $usertype ne 'analytics_client' ; $fcol = 4 ; $add_form_fields .= &common_min_form_input('contact_name',$db{$table}{$id}{contact_name},'') ; @@ -119,8 +119,9 @@ sub analytics_event_bookings_tabs_build_qt_left { $add_form_fields = "" ; - foreach (keys %service_types) { + foreach (sort {$a <=> $b} keys %service_types) { $opts{service_type_id} .= qq~~ ; + $opts{service_type} .= qq~~ ; } foreach (split(/\,/,$db{$table}{$id}{sport_type_ids})) { @@ -129,7 +130,7 @@ sub analytics_event_bookings_tabs_build_qt_left { $db{$table}{$id}{service_type_id} = 3 unless $db{$table}{$id}{service_type_id}; - $opts{service_type_id} =~ s/value="$db{$table}{$id}{service_type_id}"/value="$db{$table}{$id}{service_type_id}" SELECTED/g ; + # $opts{service_type} = $opts{service_type_id} ; for (1 .. 100) { $opts{total_fixtures} .= qq~~ ; @@ -173,17 +174,54 @@ sub analytics_event_bookings_tabs_build_qt_left { # $allow_deselect{client_id} = 1 ; # $required{client_id} = 1 ; - + # $db{$table}{$id}{total_fixtures} = 2 ; + $add_form_fields .= &common_min_form_select('client_id',$db{$table}{$id}{client_id}) ; + $add_form_fields .= &common_min_form_select('sport_type_ids',$db{$table}{$id}{sport_type_ids}) ; + + $db{$table}{$id}{default_fixtures_sport} = "0" unless $db{$table}{$id}{default_fixtures_sport} ; + + $add_form_fields .= qq~~ ; + $add_form_fields .= &common_min_form_input('event_name',$db{$table}{$id}{event_name}) ; $add_form_fields .= &common_min_form_datetimepicker('start_date_time',$db{$table}{$id}{start_date_time}) ; $add_form_fields .= &common_min_form_datetimepicker('end_date_time',$db{$table}{$id}{end_date_time}) ; - $add_form_fields .= &common_min_form_select('sport_type_ids',$db{$table}{$id}{sport_type_ids}) ; + $add_form_fields .= &common_min_form_select('total_fixtures',$db{$table}{$id}{total_fixtures}) ; + + $opts{service_type_id} =~ s/value="$db{$table}{$id}{service_type_id}"/value="$db{$table}{$id}{service_type_id}" SELECTED/g ; + $add_form_fields .= &common_min_form_select('service_type_id',$db{$table}{$id}{service_type_id}) ; + $trigger_jquery_raw .= qq~ + \$("#selectService_type_id").on("change", function () { + let this_val = \$(this).val() ; + \$("#three [id^='selectService_type_fixtures_']").each( function () { + let row_nr = get_row_nr(this.id) ; + \$(this).val(this_val).trigger("chosen:updated") ; + if (this_val == "1") { + \$("#selectFootage_type_fixtures_"+row_nr).val("r").trigger("chosen:updated") ; + } + }) ; + }) ; + + ~ ; + + $trigger_jquery_raw .= qq~ + \$("#selectService_type_id").change( function () { + for (let i = 1; i<=100 ; i++) { + if (!\$("#fixtures_"+i).html()) { + break ; + } + if (!\$("#selectService_type_fixtures_"+i).val()) { + \$("#selectService_type_fixtures_"+i).val(\$(this).val()).trigger("chosen:updated") ; + } + } + }) ; + ~ ; + $db{$table}{$id}{tournament_festival_id} = 1 if !$db{$table}{$id}{derby_day_weekly_fixture_id} && !$db{$table}{$id}{tournament_festival_id} ; - + $add_form_fields .= &common_min_form_checkbox('derby_day_weekly_fixture_id',$db{$table}{$id}{derby_day_weekly_fixture_id}) ; $add_form_fields .= &common_min_form_checkbox('tournament_festival_id',$db{$table}{$id}{tournament_festival_id}) ; @@ -219,27 +257,134 @@ sub analytics_event_bookings_tabs_build_qt_left { updateChosen(\$el); }; - \$("#checkboxDerby_day_weekly_fixture_id").on("change",function () { + + // if (check_team_names_match_client && client_id == "") { + // client_id = getClientId() ; + // if (client_id == null) { + // client_id = -1 ; + // } + // } + + // if (client_id == "" || client_id == -1 || client_id == null) { + // \$("input[name='typeahead_"+field_name+"']").val("") ; + // \$("input[name='"+field_name+"']").val("") ; + // client_id = "" ; + // } else if (check_team_names_match_client) { + // let url_teams = `$useropts{scripts}/get/get_sss_teams_from_client.pl?client_id=\${client_id}` ; + // teams = await fetchJSON(url_teams); + // const idToCheck = \$("input[name='"+field_name+"']").val() ; + // console.log("idToCheck : "+idToCheck) ; + // if (idToCheck) { + // const exists = teams.some(item => item.id === idToCheck) ; + // if (exists == false) { + // \$("input[name='typeahead_"+field_name+"']").val("") ; + // \$("input[name='"+field_name+"']").val("") ; + // } + // } + // } + + + + \$("#checkboxDerby_day_weekly_fixture_id").on("change",async function () { + if (\$(this).is(":checked")) { \$("#checkboxTournament_festival_id").prop("checked",false) ; \$("#add_existing_home_team").css("display","none") ; - build_teams_from_client() ; + \$("#add_existing_away_team").css("display","none") ; + // build_teams_from_client() ; + let clientId = getClientId() ; + if (clientId == null) { + clientId = -1 ; + } + create_typeahead("fixtures_table","[name^='typeahead_home_team_']",clientId,1) ; + + let found_blank = 0 ; let first_non_blank = "" ; + + let teams = [] ; + + if (clientId == "" || clientId == -1 || clientId == null) { + } else { + let url_teams = `$useropts{scripts}/get/get_sss_teams_from_client.pl?client_id=\${clientId}` ; + teams = await fetchJSON(url_teams); + } + + \$("#three input[name^='home_team_']").each( function () { + + if ((\$("input[name='"+this.name+"']").val() && teams.some(item => item.id === \$("input[name='"+this.name+"']").val()) === false) || !\$("#selectClient_id").val()) { + \$("input[name='"+this.name+"']").val("") ; + \$("input[name='typeahead_"+this.name+"']").val("") ; + } + + if (!\$("input[name='"+this.name+"']").val() && !found_blank) { + found_blank = 1 ; + } + if (\$("input[name='"+this.name+"']").val() && first_non_blank == "") { + first_non_blank = this.name ; + } + + }) ; + + if (found_blank && first_non_blank != "") { + apply_home_team_to_all_blank(first_non_blank) ; + } + } else { \$("#checkboxTournament_festival_id").prop("checked",true) ; \$("#add_existing_home_team").css("display","") ; + \$("#add_existing_away_team").css("display","") ; + create_typeahead("fixtures_table","[name^='typeahead_home_team_']","",3) ; } - }) ; - \$("#checkboxTournament_festival_id").change( function () { - if (\$(this).is(":checked")) { - \$("#add_existing_home_team").css("display","") ; - \$("#checkboxDerby_day_weekly_fixture_id").prop("checked",false) ; - } else { - \$("#add_existing_home_team").css("display","none") ; - \$("#checkboxDerby_day_weekly_fixture_id").prop("checked",true) ; - build_teams_from_client() ; - } + }) ; + \$("#checkboxTournament_festival_id").change( async function () { + if (\$(this).is(":checked")) { + \$("#add_existing_home_team").css("display","") ; + \$("#add_existing_away_team").css("display","") ; + \$("#checkboxDerby_day_weekly_fixture_id").prop("checked",false) ; + create_typeahead("fixtures_table","[name^='typeahead_home_team_']","",3) ; + } else { + \$("#checkboxTournament_festival_id").prop("checked",false) ; + \$("#add_existing_home_team").css("display","none") ; + \$("#add_existing_away_team").css("display","none") ; + // build_teams_from_client() ; + let clientId = getClientId() ; + if (clientId == null) { + clientId = -1 ; + } + create_typeahead("fixtures_table","[name^='typeahead_home_team_']",clientId,0) ; + + let found_blank = 0 ; let first_non_blank = "" ; + + let teams = "[]" ; + + if (clientId == "" || clientId == -1 || clientId == null) { + } else { + let url_teams = `$useropts{scripts}/get/get_sss_teams_from_client.pl?client_id=\${clientId}` ; + teams = await fetchJSON(url_teams); + } + + \$("#three input[name^='home_team_']").each( function () { + + if (\$("input[name='"+this.name+"']").val() && teams.some(item => item.id === \$("input[name='"+this.name+"']").val()) === false) { + \$("input[name='"+this.name+"']").val("") ; + \$("input[name='typeahead_"+this.name+"']").val("") ; + } + + if (!\$("input[name='"+this.name+"']").val() && !found_blank) { + found_blank = 1 ; + } + if (\$("input[name='"+this.name+"']").val() && first_non_blank == "") { + first_non_blank = this.name ; + } + + }) ; + + if (found_blank && first_non_blank != "") { + apply_home_team_to_all_blank(first_non_blank,clientId,1) ; + } + } + }) ; async function build_teams_from_client () { @@ -285,7 +430,7 @@ sub analytics_event_bookings_tabs_build_qt_left { # custom_selected_region" # custom_selected_country - + $trigger_jquery_raw .= qq~ let map_client_to_country = {} ; @@ -323,26 +468,25 @@ sub analytics_event_bookings_tabs_build_qt_left { // \$el.val("").trigger("chosen:updated"); // }; - - const getInputValue = name => \$(`input[name='\${name}']`).val(); const setInputValue = (name, val = "") => \$(`input[name='\${name}']`).val(val); - let prev_country_id = \$countrySelect.val() ; let prev_region_id = \$regionSelect.val() ; \$clientSelect.on("change", async function () { - + dispCustomer() ; const hasCustomRegion = !!getInputValue('custom_selected_region') ; const clientId = getClientId() ; const hasCustomCountry = !!getInputValue('custom_selected_country') ; - if (clientId && !hasCustomRegion) { + if (clientId && !hasCustomRegion) { + let url1 = `$useropts{scripts}/get/get_region_country_from_client.pl?client_id=\${clientId}` ; - if (!hasCustomRegion || !hasCustomCountry) { + + if (!hasCustomRegion || !hasCustomCountry) { const data = await fetchJSON(url1) ; data.forEach(({region_id,country_id}) => { if (region_id == '0') region_id = '' ; @@ -360,26 +504,99 @@ sub analytics_event_bookings_tabs_build_qt_left { } let cnt = 0 ; let teams = "[]" ; - + if (clientId) { + let url_teams2 = `$useropts{scripts}/get/get_sss_teams_from_client.pl?client_id=\${clientId}` ; - teams = await fetchJSON(url_teams2); + + teams = await fetchJSON(url_teams2); + + if (\$("#checkboxDerby_day_weekly_fixture_id").is(":checked")) { + + \$("#three input[name^='home_team_']").each( function () { + + let id_name = this.name ; + const \$teamSelect = \$("input[name='"+id_name+"']") ; + + const idToCheck = \$teamSelect.val() ; + const exists = teams.some(item => item.id === idToCheck) ; + if (!exists || exists == false) { + \$teamSelect.val("") ; + \$("input[name='typeahead_"+id_name+"']").val("") ; + } + + // if (!\$teamSelect.val() && teams.length == 1 && teams != "[]") { // only select if 1 in the list + if (!\$teamSelect.val() && teams != "[]") { // select the first available team + // \$teamSelect.val(teams[0].name) ; + // \$("input[name='typeahead_"+id_name+"']").val(teams[0].id) ; + + \$teamSelect.val(teams[0].id) ; + \$("input[name='typeahead_"+id_name+"']").val(teams[0].name) ; + } + }) ; + + create_typeahead("fixtures_table","[name^='typeahead_home_team_']",clientId,1) ; + } else { + // create_typeahead("fixtures_table","[name^='typeahead_home_team_']","",3) ; + } + // else { + // create_typeahead("fixtures_table","[name^='typeahead_home_team_']",clientId,1) ; + // } + + } else { + if (\$("#checkboxDerby_day_weekly_fixture_id").is(":checked")) { + + \$("#three input[name^='home_team_']").each( function () { + \$("input[name='"+this.name+"']").val("") ; + \$("input[name='typeahead_"+this.name+"']").val("") ; + }) ; + + create_typeahead("fixtures_table","[name^='typeahead_home_team_']","-1",1) ; + + } else { + create_typeahead("fixtures_table","[name^='typeahead_home_team_']","",3) ; + } + // else { + // create_typeahead("fixtures_table","[name^='typeahead_home_team_']","clientId",1) ; + // } + // create_typeahead("fixtures_table","[name^='typeahead_home_team_']",-1,3) ; } if (teams.length > 0 && teams != "[]") { + \$("input[name='home_teams_built_on_regions']").val("") ; - \$("#fixtures_table select[id^='selectHome_team_']").each( function () { - let selected_val = (\$(this).val()) ? \$(this).val() : "" ; - const \$teamSelect = \$(this) ; - clearSelect(\$teamSelect); - fillTeamSelect(\$teamSelect,teams) ; - if (teams.length === 1) { - \$teamSelect.val(teams[0].id).trigger("chosen:updated") ; - } else { - \$teamSelect.val(selected_val).trigger("chosen:updated") ; + // \$("#fixtures_table select[id^='selectHome_team_']").each( function () { + \$("#fixtures_table input[name^='typeahead_home_team_']").each( function () { + + // let selected_val = (\$(this).val()) ? \$(this).val() : "" ; + // const \$teamSelect = \$(this) ; + + let id_name = this.name ; + + const \$teamSelect = \$("input[name='"+id_name+"']") ; + + console.log("1 id_name : "+id_name) ; + + id_name = id_name.replace("typeahead_","") ; + + // console.log("2 id_name : "+id_name) ; + // console.log("3 id_name val : "+\$("input[name='"+id_name+"']").val()) ; + // console.log("4 teams[0].id : "+teams[0].id) ; + // console.log("5 teams[0].name : "+teams[0].name) ; + + // clearSelect(\$teamSelect); + // fillTeamSelect(\$teamSelect,teams) ; + // if (teams.length === 1 && !\$("#checkboxDerby_day_weekly_fixture_id").is(":checked") && !\$("input[name='"+id_name+"']").val()) { // only select if 1 in the list + if (!\$("#checkboxDerby_day_weekly_fixture_id").is(":checked") && !\$("input[name='"+id_name+"']").val()) { // select the first available team + \$teamSelect.val(teams[0].name) ; // with _typahead + \$("input[name='"+id_name+"']").val(teams[0].id) ;// without _typahead + } else if (\$("#checkboxDerby_day_weekly_fixture_id").is(":checked")) { + // \$teamSelect.val(selected_val).trigger("chosen:updated") ; } }) ; + + } else if (\$regionSelect.val() && \$regionSelect.val() != prev_region_id) { \$("input[name='home_teams_built_on_regions']").val("1") ; await build_teams_from_region(\$regionSelect.val()) ; @@ -412,7 +629,11 @@ sub analytics_event_bookings_tabs_build_qt_left { // } hide_or_display_buttom_to_add_hometeam_from_existing() ; - + + if (!\$("#checkboxDerby_day_weekly_fixture_id").is(":checked") && clientId) { + create_typeahead("fixtures_table","[name^='typeahead_home_team_']","",3) ; + } + }) ; \$countrySelect.on("change", async function () { @@ -463,7 +684,7 @@ sub analytics_event_bookings_tabs_build_qt_left { const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}`; - console.log("regionUrl : "+regionUrl) ; + // console.log("regionUrl : "+regionUrl) ; const regions = await fetchJSON(regionUrl); @@ -504,11 +725,13 @@ sub analytics_event_bookings_tabs_build_qt_left { } async function build_teams_from_region (regionId="",countryId="") { - + + return ; + let url_teams1 = `$useropts{scripts}/get/get_sss_teams_from_region.pl?region_id=\${regionId}&country_id=\${countryId}` ; // let tabs = (\$("input[name='home_teams_built_on_regions']").val() == "1") ? "#fixtures_table select[id^='selectHome_team_'],#fixtures_table select[id^='selectAway_team_']" : "#fixtures_table select[id^='selectAway_team_']" ; - console.log("build_teams_from_region URL : "+url_teams1) ; + // console.log("build_teams_from_region URL : "+url_teams1) ; let tabs = (\$("input[name='home_teams_built_on_regions']").val() == "1") ? "#fixtures_table select[id^='selectHome_team_']" : "" ; const teams = await fetchJSON(url_teams1); @@ -530,6 +753,57 @@ sub analytics_event_bookings_tabs_build_qt_left { return if $ret; + our $on_team_change_extra_trigger_jquery_raw = qq~~ ; + + $on_team_change_extra_trigger_jquery_raw .= qq~ + apply_home_team_to_all_blank(field_name) ; + + ~ ; + + our $on_team_change_extra_trigger_jquery_raw_2 = qq~ + apply_home_team_to_all_blank(field_name) ; + ~ ; + + $trigger_jquery_raw .= qq~ + + // function apply_home_team_to_all_blank (field_name,client_id="",check_team_names_match_client=0) { + function apply_home_team_to_all_blank (field_name) { + + if (!field_name || !\$("#checkboxDerby_day_weekly_fixture_id").is(":checked")) { + return ; + } + + \$("#three input[name^='home_team_']").each( function () { + if (!\$("input[name='typeahead_"+this.name+"']").val() && field_name != this.name) { + \$("input[name='typeahead_"+this.name+"']").val(\$("input[name='typeahead_"+field_name+"']").val()) ; + \$("input[name='"+this.name+"']").val(\$("input[name='"+field_name+"']").val()) ; + } + }) ; + + } + + ~ ; + + # \$("#fixtures_table input[name^='typeahead_home_team_']").each( function () { + + &common_shared_typeahead("fixtures_table","typeahead_away_team_,typeahead_home_team_") ; + + my $home_team_client = ($db{$table}{$id}{client_id}) ? $db{$table}{$id}{client_id} : -1 ; + + if ($db{$table}{$id}{derby_day_weekly_fixture_id}) { + $trigger_jquery_raw .= qq~ + create_typeahead("fixtures_table","[name^='typeahead_away_team_']","",3) ; + create_typeahead("fixtures_table","[name^='typeahead_home_team_']","$home_team_client",1) ; + ~ ; + } else { + $trigger_jquery_raw .= qq~ + create_typeahead("fixtures_table","[name^='typeahead_away_team_'],[name^='typeahead_home_team_']","",3) ; + // create_typeahead("fixtures_table","[name^='typeahead_home_team_']","",3) ; + ~ ; + } + + # $db{$table}{$id}{derby_day_weekly_fixture_id} + my $sec = '_fixtures' ; my ($sec_name,$sec_cnt,$sec_col) = &analytics_event_bookings_tabs_sec_det($sec) ; @@ -547,17 +821,28 @@ sub analytics_event_bookings_tabs_build_qt_left { push @headers, "Stream Forwarding" ; push @headers, "Stream Key" ; push @headers, "Stream URL" ; - + &report_xlsx_export_header("Analytics-Fixtures-$i{id}",'analytics_fixtures') ; + push @headers, "Can't Charge Client" ; + our $csvpath = "$htmlpath/csv/analytics_fixtures" ; our $csvname = "Analytics-Fixtures-$i{id}-" . $now_ccyymmdd . $now_hour . $now_min . $now_sec . '.csv' ; ; &csv_clear_folder($csvpath,"Analytics-Fixtures-$i{id}") ; &csv_create_new_file($csvpath,$csvname) ; + # $db{$table}{$i{id}}{cant_charge_client_fixtures} = "1;1" ; + + # $db{$table}{$i{id}}{cant_charge_client_reasons} = "Test123:|;123123" ; + &analytics_event_bookings_tabs_build_fixtures_table_headers(3) ; &analytics_event_bookings_tabs_build_fixtures_table($id,"$sec") ; + + + $db{$table}{$i{id}}{cant_charge_client_reasons} =~ s/\R/\_new_line_character_/g ; + $db{$table}{$i{id}}{cant_charge_client_reasons} =~ s/ /\ /g ; + $add_form_fields .= qq~~ ; my $add_box_icon = $box_icon ; $box_icon = "" ; @@ -567,7 +852,12 @@ sub analytics_event_bookings_tabs_build_qt_left { $worksheet{$ws}->set_column(4,4,30) ; $worksheet{$ws}->set_column(5,5,10) ; $worksheet{$ws}->set_column(6,6,30) ; - $worksheet{$ws}->set_column(7,8,10) ; + $worksheet{$ws}->set_column(7,8,15) ; + $worksheet{$ws}->set_column(9,9,20) ; + # $worksheet{$ws}->set_column(10,10,25) ; + $worksheet{$ws}->set_column(10,10,20) ; + $worksheet{$ws}->set_column(11,11,25) ; + $worksheet{$ws}->set_column(12,12,50) ; $box_icon .= qq~
    @@ -591,6 +881,25 @@ sub analytics_event_bookings_tabs_build_qt_left { $box_icon = $add_box_icon ; + $trigger_jquery_raw .= qq~ + \$("#three").on("click","[id^='checkboxCant_charge_client']", function () { + let row_nr = get_row_nr(this.id) ; + set_default_fixtures_values(row_nr) ; + // console.log("123123123 id : "+this.id) ; + if (\$("#"+this.id).is(":checked")) { + if (\$("#reason_icon_"+row_nr+"_$id").html()) { + \$("#reason_icon_"+row_nr+"_$id").css("display","") ; + } else { + dlgMdl("$useropts{scripts}/dialog/add_fixtures_charge_free_reason.pl?add&&$i{id}&"+row_nr,"Add Reason",'','medium-dialog') ; + // console.log("$useropts{'scripts'}/dialog/add_fixtures_charge_free_reason.pl?add&&$i{id}&"+row_nr) ; + } + } else { + // console.log("hide #reason_icon_"+row_nr+"_$id") ; + \$("#reason_icon_"+row_nr+"_$id").hide() ; + } + }) ; + ~ ; + $trigger_jquery_raw .= qq~ function importDoc(t,b) { dlgMdl("$useropts{'scripts'}/dialog/import_analytics_fixtures.pl?"+t+"&"+b,"Import EXCEL",'height:210px','min-dialog') ; @@ -662,6 +971,7 @@ sub analytics_event_bookings_tabs_build_qt_left { push @headers, "Stream Forwarding" ; push @headers, "Stream Key" ; push @headers, "Stream URL" ; + push @headers, "Can't Charge Client" ; %custom_header = () ; @@ -678,11 +988,18 @@ sub analytics_event_bookings_tabs_build_qt_left { &common_min_select_opts('event_quote_id','event_quotes','ref',$db{$table}{$id}{event_quote_id},'','id',"demo_id='0'",'','','id,ref') ; # $opts{} = $allow_deselect{event_quote_id} = 1 ; + if ($db{$table}{$id}{event_quote_id} && $db{$table}{$id}{event_quote_id} ne '-1') { + $opts{event_quote_id} .= qq~~ ; + } else { + $opts{event_quote_id} .= qq~~ ; + } + + $allow_deselect{event_quote_id} = '' ; + $add_form_fields .= &common_min_form_select('event_quote_id',$db{$table}{$id}{event_quote_id}) ; # $trigger_jquery .= qq~\$("#selectEvent_quote_id").chosen({ allow_single_deselect:true });~ ; $trigger_jquery .= qq~\$("#selectEvent_quote_id_chosen").css("width","100%")~ ; - &analytics_event_bookings_tabs_content_box($sec_name,$sec_col); } @@ -694,10 +1011,11 @@ sub analytics_event_bookings_tabs_build_fixtures_table_headers { my ($tab_cnt) = @_ ; $custom_header{$headers[4]} = qq~~ ; - $custom_header{$headers[4]} .= qq~~ ; + # $custom_header{$headers[4]} .= qq~~ ; $custom_header{$headers[5]} = qq~~ ; $custom_header{$headers[6]} = qq~~ ; - $custom_header{$headers[6]} .= qq~~ ; + # $custom_header{$headers[6]} .= qq~~ ; + $custom_header{$headers[13]} .= qq~~ ; &analytics_event_bookings_tabs_build_analytics_table_headers($tab_cnt) ; @@ -706,6 +1024,8 @@ sub analytics_event_bookings_tabs_build_fixtures_table_headers { sub analytics_event_bookings_tabs_build_analytics_table_headers { my ($tab_cnt) = @_ ; + + $custom_header{$headers[13]} .= qq~~ if $tab_cnt == 4 ; $add_form_fields .= qq~
    ~ ; @@ -717,25 +1037,32 @@ sub analytics_event_bookings_tabs_build_analytics_table_headers { # (($_ eq $headers[2] || $_ eq $headers[3]) && $tab_cnt == 4) ? 6 : # (($_ eq $headers[4] || $_ eq $headers[6]) && $tab_cnt == 3) ? 3 : # (($_ eq $headers[0] || $_ eq $headers[3] || $_ eq $headers[5] || $_ eq $headers[7]) && $tab_cnt == 3) ? 2 : 1 ; + my $col_width = - (($_ eq $headers[2] || $_ eq $headers[3]) && $tab_cnt == 4) ? 6 : - (($_ eq $headers[0]) && $tab_cnt == 3) ? 6 : - (($_ eq $headers[1]) && $tab_cnt == 3) ? 4 : - (($_ eq $headers[4] || $_ eq $headers[6]) && $tab_cnt == 3) ? 3 : - (($_ eq $headers[2] || $_ eq $headers[5] || $_ eq $headers[7]) && $tab_cnt == 3) ? 2 : - 1 ; - + (($_ eq $headers[2] || $_ eq $headers[3]) && $tab_cnt == 4) ? 6 : + (($_ eq $headers[11] || $_ eq $headers[12]) && $tab_cnt == 4) ? 4 : + (($_ eq $headers[10] || $_ eq $headers[13]) && $tab_cnt == 4) ? 2 : + (($_ eq $headers[0]) && $tab_cnt == 3) ? 6 : + (($_ eq $headers[1] || $_ eq $headers[11] || $_ eq $headers[12]) && $tab_cnt == 3) ? 4 : + # (($_ eq $headers[4] || $_ eq $headers[6]) && $tab_cnt == 3) ? 3 : + (($_ eq $headers[4] || $_ eq $headers[6]) && $tab_cnt == 3) ? 2 : + (($_ eq $headers[2] || $_ eq $headers[5] || $_ eq $headers[7] || $_ eq $headers[9] || $_ eq $headers[10] || $_ eq $headers[13]) && $tab_cnt == 3) ? 2 : + 1 ; + my $header_label = ($custom_header{$_}) ? qq~$custom_header{$_}~ : qq~~ ; # $add_form_fields .= ($_ eq $headers[2] && $tab_cnt == 4) ? qq~
    ~ : ($_ eq $headers[3] && $tab_cnt == 3) ? qq~
    ~ : qq~~ ; - $add_form_fields .= ($_ eq $headers[2] && $tab_cnt == 4) ? qq~
    ~ : + $add_form_fields .= ($_ eq $headers[2] && $tab_cnt == 4) ? qq~
    ~ : qq~~ ; + $add_form_fields .= ($_ eq $headers[10] && $tab_cnt == 4) ? qq~
    ~ : qq~~ ; + + $add_form_fields .= ($_ eq $headers[10] && $tab_cnt == 3) ? qq~
    ~ : ($_ eq $headers[0] && $tab_cnt == 3) ? qq~
    ~ : ($_ eq $headers[3] && $tab_cnt == 3) ? qq~
    ~ : qq~~ ; $add_form_fields .= qq~
    $header_label
    ~ ; # $add_form_fields .= (($_ eq $headers[3] && $tab_cnt == 4) || ($_ eq $headers[7] && $tab_cnt == 3)) ? qq~
    ~ : qq~~ ; - $add_form_fields .= (($_ eq $headers[3] && $tab_cnt == 4) || (($_ eq $headers[2] || $_ eq $headers[8]) && $tab_cnt == 3)) ? qq~
    ~ : qq~~ ; + $add_form_fields .= (($_ eq $headers[13] && $tab_cnt == 4) || ($_ eq $headers[13] && $tab_cnt == 3) || ($_ eq $headers[3] && $tab_cnt == 4) || (($_ eq $headers[2] || $_ eq $headers[9]) && $tab_cnt == 3)) ? qq~
    ~ : qq~~ ; - &xlsxcreator_write_xlsx($ws,2,$xlsxcol,$_,$format93) ; + &xlsxcreator_write_xlsx($ws,2,$xlsxcol,$_,$format93) if $_ ne $headers[-1] ; $xlsxcol++ ; } @@ -762,7 +1089,7 @@ sub analytics_event_bookings_tabs_build_fixtures_table { $opts{age_group} .= qq~~; - $opts{coding_type} .= qq~~; + $opts{coding_type} .= qq~~; $opts{footage_type} .= qq~~; @@ -788,9 +1115,9 @@ sub analytics_event_bookings_tabs_build_fixtures_table { our $nr_of_displayed_rows = ($db{$table}{$id}{total_fixtures}) ? $db{$table}{$id}{total_fixtures} : 1 ; - our %default_val = (); + our %default_val = () ; # 1;2025-06-03 08:00:00;5;open;;;a;;;3404;;;1;;;3404;;;s;;;s;;|2;2025-06-03 08:00:00;6;u19;;;b;;;6046;;;1;;;6046;;;p;;;r;; - my @table_selects_field_keys = ("age_group","team","home_team","ht_colour","away_team","coding_type","footage_type") ; + my @table_selects_field_keys = ("age_group","team","home_team","ht_colour","away_team","coding_type","footage_type","service_type") ; $allow_deselect{age_group} = 0 ; $allow_deselect{team} = 0 ; @@ -811,7 +1138,11 @@ sub analytics_event_bookings_tabs_build_fixtures_table { my @analytics_saved_values_arr = split(/\|/,$db{$table}{$id}{analytics_saved_values}) ; - foreach my $row_defs (split(/\|/,$db{$table}{$id}{fixtures_saved_values})) { + my @cant_charge_client_fixtures_arr = split(/\;/,$db{$table}{$id}{cant_charge_client_fixtures}) ; + my @cant_charge_client_reasons_arr = split(/\:\|;/,$db{$table}{$id}{cant_charge_client_reasons}) ; + my @fixtures_row_split = split(/\|/,$db{$table}{$id}{fixtures_saved_values}) ; + + foreach my $row_defs (@fixtures_row_split) { my @def_split = split(/\;/,$row_defs) ; @@ -829,7 +1160,8 @@ sub analytics_event_bookings_tabs_build_fixtures_table { $all_blank = 0 if $def_split[$cnt] ; } - $default_val{$row_nr}{service_type} = $service_types{$db{$table}{$id}{service_type_id}} ; + $default_val{$row_nr}{service_type} = ($default_val{$row_nr}{service_type}) ? $service_types{$default_val{$row_nr}{service_type}} : $service_types{$db{$table}{$id}{service_type_id}} ; + # $default_val{$row_nr}{service_type} = ($default_val{$row_nr}{service_type}) ? $service_types{$default_val{$row_nr}{service_type}} : '' ; $all_blank = 0 if $service_types{$db{$table}{$id}{service_type_id}} ; $default_val{$row_nr}{later_readonly_sport} = ($def_split[1]) ? $db{sport_types}{$def_split[1]}{name} : ($db{$table}{$id}{sport_type_ids} !~ /;/) ? $db{sport_types}{$db{$table}{$id}{sport_type_ids}}{name} : "N/A" ; @@ -854,7 +1186,7 @@ sub analytics_event_bookings_tabs_build_fixtures_table { my @analytics_saved_values_arr_2 = split(/\;/,$analytics_saved_values_arr[$row_nr-1]) ; - for (1 .. 12) { + for (1 .. 14) { my $val = $def_split[$_ - 1] ; @@ -872,16 +1204,24 @@ sub analytics_event_bookings_tabs_build_fixtures_table { $val = $coding_type{$val} ; } elsif ($_ == 9) { $val = $footage_type{$val} ; - } elsif ($_ == 10) { - $val = ($analytics_saved_values_arr_2[0] eq '1') ? 'Yes' : ($analytics_saved_values_arr_2[0] eq '2') ? 'No' : '' ; + } elsif ($_ == 10) { + $val = ($val) ? $service_types{$val} : $service_types{$db{$table}{$id}{service_type_id}} ; } elsif ($_ == 11) { - $val = $analytics_saved_values_arr_2[1] ; + $val = ($analytics_saved_values_arr_2[0] eq '1') ? 'Yes' : ($analytics_saved_values_arr_2[0] eq '2') ? 'No' : '' ; } elsif ($_ == 12) { + $val = $analytics_saved_values_arr_2[1] ; + $val =~ s/\_semi_colon_character_/\;/g ; + $val =~ s/\_pipe_character_/\|/g ; + } elsif ($_ == 13) { $val = $analytics_saved_values_arr_2[2] ; + $val =~ s/\_semi_colon_character_/\;/g ; + $val =~ s/\_pipe_character_/\|/g ; + } elsif ($_ == 14) { + $val = ($cant_charge_client_fixtures_arr[$row_nr-1] eq '1') ? "Yes" : "No" ; } - push @csv_row,$val ; - &xlsxcreator_write_xlsx($ws,$row_nr+2,$_-1,$val,$format82) ; + push @csv_row,$val if $_ < 14 ; + &xlsxcreator_write_xlsx($ws,$row_nr+2,$_-1,$val,$format82) if $_ < 14 ; } @@ -896,7 +1236,7 @@ sub analytics_event_bookings_tabs_build_fixtures_table { } $nr_of_rows = $db{$table}{$id}{total_fixtures} if $db{$table}{$id}{total_fixtures} > $nr_of_row ; - + for my $row_cnt (1 .. $nr_of_rows) { my $display_save_butt = 0 ; @@ -956,32 +1296,72 @@ sub analytics_event_bookings_tabs_build_fixtures_table { $fcol = 2 ; + my @def_split = split(/\;/,$fixtures_row_split[$row_cnt-1]) ; + + my $old_def_val = $default_val{$row_cnt}{service_type} ; + $default_val{$row_cnt}{service_type} = ($def_split[9]) ? $def_split[9] : $db{$table}{$id}{service_type_id} ; + foreach (@table_selects_field_keys) { &fixture_table_row_selects($_,$suffix,$row_cnt) ; } - $fcol = 1 ; + $default_val{$row_cnt}{service_type} = $old_def_val ; + + $fcol = 2 ; my @analytics_saved_values_arr_2 = split(/\;/,$analytics_saved_values_arr[$row_cnt-1]) ; + # $analytics_saved_values_arr_2[0] = "1" unless $analytics_saved_values_arr_2[0] ; + $field = "stream_forwarding_fixtures_$row_cnt" ; $preferred_title{$field} = "Stream Forwarding $row_cnt" ; $opts{$field} = qq~~ ; $opts{$field} =~ s/value='$analytics_saved_values_arr_2[0]'/value='$analytics_saved_values_arr_2[0]' SELECTED/g ; - $add_form_fields .= &common_min_form_select_col($field,$analytics_saved_values_arr_2[0]) ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= &common_min_form_select_col($field,$analytics_saved_values_arr_2[0]) ; + + $fcol = 4 ; + my $hide = ($analytics_saved_values_arr_2[0] eq '2') ? 1 : 0 ; $field = "stream_key_fixtures_$row_cnt" ; $preferred_title{$field} = "Stream Key $row_cnt" ; + + $analytics_saved_values_arr_2[1] =~ s/\_semi_colon_character_/;/g ; + $analytics_saved_values_arr_2[1] =~ s/\_pipe_character_/\|/g ; + + $analytics_saved_values_arr_2[2] =~ s/\_semi_colon_character_/;/g ; + $analytics_saved_values_arr_2[2] =~ s/\_pipe_character_/\|/g ; + $add_form_fields .= &common_min_form_textarea_col($field,$analytics_saved_values_arr_2[1],22.5,$hide) ; $field = "stream_URL_fixtures_$row_cnt" ; $preferred_title{$field} = "Stream URL $row_cnt" ; $add_form_fields .= &common_min_form_textarea_col($field,$analytics_saved_values_arr_2[2],22.5,$hide) ; - $add_form_fields .= qq~
    ~; + $fcol = 2 ; + + $field = "cant_charge_client_$suffix\_$row_cnt" ; + + my $checked = ($cant_charge_client_fixtures_arr[$row_cnt-1]) ? 'CHECKED' : '' ; + + $add_form_fields .= &analytics_event_bookings_tabs_form_checkbox_col($field,'',$checked,'',1) ; + + my $disp_reason = ($checked && $cant_charge_client_reasons_arr[$row_cnt-1]) ? "" : "display:none" ; + + $cant_charge_client_reasons_arr[$row_cnt-1] =~ s/ /\ /g ; + + my $reason_url = $cant_charge_client_reasons_arr[$row_cnt-1] ; + + $reason_url =~ s/\R/\_new_line_character_/g ; + + $cant_charge_client_reasons_arr[$row_cnt-1] =~ s/\R/\
    /g ; + + $add_form_fields .= qq~  ~ if $cant_charge_client_reasons_arr[$row_cnt-1] ; + + $add_form_fields .= qq~
    ~; push @team_ids_arr, "#selectHome_team_$suffix\_$_"; push @team_ids_arr, "#selectAway_team_$suffix\_$_"; @@ -992,87 +1372,98 @@ sub analytics_event_bookings_tabs_build_fixtures_table { $trigger_jquery .= qq~\$("#fixtures_table div[id^='selectReadonly_sport_fixtures_'][id\$='_chosen'],#fixtures_table div[id^='selectStream_forwarding_fixtures_'][id\$='_chosen']").css("width","100%"); ~ ; $trigger_jquery_raw .= qq~ - - let prev_sport_ids = \$("#selectSport_type_ids").chosen().val() ; - if (prev_sport_ids == null) { prev_sport_ids = "" ; } - prev_sport_ids = prev_sport_ids.toString() ; - prev_sport_ids = prev_sport_ids.split(",") ; + + let prev_sport_ids = \$("#selectSport_type_ids").chosen().val() ; + if (prev_sport_ids == null) { prev_sport_ids = "" ; } + prev_sport_ids = prev_sport_ids.toString() ; + prev_sport_ids = prev_sport_ids.split(",") ; - \$("#selectSport_type_ids").change( function () { - - let sport_ids = \$(this).chosen().val() ; - if (sport_ids == null) { sport_ids = "" ; } - sport_ids = sport_ids.toString() ; - sport_ids = sport_ids.split(",") ; - - let prev_sport_ids_len = (prev_sport_ids != "") ? prev_sport_ids.length : 0 ; - let sport_ids_len = (sport_ids != "") ? sport_ids.length : 0 ; - - if (prev_sport_ids_len < sport_ids_len) { + \$("#selectSport_type_ids").change( function () { - \$('#selectSport_type_ids option:selected').each( function() { - - let value = \$(this).val(); - let exists = \$('#selectReadonly_sport_fixtures_1 option[value="'+value+'"]').length > 0 ; - - if (!exists) { - for (let i=1;i<=100;i++) { - if (!\$("#fixtures_"+i).html()) { break ; } - \$('#selectReadonly_sport_$suffix\_'+i).append(\$(this).clone()) ; - \$('#selectReadonly_sport_$suffix\_'+i).trigger("chosen:updated") ; - } - } - }); - - } else { + if (\$("input[name='default_fixtures_sport']").val() == "0" && \$(this).chosen().val()) { + \$("input[name='default_fixtures_sport']").val(\$(this).chosen().val()) ; + } else if (\$("input[name='default_fixtures_sport']").val() != "0" && !\$(this).chosen().val()) { + \$("input[name='default_fixtures_sport']").val("0") ; + } - \$('#selectSport_type_ids option:not(:selected)').each( function() { - let value = \$(this).val(); - if (prev_sport_ids.includes(value) && !sport_ids.includes(value)) { - for (let i = 1; i <= 100; i++) { - if (!\$("#fixtures_"+i).html()) { break ; } - \$('#selectReadonly_sport_fixtures_'+i).find('option[value="'+value+'"]').remove() ; - \$('#selectReadonly_sport_fixtures_'+i).trigger("chosen:updated") ; + let sport_ids = \$(this).chosen().val() ; + if (sport_ids == null) { sport_ids = "" ; } + sport_ids = sport_ids.toString() ; + sport_ids = sport_ids.split(",") ; + + let prev_sport_ids_len = (prev_sport_ids != "") ? prev_sport_ids.length : 0 ; + let sport_ids_len = (sport_ids != "") ? sport_ids.length : 0 ; + + if (prev_sport_ids_len < sport_ids_len) { + + \$('#selectSport_type_ids option:selected').each( function() { + + let value = \$(this).val(); + let exists = \$('#selectReadonly_sport_fixtures_1 option[value="'+value+'"]').length > 0 ; + + if (!exists) { + for (let i=1;i<=100;i++) { + if (!\$("#fixtures_"+i).html()) { break ; } + \$('#selectReadonly_sport_$suffix\_'+i).append(\$(this).clone()) ; + \$('#selectReadonly_sport_$suffix\_'+i).trigger("chosen:updated") ; + } } - } - }) ; - } - prev_sport_ids = sport_ids ; - - // for (let i = 1; i <= sport_ids.length; i++) { - // let j = i - 1 ; - // if (\$("#fixtures_"+i).html() && !\$("#selectReadonly_sport_fixtures_"+i).val()) { - // \$("#selectReadonly_sport_fixtures_"+i).val(sport_ids[j]).trigger("chosen:updated") ; - // } - // } - - for (let i = 1; i <= 100; i++) { - if (!\$("#fixtures_" + i).html()) { - break ; - } - let select_sport = \$("#selectReadonly_sport_fixtures_" + i) ; - if (\$("input[name='sport_fixtures_"+i+"']").val()) { - // if (sport_ids.length === 1 && !select_sport.val()) { - // select_sport.val(sport_ids[0]).trigger("chosen:updated"); - // } - // if (sport_ids.length !== 1) { - select_sport.val(\$("input[name='sport_fixtures_"+i+"']").val()).trigger("chosen:updated") ; - // } - continue ; - } - // && (!\$("input[name='sport_fixtures_"+i+"']").val() || (\$("input[name='sport_fixtures_"+i+"']").val() && \$("input[name='sport_fixtures_"+i+"']").val() == sport_ids[0])) + }); - if (sport_ids.length === 1) { - select_sport.val(sport_ids[0]) ; } else { - select_sport.val("") ; + + \$('#selectSport_type_ids option:not(:selected)').each( function() { + let value = \$(this).val(); + if (prev_sport_ids.includes(value) && !sport_ids.includes(value)) { + for (let i = 1; i <= 100; i++) { + if (!\$("#fixtures_"+i).html()) { break ; } + \$('#selectReadonly_sport_fixtures_'+i).find('option[value="'+value+'"]').remove() ; + \$('#selectReadonly_sport_fixtures_'+i).trigger("chosen:updated") ; + } + } + }) ; } - select_sport.trigger("chosen:updated") ; - } - - }) ; + prev_sport_ids = sport_ids ; + + // for (let i = 1; i <= sport_ids.length; i++) { + // let j = i - 1 ; + // if (\$("#fixtures_"+i).html() && !\$("#selectReadonly_sport_fixtures_"+i).val()) { + // \$("#selectReadonly_sport_fixtures_"+i).val(sport_ids[j]).trigger("chosen:updated") ; + // } + // } + + for (let i = 1; i <= 100; i++) { + if (!\$("#fixtures_" + i).html()) { + break ; + } + let select_sport = \$("#selectReadonly_sport_fixtures_" + i) ; + if (\$("input[name='sport_fixtures_"+i+"']").val()) { + // if (sport_ids.length === 1 && !select_sport.val()) { + // select_sport.val(sport_ids[0]).trigger("chosen:updated"); + // } + // if (sport_ids.length !== 1) { + select_sport.val(\$("input[name='sport_fixtures_"+i+"']").val()).trigger("chosen:updated") ; + // } + continue ; + } + // && (!\$("input[name='sport_fixtures_"+i+"']").val() || (\$("input[name='sport_fixtures_"+i+"']").val() && \$("input[name='sport_fixtures_"+i+"']").val() == sport_ids[0])) + + if (sport_ids.length === 1) { + select_sport.val(sport_ids[0]) ; + } else { + select_sport.val("") ; + } + select_sport.trigger("chosen:updated") ; + + if (!select_sport.val() && \$("input[name='default_fixtures_sport']").val() != "0" && \$("#selectAge_group_fixtures_"+i).val()) { + select_sport.val(\$("input[name='default_fixtures_sport']").val()).trigger("chosen:updated") ; + } + + } + + }) ; - ~ ; + ~ ; $add_form_fields .= qq~
    @@ -1100,8 +1491,11 @@ sub analytics_event_bookings_tabs_build_fixtures_table { row_nr = parseInt(row_nr) ; return row_nr ; } - - // + + function add_checkbox (row_nr,field_name,field_id,tindex,fcol,checked) { + let checkbox = "
    " ; + return checkbox ; + } function add_textarea (row_nr,field_name,field_id,placeholder,tindex,readonly,fcol,default_val="",width="100",height="22.5",hide="") { let textarea = "
    " ; @@ -1136,6 +1530,24 @@ sub analytics_event_bookings_tabs_build_fixtures_table { return str.charAt(0).toUpperCase() + str.slice(1) ; } + // \$('#fixtures_table').on('change',"[name^='typeahead_home_team_']", function () { + // + // if (\$("#checkboxDerby_day_weekly_fixture_id").is(":checked")) { + // let row_nr = get_row_nr(this.name) ; + // for (let i = 1; i <= 100; i++) { + // if (!\$("#fixtures_"+i).html()) { + // break ; + // } + // if (\$("input[name='changed_fixtures_date_"+i+"']").val()) { + // continue ; + // } + // \$("#datetimepickerStart_date_time_fixtures_"+i).datetimepicker("setDate",start_date) ; + // } + // + // } + // + // ) ; + \$("#selectTotal_fixtures").change( function() { let selectedValue = (\$(this).val()) ? parseInt(\$(this).val()) : 1 ; @@ -1149,66 +1561,99 @@ sub analytics_event_bookings_tabs_build_fixtures_table { let sport_field_ids = "" ; let home_team_field_ids = "" ; + let home_team_field_ids_2 = "" ; let start_date_time_field_ids = "" ; + let clientId = getClientId() ; + if (clientId == null) { + clientId = -1 ; + } + + let home_team_default_team_id = (\$("#checkboxDerby_day_weekly_fixture_id").is(":checked") && clientId && clientId != -1) ? \$("input[name='home_team_fixtures_1']").val() : "" ; + let home_team_default_team = (\$("#checkboxDerby_day_weekly_fixture_id").is(":checked") && clientId && clientId != -1) ? \$("input[name='typeahead_home_team_fixtures_1']").val() : "" ; + for (let i = 1; i <= 100; i++) { if (i <= selectedValue && !\$("#fixtures_"+i).html()) { + \$("input[name='home_team_fixtures_1']").after("") ; + \$("input[name='away_team_fixtures_1']").after("") ; + let html = "
    " ; - html += "" ; - html += "" ; - - html += "
    " ; - html += add_datetimepicker(i,"start_date_time_$suffix",1,6,\$("input[name='start_date_time']").val()) ; - html += add_select(i,"readonly_sport_$suffix\_" + i, "selectReadonly_sport_$suffix\_" + i, "Select Sport "+i, "", 2, 4, 100, "", "") ; - html += "" ; - html += add_select(i,"age_group_$suffix\_" + i,"selectAge_group_$suffix\_" + i,"Select Age Group "+i,"$opts{age_group}",3,2,100,"","") ; - - html += "
    " ; - html += "
    " ; - html += add_select(i,"team_$suffix\_" + i, "selectTeam_$suffix\_" + i, "Select Team "+i, "", 4, 1, 100, "", "") ; - html += add_select(i,"home_team_$suffix\_" + i, "selectHome_team_$suffix\_" + i, "Select Home Team "+i, "", 5, 3, 100, "", "") ; - html += add_select(i,"ht_colour_$suffix\_" + i, "selectHt_colour_$suffix\_" + i, "Select Ht Colour "+i, "", 6, 2, 100, "", "") ; - html += add_select(i,"away_team_$suffix\_" + i, "selectAway_team_$suffix\_" + i, "Select Away Team "+i, "", 7, 3, 100, "", "") ; - html += add_select(i,"coding_type_$suffix\_" + i, "selectCoding_type_$suffix\_" + i, "Select Coding Type "+i,"$opts{coding_type}", 8, 2, 100, "", "") ; - html += add_select(i,"footage_type_$suffix\_" + i, "selectFootage_type_$suffix\_" + i, "Select Footage Type "+i, "$opts{footage_type}", 9, 1, 100, "", "") ; - html += "
    " ; - - html += add_select(i,"stream_forwarding_$suffix\_" + i, "selectStream_forwarding_$suffix\_" + i, "Select Stream Forwarding "+i,"", 10, 1, 100, "", "") ; - html += add_textarea (i,"stream_key_$suffix\_"+i,"textareaStream_key_$suffix\_"+i,"Stream Key "+i,11,"",1) ; - html += add_textarea (i,"stream_URL_$suffix\_"+i,"textareaStream_URL_$suffix\_"+i,"Stream URL "+i,12,"",1) ; + html += "" ; + html += "" ; + + html += "
    " ; + html += add_datetimepicker(i,"start_date_time_$suffix",1,6,\$("input[name='start_date_time']").val()) ; + html += add_select(i,"readonly_sport_$suffix\_" + i, "selectReadonly_sport_$suffix\_" + i, "Select Sport "+i, "", 2, 4, 100, "", "") ; + html += "" ; + html += add_select(i,"age_group_$suffix\_" + i,"selectAge_group_$suffix\_" + i,"Select Age Group "+i,"$opts{age_group}",3,2,100,"","") ; + html += "
    " ; + html += "
    " ; + html += add_select(i,"team_$suffix\_" + i, "selectTeam_$suffix\_" + i, "Select Team "+i, "", 4, 1, 100, "", "") ; + // html += add_select(i,"home_team_$suffix\_" + i, "selectHome_team_$suffix\_" + i, "Select Home Team "+i, "", 5, 2, 100, "", "") ; + html += add_input(i,"typeahead_home_team_$suffix\_" + i, "inputTypeahead_home_team_$suffix\_" + i, "Select Home Team "+i, 5, "", 2,home_team_default_team) ; + html += add_select(i,"ht_colour_$suffix\_" + i, "selectHt_colour_$suffix\_" + i, "Select Ht Colour "+i, "", 6, 2, 100, "", "") ; + // html += add_select(i,"away_team_$suffix\_" + i, "selectAway_team_$suffix\_" + i, "Select Away Team "+i, "", 7, 2, 100, "", "") ; + html += add_input(i,"typeahead_away_team_$suffix\_" + i, "inputTypeahead_away_team_$suffix\_" + i, "Select Away Team "+i, 7, "",2,'') ; + html += add_select(i,"coding_type_$suffix\_" + i, "selectCoding_type_$suffix\_" + i, "Select Coding Type "+i,"$opts{coding_type}", 8, 2, 100, "", "") ; + html += add_select(i,"footage_type_$suffix\_" + i, "selectFootage_type_$suffix\_" + i, "Select Footage Type "+i, "$opts{footage_type}", 9, 1, 100, "", "") ; + html += add_select(i,"service_type_$suffix\_" + i, "selectService_type_$suffix\_" + i, "Select Service Type "+i, "", 9, 2, 100, "", "") ; + html += "
    " ; + + html += "
    " ; + html += add_select(i,"stream_forwarding_$suffix\_" + i, "selectStream_forwarding_$suffix\_" + i, "Select Stream Forwarding "+i,"", 10, 2, 100, "", "") ; + html += add_textarea (i,"stream_key_$suffix\_"+i,"textareaStream_key_$suffix\_"+i,"Stream Key "+i,11,"",4) ; + html += add_textarea (i,"stream_URL_$suffix\_"+i,"textareaStream_URL_$suffix\_"+i,"Stream URL "+i,12,"",4) ; + html += add_checkbox (i,"cant_charge_client_$suffix\_"+i,"checkboxCant_charge_client_"+i,13,2,"") + html += "
    " ; // add_textarea html += "
    " ; if (select_ids1) { select_ids1 += "," ; } - select_ids1 += "#selectAge_group_$suffix\_"+i+",#selectTeam_$suffix\_"+i+",#selectStream_forwarding_$suffix\_"+i ; + select_ids1 += "#selectAge_group_$suffix\_"+i+",#selectTeam_$suffix\_"+i+",#selectStream_forwarding_$suffix\_"+i+",#selectService_type_$suffix\_"+i ; if (select_ids2) { select_ids2 += "," ; } - select_ids2 += "#selectReadonly_sport_$suffix\_"+i+",#selectHome_team_$suffix\_"+i+",#selectHt_colour_$suffix\_"+i+",#selectAway_team_$suffix\_"+i+",#selectCoding_type_$suffix\_"+i+",#selectFootage_type_$suffix\_"+i ; + select_ids2 += "#selectReadonly_sport_$suffix\_"+i+",#selectHt_colour_$suffix\_"+i+",#selectCoding_type_$suffix\_"+i+",#selectFootage_type_$suffix\_"+i ; if (select_ids3) { select_ids3 += "," ; } - select_ids3 += "#selectReadonly_sport_$suffix\_"+i+"_chosen,#selectAge_group_$suffix\_"+i+"_chosen,#selectTeam_$suffix\_"+i+"_chosen,#selectHome_team_$suffix\_"+i+"_chosen,#selectHt_colour_$suffix\_"+i+"_chosen,#selectAway_team_$suffix\_"+i+"_chosen,#selectCoding_type_$suffix\_"+i+"_chosen,#selectFootage_type_$suffix\_"+i+"_chosen,#selectStream_forwarding_$suffix\_"+i+"_chosen" ; + select_ids3 += "#selectService_type_$suffix\_"+i+"_chosen,#selectReadonly_sport_$suffix\_"+i+"_chosen,#selectAge_group_$suffix\_"+i+"_chosen,#selectTeam_$suffix\_"+i+"_chosen,#selectHt_colour_$suffix\_"+i+"_chosen,#selectCoding_type_$suffix\_"+i+"_chosen,#selectFootage_type_$suffix\_"+i+"_chosen,#selectStream_forwarding_$suffix\_"+i+"_chosen" ; \$("#fixtures_table").append(html).trigger("chosen:updated") ; + if (\$("#checkboxDerby_day_weekly_fixture_id").is(":checked")) { + create_typeahead('fixtures_table',"[name^='typeahead_away_team_$suffix\_"+i+"']","",3) ; + // let clientId = getClientId() ; + // if (clientId == null) { + // clientId = -1 ; + // } + create_typeahead('fixtures_table',"[name^='typeahead_home_team_$suffix\_"+i+"']",clientId,1) ; + + } else { + create_typeahead('fixtures_table',"[name^='typeahead_away_team_$suffix\_"+i+"'],[name^='typeahead_home_team_$suffix\_"+i+"']","",3) ; + // create_typeahead('fixtures_table',"[name^='typeahead_home_team_$suffix\_"+i+"']",clientId,1) ; + } + if (start_date_time_field_ids != "") { start_date_time_field_ids = start_date_time_field_ids+",#datetimepickerStart_date_time_$suffix\_"+i ; } else { start_date_time_field_ids = "#datetimepickerStart_date_time_$suffix\_"+i ; } if (sport_field_ids != "") { sport_field_ids = sport_field_ids+",#selectReadonly_sport_$suffix\_"+i ; } else { sport_field_ids = "#selectReadonly_sport_$suffix\_"+i ; } - ["Readonly_sport","Team","Home_team","Ht_colour","Away_team","Stream_forwarding"].forEach( function (prefix) { + ["Readonly_sport","Team","Ht_colour","Stream_forwarding"].forEach( function (prefix) { \$("#select"+prefix+"_$suffix\_" +i).append(\$("#select"+prefix+"_$suffix\_1").children().clone()).trigger("chosen:updated") ; }) ; - + + \$("#selectService_type_$suffix\_"+i).append(\$("#selectService_type_id").children().clone()).trigger("chosen:updated") ; + if ((\$("input[name='home_teams_built_on_regions']").val() == "" || \$("input[name='home_teams_built_on_regions']").val() == "0") && \$("#selectHome_team_$suffix\_1").val()) { - if (home_team_field_ids != "") { home_team_field_ids = home_team_field_ids+",#selectHome_team_$suffix\_"+i ; } else { home_team_field_ids = "#selectHome_team_$suffix\_"+i ; } + // if (home_team_field_ids != "") { home_team_field_ids = home_team_field_ids+",#selectHome_team_$suffix\_"+i ; } else { home_team_field_ids = "#selectHome_team_$suffix\_"+i ; } + if (home_team_field_ids != "") { home_team_field_ids = home_team_field_ids+",input[name='typeahead_home_team_$suffix\_"+i+"']" ; } else { home_team_field_ids = "input[name='typeahead_home_team_$suffix\_"+i+"']" ; } + if (home_team_field_ids_2 != "") { home_team_field_ids_2 = home_team_field_ids_2+",input[name='home_team_$suffix\_"+i+"']" ; } else { home_team_field_ids_2 = "input[name='home_team_$suffix\_"+i+"']" ; } } \$("#selectHome_team_$suffix\_"+i).change( function () { auto_select_home_teams(this.id) ; }) ; - } else if (i <= selectedValue && \$("#fixtures_"+i).css("display") === "none" && \$("#fixtures_"+i).html()) { \$("#fixtures_"+i).show() ; @@ -1235,9 +1680,16 @@ sub analytics_event_bookings_tabs_build_fixtures_table { if (sport_field_ids != "") { \$(sport_field_ids).val(\$("#selectReadonly_sport_$suffix\_1").val()).trigger("chosen:updated") ; } - if (home_team_field_ids != "") { - \$(home_team_field_ids).val(\$("#selectHome_team_$suffix\_1").val()).trigger("chosen:updated") ; - } + + // console.log("typeahead_home_team_$suffix\_1 : "+\$("input[name='typeahead_home_team_$suffix\_1']").val()) ; + + // if (home_team_field_ids != "") { + // \$(home_team_field_ids).val(\$("input[name='typeahead_home_team_$suffix\_1']").val()) ; + // } + + // if (home_team_field_ids_2 != "") { + // \$(home_team_field_ids_2).val(\$("input[name='home_team_$suffix\_1']").val()) ; + // } if (select_ids1 != "") { \$(select_ids1).chosen({ allow_single_deselect:false }) ; @@ -1261,9 +1713,49 @@ sub analytics_event_bookings_tabs_build_fixtures_table { // let some_fixtures_date_was_changed + function set_default_fixtures_values (row_nr) { + + if (!\$("#selectFootage_type_fixtures_"+row_nr).val()) { + \$("#selectFootage_type_fixtures_"+row_nr).val("s").trigger("chosen:updated") ; + } + + if (!\$("#selectCoding_type_fixtures_"+row_nr).val()) { + \$("#selectCoding_type_fixtures_"+row_nr).val("s").trigger("chosen:updated") ; + } + + if (!\$("#selectReadonly_sport_fixtures_"+row_nr).val()) { + \$("#selectReadonly_sport_fixtures_"+row_nr).val(\$("input[name='default_fixtures_sport']").val()).trigger("chosen:updated") ; + } + + if (!\$("#selectAge_group_fixtures_"+row_nr).val()) { + \$("#selectAge_group_fixtures_"+row_nr).val("open").trigger("chosen:updated") ; + } + + if (!\$("#selectTeam_fixtures_"+row_nr).val()) { + \$("#selectTeam_fixtures_"+row_nr).val("a").trigger("chosen:updated") ; + } + + if (!\$("#selectHt_colour_fixtures_"+row_nr).val()) { + \$("#selectHt_colour_fixtures_"+row_nr).val("5").trigger("chosen:updated") ; + } + + if (!\$("#selectStream_forwarding_fixtures_"+row_nr).val()) { + \$("#selectStream_forwarding_fixtures_"+row_nr).val("1").trigger("chosen:updated") ; + } + + } + + \$("#three").on("change", "[id^='selectAge_group_'],[id^='selectTeam_'],[id^='selectHome_team_'],[id^='selectAway_team_'],[id^='selectCoding_type_'],[id^='selectHt_colour_'],[id^='selectFootage_type_']", function () { + + let row_nr = get_row_nr(this.id) ; + set_default_fixtures_values(row_nr) ; + + }) ; + \$("#three").on("changeDate", "[id^='datetimepickerStart_date_time_fixtures_']", function () { let row_nr = get_row_nr(this.id) ; + set_default_fixtures_values(row_nr) ; \$("input[name='changed_fixtures_date_"+row_nr+"']").val("1") ; let this_date = new Date(\$("input[name='start_date_time_fixtures_"+row_nr+"']").val()) ; @@ -1470,7 +1962,9 @@ sub analytics_event_bookings_tabs_build_fixtures_table { \$("#three").on("change", "[id^='selectReadonly_sport_']", function () { let row_nr = get_row_nr(this.id) ; \$("input[name='sport_fixtures_"+row_nr+"']").val(\$(this).val()) ; - console.log("CHANGED ADDED SPORT "+row_nr) ; + // console.log("CHANGED ADDED SPORT "+row_nr) ; + set_default_fixtures_values(row_nr) ; + }) ; @@ -1562,20 +2056,31 @@ sub fixture_table_row_selects { my ($field_key,$suffix,$row_nr) = @_ ; # ("age_group","team","home_team","ht_colour","away_team","coding_type","footage_type") $field = "$field_key\_$suffix\_$row_nr"; + # $fcol = ($field_key eq 'home_team' || $field_key eq 'away_team') ? 3 : ($field_key eq 'team' || $field_key eq 'ht_colour' || $field_key eq 'coding_type') ? 2 : 1; - $fcol = ($field_key eq 'home_team' || $field_key eq 'away_team') ? 3 : ($field_key eq 'age_group' || $field_key eq 'ht_colour' || $field_key eq 'coding_type') ? 2 : 1 ; - my $field_key2 = join(" ", map { ucfirst $_ } split(/\_/,$field_key)) ; - $preferred_title{$field} = "$field_key2 $row_nr"; - $opts{$field} = $opts{$field_key}; + $fcol = ($field_key eq 'home_team' || $field_key eq 'away_team') ? 2 : ($field_key eq 'age_group' || $field_key eq 'ht_colour' || $field_key eq 'coding_type' || $field_key eq 'service_type') ? 2 : 1 ; + + if ($field_key eq 'home_team' || $field_key eq 'away_team') { + $preferred_placeholder{"typeahead_$field"} = "$field_key\_$row_nr" ; + $preferred_placeholder{"typeahead_$field"} = "Select " . join(" ", map { ucfirst $_ } split(/\_/,$preferred_placeholder{"typeahead_$field"})) ; + $print_box_content_rows .= qq~~ ; + $add_form_fields .= &common_min_form_input_col("typeahead_$field",$db{teams}{$default_val{$row_nr}{$field_key}}{name}) ; + return ; + } + + my $field_key2 = join(" ", map { ucfirst $_ } split(/\_/,$field_key)) ; + $preferred_title{$field} = "$field_key2 $row_nr" ; + $opts{$field} = $opts{$field_key} ; $opts{$field} =~ s/value='\Q$default_val{$row_nr}{$field_key}\E'/value='$default_val{$row_nr}{$field_key}' SELECTED/g if $default_val{$row_nr}{$field_key} ; + $allow_deselect{$field} = $allow_deselect{$field_key} ; - $add_form_fields .= qq~
    ~ if $field_key eq "team" ; - $add_form_fields .= &common_min_form_select_col($field,$default_val{$row_nr}{$field_key}); - $add_form_fields .= qq~
    ~ if $field_key eq "footage_type" || $field_key eq "age_group" ; + $add_form_fields .= qq~
    ~ if $field_key eq "team" ; + $add_form_fields .= &common_min_form_select_col($field,$default_val{$row_nr}{$field_key}) ; + $add_form_fields .= qq~
    ~ if $field_key eq "service_type" || $field_key eq "age_group" ; $field_key = "#select" . ucfirst $field ; - push @all_selects_ids,"$field_key"; - $field_key = $field_key . "_chosen" ; - push @all_selects_tab,"$field_key"; + push @all_selects_ids,"$field_key" ; + $field_key = $field_key . "_chosen" ; + push @all_selects_tab,"$field_key" ; } #------------------------------------------------------------------------------------------ @@ -1585,7 +2090,7 @@ sub analytics_table_row_labels { # ("age_group","team","home_team","ht_colour","away_team","coding_type","footage_type") $field = "$field_key\_$suffix\_$row_nr"; # $fcol = ($field_key eq 'home_team' || $field_key eq 'away_team') ? 3 : ($field_key eq 'start_date_time' || $field_key eq 'team' || $field_key eq 'ht_colour' || $field_key eq 'coding_type') ? 2 : 1 ; - $fcol = ($field_key eq 'age_group' || $field_key eq 'team') ? 6 : 1 ; + $fcol = ($field_key eq 'age_group' || $field_key eq 'team') ? 6 : ($field_key eq 'stream_key' || $field_key eq 'stream_URL') ? 4 : ($field_key eq 'stream_forwarding' || $field_key eq 'cant_charge_client') ? 2 : 1 ; my $field_key2 = join(" ", map { ucfirst $_ } split(/\_/,$field_key)) ; $preferred_title{$field} = "$field_key2 $row_nr"; $opts{$field} = $opts{$field_key}; @@ -1593,7 +2098,9 @@ sub analytics_table_row_labels { # $allow_deselect{$field} = $allow_deselect{$field_key} ; # $add_form_fields .= qq~
    ~ if $field_key eq "team" ; $add_form_fields .= qq~
    ~ if $field_key eq "age_group" ; + $add_form_fields .= qq~
    ~ if $field_key eq "stream_forwarding" ; $default_val{$row_nr}{$field_key} = &common_min_date_as_string($default_val{$row_nr}{$field_key}) if $field_key eq 'start_date_time' ; + # my @table_selects_field_keys = ("start_date_time","readonly_sport","age_group","team","home_team","ht_colour","away_team","coding_type","footage_type","service_type","stream_forwarding","stream_key","stream_URL","cant_charge_client") ; if ($field_key eq 'stream_forwarding') { $opts{$field} = $opts{stream_forwarding} ; @@ -1602,13 +2109,18 @@ sub analytics_table_row_labels { $add_form_fields .= &common_min_form_select_col($field,$default_val{$row_nr}{$field_key}) ; } elsif ($field_key eq 'stream_key' || $field_key eq 'stream_URL') { my $hide = ($default_val{$row_nr}{stream_forwarding} eq '2') ? 1 : 0 ; + $default_val{$row_nr}{$field_key} =~ s/\_semi_colon_character_/;/g ; + $default_val{$row_nr}{$field_key} =~ s/\_pipe_character_/|/g ; $add_form_fields .= &common_min_form_textarea_col($field,$default_val{$row_nr}{$field_key},22.5,$hide) ; + } elsif ($field_key eq 'cant_charge_client') { + my $tt = ($default_val{$row_nr}{cant_charge_client_reason} && $default_val{$row_nr}{cant_charge_client} eq 'Yes') ? qq~title data-toggle="tooltip" data-placement="left" data-original-title="$default_val{$row_nr}{cant_charge_client_reason}"~ : qq~~ ; + $add_form_fields .= qq~
    $default_val{$row_nr}{cant_charge_client}
    ~ ; } else { $add_form_fields .= qq~
    $default_val{$row_nr}{$field_key}
    ~ ; } # $add_form_fields .= qq~
    ~ if $field_key eq "coding_type" ; - $add_form_fields .= qq~
    ~ if $field_key eq "team" ; + $add_form_fields .= qq~
    ~ if $field_key eq "team" || $field_key eq "cant_charge_client" ; } #------------------------------------------------------------------------------------------ @@ -1650,12 +2162,17 @@ sub analytics_event_bookings_tabs_build_analytics_table { $add_form_fields .= qq~
    ~; - my @table_selects_field_keys = ("start_date_time","readonly_sport","age_group","team","home_team","ht_colour","away_team","coding_type","footage_type","service_type","stream_forwarding","stream_key","stream_URL") ; + my @table_selects_field_keys = ("start_date_time","readonly_sport","age_group","team","home_team","ht_colour","away_team","coding_type","footage_type","service_type","stream_forwarding","stream_key","stream_URL","cant_charge_client") ; my @sport_type_ids = split(/\;/,$db{$table}{$id}{sport_type_ids}) ; my @analytics_saved_values_arr = split(/\|/,$db{$table}{$id}{analytics_saved_values}) ; - + # my @analytics_saved_values_arr = split(/\|/,$db{$table}{$id}{analytics_saved_values}) ; + # my @analytics_saved_values_arr = split(/\|/,$db{$table}{$id}{analytics_saved_values}) ; + + my @cant_charge_client_fixtures_arr = split(/\;/,$db{$table}{$id}{cant_charge_client_fixtures}) ; + my @cant_charge_client_reasons_arr = split(/\:\|;/,$db{$table}{$id}{cant_charge_client_reasons}) ; + for my $row_cnt (1 .. $nr_of_rows) { $default_val{$row_cnt}{readonly_sport} = ($default_val{$row_cnt}{later_readonly_sport}) ? $default_val{$row_cnt}{later_readonly_sport} : $db{sport_types}{$db{$table}{$id}{sport_type_ids}}{name} ; @@ -1677,7 +2194,10 @@ sub analytics_event_bookings_tabs_build_analytics_table { $default_val{$row_cnt}{stream_forwarding} = $analytics_saved_values_arr_2[0] ; $default_val{$row_cnt}{stream_key} = $analytics_saved_values_arr_2[1] ; $default_val{$row_cnt}{stream_URL} = $analytics_saved_values_arr_2[2] ; - + + $default_val{$row_cnt}{cant_charge_client} = ($cant_charge_client_fixtures_arr[$row_cnt-1]) ? "Yes" : "No" ; + $default_val{$row_cnt}{cant_charge_client_reason} = $cant_charge_client_reasons_arr[$row_cnt-1] ; + if ($row_cnt <= $nr_of_rows) { my $style = ($nr_of_displayed_rows < $row_cnt) ? qq~style="display:none;"~ : qq~~ ; $add_form_fields .= qq~
    ~ ; @@ -1699,7 +2219,7 @@ sub analytics_event_bookings_tabs_build_analytics_table { \$("#analytics_event_bookings-form").on("change","[id^='selectStream_forwarding_']", function () { let row_nr = get_row_nr (this.id) ; - + set_default_fixtures_values(row_nr) ; let suffix = (this.id.includes("_$suffix\_")) ? "analytics" : "fixtures" ; let other_suffix = (this.id.includes("_$suffix\_")) ? "fixtures" : "analytics" ; @@ -1727,6 +2247,7 @@ sub analytics_event_bookings_tabs_build_analytics_table { \$("#analytics_event_bookings-form").on("change","[id^='textareaStream_key_'],[id^='textareaStream_URL_']", function () { let row_nr = get_row_nr (this.id) ; + set_default_fixtures_values(row_nr) ; let other_suffix = (this.id.includes("_analytics_")) ? "fixtures" : "analytics" ; if (this.id.includes("Stream_key")) { @@ -2026,4 +2547,180 @@ sub analytics_event_bookings_tabs_sec_det { } #------------------------------------------------------------------------------------ +sub analytics_event_bookings_tabs_form_checkbox_col { + +my ($field,$val,$checked,$classic,$dont_end_col) = @_ ; + +my $ucfirst_field = ucfirst $field ; +my $print_field = &common_min_print_field($field) ; if ($preferred_title{$field}) { $print_field = $preferred_title{$field} ; } +my $field_id = "checkbox$ucfirst_field" ; +my $check_class = ($classic) ? 'class="iphone-toggle"' : '' ; + +my $label = '' ; if ($label{$field}) { $label = "" ; } + +$tindex++ ; + +my $row = qq~ +
    + + $label +~ ; + +$row .= qq~
    ~ unless $dont_end_col ; + +unless ($excl_on_change{$field}) { push @jquery_trigger_fields, $field_id ; } +# unless ($excl_on_change{$field}) { push @jquery_workings_trigger_fields, $field_id ; } + +return ($row) ; + +} #------------------------------------------------------------------------------------------ + +sub analytics_event_booking_tabs_update_credits_used { + + my ($id,$id2) = @_ ; + + my %credits_used = () ; my $row_cnt = 0 ; + + my @cnt_charge = split(/\;/,$db{$table}{$id}{cant_charge_client_fixtures}) ; + + if ($db{$table}{$id}{client_id}) { + foreach my $fixture_row (@fixtures_saved_values_split) { + $row_cnt++ ; + last if $row_cnt > $db{$table}{$id}{total_fixtures} ; + my @fixtures_saved_values_split_2 = split(/\;/,$fixture_row) ; + my $sport_id = ($db{$table}{$id}{sport_type_ids} !~ /;/) ? $db{$table}{$id}{sport_type_ids} : $fixtures_saved_values_split_2[1] ; + + next unless $sport_id ; + + $credits_used{previous}{premium}{$db{$table}{$id}{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 'p' && !$cnt_charge[$row_cnt-1] ; + $credits_used{previous}{standard}{$db{$table}{$id}{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 's' && !$cnt_charge[$row_cnt-1] ; + $credits_used{previous}{individual}{$db{$table}{$id}{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 'i' && !$cnt_charge[$row_cnt-1] ; + } + } + + if ($i{client_id}) { + + @fixtures_saved_values_split = split(/\|/,$i{fixtures_saved_values}) ; + $row_cnt = 0 ; + @cnt_charge = split(/\;/,$i{cant_charge_client_fixtures}) ; + + foreach my $fixture_row (@fixtures_saved_values_split) { + + $row_cnt++ ; + last if $row_cnt > $i{total_fixtures} ; + my @fixtures_saved_values_split_2 = split(/\;/,$fixture_row) ; + + my $sport_id = ($i{sport_type_ids} !~ /;/) ? $db{$table}{$id}{sport_type_ids} : $fixtures_saved_values_split_2[1] ; + + next unless $sport_id ; + + $credits_used{new}{premium}{$i{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 'p' && !$cnt_charge[$row_cnt-1] ; + $credits_used{new}{standard}{$i{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 's' && !$cnt_charge[$row_cnt-1] ; + $credits_used{new}{individual}{$i{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 'i' && !$cnt_charge[$row_cnt-1] ; + + } + + my %seen = () ; + + } + + $seen{client}{$i{client_id}} = 1 if $i{client_id} ; + $seen{client}{$db{$table}{$id}{client_id}} = 1 if $db{$table}{$id}{client_id} ; + + foreach (split(/\;/,$db{$table}{$id}{sport_type_ids})) { + $seen{sport}{$_} = 1 if $_ ; + } + + if ($i{sport_type_ids}) { + foreach (split(/\;/,$i{sport_type_ids})) { + $seen{sport}{$_} = 1 if $_ ; + } + } + + my $sport_sql = join(" OR ",map{"sport_type_id='$_'"} keys %{$seen{sport}}) ; + my $client_sql = join(" OR ",map{"client_id='$_'"} keys %{$seen{client}}) ; + my $id_sql = ($id2) ? "analytics_event_id='$id2'" : ($id) ? "analytics_event_id='$id'" : "" ; + + my @sql_where_arr = () ; + push @sql_where_arr,"($sport_sql)" if $sport_sql ; + push @sql_where_arr,"($client_sql)" if $client_sql ; + push @sql_where_arr,$id_sql if $id_sql ; + + my $sql_where = join(" AND ",@sql_where_arr) ; + + &db_min_ro('credits_used','*',$sql_where,'','') ; my %exists = () ; + + my %db_credits_used = %db ; + + foreach my $_id (keys %{$db{credits_used}}) { + $exists{$db{credits_used}{$_id}{sport_type_id}}{$db{credits_used}{$_id}{client_id}} = 1 ; + } + + my $new_id = 0 ; + + foreach my $client_id (sort {$a <=> $b} keys %{$seen{client}}) { + foreach my $sport_id (sort {$a <=> $b} keys %{$seen{sport}}) { + unless ($exists{$sport_id}{$client_id}) { + if ($new_id) { + $new_id++ ; + } else { + $new_id = &db_min_get_max('credits_used','id') ; + } + + $db_credits_used{credits_used}{$new_id}{sport_type_id} = $sport_id ; + $db_credits_used{credits_used}{$new_id}{client_id} = $client_id ; + + } + } + } + + my %hidden_old = %hidden ; + %hidden = () ; + my %ignore_old = %ignore ; + %ignore = () ; + my %ij = %i ; + + # cant_charge_client_fixtures_1 + foreach my $_id (keys %{$db_credits_used{credits_used}}) { + + my $premium_credits = ($db_credits_used{credits_used}{$_id}{premium_credits_used}) ? $db_credits_used{credits_used}{$_id}{premium_credits_used} : 0 ; + my $standard_credits = ($db_credits_used{credits_used}{$_id}{standard_credits_used}) ? $db_credits_used{credits_used}{$_id}{standard_credits_used} : 0 ; + my $individual_credits = ($db_credits_used{credits_used}{$_id}{individual_credits_used}) ? $db_credits_used{credits_used}{$_id}{individual_credits_used} : 0 ; + + my $sport_id = $db_credits_used{credits_used}{$_id}{sport_type_id} ; + my $client_id = $db_credits_used{credits_used}{$_id}{client_id} ; + + %i = () ; + + $i{premium_credits_used} = $credits_used{new}{premium}{$client_id}{$sport_id} ; + $i{standard_credits_used} = $credits_used{new}{standard}{$client_id}{$sport_id} ; + $i{individual_credits_used} = $credits_used{new}{individual}{$client_id}{$sport_id} ; + + $i{premium_credits_used} = 0 unless $i{premium_credits_used} ; + $i{standard_credits_used} = 0 unless $i{standard_credits_used} ; + $i{individual_credits_used} = 0 unless $i{individual_credits_used} ; + + $ignore{premium_credits_used} = ($credits_used{new}{premium}{$client_id}{$sport_id} ne $premium_credits) ? 0 : 1 ; + $ignore{standard_credits_used} = ($credits_used{new}{standard}{$client_id}{$sport_id} ne $standard_credits) ? 0 : 1 ; + $ignore{individual_credits_used} = ($credits_used{new}{individual}{$client_id}{$sport_id} ne $individual_credits) ? 0 : 1 ; + + if (!$exists{$sport_id}{$client_id} && ($i{premium_credits_used} || $i{standard_credits_used} || $i{individual_credits_used}) && $ij{event_accepted}) { + $i{id} = "$_id" ; + $i{sport_type_id} = "$sport_id" ; + $i{client_id} = "$client_id" ; + $i{analytics_event_id} = ($id2) ? "$id2" : ($id) ? "$id" : "0" ; + &db_min_insert('credits_used') ; + } elsif ($exists{$sport_id}{$client_id} && ($i{premium_credits_used} || $i{standard_credits_used} || $i{individual_credits_used}) && $ij{event_accepted}) { + &db_min_upd('credits_used',"id='$_id'") ; + } elsif ($exists{$sport_id}{$client_id} && ((!$i{premium_credits_used} && !$i{standard_credits_used} && !$i{individual_credits_used}) || !$ij{event_accepted})) { + &db_min_delete('credits_used',"id='$_id'") ; + } + } + + %ignore = %ignore_old ; + %hidden = %hidden_old ; + %i = %ij ; + +} #------------------------------------------------------------------------------------------ + 1; diff --git a/libs/modules/cfg.pm b/libs/modules/cfg.pm index 694c82d..c0445a7 100644 --- a/libs/modules/cfg.pm +++ b/libs/modules/cfg.pm @@ -33,10 +33,8 @@ sub check_ticket_inbox { } #------------------------------------------------------------------------------------ sub session_state { - - if ($ENV{SCRIPT_NAME} =~ m/index.pl/gi) { return ; } - if ($ENV{SCRIPT_NAME} =~ m/cron/gi) { return ; } - if ($ENV{SCRIPT_NAME} =~ m/get/gi) { return ; } + + return if $ENV{SCRIPT_NAME} =~ m/index.pl/gi || $ENV{SCRIPT_NAME} =~ m/cron/gi || $ENV{SCRIPT_NAME} =~ m/get/gi ; unless ($session_state eq 'active') { print 'Status: 302 Moved', "\r\n", "Location: https://$ENV{SERVER_NAME}/", "\r\n\r\n" ; } @@ -54,9 +52,10 @@ sub config_session_state { } #------------------------------------------------------------------------------------ sub check_access { - + # return unless $pixellot_limit{$username} || $events_limit{$username} || $is_operator || $usertype eq 'external' || $usertype eq 'schools_manager' ; return if $glod_user_level >= 5 ; + # return if $glod_user_level >= 0 ; # my $path_prefix_ = '/cgi-bin/scripts/' ; my $path_prefix_ = $useropts{'scripts'} . '/' ; @@ -97,6 +96,18 @@ sub check_access { $exempt_query{$ENV{QUERY_STRING}} = 1 ; } + if ($usertype eq 'coding_provider') { + $exempt_script{$path_prefix_ . 'get/get_analytics_charge_client.pl'} = 1 ; + $exempt_script{$path_prefix_ . 'get/get_analyst_from_coding_provider.pl'} = 1 ; + $exempt_script{$path_prefix_ . 'dialog/add_fixtures_charge_free_table_reason.pl'} = 1 ; + $exempt_script{$path_prefix_ . 'allfixtures_report.pl'} = 1 ; + $exempt_script{$path_prefix_ . 'all_fixtures_report.pl'} = 1 ; + $exempt_script{$path_prefix_ . 'dialog/add_fixtures_analyst.pl'} = 1 ; + } + if ($usertype eq 'analytics_client') { + $exempt_script{$path_prefix_ . 'analytics_event_bookings.pl'} = 1 ; + } + if ($glod_user_level > 1) { $exempt_script{$path_prefix_ . 'event_quotes.pl'} = 1 ; $exempt_script{$path_prefix_ . 'event_quotes_test.pl'} = 1 ; @@ -118,6 +129,7 @@ sub check_access { $exempt_script{$path_prefix_ . 'get/get_country_from_region.pl'} = 1 ; $exempt_script{$path_prefix_ . 'get/get_region_country_from_client.pl'} = 1 ; $exempt_script{$path_prefix_ . 'get/get_sss_teams_from_client.pl'} = 1 ; + $exempt_script{$path_prefix_ . 'get/get_teams_from_typeahead.pl'} = 1 ; $exempt_script{$path_prefix_ . 'get/get_regions_from_country.pl'} = 1 ; $exempt_script{$path_prefix_ . 'get/get_sss_teams_from_region.pl'} = 1 ; $exempt_script{$path_prefix_ . 'get/get_region_from_city.pl'} = 1 ; @@ -135,10 +147,13 @@ sub check_access { if ($glod_user_level > 2) { $exempt_script{$path_prefix_ . 'operators.pl'} = 1 ; - $exempt_script{$path_prefix_ . 'monitoring_report.pl'} = 1 ; + # $exempt_script{$path_prefix_ . 'monitoring_report.pl'} = 1 ; + $exempt_script{$path_prefix_ . 'sss_event_feedback.pl'} = 1 ; + $exempt_script{$path_prefix_ . 'aisa_event_feedback.pl'} = 1 ; $exempt_script{$path_prefix_ . 'temp_calibrator_report.pl'} = 1 ; $exempt_script{$path_prefix_ . 'mobile_site_surveys_report.pl'} = 1 ; $exempt_script{$path_prefix_ . 'mobile_system_tracking_report.pl'} = 1 ; + $exempt_script{$path_prefix_ . 'troubleshoot_monitoring_report.pl'} = 1 ; } if ($usertype eq 'support') { @@ -149,7 +164,13 @@ sub check_access { %exempt_script = () ; $exempt_script{$path_prefix_ . 'index.pl'} = 1 ; $exempt_script{$path_prefix_ . 'logistics_report.pl'} = 1 ; - } + } + + # print "Content-type: text/html\n\n"; + # print "SCRIPT_NAME=$ENV{SCRIPT_NAME}\n" ; + # print "QUERY_STRING=$ENV{QUERY_STRING}\n" ; + # print "path_prefix_=$path_prefix_ \n" ; + # print "exempt_script=$exempt_script{$ENV{SCRIPT_NAME}} \n" ; unless ($exempt_script{$ENV{SCRIPT_NAME}}) { print "Content-type: text/html\n\n"; require '401.pm' ; exit ; } unless ($exempt_query{$ENV{QUERY_STRING}} || length($ENV{QUERY_STRING}) > 10) { print "Content-type: text/html\n\n"; require '401.pm' ; exit ; } diff --git a/libs/modules/cfg_paths.pm b/libs/modules/cfg_paths.pm index 79616ec..ae2a7d1 100644 --- a/libs/modules/cfg_paths.pm +++ b/libs/modules/cfg_paths.pm @@ -6,16 +6,16 @@ sub config_set_vars { $useropts{acronym} = 'AISA' ; $useropts{short} = 'AI Sport Africa' ; $useropts{title} = ($env eq 'DEV') ? "*DEV* " : '' ; -$useropts{title} .= "$useropts{short} Admin | " . ucfirst $username ; +$useropts{title} .= "$useropts{acronym} admin | " . ucfirst $username ; $title = $useropts{title} ; $useropts{salt} = '1Tv4dM1n' ; $useropts{company} = "$useropts{short} (Pty) Ltd" ; $useropts{lc} = lc $useropts{acronym} ; # $useropts{logo} = 'itv_logo.jpg' ; $useropts{logo} = 'aisa_logo.jpg' ; -$useropts{domainpart} = 'itvadmin' ; +$useropts{domainpart} = 'aisadmin' ; $useropts{table_id} = 'itv-table' ; -$useropts{web} = 'itvadmin.co.za' ; +$useropts{web} = 'aisadmin.co.za' ; $useropts{address1} = '16 Wessel Road, Unit 3' ; $useropts{address2} = 'Eden Gardens' ; $useropts{address3} = 'Rivonia' ; @@ -26,10 +26,6 @@ $useropts{tel} = '+27 10 534 7011' ; $useropts{vat_nr} = '4280292691' ; $useropts{co_reg} = '2020/535585/07' ; $useropts{email} = 'info@aisport.africa' ; -# $useropts{linkcolor} = '#0092dc' ; -# $useropts{infocolor} = '#039deb' ; -# $useropts{primarycolor} = '#00559b' ; -# $useropts{pdfcolor} = '#0098e3' ; $useropts{boss}{'vivian'} = 1 ; $useropts{boss}{'shaun'} = 1 ; @@ -59,11 +55,13 @@ our $is_dcb_partner = ($usertype eq 'dcb_partner') ? 1 : 0 ; our $is_schools_manager = ($usertype eq 'schools_manager') ? 1 : 0 ; our $is_operator = (substr($usertype,0,6) eq 'casual') ? 1 : 0 ; our $is_temp_calibrator = ($usertype eq 'casual_calibrator') ? 1 : 0 ; +our $is_coding_provider = ($usertype eq 'coding_provider') ? 1 : 0 ; +our $is_analytics_client = ($usertype eq 'analytics_client') ? 1 : 0 ; our $operator_level = ($is_operator && (substr($usertype,-1,1) eq 'a' || substr($usertype,-10,10) eq 'calibrator')) ? 1 : ($is_operator && substr($usertype,-1,1) eq 'b') ? 2 : ($is_operator && substr($usertype,-1,1) eq 'c') ? 3 : 0 ; if ($is_operator && $operator_level) { $glod_user_level = $operator_level ; -} elsif ($usertype eq 'external' || $usertype eq 'installation_partner' || $usertype eq 'dcb_partner') { +} elsif ($usertype eq 'external' || $usertype eq 'installation_partner' || $usertype eq 'dcb_partner' || $usertype eq 'coding_provider' || $usertype eq 'analytics_client') { $glod_user_level = 1 ; } elsif ($usertype eq 'schools_manager' || $usertype eq 'support') { $glod_user_level = 2 ; @@ -88,10 +86,13 @@ our %email_events = () ; $email_events{7} = 'mitheel@aisport.africa' ; $email_events{8} = 'mikhaar@aisport.africa' ; $email_events{9} = 'daniel@aisport.africa' ; - $email_events{10} = 'events@kre8it.co.za' ; + $email_events{10} = 'vusi@aisport.africa' ; + $email_events{11} = 'events@kre8it.co.za' ; + our $email_it_1 = 'rory@kre8it.co.za' ; our $email_it_2 = 'handre@kre8it.co.za' ; our $email_accounts = 'viv@aisport.africa' ; +our $email_analytics = 'analytics@aisport.africa' ; our $afrihost_smtp = 'mail.aisport.africa'; our $afrihost_psw = 'Events@2025' ; @@ -109,11 +110,11 @@ our ($subdomain,$domain,$ext) = split(/\./,$ENV{SERVER_NAME}) ; sub config_set_paths { -# $cgipath = "/home/libs" ; -# $htmlpath = "/var/www/html" ; +# $cgipath = "/home/libs" ; +# $htmlpath = "/var/www/html" ; # $htmlpath_sss = "/var/www/sssadmin.co.za/public_html" ; -# $useropts{'scripts'} = '/cgi-bin/scripts'; +# $useropts{'scripts'} = '/cgi-bin/scripts'; $useropts{'folder'} = ''; $useropts{'js'} = '/js' ; diff --git a/libs/modules/common.pm b/libs/modules/common.pm index c356d2d..20a57e6 100644 --- a/libs/modules/common.pm +++ b/libs/modules/common.pm @@ -27,7 +27,7 @@ $nline =~ s/[ ]+/ /g ; # Replaces all occurances of two spaces with one space # my $serverpath = (substr($ENV{SERVER_NAME},0,6) eq 'client') ? 'gwtruckassist' : 'gatewaytruckassa' ; -my $logfile = "/home/libs/data/logs/$log"; +my $logfile = "$cgipath/data/logs/$log"; open (LFILE, ">>$logfile") or die "can't open $logfile : $!" ; flock (LFILE, LOCK_EX) or die "can't lock $logfile : $!" ; @@ -47,7 +47,7 @@ $nline =~ s/\n/ /g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie $nline =~ s/\t/ /g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc $nline =~ s/\r/ /g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc -my $logfile = "/home/libs/data/logs/$log"; +my $logfile = "$cgipath/data/logs/$log"; open (LFILE, "+>>$logfile") or die "can't open $logfile : $!" ; flock (LFILE, LOCK_EX) or die "can't lock $logfile : $!" ; @@ -99,7 +99,7 @@ $nline =~ s/> <' with '><' # my $serverpath = (substr($ENV{SERVER_NAME},0,6) eq 'client') ? 'gwtruckassist' : 'gatewaytruckassa' ; -my $logfile = "/home/libs/data/logs/$log"; +my $logfile = "$cgipath/data/logs/$log"; open (LFILE, "+>>$logfile") or die "can't open $logfile : $!" ; flock (LFILE, LOCK_EX) or die "can't lock $logfile : $!" ; @@ -1816,7 +1816,7 @@ $nline =~ s/\n/ /g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie $nline =~ s/\t/ /g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc $nline =~ s/\r/ /g ; # substitutes a whitespace (\t\n\r\f) by a nothing - ie : removes all CR / LF etc -my $logfile = "/home/libs/data/logs/$log"; +my $logfile = "$cgipath/data/logs/$log"; open (LFILE, "+>>$logfile") or die "can't open $logfile : $!" ; flock (LFILE, LOCK_EX) or die "can't lock $logfile : $!" ; diff --git a/libs/modules/common_min.pm b/libs/modules/common_min.pm index 6be46bc..d5765bc 100644 --- a/libs/modules/common_min.pm +++ b/libs/modules/common_min.pm @@ -1054,7 +1054,7 @@ sub common_min_form_radio_col { $print_radios .= qq~
    ~ if $display_horizontally ; foreach my $option (@opts) { - + $cnt++ ; my $row_id = ($radio_row_id) ? "$radio_row_id\_$cnt" : "" ; @@ -1073,7 +1073,7 @@ sub common_min_form_radio_col { my $value = $option; $value = lc $value ; $value =~ s/ /\_/g ; my $radio_nr = ($display_horizontally) ? $display_horizontally : ($row_cnt*$columns - $columns) + $_ ; - + # print "\n value : $value eq default_checked : $default_checked[$radio_nr - 1]" if $useropts{it}{$username} ; if ($value eq $default_checked[$radio_nr - 1]) { $checked = 'CHECKED'; } else { $checked = ''; } $print_radios .= qq~~ if $cnt == 1 ; @@ -2251,7 +2251,7 @@ sub common_min_table_textarea { $val = qq~
    - +
    ~ ; @@ -2363,7 +2363,10 @@ sub common_min_table_select { my $print_field = ($preferred_placeholder{$field_id}) ? $preferred_placeholder{$field_id} : ($preferred_title{$field_id}) ? "Select $preferred_title{$field_id}" : "Select " . &common_min_print_field($field_id) ; - push @all_select_ids,"#$ucfirstfield" if $ucfirstfield ; + unless ($dont_allow_deselect_in_table{$field_id}) { + push @all_select_ids,"#$ucfirstfield" if $ucfirstfield ; + } + if ($multiple{$field_id}) { push @all_multi_select_ids,"#$ucfirstfield" if $ucfirstfield ; $multi_select_ids .= qq~"$ucfirstfield":"1",~ if $ucfirstfield ; diff --git a/libs/modules/db.pm b/libs/modules/db.pm index 8360829..f8d9f9e 100644 --- a/libs/modules/db.pm +++ b/libs/modules/db.pm @@ -58,10 +58,15 @@ sub ops_db_credentials { my ($sys) = @_ ; - my $db = "itv_admin_db"; + # my $db = "itv_admin_db"; + # my $dbhost = "localhost"; + # my $dbuser = "itv_admin_user"; + # my $dbpass = '!Ja16Q7P0X3SVTWr'; + + my $db = "aisa_admin_db"; my $dbhost = "localhost"; - my $dbuser = "itv_admin_user"; - my $dbpass = '!Ja16Q7P0X3SVTWr'; + my $dbuser = "aisa_admin_user"; + my $dbpass = 's5pCDPUZo18oip29!'; if ($env eq 'DEV') { $db = 'dev_aisa' ; diff --git a/libs/modules/schedule.pm b/libs/modules/schedule.pm index 51c88e9..01f0cf9 100644 --- a/libs/modules/schedule.pm +++ b/libs/modules/schedule.pm @@ -36,6 +36,8 @@ sub schedule_load_list_vars { &db_min_ro('event_systems','*',$event_systems_sql_where,'','') ; + $where = "1" unless $where ; + &db_min_ro($table,"id,club_ids,qty,ref,organisation_ids,quote_accepted,event_system_id_multiple,region_id,sport_type_ids,operator_ids,date_from,date_to,times_from,times_to,daily_operator_ids,days_active,monitor_ids,temp_calibrator_ids$extra_column","$where AND `quote_accepted` = '1'",'','') ; my $min_id = 0 ; my $max_id = 0 ; @@ -1107,6 +1109,7 @@ sub schedule_build_table { ($db{event_systems}{$event_sys_id}{system_type} eq 'fixed') ? "F" : ""; } elsif ($_ eq 'system') { $val = '' ; + # $val = qq~($event_sys_id)$db{event_systems}{$event_sys_id}{name}~ ; $val = qq~$db{event_systems}{$event_sys_id}{name}~ ; $val .= qq~ ($db{event_systems}{$event_sys_id}{description})~ if $db{event_systems}{$event_sys_id}{description} ; } elsif ($_ eq 'sport') { @@ -1118,7 +1121,7 @@ sub schedule_build_table { $val = substr($val,0,-4) if $val ; } elsif ($_ eq 'club_name') { $val = $db{clubs}{$club_ids[$system_count - 1]}{name} ; - } elsif ($_ eq 'operator') { + } elsif ($_ eq 'operator') { $val = '' ; # $val = $db{users}{$table_op_ids[$system_count - 1]}{name} if $table_op_ids[$system_count - 1] ; $val = ($default_op_ids{$system_count}{$cnt{$event_sys_id}{$id}}) ? $db{users}{$default_op_ids{$system_count}{$cnt{$event_sys_id}{$id}}}{name} : (!$default_op_ids{$system_count}{$system_day_cnt} && $system_has_daily_op{$system_count}) ? "None" : $db{users}{$op_ids[$system_count - 1]}{name} ; @@ -1143,6 +1146,7 @@ sub schedule_build_table { my $background_color = qq~~ ; if ($_ eq 'status' && $default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}) { $val_min = $db{monitor_status}{$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id}}{status} ; + if ($default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id} eq '1') { $background_color = qq~rgb(81, 181, 41)~ ; $formatting = $format94 ; @@ -1158,18 +1162,23 @@ sub schedule_build_table { } $val = &common_min_table_select($field{$_},$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},'',$table_row,$last_child{$_},$background_color,$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},$_) ; + } elsif ($_ eq 'comments') { + $field{$_} = "$_\_event$event_sys_id\_$sys_day_cnt\_$id" ; + $val = &common_min_table_textarea($field{$_},$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},'',$table_row,$last_child{$_},$background_color,$default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id},$_) ; + $val_min = $default_values{$_}{$event_sys_id}{$sys_day_cnt}{$id} ; } elsif ($_ eq 'update') { my $field = "update_event$event_sys_id\_$sys_day_cnt\_$id" ; $val = &common_min_form_checkbox_col($field,'') ; chop $default_javascript if $default_javascript ; + # 12=s:;t:|s:1;t:1|s:2;t:2-13=|s:3;t:3|s:4;t:4 if ($default_javascript) { push @default_javascript_by_id, qq~"event$event_sys_id\_$sys_day_cnt\_$id":{$default_javascript}~ ; } } - if ($_ ne 'status' && $_ ne 'calibrator' && substr($_,0,5) ne 'shift' && $_ ne 'update' && $_ ne 'status' && $_ ne 'fixture_check') { + if ($_ ne 'comments' && $_ ne 'status' && $_ ne 'calibrator' && substr($_,0,5) ne 'shift' && $_ ne 'update' && $_ ne 'status' && $_ ne 'fixture_check') { $val_min = $val ; $val_min =~ s/\
    /\;/g ; } @@ -1880,4 +1889,271 @@ sub schedule_payments_report_screen { } #------------------------------------------------------------------------------------------ +sub schedule_update_monitor_reports { + + my @table_sql_where = () ; + + if ($i{client_id}) { + push @table_sql_where, "`quote_to`='$i{client_id}'" ; + } + if ($i{date_from} && $i{date_to}) { # check dates + push @table_sql_where, "(('$i{date_from} 00:00:00' <= `date_from` AND `date_from` <= '$i{date_to} 23:59:59') OR ('$i{date_from} 00:00:00' <= `date_to` AND `date_to` <= '$i{date_to} 23:59:59') OR (`date_from` <= '$i{date_from} 00:00:00' AND '$i{date_to} 23:59:59' <= `date_to`))" ; ############################################### > OR >= + + } + + # if ($i{monitor_id} and $i{monitor_id} ne 'all') { + # push @table_sql_where,"`MONITOR` = '$db{users}{1}{name}'" ; + # } + + # if ($i{monitor_id} and $i{monitor_id} ne 'all') { + # push @table_sql_where,"`TROUBLESHOOT MONITOR` = '$db{users}{1}{name}'" ; + # } + + + my $table_sql_where_str = join(" AND ",@table_sql_where) ; + + &db_min_ro($table,"id,monitor_report_saved_data","$table_sql_where_str",'','') ; + + my %saved_field_hash = () ; + + foreach my $id (keys %{$db{$table}}) { + + # my @saved_data_split_1 = split(/\-/,$db{$table}{$id}{monitor_report_saved_data}) ; + my @saved_data_split_1 = split /-(?=\d+=(?:blank\||f:\d+|s:\d+|c:))/, $db{$table}{$id}{monitor_report_saved_data}; + + foreach my $a (@saved_data_split_1) { + + # my @saved_data_split_2 = split(/\=/,$a) ; + + my @saved_data_split_2 = () ; + if ($a =~ /^(\d+|none)=(.*)$/) { + @saved_data_split_2 = ($1, $2); + } else { + @saved_data_split_2 = ($a); + } + + my $event_sys_id = $saved_data_split_2[0] ; + # my @saved_data_split_3 = split(/\|/,$saved_data_split_2[1]) ; + # my @saved_data_split_3 = split /\|(?=(?:blank\|f:\d+|blank\|s:\d+|blank\|c:|f:\d+|s:\d+|c:))/, $saved_data_split_2[1]; + + my @saved_data_split_3 = split( + /\| + (?= # Look ahead for allowed patterns + # blank$ # 1) blank + end + blank\|s:\d+ # 2) blank|s: + | blank\|f:\d+ # 3) blank|f: + | blank\|c: # 4) blank|c: + | f:\d+ # 5) f: + | s:\d+ # 6) s: + | c: # 7) c: + | blank\|blank\| # 8) blank|s: + ) + /x, + $saved_data_split_2[1] + ); + + + my $day_cnt = 0 ; + foreach my $b (@saved_data_split_3) { + $day_cnt++ ; + next if !$b || $b eq 'blank' ; + $b =~ s/\|/\pipe_in_comment_to_be_removed/g ; + $saved_field_hash{$id}{$event_sys_id}{$day_cnt} = $b ; + } + } + } + + foreach my $field_name (keys %i) { + + next if ($field_name =~ /update_event/ && !$i{$field_name}) || $field_name !~ /update_event/ ; + + my @fields = split(/\_/,$field_name) ; + + my $system_id = substr($fields[-3],5) ; + my $day_cnt = $fields[-2] ; + my $event_id = $fields[-1] ; + + my $fixture_field = "fixture_check_event$system_id\_$day_cnt\_$event_id" ; + my $status_field = "status_event$system_id\_$day_cnt\_$event_id" ; + my $comments_field = "comments_event$system_id\_$day_cnt\_$event_id" ; + + $saved_field_hash{$event_id}{$system_id}{$day_cnt} = qq~~ ; + $saved_field_hash{$event_id}{$system_id}{$day_cnt} = ($i{$fixture_field}) ? qq~f:$i{$fixture_field};~ : qq~~ ; + $saved_field_hash{$event_id}{$system_id}{$day_cnt} .= ($i{$status_field}) ? qq~s:$i{$status_field};~ : qq~~ ; + $saved_field_hash{$event_id}{$system_id}{$day_cnt} =~ s/;+$//g unless $i{$comments_field} ; + $i{$comments_field} =~ s/\|/\pipe_in_comment_to_be_removed/g ; + $saved_field_hash{$event_id}{$system_id}{$day_cnt} .= qq~c:$i{$comments_field}~ if $i{$comments_field} ; + + } + + %ii = %i ; + %i = () ; + + foreach my $event_id (keys %saved_field_hash) { + + $i{monitor_report_saved_data} = qq~~ ; + + foreach my $system_id (sort { $a <=> $b } keys %{$saved_field_hash{$event_id}}) { + + # $i{monitor_report_saved_data} .= qq~$system_id\=~ ; + my $saved_by_system = qq~~ ; + + foreach my $day_max (sort { $b <=> $a } keys %{$saved_field_hash{$event_id}{$system_id}}) { + + for my $day_cnt (1 .. $day_max) { + # $saved_field_hash{$event_id}{$system_id}{$day_cnt} =~ s/;+$//g ; + $saved_by_system .= qq~$saved_field_hash{$event_id}{$system_id}{$day_cnt}|~ ; + } + # chop $saved_by_system if $day_max ; + $saved_by_system =~ s/\|+$//g ; + last ; + } + + if ($saved_by_system =~ /\||/) { + $saved_by_system =~ s/\|(?=\|)/|blank/g ; + } + + if ($saved_by_system =~ /^\|/) { + $saved_by_system =~ s/^\|/blank|/g ; + } + + # if ($saved_by_system =~ /\|$/) { + # $saved_by_system =~ s/\|$/|blank/; + # } + + $saved_by_system =~ s/pipe_in_comment_to_be_removed/\|/g ; + + $i{monitor_report_saved_data} .= qq~$system_id\=$saved_by_system\-~ if $saved_by_system ; + } + + chop $i{monitor_report_saved_data} if $i{monitor_report_saved_data} ; + + next if ($i{monitor_report_saved_data} eq $db{$table}{$event_id}{monitor_report_saved_data}) || (!$i{monitor_report_saved_data} && !$db{$table}{$event_id}{monitor_report_saved_data}) ; + + &db_min_upd($table,"id='$event_id'") ; + + } + + %i = %ii ; + +} #------------------------------------------------------------------------------------------ + +sub schedule_get_monitor_reports_default_values { + + our %default_values = () ; + # 12=f:;s:|s:1;t:1|f:2;s:2-13=|f:3;s:3|f:4;s:4 + foreach my $id (keys %{$db{$table}}) { + + # $db{$table}{$id}{monitor_report_saved_data} = "12=f:1;s:1|s:1;t:1|f:2;s:2;c:1|-23-123=f2-13=blank|f:3;s:3|f:4;s:4-133=blank|blank|f:3;s:3|f:4;s:4-1232=c:as" ; + + # next if $id eq '5136' ; + + # my @saved_data_split_1 = split /\-(?=\d+=[\f:\d+|\s:\d+|\c:|blank\|])/x, $db{$table}{$id}{monitor_report_saved_data}; + my @saved_data_split_1 = split /-(?=\d+=(?:blank\||f:\d+|s:\d+|c:))/, $db{$table}{$id}{monitor_report_saved_data} ; ## split on "-" if and only if it it is followed by an integer = blank or f:integer or s:integer or c: + + foreach my $a (@saved_data_split_1) { + + # my @saved_data_split_2 = split /(?<=^(\d+))=/, $a; + my @saved_data_split_2 = () ; + + $a =~ s/[\n\r]+/_new_line_character_/g if $a ; + + if ($a =~ /^(\d+|none)=(.*)$/) { + @saved_data_split_2 = ($1, $2); + } else { + @saved_data_split_2 = ($a); + } + + # my @saved_data_split_2 = split(/(?<=^\d+)=/,$a) ; + + my $event_sys_id = $saved_data_split_2[0] ; + # my $remaining_data = join(";", @saved_data_split_3[3 .. $#saved_data_split_3]) ; + # my @saved_data_split_3 = split(/\|/,$saved_data_split_2[1]) ; + # my @saved_data_split_3 = split /(?<=^(?:f:(\d+)|s:(\d+)|f:|s:|c:|blank))\|(?=(?:f:|s:|c:|blank))/x, $saved_data_split_2[1]; + + my @saved_data_split_3 = () ; + + # while ($saved_data_split_2[1] =~ /\G((?:f:(\d+)|s:(\d+)|f:|s:|c:|blank)?)\|(?=(?:f:|s:|c:|blank|$))/xg) { + # push @saved_data_split_3, $1; + # } + + # my $final_element = $saved_data_split_2[1] ; + + # foreach (@saved_data_split_3) { + # $final_element =~ s/^$_\|//g ; + # } + + # push @saved_data_split_3, $final_element ; + + # $saved_data_split_2[1] = "blank|s:3|s:3|s:3|blank|blank" ; + + # my @saved_data_split_3 = split(/\|(?=(?:+$|blank\|+$|blank\|blank|blank\|f:\d+|blank\|s:\d+|blank\|c:|f:\d+|s:\d+|c:))/, "$saved_data_split_2[1]") ; + my @saved_data_split_3 = split( + /\| + (?= # Look ahead for allowed patterns + # blank$ # 1) blank + end + blank\|s:\d+ # 2) blank|s: + | blank\|f:\d+ # 3) blank|f: + | blank\|c: # 4) blank|c: + | f:\d+ # 5) f: + | s:\d+ # 6) s: + | c: # 7) c: + | blank\|blank\| # 8) blank|s: + ) + /x, + $saved_data_split_2[1] + ); + + my $day_cnt = 0 ; + foreach my $b (@saved_data_split_3) { + $day_cnt++ ; + + next if !$b || $b eq 'blank' ; + + # $b =~ s/\;+$//g ; + + my @saved_data_split_3 = split(/\;/,$b) ; + my @saved_data_split_4 = ($saved_data_split_3[0]) ? split(/\:/,$saved_data_split_3[0]) : () ; + my @saved_data_split_5 = ($saved_data_split_3[1]) ? split(/\:/,$saved_data_split_3[1]) : () ; + my @saved_data_split_6 = ($saved_data_split_3[2]) ? split(/\:/,$saved_data_split_3[2]) : () ; + + if ($saved_data_split_3[0] =~ /^f:\d+/) { + $default_values{$sql_col_display[-4]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_4[1] ; + } + + if ($saved_data_split_3[0] =~ /^s:\d+/) { + $default_values{$sql_col_display[-3]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_4[1] ; + } elsif ($saved_data_split_3[1] =~ /^s:\d+/ && $saved_data_split_3[0] =~ /^f:\d+/) { + $default_values{$sql_col_display[-3]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_5[1] ; + } + + my $comments_after_semicolon = "" ; ## In case the comments contain a ; when we split on ; + my $comments_before_semicolon = "" ; ## In case the comments contain a ; when we split on ; + + if ($saved_data_split_3[0] =~ /^c:/) { + $comments_after_semicolon = join(";", @saved_data_split_3[1 .. $#saved_data_split_3]) ; + $comments_before_semicolon = $saved_data_split_4[1] . join(":", @saved_data_split_4[2 .. $#saved_data_split_4]) ; + # $default_values{$sql_col_display[-2]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_4[1] . join(":", @saved_data_split_4[2 .. $#saved_data_split_4]) ; + } elsif ($saved_data_split_3[1] =~ /^c:/ && ($saved_data_split_3[0] =~ /^f:\d+/ || $saved_data_split_3[0] =~ /^s:\d+/)) { + $comments_after_semicolon = join(";", @saved_data_split_3[2 .. $#saved_data_split_3]) ; + $comments_before_semicolon = $saved_data_split_5[1] . join(":", @saved_data_split_5[2 .. $#saved_data_split_5]) ; + # $default_values{$sql_col_display[-2]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_5[1] . join(":", @saved_data_split_5[2 .. $#saved_data_split_5]) ; + } elsif ($saved_data_split_3[2] =~ /^c:/ && $saved_data_split_3[1] =~ /^s:\d+/ && $saved_data_split_3[0] =~ /^f:\d+/) { + $comments_after_semicolon = join(";", @saved_data_split_3[3 .. $#saved_data_split_3]) ; + $comments_before_semicolon = $saved_data_split_6[1] . join(":", @saved_data_split_6[2 .. $#saved_data_split_6]) ; + # $default_values{$sql_col_display[-2]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_6[1] . join(":", @saved_data_split_6[2 .. $#saved_data_split_6]) ; + } + + $comments_before_semicolon =~ s/_new_line_character_/\n/g ; + $comments_after_semicolon =~ s/_new_line_character_/\n/g ; + + $default_values{$sql_col_display[-2]}{$event_sys_id}{$day_cnt}{$id} .= "$comments_before_semicolon" ; + $default_values{$sql_col_display[-2]}{$event_sys_id}{$day_cnt}{$id} .= ";$comments_after_semicolon" if $comments_after_semicolon || $b =~ /c:;+$/ ; + + } + } + } + +} #------------------------------------------------------------------------------------------ + 1 ; \ No newline at end of file diff --git a/libs/modules/session.pm b/libs/modules/session.pm index 3fce5fa..1ae5e5d 100644 --- a/libs/modules/session.pm +++ b/libs/modules/session.pm @@ -10,39 +10,39 @@ sub check_session { use db ; &db_open_ro ; - $userid = 0 ; - $session = load CGI::Session("driver:MySQL", $cgisessid, {Handle=>$dbh}); - $userid = $session->param(-name=>'id'); - $is_logged_in = $session->param(-name=>'_IS_LOGGED_IN'); - $username = lc $session->param(-name=>'uname'); - $useremail = lc $session->param(-name=>'uemail'); - $usertype = lc $session->param(-name=>'utype'); - $orgids = $session->param(-name=>'oids'); - $regids = $session->param(-name=>'rids'); - $custids = $session->param(-name=>'cids'); + $userid = 0 ; + $session = load CGI::Session("driver:MySQL", $cgisessid, {Handle=>$dbh}); + $userid = $session->param(-name=>'id'); + $is_logged_in = $session->param(-name=>'_IS_LOGGED_IN'); + $username = lc $session->param(-name=>'uname'); + $useremail = lc $session->param(-name=>'uemail'); + $usertype = lc $session->param(-name=>'utype'); + $orgids = $session->param(-name=>'oids'); + $regids = $session->param(-name=>'rids'); + $custids = $session->param(-name=>'cids'); - my @orgids = split(/\,/,$orgids); - foreach (@orgids) { $glob_orgids{$userid}{$_} = 1 ; } + my @orgids = split(/\,/,$orgids); + foreach (@orgids) { $glob_orgids{$userid}{$_} = 1 ; } - my @regids = split(/\,/,$regids); - foreach (@regids) { next unless $_ > 0 ; $glob_regids{$userid}{$_} = 1 ; } + my @regids = split(/\,/,$regids); + foreach (@regids) { next unless $_ > 0 ; $glob_regids{$userid}{$_} = 1 ; } - my @custids = split(/\,/,$custids); - foreach (@custids) { next unless $_ > 0 ; $glob_custids{$userid}{$_} = 1 ; } + my @custids = split(/\,/,$custids); + foreach (@custids) { next unless $_ > 0 ; $glob_custids{$userid}{$_} = 1 ; } - $sessionid = $session->id(); + $sessionid = $session->id(); - if ($sessionid && $is_logged_in > 0 && $userid > 0) { # if $userid and $is_logged_in is -1 not allowed in - $session_state = 'active' ; - } elsif ($session->is_expired) { - $session_state = 'expired' ; - $session->delete() ; - } elsif ($session->is_empty) { - $session_state = 'empty' ; - } else { - $session_state = 'empty' ; - $session->delete() ; - } + if ($sessionid && $is_logged_in > 0 && $userid > 0) { # if $userid and $is_logged_in is -1 not allowed in + $session_state = 'active' ; + } elsif ($session->is_expired) { + $session_state = 'expired' ; + $session->delete() ; + } elsif ($session->is_empty) { + $session_state = 'empty' ; + } else { + $session_state = 'empty' ; + $session->delete() ; + } &db_close_conn ; diff --git a/libs/modules/tabs.pm b/libs/modules/tabs.pm index 771567b..1437ba4 100644 --- a/libs/modules/tabs.pm +++ b/libs/modules/tabs.pm @@ -1,5 +1,270 @@ our %sec_cnt = ('a_systems' => "3-Systems", 'b_software_licence' => "3-Software Licence (Monthly Fee)", 'c_game_breakdown_analytics' => "2-Game Breakdown and Analytics (Annual Fee)", 'd_installation_kits' => "7-Installation Kits", 'e_hardware_add_ons' => "7-Hardware Add Ons", 'f_additional_services' => "7-Additional Services", 'g_match_credits' => "4-Match Credits", 'h_other' => "5-Other", 'i_rental' => "2-Rental" , "j_hardware" => "1-Hardware"); +sub tabs_costings_forms_jquery { + + $onload .= qq~onload="add_up_totals('costing',\$('#inputRoe').val(),1);"~ if $iaction ne 'add' ; + + $trigger_jquery_raw .= qq~ + + let prev_currency = \$("#selectCurrency").val() ; + + \$("#selectCurrency").change(function () { + + if ((\$(this).val() == 'USD' && \$("input[name='roe']").val() == '20.00' && prev_currency != 'ZAR') || (prev_currency != 'ZAR' && \$(this).val() != 'ZAR' && prev_currency != 'USD' && \$(this).val() != 'USD')) { + return ; + } + let roe = 1 ; + if (\$(this).val() == 'USD') { + roe = 20 ; + } + + \$("input[name='roe']").val(roe.toFixed(2)) ; + + let j = 1 ; + + let tab = "costing" ; + + if (\$(this).val() == 'ZAR') { + while (\$("#"+tab+"_"+j).html()) { + if (!\$("#checkboxVat_"+tab+"_"+j).is(":checked")) { + \$("#checkboxVat_"+tab+"_"+j).prop('checked',true) ; + } + j++ ; + } + } else if (\$(this).val() != 'ZAR' && prev_currency == 'ZAR') { + while (\$("#"+tab+"_"+j).html()) { + if (\$("#checkboxVat_"+tab+"_"+j).is(":checked")) { + \$("#checkboxVat_"+tab+"_"+j).prop('checked',false) ; + } + j++ ; + } + } + + prev_currency = \$(this).val() ; + + add_up_totals("costing",roe,1) ; + + }) ; + + \$("input[name='roe']").change(function () { + if (\$("#selectCurrency").val() == 'ZAR' && \$(this).val() != '1.00') { + \$("input[name='roe']").val("1.00") ; + return ; + } + update_with_roe(\$(this).val()) ; + }) ; + + function update_with_roe (roe="") { + if (roe <= 0 || !roe || roe == "") { + roe = 1 ; + } + \$("input[name='roe']").val(parseFloat(roe).toFixed(2)) ; + let sub_total = 0 ; let vat_total = 0 ; + add_up_totals("costing",roe,1) ; + } + + function add_up_totals (tab,roe,recalc_totals) { + + let sub_total = 0 ; let vat_total = 0 ; + + let i = 1 ; + + while (\$("#"+tab+"_"+i).html()) { + + if (\$("#inputDescription_"+tab+"_"+i).val()) { + if (\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { i++ ; continue ; } + let ttl = 0 ; + if (recalc_totals) { + ttl = parseFloat(\$("#inputZar_amount_"+tab+"_"+i).val()) * parseFloat(\$("#inputQty_"+tab+"_"+i).val()) * parseFloat(roe) ; + } else { + ttl = parseFloat(\$("#inputTotal_"+tab+"_"+i).val().replace(/,/g, '')) + } + \$("#inputTotal_"+tab+"_"+i).val(ttl.toFixed(2)) ; + if (!\$("#inputTotal_"+tab+"_"+i).val() || \$("#inputTotal_"+tab+"_"+i).val() == "NaN") { + \$("#inputTotal_"+tab+"_"+i).val("0.00") ; + ttl = 0 ; + } + sub_total += ttl ; + if (\$("#checkboxVat_"+tab+"_"+i).is(":checked")) { + vat_total += ttl*0.15 ; + } + } else if (!\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { + \$("#checkboxExcl_"+tab+"_"+i).prop('checked',true) ; + } + i++ ; + } + + \$("input[name='subtotal']").val(sub_total.toFixed(2)) ; + \$("input[name='vat']").val(vat_total.toFixed(2)) ; + \$("input[name='total']").val((sub_total+vat_total).toFixed(2)) ; + + } + + \$("#two").on("click","[id^='checkboxVat_']", function () { + changed_vat(this.id) ; + }) ; + + \$("#two").on("click","[id^='checkboxExcl_']", function () { + changed_others(this.id) ; + }) ; + + \$("#two").on("change","[id^='inputQty_'],[id^='inputZar_amount_']", function () { + changed_others(this.id) ; + }) ; + + \$("#two").on("change","[id^='inputDescription_']", function () { + let row_cnt = get_row_nr(this.id) ; + if (\$(this).val()) { + if (row_cnt > \$("input[name='nr_of_costing_rows']").val()) { + \$("input[name='nr_of_costing_rows']").val(row_cnt) ; + } + } else { + let k = 1 ; let desc_row_cnt = 0 ; + while (\$("#costing_"+k).html()) { + if (\$("#inputDescription_costing_"+k).val()) { + desc_row_cnt = k ; + } + k++ ; + } + \$("input[name='nr_of_costing_rows']").val(desc_row_cnt) ; + } + changed_others(this.id) ; + }) ; + + function get_tab (id) { + let tab = "" ; + if (id.includes("costing")) { + tab = "costing" ; + } + return tab ; + } + + function changed_vat (id) { + let tab = get_tab (id) ; + let row_nr = get_row_nr(id) ; + calc_totals(row_nr,tab) ; + } + + function changed_others (id) { + + let row_nr = get_row_nr(id) ; + let firstIndex = id.indexOf('_'); + let col = id.substring(0,firstIndex); + let tab = get_tab (id) ; + + if (col == "inputZar") { + let inp = parseFloat(\$("#"+id).val()) ; + inp = parseFloat(inp) ; + \$("#"+id).val(inp.toFixed(2)) ; + } + + calc_totals(row_nr,tab) ; + } + + function calc_totals (row_cnt,tab) { + + var qty = \$("#inputQty_"+tab+"_"+row_cnt) ; + var usd = \$("#inputZar_amount_"+tab+"_"+row_cnt) ; + var conv = \$("#inputTotal_"+tab+"_"+row_cnt) ; + var excl = \$("#checkboxExcl_"+tab+"_"+row_cnt) ; + var item = \$("#inputDescription_"+tab+"_"+row_cnt) ; + + if (!usd.val() && !qty.val()) { + if (!item.val()) { + excl.prop("checked",true) ; + } else if (item.val() && excl.is(":checked")) { + excl.prop("checked",false) ; + } + return ; + } + + var vat = \$("#checkboxVat_"+tab+"_"+row_cnt) ; + + if (!item.val()) { + excl.prop("checked",true) ; + vat.prop("checked",true) ; + qty.val("") ; + usd.val("") ; + conv.val("") ; + } else if (item.val() && excl.is(":checked")) { + // excl.prop("checked",false) ; + } + + if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) ; } + + let roe = parseFloat(\$("#inputRoe").val()) ; + + let ttl = usd.val() * qty.val() * roe ; + + conv.val(ttl.toFixed(2)) ; + + let sub_total = 0 ; let vat_total = 0 ; + + let nr_of_rows = 50 ; + + add_up_totals (tab,roe,0) ; + + } + + function add_costing_row (row_nr,tab,options1,options2) { + + let tindex = "$tindex" ; + tindex = parseInt(tindex) ; + row_nr = parseInt(row_nr) ; + tindex = tindex - 10*(1+50-row_nr) ; + + row_nr = row_nr + 1 ; + + let row = "
    " ; + + row = row+add_checkbox(row_nr,"excl_"+tab+"_"+row_nr,"checkboxExcl_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + // row = row+add_select(row_nr,"description_"+tab+"_"+row_nr,"selectDescription_"+tab+"_"+row_nr,"Select Description "+row_nr,options1,tindex,2,90,'','') ; tindex++ ; + row = row+add_input(row_nr,"description_"+tab+"_"+row_nr,"inputDescription_"+tab+"_"+row_nr,"Description "+row_nr,tindex,'',2) ; tindex++ ; + row = row+add_input(row_nr,"qty_"+tab+"_"+row_nr,"inputQty_"+tab+"_"+row_nr,"Qty "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"zar_amount_"+tab+"_"+row_nr,"inputZar_amount_"+tab+"_"+row_nr,"Rate "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"total_"+tab+"_"+row_nr,"inputTotal_"+tab+"_"+row_nr,"Total "+row_nr,tindex,"readonly",1) ; tindex++ ; + row = row+add_checkbox(row_nr,"vat_"+tab+"_"+row_nr,"checkboxVat_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + + row = row+"
    " ; + row = row+"
    " ; + + return row ; + } + + function get_row_nr (id) { + let lastIndex = id.lastIndexOf('_'); + lastIndex = parseInt(lastIndex) ; + let row_nr = id.substring(1+lastIndex); + row_nr = parseInt(row_nr) ; + return row_nr ; + } + + function add_checkbox (row_nr,field_name,field_id,tindex,fcol) { + let checkbox = "
    " ; + return checkbox ; + } + + function add_input (row_nr,field_name,field_id,placeholder,tindex,readonly,fcol) { + let input = "
    " ; + return input ; + } + + function add_select (row_nr,field_name,field_id,placeholder,options,tindex,fcol,width,div_id,hide_div) { + let select = "
    " ; + select = select + add_select_raw(row_nr,field_name,field_id,placeholder,options,tindex,width) ; + select = select + "
    " ; + return select ; + } + + function add_select_raw (row_nr,field_name,field_id,placeholder,options,tindex,width) { + let select_raw = "
    " ; + return select_raw ; + } + + ~ ; + +} #------------------------------------------------------------------------------------------ + sub tabs_get_default_totals { my ($id) = @_ ; @@ -95,7 +360,7 @@ if ($tab==1) { # Cusotmer Details $fcol = 9 ; - $add_form_fields .= &common_min_form_select('type',$db{$table}{$id}{type},'') ; + # $add_form_fields .= &common_min_form_select('type',$db{$table}{$id}{type},'') ; my $checked = 'CHECKED' if $db{$table}{$id}{quote_accepted} ; $add_form_fields .= &common_min_form_checkbox('quote_accepted',$db{$table}{$id}{quote_accepted},$checked) ; @@ -151,464 +416,486 @@ $trigger_jquery_raw .= qq~ # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- } -if ($tab == 2) { # Costing +# if ($tab == 2) { # Costing + + # # --------------- START COSTING ---------------------------------------------------------------------------------------------------------------- + + # $add_form_fields = '' ; + + # $lcol = 1 ; $fcol = 2 ; + # $preferred_title{currency} = 'Currency' ; + # $add_form_fields .= &common_min_form_select('currency',$db{$table}{$id}{currency},1) ; + # $trigger_jquery .= qq~\$("#selectCurrency_chosen").css( "width", "96%" );~ ; + # $preferred_title{roe} = ' ROE ' ; $fcol = 1 ; + # $add_form_fields .= &common_min_form_label_col('roe') ; + # $add_form_fields .= &common_min_form_input_col('roe',$db{$table}{$id}{roe},1) ; + # $add_form_fields .= qq~
    ~ ; + # my $sec = '_costing' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + + # return if $ret ; + + # &tab_costing_select_opts('price_list','description',"`excl`<>'1'",$sec) ; + + # # &db_min_ro('quotes_pdf_titles', '*', "quote_id = $id", '', '') ; + # foreach (keys %{$db{quotes_pdf_titles}}){ + # next unless $db{quotes_pdf_titles}{$_}{quote_id} == $id ; + # $old_title_to_new_title{$db{quotes_pdf_titles}{$_}{old_name}}{$db{quotes_pdf_titles}{$_}{quote_id}} = $db{quotes_pdf_titles}{$_}{new_name} ; + # } + + # foreach (sort keys %sec_cnt) { + # $_k = substr($_,1) ; + # next if $_k eq '_hardware' ; + # my @parts = split(/\-/,$sec_cnt{$_}) ; + + # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + # # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + # $fcol = 3 ; + # $add_form_fields .= qq~
    PDF title :
    ~ ; + # # $add_form_fields .= qq~
    PDF TITLE :
    ~ ; + # if ($old_title_to_new_title{$parts[1]}{$id} and $old_title_to_new_title{$parts[1]}{$id} ne $parts[1]){ + # $add_form_fields .= &common_min_form_input_col($_k, $old_title_to_new_title{$parts[1]}{$id}) ; + # } + # else { + # $add_form_fields .= &common_min_form_input_col($_k,'') ; + # } + + # $add_form_fields .= qq~
    ~ ; + # &tab_build_qt_col_headers("$sec$_k") ; + # &build_cost_form($id,$tab,$parts[0],"$sec$_k") ; + # if ($_k eq '_systems') { + # $preferred_title{'systems_included'} = ' ' ; $preferred_placeholder{'systems_included'} = 'Included' ; $fcol = 3 ; + # $add_form_fields .= &common_min_form_textarea('systems_included',$db{$table}{$id}{systems_included},'') ; + # } + # if ($_k eq '_rental') { + # $preferred_title{'rental_included'} = ' ' ; $preferred_placeholder{'rental_included'} = 'Included' ; $fcol = 3 ; + # $add_form_fields .= &common_min_form_textarea('rental_included',$db{$table}{$id}{rental_included},'') ; + # } + # if ($_k eq '_other') { + # $preferred_title{'other_included'} = ' ' ; $preferred_placeholder{'other_included'} = 'Included' ; $fcol = 3 ; + # $add_form_fields .= &common_min_form_textarea('other_included',$db{$table}{$id}{other_included},'') ; + # } + # } + + # $add_form_fields .= qq~
     
    ~ ; + # $add_form_fields .= qq~
    PDF total :
    ~ ; + + # $lcol = 3 ; + + # if ($old_title_to_new_title{"Hardware"}{$id} and $old_title_to_new_title{"Hardware"}{$id} ne "Hardware"){ + # $add_form_fields .= &common_min_form_input_col('_hardware', $old_title_to_new_title{"Hardware"}{$id}) ; + # } + # else { + # $add_form_fields .= &common_min_form_input_col('_hardware','') ; + # } + + # my @ttlarr_labels = ("sub_total","vat_total","grand_total") ; + # $lcol = 1 ; $fcol = 1 ; + # foreach (@ttlarr_labels) { + # $readonly{$_} = "READONLY" ; + # my $val = $db{$table}{$id}{$_} ; $val = '0.00' unless $val ; + # $type = 'hidden' ; $add_form_fields .= &common_min_form_input_col($_,$val) ; $type = '' ; + # $lcol = 1 ; $add_form_fields .= &common_min_form_label_col($_) ; + # } + + # $add_form_fields .= qq~
    ~ ; + + # $lcol = 1 ; $fcol = 1 ; + + # foreach my $a (@ttlarr) { + + # $readonly{$a} = "READONLY" ; + + # $add_form_fields .= qq~
    ~ ; + + # $lcol = 2 ; + # $add_form_fields .= &common_min_form_label_col($a) ; + # $lcol = 1 ; + + # foreach my $b (@ttlarr2) { + # $field = "$b\_$a\_1" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # my $val = ($default_totals{$field}{1}) ? $default_totals{$field}{1} : '0.00' ; + # $add_form_fields .= &common_min_form_input_col($field,$val) ; + # } + # $add_form_fields .= qq~
    ~ ; + + # } + + # $add_form_fields .= qq~
     
    ~ ; + + # &tab_content_box($sec_name,$sec_col) ; + + # # --------------- END COSTING ---------------------------------------------------------------------------------------------------------------- + + + # # $trigger_jquery_raw .= qq~ + + # # function get_tab (id) { + # # let tab = "" ; + # # if (id.includes("workings_event")) { + # # tab = "workings_event" ; + # # } else if (id.includes("costing_event")) { + # # tab = "costing_event" ; + # # } + # # return tab ; + # # } + + # # function changed_vat (id) { + # # let tab = get_tab (id) ; + # # let row_nr = get_row_nr(id) ; + # # calc_totals(row_nr,tab) ; + # # } + + # # function changed_others (id) { + + # # let row_nr = get_row_nr(id) ; + # # let firstIndex = id.indexOf('_'); + # # let col = id.substring(0,firstIndex); + # # let tab = get_tab (id) ; + # # if (col == "inputAmount") { + # # let inp = parseFloat(\$("#"+id).val()) ; + # # inp = parseFloat(inp) ; + # # \$("#"+id).val(inp.toFixed(2)) ; + # # } else if (\$("#selectDescription_"+tab+"_"+row_nr).val() && \$("#selectDescription_"+tab+"_"+row_nr).val() != 14 && \$("#selectOperator_"+tab+"_"+row_nr).val()) { + # # // \$("#selectOperator_"+tab+"_"+row_nr).val("") ; + # # // \$("#selectOperator_"+tab+"_"+row_nr).trigger("chosen:updated") ; + # # } + # # // else if (col == "selectOperator" && \$("#selectDescription"+tab+"_"+row_nr).val() != 14) { + + # # // } + + # # if (col == "selectOperator") { // || (col == "selectDescription" && \$("#selectDescription_"+tab+"_"+row_nr).val( + # # return ; + # # } + + # # calc_totals(row_nr,tab) ; + # # } + + # # // \$("$vat_field_ids_string").change(function() { + # # \$("#content").on("change","[id^='checkboxVat_']", function () { + # # const id = this.id ; + # # changed_vat(id) ; + # # }); + + # # // \$("$excl_field_ids_string,$description_field_ids_string,$qty_field_ids_string,$amount_usd_field_ids_string,$operator_field_ids_string").change(function() { + # # \$("#content").on("change","[id^='checkboxExcl_'],[id^='selectDescription_'],[id^='inputQty_'],[id^='inputZar_amount_'],[id^='selectOperator_workings_event_']", function () { + # # const id = this.id ; + # # changed_others(id) ; + # # }); + # # ~ ; + + # # $trigger_jquery_raw .= qq~ + + # # \$("#content").on("click","[id^='btn_workings_event_'],[id^='btn_costing_event_']", function () { + # # // \$("$btn_ids_string").click(function () { + # # const id = this.id ; + # # let tab = get_tab (id) ; + + # # console.log("id : "+id) ; + # # console.log("tab : "+tab) ; + + # # add_quote_expenses_row_all(id,tab) ; + # # }); + + # # function add_quote_expenses_row_all (id,tab) { + + # # let row_nr = get_row_nr(id) ; + # # \$("#"+tab+"_"+row_nr).show(); + # # let row_html = "" ; + # # if (tab == "workings_event") { + # # row_html = add_quote_expenses_row(row_nr,tab,"$description_options_workings","$operator_options") ; + # # } else if (tab == "costing_event") { + # # row_html = add_quote_expenses_row(row_nr,tab,"$description_options_costing","") ; + # # } + # # \$("#"+tab+"_"+row_nr).html(row_html); + # # // \$("#$suffix\_"+row_nr).trigger("chosen:updated") ; + + # # \$("#selectDescription_"+tab+"_"+row_nr).chosen({ allow_single_deselect:true }) ; + + # # if (tab == "workings_event") { + # # \$("#selectOperator_workings_event_"+row_nr).chosen({ allow_single_deselect:true }); + # # \$("#inputRemarks_workings_event_"+row_nr).css("text-align","") ; + # # \$("#inputSupplier_workings_event_"+row_nr).css("text-align","") ; + # # \$("#inputRef_nr_workings_event_"+row_nr).css("text-align","") ; + # # } + + # # \$("#btn_"+tab+"_"+row_nr).hide(); + # # var v = row_nr + 1 ; + + # # // \$("#btn_$suffix\_"+v).css("padding-left","16px") ; + # # \$("#btn_"+tab+"_"+v).html("") ; + # # \$("#btn_"+tab+"_"+v).show(); + # # \$("#btn_row_"+tab+"_"+v).show() ; + # # \$("#2_"+tab+"_"+row_nr).show() ; + + # # \$("#checkboxExcl_"+tab+"_"+row_nr).prop('checked',false) ; + + # # // \$("#"+tab+"_"+row_nr).on("change","#checkboxVat_"+tab+"_"+row_nr+"", function() { + # # // const id = this.id ; + # # // changed_vat(id) ; + # # // }); + + # # // \$("#"+tab+"_"+row_nr).on("change","#checkboxExcl_"+tab+"_"+row_nr+",#selectDescription_"+tab+"_"+row_nr+",#selectOperator_"+tab+"_"+row_nr+",#inputQty_"+tab+"_"+row_nr+",#inputZar_amount_"+tab+"_"+row_nr+"", function() { + # # // const id = this.id ; + # # // changed_others(id) ; + # # // }); + + # # } + + # # ~ if $btn_ids_string ; + + # # $trigger_jquery_raw .= qq~ + + # # \$("#selectCurrency").change(function () { + + # # }) ; + + # # \$("input[name='roe']").change(function () { + + # # let roe = \$(this).val() ; + # # if (roe < 0 || !roe) { + # # roe = 1 ; + # # } + # # \$(this).val(parseFloat(roe).toFixed(2)) ; + + # # var sub_total = 0 ; var vat_total = 0 ; var sub_total_quote = 0 ; var vat_total_quote = 0 ; + + # # [sub_total,vat_total] = add_up_totals("workings_event",50,roe,1) ; + # # [sub_total_quote,vat_total_quote] = add_up_totals("costing_event",30,roe,1) ; + + # # // // // \$("input[name='income']").val((sub_total_quote+vat_total_quote).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # \$("input[name='income']").val((sub_total_quote+vat_total_quote).toFixed(2)) ; + # # \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + # # update_overall_totals(sub_total,vat_total,"workings_event") ; + # # update_overall_totals(sub_total_quote,vat_total_quote,"costing_event") ; + + # # }) ; + + # # function add_up_totals (tab,nr_of_rows,roe,recalc_totals) { + + # # let sub_total = 0 ; let vat_total = 0 ; + # # for (let i=1; i<=nr_of_rows; i++) { + # # if (!\$("#"+tab+"_"+i).html()) { break ; } + # # if (\$("#selectDescription_"+tab+"_"+i).val()) { + # # if (\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { continue ; } + # # let ttl = 0 ; + # # if (recalc_totals) { + # # ttl = parseFloat(\$("#inputZar_amount_"+tab+"_"+i).val()) * parseFloat(\$("#inputQty_"+tab+"_"+i).val()) * parseFloat(roe) ; + # # } else { + # # ttl = parseFloat(\$("#inputTotal_"+tab+"_"+i).val().replace(/,/g, '')) + # # } + # # // // // // \$("#inputTotal_"+tab+"_"+i).val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # \$("#inputTotal_"+tab+"_"+i).val(ttl.toFixed(2)) ; + # # if (!\$("#inputTotal_"+tab+"_"+i).val() || \$("#inputTotal_"+tab+"_"+i).val() == "NaN") { + # # \$("#inputTotal_"+tab+"_"+i).val("0.00") ; + # # ttl = 0 ; + # # } + # # sub_total += ttl ; + # # if (\$("#checkboxVat_"+tab+"_"+i).is(":checked")) { + # # vat_total += ttl*0.15 ; + # # } + # # } else if (!\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { + # # \$("#checkboxExcl_"+tab+"_"+i).prop('checked',true) ; + # # } + # # } + # # return [sub_total,vat_total] ; + # # } + + # # // function getNum(val) { + + # # // if (isNaN(val)) { + # # // return 0; + # # // } + # # // return val; + # # // } + + # # function calc_totals (row_cnt,tab) { + + # # var qty = \$("#inputQty_"+tab+"_"+row_cnt) ; + # # var usd = \$("#inputZar_amount_"+tab+"_"+row_cnt) ; + # # var conv = \$("#inputTotal_"+tab+"_"+row_cnt) ; + # # var excl = \$("#checkboxExcl_"+tab+"_"+row_cnt) ; + # # var item = \$("#selectDescription_"+tab+"_"+row_cnt) ; + + # # if (!usd.val() && !conv.val() && !usd.val()) { + # # // console.log("skip calc_totals_workings") ; + # # if (!item.val()) { + # # excl.prop("checked",true) ; + # # } + # # return ; + # # } + + # # var vat = \$("#checkboxVat_"+tab+"_"+row_cnt) ; + + # # if (!item.val()) { + + # # excl.prop("checked",true) ; + # # vat.prop("checked",true) ; + # # qty.val("") ; + # # usd.val("") ; + # # conv.val(""); + # # if (tab == "workings_event") { + # # var rem = \$("#inputRemarks_"+tab+"_"+row_cnt) ; + # # var sup = \$("#inputSupplier_"+tab+"_"+row_cnt) ; + # # var ref = \$("#inputRef_nr_"+tab+"_"+row_cnt) ; + # # var op = \$("#selectOperator_"+tab+"_"+row_cnt) ; + # # rem.val("") ; + # # sup.val("") ; + # # ref.val("") ; + # # op.val("") ; + # # op.trigger("chosen:updated") ; + # # } + # # } else if (excl.is(":checked") && item.val() && conv.val() == "0.00") { + # # excl.prop("checked",false) ; + # # } + + # # if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) ; } + + # # let roe = parseFloat(\$("#inputRoe").val()) ; + + # # let ttl = usd.val() * qty.val() * roe ; + + # # // // // conv.val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # conv.val(ttl.toFixed(2)) ; + + # # let sub_total = 0 ; let vat_total = 0 ; + + # # let nr_of_rows = 50 ; + # # if (tab == "costing_event") { + # # nr_of_rows = 30 ; + # # } + + # # [sub_total,vat_total] = add_up_totals (tab,nr_of_rows,roe,0) ; + + # # if (tab == "workings_event") { + # # // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + # # update_overall_totals(sub_total,vat_total,tab) ; + # # } else { + # # // // // \$("input[name='income']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # \$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; + # # update_overall_totals(sub_total,vat_total,tab) ; + # # // update_overall_totals_costings(sub_total,vat_total) ; + # # } + # # } + + # # function update_overall_totals (sub_total,vat_total,tab) { + + # # let profit_loss = parseFloat(\$("input[name='income']").val().replace(/,/g, '')) - parseFloat(\$("input[name='expenses']").val().replace(/,/g, '')) ; + + # # // // // \$("input[name='profit_loss']").val(profit_loss.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # // // // \$("input[name='sub_total_"+tab+"']").val(sub_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # // // // \$("input[name='vat_total_"+tab+"']").val(vat_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + # # // // // \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + + # # \$("input[name='profit_loss']").val(profit_loss.toFixed(2)) ; + # # \$("input[name='sub_total_"+tab+"']").val(sub_total.toFixed(2)) ; + # # \$("input[name='vat_total_"+tab+"']").val(vat_total.toFixed(2)) ; + # # \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toFixed(2)) ; + # # } + + # # function add_quote_expenses_row (row_nr,tab,options1,options2) { + + # # let tindex = $tindex ; + # # tindex = parseInt(tindex) ; + # # row_nr = parseInt(row_nr) ; + # # tindex = tindex - 10*(1+50-row_nr) ; + + # # let row = add_checkbox(row_nr,"excl_"+tab+"_"+row_nr,"checkboxExcl_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + + # # row = row+""+add_select(row_nr,"description_"+tab+"_"+row_nr,"selectDescription_"+tab+"_"+row_nr,"Select Description "+row_nr,options1,tindex,2,90,'','') ; tindex++ ; + # # if (tab == "workings_event") { + # # row = row+add_select(row_nr,"operator_workings_event_"+row_nr,"selectOperator_workings_event_"+row_nr,"Select Operator "+row_nr,options2,tindex,2,90,'','') ; tindex++ ; + # # row = row+add_input(row_nr,"remarks_workings_event_"+row_nr,"inputRemarks_workings_event_"+row_nr,"Remarks "+row_nr,tindex,'',1) ; tindex++ ; + # # row = row+add_input(row_nr,"supplier_workings_event_"+row_nr,"inputSupplier_workings_event_"+row_nr,"Supplier "+row_nr,tindex,'',1) ; tindex++ ; + # # row = row+add_input(row_nr,"ref_nr_workings_event_"+row_nr,"inputRef_nr_workings_event_"+row_nr,"Ref Nr "+row_nr,tindex,'',1) ; tindex++ ; + # # } + # # row = row+add_input(row_nr,"qty_"+tab+"_"+row_nr,"inputQty_"+tab+"_"+row_nr,"Qty "+row_nr,tindex,'',1) ; tindex++ ; + # # row = row+add_input(row_nr,"amount_usd_"+tab+"_"+row_nr,"inputZar_amount_"+tab+"_"+row_nr,"Amount "+row_nr,tindex,'',1) ; tindex++ ; + # # row = row+add_input(row_nr,"amount_ttl_"+tab+"_"+row_nr,"inputTotal_"+tab+"_"+row_nr,"Total Amount "+row_nr,tindex,"readonly",1) ; tindex++ ; + # # row = row+add_checkbox(row_nr,"vat_"+tab+"_"+row_nr,"checkboxVat_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + # # return row ; + # # } + # # ~ ; + +# } + +if ($tab==2) { # Costing # --------------- START COSTING ---------------------------------------------------------------------------------------------------------------- $add_form_fields = '' ; - $lcol = 1 ; $fcol = 2 ; - $preferred_title{currency} = 'Currency' ; + $lcol = 1 ; $fcol = 2 ; + + $db{$table}{$id}{currency} = "ZAR" unless $db{$table}{$id}{currency} ; + + $opts{currency} = qq~~ ; + $opts{currency} =~ s/value="\Q$db{$table}{$id}{currency}\E"/value="$db{$table}{$id}{currency}" SELECTED/g ; + $add_form_fields .= &common_min_form_select('currency',$db{$table}{$id}{currency},1) ; $trigger_jquery .= qq~\$("#selectCurrency_chosen").css( "width", "96%" );~ ; $preferred_title{roe} = ' ROE ' ; $fcol = 1 ; $add_form_fields .= &common_min_form_label_col('roe') ; + + $db{$table}{$id}{roe} = "1.00" unless $db{$table}{$id}{roe} ; + $add_form_fields .= &common_min_form_input_col('roe',$db{$table}{$id}{roe},1) ; $add_form_fields .= qq~
    ~ ; - my $sec = '_costing' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; - $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; - - return if $ret ; - - &tab_costing_select_opts('price_list','description',"`excl`<>'1'",$sec) ; - - # &db_min_ro('quotes_pdf_titles', '*', "quote_id = $id", '', '') ; - foreach (keys %{$db{quotes_pdf_titles}}){ - next unless $db{quotes_pdf_titles}{$_}{quote_id} == $id ; - $old_title_to_new_title{$db{quotes_pdf_titles}{$_}{old_name}}{$db{quotes_pdf_titles}{$_}{quote_id}} = $db{quotes_pdf_titles}{$_}{new_name} ; - } - - foreach (sort keys %sec_cnt) { - $_k = substr($_,1) ; - next if $_k eq '_hardware' ; - my @parts = split(/\-/,$sec_cnt{$_}) ; - $add_form_fields .= qq~

    $parts[1] :

    ~ ; - # $add_form_fields .= qq~

    $parts[1] :

    ~ ; - $fcol = 3 ; - $add_form_fields .= qq~
    PDF title :
    ~ ; - # $add_form_fields .= qq~
    PDF TITLE :
    ~ ; - if ($old_title_to_new_title{$parts[1]}{$id} and $old_title_to_new_title{$parts[1]}{$id} ne $parts[1]){ - $add_form_fields .= &common_min_form_input_col($_k, $old_title_to_new_title{$parts[1]}{$id}) ; - } - else { - $add_form_fields .= &common_min_form_input_col($_k,'') ; - } - - $add_form_fields .= qq~
    ~ ; - &tab_build_qt_col_headers("$sec$_k") ; - &build_cost_form($id,$tab,$parts[0],"$sec$_k") ; - if ($_k eq '_systems') { - $preferred_title{'systems_included'} = ' ' ; $preferred_placeholder{'systems_included'} = 'Included' ; $fcol = 3 ; - $add_form_fields .= &common_min_form_textarea('systems_included',$db{$table}{$id}{systems_included},'') ; - } - if ($_k eq '_rental') { - $preferred_title{'rental_included'} = ' ' ; $preferred_placeholder{'rental_included'} = 'Included' ; $fcol = 3 ; - $add_form_fields .= &common_min_form_textarea('rental_included',$db{$table}{$id}{rental_included},'') ; - } - if ($_k eq '_other') { - $preferred_title{'other_included'} = ' ' ; $preferred_placeholder{'other_included'} = 'Included' ; $fcol = 3 ; - $add_form_fields .= &common_min_form_textarea('other_included',$db{$table}{$id}{other_included},'') ; - } - } - - $add_form_fields .= qq~
     
    ~ ; - $add_form_fields .= qq~
    PDF total :
    ~ ; - - $lcol = 3 ; - - if ($old_title_to_new_title{"Hardware"}{$id} and $old_title_to_new_title{"Hardware"}{$id} ne "Hardware"){ - $add_form_fields .= &common_min_form_input_col('_hardware', $old_title_to_new_title{"Hardware"}{$id}) ; - } - else { - $add_form_fields .= &common_min_form_input_col('_hardware','') ; - } - - my @ttlarr_labels = ("sub_total","vat_total","grand_total") ; - $lcol = 1 ; $fcol = 1 ; - foreach (@ttlarr_labels) { - $readonly{$_} = "READONLY" ; - my $val = $db{$table}{$id}{$_} ; $val = '0.00' unless $val ; - $type = 'hidden' ; $add_form_fields .= &common_min_form_input_col($_,$val) ; $type = '' ; - $lcol = 1 ; $add_form_fields .= &common_min_form_label_col($_) ; - } - - $add_form_fields .= qq~
    ~ ; - - $lcol = 1 ; $fcol = 1 ; - - foreach my $a (@ttlarr) { - - $readonly{$a} = "READONLY" ; - - $add_form_fields .= qq~
    ~ ; - - $lcol = 2 ; - $add_form_fields .= &common_min_form_label_col($a) ; - $lcol = 1 ; - - foreach my $b (@ttlarr2) { - $field = "$b\_$a\_1" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; - my $val = ($default_totals{$field}{1}) ? $default_totals{$field}{1} : '0.00' ; - $add_form_fields .= &common_min_form_input_col($field,$val) ; - } - $add_form_fields .= qq~
    ~ ; - - } - - $add_form_fields .= qq~
     
    ~ ; - - &tab_content_box($sec_name,$sec_col) ; - - # --------------- END COSTING ---------------------------------------------------------------------------------------------------------------- - - - # $trigger_jquery_raw .= qq~ - - # function get_tab (id) { - # let tab = "" ; - # if (id.includes("workings_event")) { - # tab = "workings_event" ; - # } else if (id.includes("costing_event")) { - # tab = "costing_event" ; - # } - # return tab ; - # } - - # function changed_vat (id) { - # let tab = get_tab (id) ; - # let row_nr = get_row_nr(id) ; - # calc_totals(row_nr,tab) ; - # } - - # function changed_others (id) { - - # let row_nr = get_row_nr(id) ; - # let firstIndex = id.indexOf('_'); - # let col = id.substring(0,firstIndex); - # let tab = get_tab (id) ; - # if (col == "inputAmount") { - # let inp = parseFloat(\$("#"+id).val()) ; - # inp = parseFloat(inp) ; - # \$("#"+id).val(inp.toFixed(2)) ; - # } else if (\$("#selectDescription_"+tab+"_"+row_nr).val() && \$("#selectDescription_"+tab+"_"+row_nr).val() != 14 && \$("#selectOperator_"+tab+"_"+row_nr).val()) { - # // \$("#selectOperator_"+tab+"_"+row_nr).val("") ; - # // \$("#selectOperator_"+tab+"_"+row_nr).trigger("chosen:updated") ; - # } - # // else if (col == "selectOperator" && \$("#selectDescription"+tab+"_"+row_nr).val() != 14) { - - # // } - - # if (col == "selectOperator") { // || (col == "selectDescription" && \$("#selectDescription_"+tab+"_"+row_nr).val( - # return ; - # } - - # calc_totals(row_nr,tab) ; - # } - - # // \$("$vat_field_ids_string").change(function() { - # \$("#content").on("change","[id^='checkboxVat_']", function () { - # const id = this.id ; - # changed_vat(id) ; - # }); - - # // \$("$excl_field_ids_string,$description_field_ids_string,$qty_field_ids_string,$amount_usd_field_ids_string,$operator_field_ids_string").change(function() { - # \$("#content").on("change","[id^='checkboxExcl_'],[id^='selectDescription_'],[id^='inputQty_'],[id^='inputAmount_usd_'],[id^='selectOperator_workings_event_']", function () { - # const id = this.id ; - # changed_others(id) ; - # }); - # ~ ; - - # $trigger_jquery_raw .= qq~ - - # \$("#content").on("click","[id^='btn_workings_event_'],[id^='btn_costing_event_']", function () { - # // \$("$btn_ids_string").click(function () { - # const id = this.id ; - # let tab = get_tab (id) ; - - # console.log("id : "+id) ; - # console.log("tab : "+tab) ; - - # add_quote_expenses_row_all(id,tab) ; - # }); - - # function add_quote_expenses_row_all (id,tab) { - - # let row_nr = get_row_nr(id) ; - # \$("#"+tab+"_"+row_nr).show(); - # let row_html = "" ; - # if (tab == "workings_event") { - # row_html = add_quote_expenses_row(row_nr,tab,"$description_options_workings","$operator_options") ; - # } else if (tab == "costing_event") { - # row_html = add_quote_expenses_row(row_nr,tab,"$description_options_costing","") ; - # } - # \$("#"+tab+"_"+row_nr).html(row_html); - # // \$("#$suffix\_"+row_nr).trigger("chosen:updated") ; - - # \$("#selectDescription_"+tab+"_"+row_nr).chosen({ allow_single_deselect:true }) ; - - # if (tab == "workings_event") { - # \$("#selectOperator_workings_event_"+row_nr).chosen({ allow_single_deselect:true }); - # \$("#inputRemarks_workings_event_"+row_nr).css("text-align","") ; - # \$("#inputSupplier_workings_event_"+row_nr).css("text-align","") ; - # \$("#inputRef_nr_workings_event_"+row_nr).css("text-align","") ; - # } - - # \$("#btn_"+tab+"_"+row_nr).hide(); - # var v = row_nr + 1 ; - - # // \$("#btn_$suffix\_"+v).css("padding-left","16px") ; - # \$("#btn_"+tab+"_"+v).html("") ; - # \$("#btn_"+tab+"_"+v).show(); - # \$("#btn_row_"+tab+"_"+v).show() ; - # \$("#2_"+tab+"_"+row_nr).show() ; - - # \$("#checkboxExcl_"+tab+"_"+row_nr).prop('checked',false) ; - - # // \$("#"+tab+"_"+row_nr).on("change","#checkboxVat_"+tab+"_"+row_nr+"", function() { - # // const id = this.id ; - # // changed_vat(id) ; - # // }); - - # // \$("#"+tab+"_"+row_nr).on("change","#checkboxExcl_"+tab+"_"+row_nr+",#selectDescription_"+tab+"_"+row_nr+",#selectOperator_"+tab+"_"+row_nr+",#inputQty_"+tab+"_"+row_nr+",#inputAmount_usd_"+tab+"_"+row_nr+"", function() { - # // const id = this.id ; - # // changed_others(id) ; - # // }); - - # } - - # ~ if $btn_ids_string ; - - # $trigger_jquery_raw .= qq~ - - # \$("#selectCurrency").change(function () { - - # }) ; - - # \$("input[name='roe']").change(function () { - - # let roe = \$(this).val() ; - # if (roe < 0 || !roe) { - # roe = 1 ; - # } - # \$(this).val(parseFloat(roe).toFixed(2)) ; - - # var sub_total = 0 ; var vat_total = 0 ; var sub_total_quote = 0 ; var vat_total_quote = 0 ; - - # [sub_total,vat_total] = add_up_totals("workings_event",50,roe,1) ; - # [sub_total_quote,vat_total_quote] = add_up_totals("costing_event",30,roe,1) ; - - # // // // \$("input[name='income']").val((sub_total_quote+vat_total_quote).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; - # // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; - # \$("input[name='income']").val((sub_total_quote+vat_total_quote).toFixed(2)) ; - # \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; - # update_overall_totals(sub_total,vat_total,"workings_event") ; - # update_overall_totals(sub_total_quote,vat_total_quote,"costing_event") ; - - # }) ; - - # function add_up_totals (tab,nr_of_rows,roe,recalc_totals) { - - # let sub_total = 0 ; let vat_total = 0 ; - # for (let i=1; i<=nr_of_rows; i++) { - # if (!\$("#"+tab+"_"+i).html()) { break ; } - # if (\$("#selectDescription_"+tab+"_"+i).val()) { - # if (\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { continue ; } - # let ttl = 0 ; - # if (recalc_totals) { - # ttl = parseFloat(\$("#inputAmount_usd_"+tab+"_"+i).val()) * parseFloat(\$("#inputQty_"+tab+"_"+i).val()) * parseFloat(roe) ; - # } else { - # ttl = parseFloat(\$("#inputAmount_ttl_"+tab+"_"+i).val().replace(/,/g, '')) - # } - # // // // // \$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; - # \$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toFixed(2)) ; - # if (!\$("#inputAmount_ttl_"+tab+"_"+i).val() || \$("#inputAmount_ttl_"+tab+"_"+i).val() == "NaN") { - # \$("#inputAmount_ttl_"+tab+"_"+i).val("0.00") ; - # ttl = 0 ; - # } - # sub_total += ttl ; - # if (\$("#checkboxVat_"+tab+"_"+i).is(":checked")) { - # vat_total += ttl*0.15 ; - # } - # } else if (!\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { - # \$("#checkboxExcl_"+tab+"_"+i).prop('checked',true) ; - # } - # } - # return [sub_total,vat_total] ; - # } - - # // function getNum(val) { - - # // if (isNaN(val)) { - # // return 0; - # // } - # // return val; - # // } - - # function calc_totals (row_cnt,tab) { - - # var qty = \$("#inputQty_"+tab+"_"+row_cnt) ; - # var usd = \$("#inputAmount_usd_"+tab+"_"+row_cnt) ; - # var conv = \$("#inputAmount_ttl_"+tab+"_"+row_cnt) ; - # var excl = \$("#checkboxExcl_"+tab+"_"+row_cnt) ; - # var item = \$("#selectDescription_"+tab+"_"+row_cnt) ; - - # if (!usd.val() && !conv.val() && !usd.val()) { - # // console.log("skip calc_totals_workings") ; - # if (!item.val()) { - # excl.prop("checked",true) ; - # } - # return ; - # } - - # var vat = \$("#checkboxVat_"+tab+"_"+row_cnt) ; - - # if (!item.val()) { - - # excl.prop("checked",true) ; - # vat.prop("checked",true) ; - # qty.val("") ; - # usd.val("") ; - # conv.val(""); - # if (tab == "workings_event") { - # var rem = \$("#inputRemarks_"+tab+"_"+row_cnt) ; - # var sup = \$("#inputSupplier_"+tab+"_"+row_cnt) ; - # var ref = \$("#inputRef_nr_"+tab+"_"+row_cnt) ; - # var op = \$("#selectOperator_"+tab+"_"+row_cnt) ; - # rem.val("") ; - # sup.val("") ; - # ref.val("") ; - # op.val("") ; - # op.trigger("chosen:updated") ; - # } - # } else if (excl.is(":checked") && item.val() && conv.val() == "0.00") { - # excl.prop("checked",false) ; - # } - - # if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) ; } - - # let roe = parseFloat(\$("#inputRoe").val()) ; - - # let ttl = usd.val() * qty.val() * roe ; - - # // // // conv.val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; - # conv.val(ttl.toFixed(2)) ; - - # let sub_total = 0 ; let vat_total = 0 ; - - # let nr_of_rows = 50 ; - # if (tab == "costing_event") { - # nr_of_rows = 30 ; - # } - - # [sub_total,vat_total] = add_up_totals (tab,nr_of_rows,roe,0) ; - - # if (tab == "workings_event") { - # // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; - # \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; - # update_overall_totals(sub_total,vat_total,tab) ; - # } else { - # // // // \$("input[name='income']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; - # \$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; - # update_overall_totals(sub_total,vat_total,tab) ; - # // update_overall_totals_costings(sub_total,vat_total) ; - # } - # } - - # function update_overall_totals (sub_total,vat_total,tab) { - - # let profit_loss = parseFloat(\$("input[name='income']").val().replace(/,/g, '')) - parseFloat(\$("input[name='expenses']").val().replace(/,/g, '')) ; - - # // // // \$("input[name='profit_loss']").val(profit_loss.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; - # // // // \$("input[name='sub_total_"+tab+"']").val(sub_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; - # // // // \$("input[name='vat_total_"+tab+"']").val(vat_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; - # // // // \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; - - # \$("input[name='profit_loss']").val(profit_loss.toFixed(2)) ; - # \$("input[name='sub_total_"+tab+"']").val(sub_total.toFixed(2)) ; - # \$("input[name='vat_total_"+tab+"']").val(vat_total.toFixed(2)) ; - # \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toFixed(2)) ; - # } - - # function add_quote_expenses_row (row_nr,tab,options1,options2) { - - # let tindex = $tindex ; - # tindex = parseInt(tindex) ; - # row_nr = parseInt(row_nr) ; - # tindex = tindex - 10*(1+50-row_nr) ; - - # let row = add_checkbox(row_nr,"excl_"+tab+"_"+row_nr,"checkboxExcl_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; - - # row = row+""+add_select(row_nr,"description_"+tab+"_"+row_nr,"selectDescription_"+tab+"_"+row_nr,"Select Description "+row_nr,options1,tindex,2,90,'','') ; tindex++ ; - # if (tab == "workings_event") { - # row = row+add_select(row_nr,"operator_workings_event_"+row_nr,"selectOperator_workings_event_"+row_nr,"Select Operator "+row_nr,options2,tindex,2,90,'','') ; tindex++ ; - # row = row+add_input(row_nr,"remarks_workings_event_"+row_nr,"inputRemarks_workings_event_"+row_nr,"Remarks "+row_nr,tindex,'',1) ; tindex++ ; - # row = row+add_input(row_nr,"supplier_workings_event_"+row_nr,"inputSupplier_workings_event_"+row_nr,"Supplier "+row_nr,tindex,'',1) ; tindex++ ; - # row = row+add_input(row_nr,"ref_nr_workings_event_"+row_nr,"inputRef_nr_workings_event_"+row_nr,"Ref Nr "+row_nr,tindex,'',1) ; tindex++ ; - # } - # row = row+add_input(row_nr,"qty_"+tab+"_"+row_nr,"inputQty_"+tab+"_"+row_nr,"Qty "+row_nr,tindex,'',1) ; tindex++ ; - # row = row+add_input(row_nr,"amount_usd_"+tab+"_"+row_nr,"inputAmount_usd_"+tab+"_"+row_nr,"Amount "+row_nr,tindex,'',1) ; tindex++ ; - # row = row+add_input(row_nr,"amount_ttl_"+tab+"_"+row_nr,"inputAmount_ttl_"+tab+"_"+row_nr,"Total Amount "+row_nr,tindex,"readonly",1) ; tindex++ ; - # row = row+add_checkbox(row_nr,"vat_"+tab+"_"+row_nr,"checkboxVat_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; - # return row ; - # } - # ~ ; - -} - -if ($tab==3) { # Costing - - # --------------- START COSTING ---------------------------------------------------------------------------------------------------------------- - - $add_form_fields = '' ; - - $lcol=1; $fcol=2; - - my $sec = '_costing' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + my $sec = 'costing' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; if ($ret) { return ; } - %sec_cnt = ('a_other' => "5-Other"); + %sec_cnt = ('a' => "10-Other"); + + our $nr_of_costing_rows = 0 ; foreach (sort keys %sec_cnt) { + $_k = substr($_,1) ; next if $_k eq '_hardware' ; my @parts = split(/\-/,$sec_cnt{$_}) ; - $add_form_fields .= qq~

    $parts[1] :

    ~ ; - # $add_form_fields .= qq~

    $parts[1] :

    ~ ; + # $add_form_fields .= qq~

    $parts[1] :

    ~ ; $fcol = 3 ; - $add_form_fields .= qq~
    PDF title :
    ~ ; - # $add_form_fields .= qq~
    PDF TITLE :
    ~ ; - if ($old_title_to_new_title{$parts[1]}{$id} and $old_title_to_new_title{$parts[1]}{$id} ne $parts[1]){ - $add_form_fields .= &common_min_form_input_col($_k, $old_title_to_new_title{$parts[1]}{$id}) ; - } - else { - $add_form_fields .= &common_min_form_input_col($_k,'') ; - } + # $add_form_fields .= qq~
    PDF title :
    ~ ; + + # if ($old_title_to_new_title{$parts[1]}{$id} and $old_title_to_new_title{$parts[1]}{$id} ne $parts[1]) { + # $add_form_fields .= &common_min_form_input_col($_k, $old_title_to_new_title{$parts[1]}{$id}) ; + # } else { + # $add_form_fields .= &common_min_form_input_col($_k,'') ; + # } - $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; &tab_build_qt_col_headers("$sec$_k") ; &build_cost_form($id,$tab,$parts[0],"$sec$_k") ; - if ($_k eq '_systems') { - $preferred_title{'systems_included'} = ' ' ; $preferred_placeholder{'systems_included'} = 'Included' ; $fcol = 3 ; - $add_form_fields .= &common_min_form_textarea('systems_included',$db{$table}{$id}{systems_included},'') ; - } - if ($_k eq '_rental') { - $preferred_title{'rental_included'} = ' ' ; $preferred_placeholder{'rental_included'} = 'Included' ; $fcol = 3 ; - $add_form_fields .= &common_min_form_textarea('rental_included',$db{$table}{$id}{rental_included},'') ; - } - if ($_k eq '_other') { - $preferred_title{'other_included'} = ' ' ; $preferred_placeholder{'other_included'} = 'Included' ; $fcol = 3 ; - $add_form_fields .= &common_min_form_textarea('other_included',$db{$table}{$id}{other_included},'') ; - } + + # if ($_k eq '_systems') { + # $preferred_title{'systems_included'} = ' ' ; $preferred_placeholder{'systems_included'} = 'Included' ; $fcol = 3 ; + # $add_form_fields .= &common_min_form_textarea('systems_included',$db{$table}{$id}{systems_included},'') ; + # } + + # if ($_k eq '_rental') { + # $preferred_title{'rental_included'} = ' ' ; $preferred_placeholder{'rental_included'} = 'Included' ; $fcol = 3 ; + # $add_form_fields .= &common_min_form_textarea('rental_included',$db{$table}{$id}{rental_included},'') ; + # } + + # if ($_k eq '_other') { + # $preferred_title{'other_included'} = ' ' ; $preferred_placeholder{'other_included'} = 'Included' ; $fcol = 3 ; + # $add_form_fields .= &common_min_form_textarea('other_included',$db{$table}{$id}{other_included},'') ; + # } + } - $add_form_fields .= qq~
     
    ~ ; + # $add_form_fields .= qq~
     
    ~ ; # $add_form_fields .= qq~
     
    ~ ; - $add_form_fields .= qq~
    PDF total :
    ~ ; + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    PDF total :
    ~ ; + $add_form_fields .= qq~
    ~ ; $lcol = 3 ; # if ($old_title_to_new_title{"Hardware"}{$id} and $old_title_to_new_title{"Hardware"}{$id} ne "Hardware") { # $add_form_fields .= &common_min_form_input_col('_hardware', $old_title_to_new_title{"Hardware"}{$id}) ; @@ -621,11 +908,8 @@ if ($tab==3) { # Costing # @ttlarr2 = ("subtotal","vat","total") ; $lcol = 1 ; $fcol = 1 ; - - print "\n Other Costing Tab " ; - - foreach (@ttlarr) { - print "\n 1 ttlarr : $_ " ; + + foreach (@ttlarr2) { $readonly{$_} = "READONLY" ; my $val = $db{$table}{$id}{$_} ; $val = '0.00' unless $val ; # $add_form_fields .= qq~
    ~ ; $lcol=2; @@ -638,64 +922,118 @@ if ($tab==3) { # Costing } $add_form_fields .= qq~
    ~ ; - + # $add_form_fields .= qq~
     
    ~ ; # my @ttlarr = ("one_time_fee","monthly_recurring_fee","annual_fee") ; $lcol = 1 ; $fcol = 1 ; - foreach my $a (@ttlarr) { + # foreach my $a (@ttlarr) { - $readonly{$a} = "READONLY" ; + # $readonly{$a} = "READONLY" ; - # if ($_ eq 'one_time_fee') { + # # if ($_ eq 'one_time_fee') { - # $add_form_fields .= qq~
    PDF total :
    ~ ; - # $lcol = 1 ; - # if ($old_title_to_new_title{"Hardware"}{$id} and $old_title_to_new_title{"Hardware"}{$id} ne "Hardware"){ - # $add_form_fields .= &common_min_form_input_col('_hardware', $old_title_to_new_title{"Hardware"}{$id}) ; - # } - # else { - # $add_form_fields .= &common_min_form_input_col('_hardware','') ; - # } - # } + # # $add_form_fields .= qq~
    PDF total :
    ~ ; + # # $lcol = 1 ; + # # if ($old_title_to_new_title{"Hardware"}{$id} and $old_title_to_new_title{"Hardware"}{$id} ne "Hardware"){ + # # $add_form_fields .= &common_min_form_input_col('_hardware', $old_title_to_new_title{"Hardware"}{$id}) ; + # # } + # # else { + # # $add_form_fields .= &common_min_form_input_col('_hardware','') ; + # # } + # # } - # else { - $add_form_fields .= qq~
    ~ ; - # } + # # else { + # $add_form_fields .= qq~
    ~ ; + # # } - $lcol = 2 ; - $add_form_fields .= &common_min_form_label_col($a) ; + # $lcol = 2 ; + # $add_form_fields .= &common_min_form_label_col($a) ; + # $lcol = 1 ; + + # foreach my $b (@ttlarr2) { + + # $field = "$b\_$a\_2" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + # my $val = $default_totals{$field}{2} ? $default_totals{$field}{2} : '0.00' ; + # $add_form_fields .= &common_min_form_input_col($field,$val) ; + # } + + # # $field = "2_subtotal_$_" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + # # my $val = $db{$table}{$id}{$field} ? $db{$table}{$id}{$field} : '0.00' ; + # # $add_form_fields .= &common_min_form_input_col($field,$val) ; + + # # $field = "2_vat_$_" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + # # my $val = $db{$table}{$id}{$field} ? $db{$table}{$id}{$field} : '0.00' ; + # # $add_form_fields .= &common_min_form_input_col($field,$val) ; + + # # $field = "2_total_$_" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + # # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; + # # my $val = $db{$table}{$id}{$field} ? $db{$table}{$id}{$field} : '0.00' ; + # # $add_form_fields .= &common_min_form_input_col($field,$val) ; + # $add_form_fields .= qq~
    ~ ; + + # } + + $add_form_fields .= qq~
    ~ ; + + foreach my $a (@ttlarr2) { + $readonly{$a} = "READONLY" ; $lcol = 1 ; - - foreach my $b (@ttlarr2) { - - $field = "$b\_$a\_2" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; - # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; - my $val = $default_totals{$field}{2} ? $default_totals{$field}{2} : '0.00' ; - $add_form_fields .= &common_min_form_input_col($field,$val) ; - } - - # $field = "2_subtotal_$_" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; - # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; - # my $val = $db{$table}{$id}{$field} ? $db{$table}{$id}{$field} : '0.00' ; - # $add_form_fields .= &common_min_form_input_col($field,$val) ; - - # $field = "2_vat_$_" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; - # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; - # my $val = $db{$table}{$id}{$field} ? $db{$table}{$id}{$field} : '0.00' ; - # $add_form_fields .= &common_min_form_input_col($field,$val) ; - - # $field = "2_total_$_" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; - # # my $val = $db{$table}{$id}{$field} ; $val = '0.00' unless $val ; - # my $val = $db{$table}{$id}{$field} ? $db{$table}{$id}{$field} : '0.00' ; - # $add_form_fields .= &common_min_form_input_col($field,$val) ; - $add_form_fields .= qq~
    ~ ; - + $field = "$a" ; $readonly{$field} = "READONLY"; $input_style{$field} = qq~style="text-align:right;"~ ; + my $val = $default_totals{$field}{2} ? $default_totals{$field}{2} : '0.00' ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; } - + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
     
    ~ ; - + + $preferred_title{'include_exclude'} = 'Include/Exclude' ; $preferred_placeholder{'include_exclude'} = 'Include/Exclude' ; $fcol = 5 ; + $add_form_fields .= &common_min_form_textarea('include_exclude',$db{$table}{$id}{include_exclude},'') ; + + $add_form_fields .= qq~
     
    ~ ; + + $add_form_fields .= qq~
    ~ ; + + my @docs = ("1","2","3") ; + + # ($db{$table}{$id}{costing_1},$db{$table}{$id}{costing_2},$db{$table}{$id}{costing_3}) = split(/\:;:/,$db{$table}{$id}{costing_uploads}) ; + + $db{$table}{$id}{costing_1} = "costing_1-$db{$table}{$id}{costing_1}" if $db{$table}{$id}{costing_1} ; + $db{$table}{$id}{costing_2} = "costing_2-$db{$table}{$id}{costing_2}" if $db{$table}{$id}{costing_2} ; + $db{$table}{$id}{costing_3} = "costing_3-$db{$table}{$id}{costing_3}" if $db{$table}{$id}{costing_3} ; + + $db{$table}{$id}{costing_1} = "" if $db{$table}{$id}{costing_1} && not -f "$htmlpath/uploads/costings/$id/$db{$table}{$id}{costing_1}" ; + $db{$table}{$id}{costing_2} = "" if $db{$table}{$id}{costing_2} && not -f "$htmlpath/uploads/costings/$id/$db{$table}{$id}{costing_2}" ; + $db{$table}{$id}{costing_3} = "" if $db{$table}{$id}{costing_3} && not -f "$htmlpath/uploads/costings/$id/$db{$table}{$id}{costing_3}" ; + + foreach (@docs) { + + my $doc = lc $_ ; $doc =~ s/ /\_/ ; $doc =~ s/&/\_/ ; + $costing_uploads = &common_get_field_uploads($id,"costing_$doc",'id') ; + + if ($costing_uploads) { + $add_form_fields .= qq~
    $costing_uploads
    ~; + } else { + $add_form_fields .= qq~ +
    +
    + + +

    Upload file from PC.

    +
    +
    + ~; + } + } + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~~ ; + # $print_box_content_rows .= qq~
    ~ ; # $print_box_content_rows .= $add_form_fields ; # $print_box_content_rows .= &common_min_box_foot; @@ -704,284 +1042,277 @@ if ($tab==3) { # Costing # --------------- END COSTING ---------------------------------------------------------------------------------------------------------------- - - $trigger_jquery_raw .= qq~ - - - - ~ ; - } -if ($tab==4) { # Purchase Summary +# if ($tab==4) { # Purchase Summary - # --------------- START PURCHASE SUMMARY ---------------------------------------------------------------------------------------------------------------- + # # --------------- START PURCHASE SUMMARY ---------------------------------------------------------------------------------------------------------------- - $add_form_fields = '' ; + # $add_form_fields = '' ; - my $sec = '_purchase_summary' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + # my $sec = '_purchase_summary' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; - $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; - if ($ret) { return ; } + # if ($ret) { return ; } - my $style_vat = '' ; if ($no_vat{$sec}) { $style_vat = 'style="display:none;"' ; } + # my $style_vat = '' ; if ($no_vat{$sec}) { $style_vat = 'style="display:none;"' ; } - $add_form_fields .= qq~
     
    ~ ; + # $add_form_fields .= qq~
     
    ~ ; - my $field = "excl$sec" ; - if ($db{$table}{$id}{$field} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } - $label{$field} = 1 ; - $add_form_fields .= qq~
    ~ ;$fcol=1 ; - $add_form_fields .= &common_min_form_checkbox_col($field,$db{$table}{$id}{$field},$checked) ; - $add_form_fields .= qq~

    Purchase Summary

    ~ ; - $add_form_fields .= qq~
    ~ ; - $add_form_fields .= qq~
    ~ ; - $add_form_fields .= qq~
    ~ ; - $add_form_fields .= qq~
    ~ ; - $add_form_fields .= qq~
    ~ ; - $add_form_fields .= qq~
    ~ ; - $add_form_fields .= qq~~ ; - $add_form_fields .= qq~~ ; - $add_form_fields .= qq~
    ~ ; - $add_form_fields .= qq~
    ~ ; + # my $field = "excl$sec" ; + # if ($db{$table}{$id}{$field} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + # $label{$field} = 1 ; + # $add_form_fields .= qq~
    ~ ;$fcol=1 ; + # $add_form_fields .= &common_min_form_checkbox_col($field,$db{$table}{$id}{$field},$checked) ; + # $add_form_fields .= qq~

    Purchase Summary

    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~~ ; + # $add_form_fields .= qq~~ ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; - my $suffix = $sec ; my $rcnt = 3 ; + # my $suffix = $sec ; my $rcnt = 3 ; - # &set_check_boxes_checked($id,$rcnt,"excl",$suffix); + # # &set_check_boxes_checked($id,$rcnt,"excl",$suffix); - $default_desc{1} = 'Hardware Purchase' ; - $default_desc{2} = 'Monthly Fees' ; - $default_desc{3} = 'Annual Fees' ; + # $default_desc{1} = 'Hardware Purchase' ; + # $default_desc{2} = 'Monthly Fees' ; + # $default_desc{3} = 'Annual Fees' ; - my @prefexes = ("excl", "item") ; + # my @prefexes = ("excl", "item") ; - foreach my $prefex (@prefexes) { + # foreach my $prefex (@prefexes) { - $col_name = "$prefex" . "$suffix" ; - $cnt = 0 ; - # if($db{quotes_min}{$id}{$col_name}){ - for my $col_input (split(";", $db{quotes_min}{$id}{$col_name})){ - $cnt++ ; - $saved_field{$prefex}{$suffix}{$cnt} = $col_input ; - } + # $col_name = "$prefex" . "$suffix" ; + # $cnt = 0 ; + # # if($db{quotes_min}{$id}{$col_name}){ + # for my $col_input (split(";", $db{quotes_min}{$id}{$col_name})){ + # $cnt++ ; + # $saved_field{$prefex}{$suffix}{$cnt} = $col_input ; # } - } - for (1 .. $rcnt) { - $add_form_fields .= qq~
    ~ ; - #---------------------------------------------------------------------------------------------------- - $field = "excl_$_$suffix" ; $fcol=1 ; - # if ($checkit{$field} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } - # if ($db{$table}{$id}{$field} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } - if ($saved_field{"excl"}{$suffix}{$_} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } - $label{$field} = 1 ; - # $add_form_fields .= &common_min_form_checkbox_col($field,$db{$table}{$id}{$field},$checked) ; - $add_form_fields .= &common_min_form_checkbox_col($field,$saved_field{"excl"}{$suffix}{$_},$checked) ; - #---------------------------------------------------------------------------------------------------- - my $field = "item_$_$suffix" ; $fcol=2 ; - $preferred_placeholder{$field} = "Item $_" ; - # my $val = $db{$table}{$id}{$field} ; - my $val = $saved_field{"item"}{$suffix}{$_} ; - $val = $default_desc{$_} unless $val ; - # $readonly{$field} = 'READONLY' ; - $add_form_fields .= &common_min_form_input_col($field,$val) ; - #---------------------------------------------------------------------------------------------------- - for my $year (1 .. 5) { - $field = "year_$year\_$_$suffix" ; $input_style{$field} = qq~style="text-align:right;"~; + # # } + # } + # for (1 .. $rcnt) { + # $add_form_fields .= qq~
    ~ ; + # #---------------------------------------------------------------------------------------------------- + # $field = "excl_$_$suffix" ; $fcol=1 ; + # # if ($checkit{$field} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + # # if ($db{$table}{$id}{$field} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + # if ($saved_field{"excl"}{$suffix}{$_} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + # $label{$field} = 1 ; + # # $add_form_fields .= &common_min_form_checkbox_col($field,$db{$table}{$id}{$field},$checked) ; + # $add_form_fields .= &common_min_form_checkbox_col($field,$saved_field{"excl"}{$suffix}{$_},$checked) ; + # #---------------------------------------------------------------------------------------------------- + # my $field = "item_$_$suffix" ; $fcol=2 ; + # $preferred_placeholder{$field} = "Item $_" ; + # # my $val = $db{$table}{$id}{$field} ; + # my $val = $saved_field{"item"}{$suffix}{$_} ; + # $val = $default_desc{$_} unless $val ; + # # $readonly{$field} = 'READONLY' ; + # $add_form_fields .= &common_min_form_input_col($field,$val) ; + # #---------------------------------------------------------------------------------------------------- + # for my $year (1 .. 5) { + # $field = "year_$year\_$_$suffix" ; $input_style{$field} = qq~style="text-align:right;"~; - unless ($year==1 and $_==3) { - $readonly{$field} = 'READONLY' ; - } else { - $trigger_jquery_raw .= qq~\$("#inputYear_1_$_$suffix").change(function() { - calcAnnual$field() ; - }); - ~; - $trigger_jquery_raw .= qq~function calcAnnual$field() - { - var annual_ttl = getNum(parseFloat(\$("#inputYear_1_$_$suffix").val())) + getNum(parseFloat(\$("#inputYear_2_$_$suffix").val())) + getNum(parseFloat(\$("#inputYear_3_$_$suffix").val())) ; - \$("#inputTotal_$_$suffix").val(annual_ttl.toFixed(2)); - }~; - } - $preferred_placeholder{$field} = "Year $year Total $_" ; - # my $val = &q_get_val($db{$table}{$id}{$field}) ; - $excl_on_change{$field} = 1 ; - $year_totals{"yearly_totals_$year"} += $db{$table}{$id}{$field} ; + # unless ($year==1 and $_==3) { + # $readonly{$field} = 'READONLY' ; + # } else { + # $trigger_jquery_raw .= qq~\$("#inputYear_1_$_$suffix").change(function() { + # calcAnnual$field() ; + # }); + # ~; + # $trigger_jquery_raw .= qq~function calcAnnual$field() + # { + # var annual_ttl = getNum(parseFloat(\$("#inputYear_1_$_$suffix").val())) + getNum(parseFloat(\$("#inputYear_2_$_$suffix").val())) + getNum(parseFloat(\$("#inputYear_3_$_$suffix").val())) ; + # \$("#inputTotal_$_$suffix").val(annual_ttl.toFixed(2)); + # }~; + # } + # $preferred_placeholder{$field} = "Year $year Total $_" ; + # # my $val = &q_get_val($db{$table}{$id}{$field}) ; + # $excl_on_change{$field} = 1 ; + # $year_totals{"yearly_totals_$year"} += $db{$table}{$id}{$field} ; - $fcol = 12 ; - $add_form_fields .= qq~
    ~ if $year <= 3 ; - $add_form_fields .= qq~~ ; - } - $fcol = 2 ; - #---------------------------------------------------------------------------------------------------- + # $fcol = 12 ; + # $add_form_fields .= qq~
    ~ if $year <= 3 ; + # $add_form_fields .= qq~~ ; + # } + # $fcol = 2 ; + # #---------------------------------------------------------------------------------------------------- - $field = "total_$_$suffix" ; $input_style{$field} = qq~style="text-align:right;"~; $readonly{$field} = 'READONLY' ; # $fcol=2 ; - $preferred_placeholder{$field} = "Total $_" ; - # my $val = &q_get_val($db{$table}{$id}{$field}) ; - $add_form_fields .= &common_min_form_input_col($field,$db{$table}{$id}{$field},1) ; - #---------------------------------------------------------------------------------------------------- - $add_form_fields .= qq~
    ~ ; - $add_form_fields .= qq~
    ~ ; - } - $add_form_fields .= qq~
    ~ ; - for my $y (1 .. 5) { - $grand_tot += $year_totals{"yearly_totals_$y"} ; - $field ="yearly_totals_$y" ; - $readonly{$field} = 'READONLY' ; - # $year_totals{"yearly_totals_$y"} = &common_commify($year_totals{"yearly_totals_$y"}) ; - $input_style{$field} = qq~style="text-align:right;"~ ; - $fcol = 12 ; - $add_form_fields .= qq~
    ~ if $y <= 3 ; - $add_form_fields .= qq~~ ; - } + # $field = "total_$_$suffix" ; $input_style{$field} = qq~style="text-align:right;"~; $readonly{$field} = 'READONLY' ; # $fcol=2 ; + # $preferred_placeholder{$field} = "Total $_" ; + # # my $val = &q_get_val($db{$table}{$id}{$field}) ; + # $add_form_fields .= &common_min_form_input_col($field,$db{$table}{$id}{$field},1) ; + # #---------------------------------------------------------------------------------------------------- + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # } + # $add_form_fields .= qq~
    ~ ; + # for my $y (1 .. 5) { + # $grand_tot += $year_totals{"yearly_totals_$y"} ; + # $field ="yearly_totals_$y" ; + # $readonly{$field} = 'READONLY' ; + # # $year_totals{"yearly_totals_$y"} = &common_commify($year_totals{"yearly_totals_$y"}) ; + # $input_style{$field} = qq~style="text-align:right;"~ ; + # $fcol = 12 ; + # $add_form_fields .= qq~
    ~ if $y <= 3 ; + # $add_form_fields .= qq~~ ; + # } - $trigger_jquery_raw .= qq~ - // console.log("suffix : "+$suffix) ;console.log("1") ; + # $trigger_jquery_raw .= qq~ + # // console.log("suffix : "+$suffix) ;console.log("1") ; - if (\$("#selectPeriod").val() == 60) { + # if (\$("#selectPeriod").val() == 60) { - for (let ii = 1; ii <= 5; ii++) { + # for (let ii = 1; ii <= 5; ii++) { - if (ii <= 3) { - \$("#year_"+ii+"_sum").removeClass("col-md-2").addClass("col-md-1") ; - \$("#total_"+ii+"").removeClass("col-md-2").addClass("col-md-1") - } - else if (ii <= 5 && ii > 3) { - \$("#year_"+ii+"_sum").removeClass("col-md-0").addClass("col-md-1") ; - \$("#total_"+ii+"").removeClass("col-md-0").addClass("col-md-1") ; - \$("#year_"+ii+"_sum").show() ; - \$("#total_"+ii+"").show() ; - } - for (let jj = 1; jj <= 3; jj++) { + # if (ii <= 3) { + # \$("#year_"+ii+"_sum").removeClass("col-md-2").addClass("col-md-1") ; + # \$("#total_"+ii+"").removeClass("col-md-2").addClass("col-md-1") + # } + # else if (ii <= 5 && ii > 3) { + # \$("#year_"+ii+"_sum").removeClass("col-md-0").addClass("col-md-1") ; + # \$("#total_"+ii+"").removeClass("col-md-0").addClass("col-md-1") ; + # \$("#year_"+ii+"_sum").show() ; + # \$("#total_"+ii+"").show() ; + # } + # for (let jj = 1; jj <= 3; jj++) { - if (ii <= 3) { - \$("#b_year_"+ii+"_"+jj+"").removeClass("col-md-2").addClass("col-md-1") ; - } - else if (ii <= 5 && ii > 3) { - \$("#b_year_"+ii+"_"+jj+"").removeClass("col-md-0").addClass("col-md-1") ; - \$("#b_year_"+ii+"_"+jj+"").show() ; - } - } - } - } + # if (ii <= 3) { + # \$("#b_year_"+ii+"_"+jj+"").removeClass("col-md-2").addClass("col-md-1") ; + # } + # else if (ii <= 5 && ii > 3) { + # \$("#b_year_"+ii+"_"+jj+"").removeClass("col-md-0").addClass("col-md-1") ; + # \$("#b_year_"+ii+"_"+jj+"").show() ; + # } + # } + # } + # } - \$("#selectPeriod").on("change", function() { + # \$("#selectPeriod").on("change", function() { - for (let i = 1; i <= 5; i++) { + # for (let i = 1; i <= 5; i++) { - if (i <= 3 && \$(this).val() == 36) { - \$("#year_"+i+"_sum").removeClass("col-md-1").addClass("col-md-2") ; - \$("#total_"+i+"").removeClass("col-md-1").addClass("col-md-2") ; - } - else if (i <= 3 && \$(this).val() == 60) { - \$("#year_"+i+"_sum").removeClass("col-md-2").addClass("col-md-1") ; - \$("#total_"+i+"").removeClass("col-md-2").addClass("col-md-1") - } - else if (i <= 5 && i > 3 && \$(this).val() == 36) { - \$("#year_"+i+"_sum").removeClass("col-md-1").addClass("col-md-0") ; - \$("#total_"+i+"").removeClass("col-md-1").addClass("col-md-0") ; - \$("#year_"+i+"_sum").hide() ; - \$("#total_"+i+"").hide() ; - } - else if (i <= 5 && i > 3 && \$(this).val() == 60) { - \$("#year_"+i+"_sum").removeClass("col-md-0").addClass("col-md-1") ; - \$("#total_"+i+"").removeClass("col-md-0").addClass("col-md-1") ; - \$("#year_"+i+"_sum").show() ; - \$("#total_"+i+"").show() ; - } - for (let j = 1; j <= 3; j++) { + # if (i <= 3 && \$(this).val() == 36) { + # \$("#year_"+i+"_sum").removeClass("col-md-1").addClass("col-md-2") ; + # \$("#total_"+i+"").removeClass("col-md-1").addClass("col-md-2") ; + # } + # else if (i <= 3 && \$(this).val() == 60) { + # \$("#year_"+i+"_sum").removeClass("col-md-2").addClass("col-md-1") ; + # \$("#total_"+i+"").removeClass("col-md-2").addClass("col-md-1") + # } + # else if (i <= 5 && i > 3 && \$(this).val() == 36) { + # \$("#year_"+i+"_sum").removeClass("col-md-1").addClass("col-md-0") ; + # \$("#total_"+i+"").removeClass("col-md-1").addClass("col-md-0") ; + # \$("#year_"+i+"_sum").hide() ; + # \$("#total_"+i+"").hide() ; + # } + # else if (i <= 5 && i > 3 && \$(this).val() == 60) { + # \$("#year_"+i+"_sum").removeClass("col-md-0").addClass("col-md-1") ; + # \$("#total_"+i+"").removeClass("col-md-0").addClass("col-md-1") ; + # \$("#year_"+i+"_sum").show() ; + # \$("#total_"+i+"").show() ; + # } + # for (let j = 1; j <= 3; j++) { - if (i <= 3 && \$(this).val() == 36) { - \$("#b_year_"+i+"_"+j+"").removeClass("col-md-1").addClass("col-md-2") ; - } - else if (i <= 5 && i > 3 && \$(this).val() == 36) { - \$("#b_year_"+i+"_"+j+"").removeClass("col-md-1").addClass("col-md-0") ; - \$("#b_year_"+i+"_"+j+"").hide() ; - } + # if (i <= 3 && \$(this).val() == 36) { + # \$("#b_year_"+i+"_"+j+"").removeClass("col-md-1").addClass("col-md-2") ; + # } + # else if (i <= 5 && i > 3 && \$(this).val() == 36) { + # \$("#b_year_"+i+"_"+j+"").removeClass("col-md-1").addClass("col-md-0") ; + # \$("#b_year_"+i+"_"+j+"").hide() ; + # } - else if (i <= 3 && \$(this).val() == 60) { - \$("#b_year_"+i+"_"+j+"").removeClass("col-md-2").addClass("col-md-1") ; - } - else if (i <= 5 && i > 3 && \$(this).val() == 60) { - \$("#b_year_"+i+"_"+j+"").removeClass("col-md-0").addClass("col-md-1") ; - \$("#b_year_"+i+"_"+j+"").show() ; - // if (\$("#b_year_"+i+"_"+j+"").text().trim() === '') { - // \$("#b_year_"+i+"_"+j+"").text("0.00") ; - // } - } - } - } - }); - ~ ; + # else if (i <= 3 && \$(this).val() == 60) { + # \$("#b_year_"+i+"_"+j+"").removeClass("col-md-2").addClass("col-md-1") ; + # } + # else if (i <= 5 && i > 3 && \$(this).val() == 60) { + # \$("#b_year_"+i+"_"+j+"").removeClass("col-md-0").addClass("col-md-1") ; + # \$("#b_year_"+i+"_"+j+"").show() ; + # // if (\$("#b_year_"+i+"_"+j+"").text().trim() === '') { + # // \$("#b_year_"+i+"_"+j+"").text("0.00") ; + # // } + # } + # } + # } + # }); + # ~ ; - $fcol = 2 ; - $field ="yearly_total" ; - $readonly{$field} = 'READONLY' ; - # $grand_tot = &common_commify($grand_tot) ; - $input_style{$field} = qq~style="text-align:right;"~ ; - $add_form_fields .= &common_min_form_input_col($field,$grand_tot,1) ; - $add_form_fields .= qq~
    ~ ; - $add_form_fields .= qq~
     
    ~ ; + # $fcol = 2 ; + # $field ="yearly_total" ; + # $readonly{$field} = 'READONLY' ; + # # $grand_tot = &common_commify($grand_tot) ; + # $input_style{$field} = qq~style="text-align:right;"~ ; + # $add_form_fields .= &common_min_form_input_col($field,$grand_tot,1) ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
     
    ~ ; - &tab_content_box($sec_name,$sec_col); + # &tab_content_box($sec_name,$sec_col); - # --------------- END PURCHASE SUMMARY ---------------------------------------------------------------------------------------------------------------- - } + # # --------------- END PURCHASE SUMMARY ---------------------------------------------------------------------------------------------------------------- + # } -if ($tab==5) { # Notes +# if ($tab==5) { # Notes - # --------------- START NOTES ---------------------------------------------------------------------------------------------------------------- + # # --------------- START NOTES ---------------------------------------------------------------------------------------------------------------- - my $sec = '_notes' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + # my $sec = '_notes' ; my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; - $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; + # $ret_pdf_link_sec .= $sec . '+' . $sec_cnt . '|' ; - if ($ret) { return ; } + # if ($ret) { return ; } - $add_form_fields = '' ; + # $add_form_fields = '' ; - # &set_check_boxes_checked($id,$sec_cnt,"excl",$sec); + # # &set_check_boxes_checked($id,$sec_cnt,"excl",$sec); - &db_min_ro('quote_notes','*',"id='1'",'','') ; + # &db_min_ro('quote_notes','*',"id='1'",'','') ; - $add_form_fields .= qq~

    Notes:

    ~ ; - &tab_build_terms_headers; + # $add_form_fields .= qq~

    Notes:

    ~ ; + # &tab_build_terms_headers; - $cntnoteloop=1; for (1 .. 12) { &tab_build_terms_fields('note',$_,$id) ; } + # $cntnoteloop=1; for (1 .. 12) { &tab_build_terms_fields('note',$_,$id) ; } - $add_form_fields .= qq~

    Payment Terms:

    ~ ; - &tab_build_terms_headers; + # $add_form_fields .= qq~

    Payment Terms:

    ~ ; + # &tab_build_terms_headers; - $cntnoteloop=1; for (1 .. 6) { &tab_build_terms_fields('payment_term',$_,$id) ; } + # $cntnoteloop=1; for (1 .. 6) { &tab_build_terms_fields('payment_term',$_,$id) ; } - $add_form_fields .= qq~

    ROE:

    ~ ; - &tab_build_terms_headers; + # $add_form_fields .= qq~

    ROE:

    ~ ; + # &tab_build_terms_headers; - $cntnoteloop=1; for (1 .. 6) { &tab_build_terms_fields('roe',$_,$id) ; } + # $cntnoteloop=1; for (1 .. 6) { &tab_build_terms_fields('roe',$_,$id) ; } - $add_form_fields .= qq~

    Delivery Time:

    ~ ; - &tab_build_terms_headers; + # $add_form_fields .= qq~

    Delivery Time:

    ~ ; + # &tab_build_terms_headers; - $cntnoteloop=1; for (1 .. 4) { &tab_build_terms_fields('delivery_time',$_,$id) ; } + # $cntnoteloop=1; for (1 .. 4) { &tab_build_terms_fields('delivery_time',$_,$id) ; } - $add_form_fields .= qq~

    Terms and Conditions:

    ~ ; - &tab_build_terms_headers; + # $add_form_fields .= qq~

    Terms and Conditions:

    ~ ; + # &tab_build_terms_headers; - $cntnoteloop=1; for (1 .. 1) { &tab_build_terms_fields_terms_and_conditions('terms',$_,$id) ; } + # $cntnoteloop=1; for (1 .. 1) { &tab_build_terms_fields_terms_and_conditions('terms',$_,$id) ; } - $trigger_jquery .= qq~\$("#selectTerms_chosen").css( "width", "100%" );~ ; + # $trigger_jquery .= qq~\$("#selectTerms_chosen").css( "width", "100%" );~ ; - &tab_content_box($sec_name,$sec_col); + # &tab_content_box($sec_name,$sec_col); - # --------------- END NOTES ---------------------------------------------------------------------------------------------------------------- - } + # # --------------- END NOTES ---------------------------------------------------------------------------------------------------------------- + # } -if ($tab==6) { # Camera Details +if ($tab==3) { # Camera Details # --------------- START CAMERA DETAILS ---------------------------------------------------------------------------------------------------------------- @@ -1193,7 +1524,7 @@ if ($tab==6) { # Camera Details # --------------- END CAMERA DETAILS ---------------------------------------------------------------------------------------------------------------- } -if ($tab==7) { # Invoice Details +if ($tab==4) { # Invoice Details # --------------- START INVOICE DETAILS -------------------------------------------------------------------------------------------------------- @@ -1281,7 +1612,7 @@ if ($tab==7) { # Invoice Details # # --------------- END RENTAL ---------------------------------------------------------------------------------------------------------- # } -if ($tab==8) { # Document Uploads +if ($tab==5) { # Document Uploads # --------------- START DOCUMENT UPLOADS ---------------------------------------------------------------------------------------------------------------- @@ -1300,7 +1631,11 @@ if ($tab==8) { # Document Uploads $add_form_fields .= qq~
    ~ ; foreach (@docs) { + my $doc = lc $_ ; $doc =~ s/ /\_/ ; $doc =~ s/&/\_/ ; + + $db{$table}{$id}{"costing_$doc"} = "costing_$doc" . '-' . $db{$table}{$id}{"costing_$doc"} if $db{$table}{$id}{"costing_$doc"} ; + $costing_uploads = &common_get_field_uploads($id,"costing_$doc",'id') ; if ($costing_uploads) { $add_form_fields .= qq~
    $costing_uploads
    ~; @@ -1326,104 +1661,104 @@ if ($tab==8) { # Document Uploads } #------------------------------------------------------------------------------------ -sub tab_costing_select_opts { +# sub tab_costing_select_opts { -my ($table,$dispfield,$where,$sec_) = @_ ; +# my ($table,$dispfield,$where,$sec_) = @_ ; -&db_min_ro($table,'*',$where,'','') ; -my @b = ( -"_costing_additional_services", -"_costing_game_breakdown_analytics", -"_costing_hardware_add_ons", -"_costing_installation_kits", -"_costing_match_credits", -"_costing_other", -"_costing_rental", -"_costing_software_licence", -"_costing_systems" ) ; +# &db_min_ro($table,'*',$where,'','') ; +# my @b = ( +# "_costing_additional_services", +# "_costing_game_breakdown_analytics", +# "_costing_hardware_add_ons", +# "_costing_installation_kits", +# "_costing_match_credits", +# "_costing_other", +# "_costing_rental", +# "_costing_software_licence", +# "_costing_systems" ) ; -foreach my $suf (@b){ - $col_name = "item" . "$suf" ; - $cnt = 0 ; - if($db{quotes_min}{$i{id}}{$col_name}){ - foreach my $col_input (split(";", $db{quotes_min}{$i{id}}{$col_name})){ - $cnt++ ; - $saved_field{"item"}{$suf}{$cnt} = $col_input ; - # &common_debug("$aa/$suffix : $cc") ; - } - } -} +# foreach my $suf (@b){ + # $col_name = "item" . "$suf" ; + # $cnt = 0 ; + # if($db{quotes_min}{$i{id}}{$col_name}){ + # foreach my $col_input (split(";", $db{quotes_min}{$i{id}}{$col_name})){ + # $cnt++ ; + # $saved_field{"item"}{$suf}{$cnt} = $col_input ; + # # &common_debug("$aa/$suffix : $cc") ; + # } + # } +# } -foreach my $id (keys %{$db{$table}}) { - foreach (sort keys %sec_cnt) { - $_k = substr($_,1) ; $k = substr($_,2) ; - # &common_debug("tab_select_opts : $db{$table}{$id}{type} ne $k") ; - unless ($db{$table}{$id}{type} eq $k) { next ; } - my @parts = split(/\-/,$sec_cnt{$_}) ; - for my $p_ (1 .. $parts[0]) { # item_1_costing_systems - my $field = "$p_$sec_$_k" ; #my $ucf_field = ucfirst $field ; my $chosen_field = ucfirst $field . '_chosen' ; - # $opts{"item_$p_$sec_$_k"} .= qq~~ ; - my $field_2 = "$sec_$_k" ; - # my $saved_val = $db{quotes}{$i{id}}{"item_$field"} ; - my $saved_val = $saved_field{"item"}{$field_2}{$p_} ; +# foreach my $id (keys %{$db{$table}}) { + # foreach (sort keys %sec_cnt) { + # $_k = substr($_,1) ; $k = substr($_,2) ; + # # &common_debug("tab_select_opts : $db{$table}{$id}{type} ne $k") ; + # unless ($db{$table}{$id}{type} eq $k) { next ; } + # my @parts = split(/\-/,$sec_cnt{$_}) ; + # for my $p_ (1 .. $parts[0]) { # item_1_costing_systems + # my $field = "$p_$sec_$_k" ; #my $ucf_field = ucfirst $field ; my $chosen_field = ucfirst $field . '_chosen' ; + # # $opts{"item_$p_$sec_$_k"} .= qq~~ ; + # my $field_2 = "$sec_$_k" ; + # # my $saved_val = $db{quotes}{$i{id}}{"item_$field"} ; + # my $saved_val = $saved_field{"item"}{$field_2}{$p_} ; - if ($saved_val) { my @valarr = split(/\:/,$saved_val) ; $saved_val = $valarr[0] ; } + # if ($saved_val) { my @valarr = split(/\:/,$saved_val) ; $saved_val = $valarr[0] ; } - if ($saved_val eq $id) { $selected = 'SELECTED' ; } else { $selected = '' ; } + # if ($saved_val eq $id) { $selected = 'SELECTED' ; } else { $selected = '' ; } - # $opts{"item_$field"} .= qq~~ ; - $opts{"item_$field"} .= qq~~ ; + # # $opts{"item_$field"} .= qq~~ ; + # $opts{"item_$field"} .= qq~~ ; - # if ($field eq '3_costing_software_licence' or $field eq '2_costing_game_breakdown_analytics') { - if ($field eq '2_costing_systems' or $field eq '3_costing_systems' or $field eq '3_costing_software_licence' or $field eq '2_costing_game_breakdown_analytics') { - $item_type = 'input' ; - } else { - $item_type = 'select' ; - } + # # if ($field eq '3_costing_software_licence' or $field eq '2_costing_game_breakdown_analytics') { + # if ($field eq '2_costing_systems' or $field eq '3_costing_systems' or $field eq '3_costing_software_licence' or $field eq '2_costing_game_breakdown_analytics') { + # $item_type = 'input' ; + # } else { + # $item_type = 'select' ; + # } - unless ($got{$field}) { - $preferred_title{"item_$field"} = &common_min_print_field("item_$p_$_k") ; - if ($item_type eq 'select') { $trigger_jquery .= qq~\$("#selectItem_$field\_chosen").css( "width", "96%" ) -~ ; } $got{$field} = 1 ; - $trigger_jquery_raw .= qq~\$("#$item_type\Item_$field, #selectDiscount").change(function() { - calcCosting$field(1) ; - }); - ~; - $trigger_jquery_raw .= qq~\$("#inputQty_$field, #inputUsd_amnt_$field").change(function() { - calcCosting$field(0) ; - }); - ~;$trigger_jquery_raw .= qq~function calcCosting$field(b) - { - if (b==1) { \$("#inputUsd_amnt_$field").val(''); } + # unless ($got{$field}) { + # $preferred_title{"item_$field"} = &common_min_print_field("item_$p_$_k") ; + # if ($item_type eq 'select') { $trigger_jquery .= qq~\$("#selectItem_$field\_chosen").css( "width", "96%" ) +# ~ ; } $got{$field} = 1 ; + # # $trigger_jquery_raw .= qq~\$("#$item_type\Item_$field, #selectDiscount").change(function() { + # # calcCosting$field(1) ; + # # }); + # # ~; + # # $trigger_jquery_raw .= qq~\$("#inputQty_$field, #inputUsd_amnt_$field").change(function() { + # # calcCosting$field(0) ; + # # }); + # # ~;$trigger_jquery_raw .= qq~function calcCosting$field(b) + # # { + # # if (b==1) { \$("#inputUsd_amnt_$field").val(''); } - var excl = \$("#checkboxExcl_$field"); - var item = \$("#$item_type\Item_$field"); - var usd = \$("#inputUsd_amnt_$field"); - var conv = \$("#inputCurr_amnt_$field"); - var qty = \$("#inputQty_$field"); - var ttl = \$("#inputItem_ttl_$field"); - var vat = \$("#checkboxVat_$field"); + # # var excl = \$("#checkboxExcl_$field"); + # # var item = \$("#$item_type\Item_$field"); + # # var usd = \$("#inputUsd_amnt_$field"); + # # var conv = \$("#inputCurr_amnt_$field"); + # # var qty = \$("#inputQty_$field"); + # # var ttl = \$("#inputItem_ttl_$field"); + # # var vat = \$("#checkboxVat_$field"); - // console.log('DISCOUNT - item: '+item.val()+', usd: '+usd.val()) ; + # # // console.log('DISCOUNT - item: '+item.val()+', usd: '+usd.val()) ; - if (!item.val()) { - excl.prop("checked", true); - usd.val(""); - conv.val(""); - qty.val(""); - ttl.val(""); - vat.val(""); - // return ; - } + # # if (!item.val()) { + # # excl.prop("checked", true); + # # usd.val(""); + # # conv.val(""); + # # qty.val(""); + # # ttl.val(""); + # # vat.val(""); + # # // return ; + # # } - calcCosting(excl,item,qty,usd,conv,vat,ttl) ; - }~; + # # calcCosting(excl,item,qty,usd,conv,vat,ttl) ; + # # }~; - } - } - } - } -} #------------------------------------------------------------------------------------------ + # } + # } + # } + # } +# } #------------------------------------------------------------------------------------------ sub tab_camera_details_select_opts { @@ -1506,7 +1841,6 @@ $max_cams = $cnt_cams{$db{quotes}{$i{id}}{quote_nr}} if $cnt_cams{$db{quotes}{$i &common_debug("$cnt_cams{$db{quotes}{$i{id}}{quote_nr}} [max_cams = $max_cams]") ; -# print "\n cnt_sel : $cnt_sel \n" ; LOOP1: foreach my $id (sort keys %{$db{$table}}) { # &common_debug("exclude_camera_from_list [$exclude_camera_from_list{$id}] : [$table] : $id") ; @@ -1568,7 +1902,6 @@ LOOP1: foreach my $id (sort keys %{$db{$table}}) { next ; } - # print "\n $qnr eq $db{quotes}{$i{id}}{quote_nr} and $db{$table}{$id}{quote_cam_num} and $_ <= $cnt_sel , field : $field" ; # &common_debug("tab_camera_details_select_opts [$field] : [$saved_val eq $id] : $selected") ; my $display_field = $db{$table}{$id}{$dispfield} ; my ($system,$camcnt) = split(/\-/,$display_field) ; $camcnt+=0; $display_field .= " [$camcnt] [$db{$table}{$id}{serial_nr}]" ; # $display_field =~ s/-//g ; @@ -1659,130 +1992,130 @@ foreach my $id (keys %{$db{$table}}) { } #------------------------------------------------------------------------------------------ -sub tab_build_terms_headers { +# sub tab_build_terms_headers { -$add_form_fields .= qq~
    ~ ; -$add_form_fields .= qq~
    ~ ; -$add_form_fields .= qq~
    ~ ; -$add_form_fields .= qq~
    ~ ; - -} #------------------------------------------------------------------------------------ - -sub tab_build_terms_fields { - -my ($sec,$cnt,$id) = @_ ; - -my $exfield = "excl_$cnt\_$sec\s" ; -my $inpfield = "$sec\_$cnt" ; - -unless ($db{quote_notes}{1}{$inpfield}) { $checkit{$exfield} = 1 ; } - -my $val = ($db{$table}{$id}{$inpfield} && $db{$table}{$id}{$inpfield} ne "-1") ? $db{$table}{$id}{$inpfield} : (($db{$table}{$id}{$inpfield} && $db{$table}{$id}{$inpfield} eq "-1")) ? "" : $db{quote_notes}{1}{$inpfield} ; - -$note_display_style = '' ; $note_display_plus_btn = '' ; -# unless ($cnt==1 or $db{quote_notes}{1}{$inpfield}) { -unless ($cnt==1 || $val) { - $note_display_style = qq~style='display:none;'~ ; - $trigger_jquery_raw .= qq~ \$("#btn_$cnt\_$sec").click(function () { - \$("#$cnt\_$sec").toggle(); - \$("#btn_$cnt\_$sec").hide(); - var v = $cnt + 1 ; - \$("#btn_"+v+"\_$sec").show(); - });~ ; - if ($cnt>$cntnoteloop) { $note_display_butt = qq~display:none;~ ; } else { $note_display_butt = '' ; } - $note_display_plus_btn = qq~~; -} else { $cntnoteloop++ ; } - -$add_form_fields .= qq~
    ~ ; - # $add_form_fields .= qq~
    ~ ; -# if ($checkit{$exfield} == 1) { $checked = 'CHECKED'; } elsif (($excl_tick{$cnt}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } - -# if ($db{$table}{$id}{$exfield} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } -$sec = "_" . $sec . "s" ; -$col_name = "excl" . "$sec" ; -$counter = 0 ; -# &db_min_ro('quotes_min', "id, excl$sec", "id = $id", '', '') ; - -foreach my $col_input (split(/\;/,$db{quotes_min}{$id}{$col_name})) { - $counter++ ; - $saved_field{"excl"}{$sec}{$counter} = $col_input ; -} - -if ($saved_field{"excl"}{$sec}{$cnt}) { $checked = 'CHECKED'; } else { $checked = '' ; } - -$label{$exfield} = 1 ; -$fcol=1 ; -$add_form_fields .= &common_min_form_checkbox_col($exfield,$checkit{$exfield},$checked) ; -$fcol=6 ; -$input_style{$inpfield} = qq~style='margin-bottom:4px;margin-top:-2px;'~ ; # add spaces between boxes -$add_form_fields .= &common_min_form_input_col($inpfield,$val,'') ; -$add_form_fields .= qq~
    ~ ; -$add_form_fields .= qq~
    $note_display_plus_btn
    ~ ; - -} #------------------------------------------------------------------------------------ - -sub tab_build_terms_fields_terms_and_conditions { +# $add_form_fields .= qq~
    ~ ; +# $add_form_fields .= qq~
    ~ ; +# $add_form_fields .= qq~
    ~ ; - my ($sec,$cnt,$id) = @_ ; +# } #------------------------------------------------------------------------------------ - my $exfield = "excl_$cnt\_$sec" ; - my $inpfield = "$sec" ; - my $quote_notes_field = "$sec\_$cnt" ; +# sub tab_build_terms_fields { + +# my ($sec,$cnt,$id) = @_ ; - unless ($db{$table}{$id}{$inpfield}) { $checkit{$exfield} = 1 ; } +# my $exfield = "excl_$cnt\_$sec\s" ; +# my $inpfield = "$sec\_$cnt" ; - if ($db{$table}{$id}{$inpfield}) { $selected{$db{$table}{$id}{$inpfield}} = 'SELECTED';} +# unless ($db{quote_notes}{1}{$inpfield}) { $checkit{$exfield} = 1 ; } - $note_display_style = '' ; - unless ($cnt==1 or $db{$table}{$id}{$inpfield}) { - $note_display_style = qq~style='display:none;'~ ; - $trigger_jquery_raw .= qq~ \$("#btn_$cnt\_$sec").click(function () { - \$("#$cnt\_$sec").toggle(); - \$("#btn_$cnt\_$sec").hide(); - var v = $cnt + 1 ; - \$("#btn_"+v+"\_$sec").show(); - });~ ; - if ($cnt>$cntnoteloop) { $note_display_butt = qq~display:none;~ ; } else { $note_display_butt = '' ; } - } else { $cntnoteloop++ ; } +# my $val = ($db{$table}{$id}{$inpfield} && $db{$table}{$id}{$inpfield} ne "-1") ? $db{$table}{$id}{$inpfield} : (($db{$table}{$id}{$inpfield} && $db{$table}{$id}{$inpfield} eq "-1")) ? "" : $db{quote_notes}{1}{$inpfield} ; - $add_form_fields .= qq~
    ~ ; +# $note_display_style = '' ; $note_display_plus_btn = '' ; +# # unless ($cnt==1 or $db{quote_notes}{1}{$inpfield}) { +# unless ($cnt==1 || $val) { + # $note_display_style = qq~style='display:none;'~ ; + # $trigger_jquery_raw .= qq~ \$("#btn_$cnt\_$sec").click(function () { + # \$("#$cnt\_$sec").toggle(); + # \$("#btn_$cnt\_$sec").hide(); + # var v = $cnt + 1 ; + # \$("#btn_"+v+"\_$sec").show(); + # });~ ; + # if ($cnt>$cntnoteloop) { $note_display_butt = qq~display:none;~ ; } else { $note_display_butt = '' ; } + # $note_display_plus_btn = qq~~; +# } else { $cntnoteloop++ ; } + +# $add_form_fields .= qq~
    ~ ; + +# # $add_form_fields .= qq~
    ~ ; +# # if ($checkit{$exfield} == 1) { $checked = 'CHECKED'; } elsif (($excl_tick{$cnt}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } + +# # if ($db{$table}{$id}{$exfield} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } +# $sec = "_" . $sec . "s" ; +# $col_name = "excl" . "$sec" ; +# $counter = 0 ; +# # &db_min_ro('quotes_min', "id, excl$sec", "id = $id", '', '') ; + +# foreach my $col_input (split(/\;/,$db{quotes_min}{$id}{$col_name})) { + # $counter++ ; + # $saved_field{"excl"}{$sec}{$counter} = $col_input ; +# } + +# if ($saved_field{"excl"}{$sec}{$cnt}) { $checked = 'CHECKED'; } else { $checked = '' ; } + +# $label{$exfield} = 1 ; +# $fcol=1 ; +# $add_form_fields .= &common_min_form_checkbox_col($exfield,$checkit{$exfield},$checked) ; +# $fcol=6 ; +# $input_style{$inpfield} = qq~style='margin-bottom:4px;margin-top:-2px;'~ ; # add spaces between boxes +# $add_form_fields .= &common_min_form_input_col($inpfield,$val,'') ; +# $add_form_fields .= qq~
    ~ ; +# $add_form_fields .= qq~
    $note_display_plus_btn
    ~ ; + +# } #------------------------------------------------------------------------------------ + +# sub tab_build_terms_fields_terms_and_conditions { + + # my ($sec,$cnt,$id) = @_ ; + + # my $exfield = "excl_$cnt\_$sec" ; + # my $inpfield = "$sec" ; + # my $quote_notes_field = "$sec\_$cnt" ; + + # unless ($db{$table}{$id}{$inpfield}) { $checkit{$exfield} = 1 ; } + + # if ($db{$table}{$id}{$inpfield}) { $selected{$db{$table}{$id}{$inpfield}} = 'SELECTED';} + + # $note_display_style = '' ; + # unless ($cnt==1 or $db{$table}{$id}{$inpfield}) { + # $note_display_style = qq~style='display:none;'~ ; + # $trigger_jquery_raw .= qq~ \$("#btn_$cnt\_$sec").click(function () { + # \$("#$cnt\_$sec").toggle(); + # \$("#btn_$cnt\_$sec").hide(); + # var v = $cnt + 1 ; + # \$("#btn_"+v+"\_$sec").show(); + # });~ ; + # if ($cnt>$cntnoteloop) { $note_display_butt = qq~display:none;~ ; } else { $note_display_butt = '' ; } + # } else { $cntnoteloop++ ; } + + # $add_form_fields .= qq~
    ~ ; - # $add_form_fields .= qq~
    ~ ; - # if ($checkit{$exfield} == 1) { $checked = 'CHECKED'; } elsif (($excl_tick{$cnt}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } - $sec_2 = "_" . $sec ; - $col_name = "excl" . "$sec_2" ; - $counter = 0 ; - # &db_min_ro('quotes_min', "id, excl$sec", "id = $id", '', '') ; + # # $add_form_fields .= qq~
    ~ ; + # # if ($checkit{$exfield} == 1) { $checked = 'CHECKED'; } elsif (($excl_tick{$cnt}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } + # $sec_2 = "_" . $sec ; + # $col_name = "excl" . "$sec_2" ; + # $counter = 0 ; + # # &db_min_ro('quotes_min', "id, excl$sec", "id = $id", '', '') ; - foreach my $col_input (split(";", $db{quotes_min}{$id}{$col_name})){ - $counter++ ; - $saved_field{"excl"}{$sec_2}{$counter} = $col_input ; - } + # foreach my $col_input (split(";", $db{quotes_min}{$id}{$col_name})){ + # $counter++ ; + # $saved_field{"excl"}{$sec_2}{$counter} = $col_input ; + # } - if ($saved_field{"excl"}{$sec_2}{$cnt}) { $checked = 'CHECKED'; } else { $checked = ''; } + # if ($saved_field{"excl"}{$sec_2}{$cnt}) { $checked = 'CHECKED'; } else { $checked = ''; } - # if ($db{$table}{$id}{$exfield} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } + # # if ($db{$table}{$id}{$exfield} == 1) { $checked = 'CHECKED'; } else { $checked = ''; } - $label{$exfield} = 1 ; - $fcol=1 ; - $add_form_fields .= &common_min_form_checkbox_col($exfield,$checkit{$exfield},$checked) ; - $fcol=6 ; - $input_style{$inpfield} = qq~style='margin-bottom:4px;margin-top:-2px;'~ ; # add spaces between boxes - $opts{$inpfield} = "" ; - for (1 .. 5){ - $quote_notes_field = "$sec\_$_" ; - next unless $db{quote_notes}{1}{$quote_notes_field} ; - $opts{$inpfield} .= qq() ; - } - $allow_deselect{$inpfield} = 1; - $add_form_fields .= &common_min_form_select_col($inpfield,$db{$table}{$id}{$inpfield},'') ; - $add_form_fields .= qq~
    ~ ; - $add_form_fields .= qq~
    $note_display_plus_btn
    ~ ; + # $label{$exfield} = 1 ; + # $fcol=1 ; + # $add_form_fields .= &common_min_form_checkbox_col($exfield,$checkit{$exfield},$checked) ; + # $fcol=6 ; + # $input_style{$inpfield} = qq~style='margin-bottom:4px;margin-top:-2px;'~ ; # add spaces between boxes + # $opts{$inpfield} = "" ; + # for (1 .. 5){ + # $quote_notes_field = "$sec\_$_" ; + # next unless $db{quote_notes}{1}{$quote_notes_field} ; + # $opts{$inpfield} .= qq() ; + # } + # $allow_deselect{$inpfield} = 1; + # $add_form_fields .= &common_min_form_select_col($inpfield,$db{$table}{$id}{$inpfield},'') ; + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    $note_display_plus_btn
    ~ ; -} #------------------------------------------------------------------------------------ +# } #------------------------------------------------------------------------------------ sub tab_build_qt_right { @@ -1815,7 +2148,7 @@ if ($tab==1) { # Cusotmer Details # --------------- END CUSOTMER DETAILS ---------------------------------------------------------------------------------------------------------- } -if ($tab==7) { # Cusotmer Details +if ($tab==4) { # Cusotmer Details # --------------- START CUSOTMER DETAILS -------------------------------------------------------------------------------------------------------- @@ -1867,11 +2200,11 @@ my $style_vat = '' ; if ($no_vat{$sec}) { $style_vat = 'style="display:none;"' ; $add_form_fields .= qq~
    ~ ; $add_form_fields .= qq~
    ~ ; -$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; $add_form_fields .= qq~
    ~ ; -$add_form_fields .= qq~
    ~ ; +$add_form_fields .= qq~
    ~ ; # $add_form_fields .= qq~
    ~ ; -$add_form_fields .= qq~
    ~ ; +# $add_form_fields .= qq~
    ~ ; $add_form_fields .= qq~
    ~ ; $add_form_fields .= qq~
    ~ ; $add_form_fields .= qq~
    ~ ; @@ -1901,9 +2234,10 @@ $cntxt{2} = 'two' ; $cntxt{3} = 'three' ; $cntxt{4} = 'four' ; $cntxt{5} = 'five' ; -$cntxt{6} = 'six' ; -$cntxt{7} = 'seven' ; -$cntxt{8} = 'eight' ; + +# $cntxt{6} = 'six' ; +# $cntxt{7} = 'seven' ; +# $cntxt{9} = 'nine' ; # $cntxt{9} = 'nine' ; } #---------------------------------------------------------------------------------------- @@ -1916,14 +2250,11 @@ my $tabname = '' ; if ($tab==1) { $tabname = 'Quote Details' ; } elsif ($tab==2) { $tabname = 'Costing' ; } -elsif ($tab==3) { $tabname = 'Costing Other' ; } -elsif ($tab==4) { $tabname = 'Purchase Summary' ; } -elsif ($tab==5) { $tabname = 'Notes' ; } -elsif ($tab==6) { $tabname = 'Camera Details' ; } -elsif ($tab==7) { $tabname = 'Invoice Details' ; } +elsif ($tab==3) { $tabname = 'Camera Details' ; } +elsif ($tab==4) { $tabname = 'Invoice Details' ; } # elsif ($tab==7) { $tabname = 'Extended Warranty' ; } # elsif ($tab==8) { $tabname = 'Rental' ; } -elsif ($tab==8) { $tabname = 'Document Uploads' ; } +elsif ($tab==5) { $tabname = 'Document Uploads' ; } return ($tabname) ; diff --git a/scripts/_FromProd/XXX-monitoring_report.pl b/scripts/_FromProd/XXX-monitoring_report.pl new file mode 100644 index 0000000..f6ba8aa --- /dev/null +++ b/scripts/_FromProd/XXX-monitoring_report.pl @@ -0,0 +1,746 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +# unless ($useropts{it}{$username}) { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; +use Time::Piece ; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $no_dates_in_table = 1 ; + +# our $debug = 1 ; +# our $testing = 1 ; + +# if ($username ne 'handre') { + # print "print "<< MAINTENANCE IN PROGRESS >>" ; exit ; +# } + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $srchscr = 1 ; + +if ($iaction eq 'save') { + &db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &common_min_load_params ; + &report_ifields ; + &update ; + &list_screen ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + # exit if $username eq 'handre' && $testing ; + &screen3 ; + # &redirect_screen; +} + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + &report_screen if $iaction eq '' ; + + if ($iaction eq 'report') { + &common_min_load_params ; + &report_ifields ; + &list_screen ; + &screen3 ; + } + + &common_min_action ; + + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub hidden_fields { + + # $ignore{id} = 1 ; + $ignore{iaction} = 1 ; + $ignore{date} = 1 ; + $ignore{monitor_id} = 1 ; + for my $d_cnt (1 .. $date_counter) { + for my $shift_cnt (1 .. 4) { + $ignore{"shiftmonitorid_$shift_cnt\_$d_cnt"} = 1 ; + $ignore{"shift_monitor_$shift_cnt\_$d_cnt"} = 1 ; + } + } + # $ignore{monitor_ids} = 1 ; + $ignore{update_table_1} = 1 ; + $ignore{update} = 1 ; + $ignore{"itv-table_length"} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + &schedule_update("shift_operator_ids","monitor_ids","shiftmonitorid","monitor_notes") ; +# 12=f:;s:|s:1;t:1|f:2;s:2-13=|f:3;s:3|f:4;s:4 + + &schedule_update_monitor_reports ; + + # my @table_sql_where = () ; + + # if ($i{client_id}) { + # push @table_sql_where, "`quote_to`='$i{client_id}'" ; + # } + # if ($i{date_from} && $i{date_to}) { # check dates + # push @table_sql_where, "(('$i{date_from} 00:00:00' <= `date_from` AND `date_from` <= '$i{date_to} 23:59:59') OR ('$i{date_from} 00:00:00' <= `date_to` AND `date_to` <= '$i{date_to} 23:59:59') OR (`date_from` <= '$i{date_from} 00:00:00' AND '$i{date_to} 23:59:59' <= `date_to`))" ; ############################################### > OR >= + + # } + + # # if ($i{monitor_id} and $i{monitor_id} ne 'all') { + # # push @table_sql_where,"`MONITOR` = '$db{users}{1}{name}'" ; + # # } + + # my $table_sql_where_str = join(" AND ",@table_sql_where) ; + + # &db_min_ro($table,"id,monitor_report_saved_data","$table_sql_where_str",'','') ; + + # my %saved_field_hash = () ; + + # foreach my $id (keys %{$db{$table}}) { + + # # my @saved_data_split_1 = split(/\-/,$db{$table}{$id}{monitor_report_saved_data}) ; + # my @saved_data_split_1 = split /-(?=\d+=(?:blank\||f:\d+|s:\d+|c:))/, $db{$table}{$id}{monitor_report_saved_data}; + + # foreach my $a (@saved_data_split_1) { + + # # my @saved_data_split_2 = split(/\=/,$a) ; + + # my @saved_data_split_2 = () ; + # if ($a =~ /^(\d+|none)=(.*)$/) { + # @saved_data_split_2 = ($1, $2); + # } else { + # @saved_data_split_2 = ($a); + # } + + # my $event_sys_id = $saved_data_split_2[0] ; + # # my @saved_data_split_3 = split(/\|/,$saved_data_split_2[1]) ; + # # my @saved_data_split_3 = split /\|(?=(?:blank\|f:\d+|blank\|s:\d+|blank\|c:|f:\d+|s:\d+|c:))/, $saved_data_split_2[1]; + + # my @saved_data_split_3 = split( + # /\| + # (?= # Look ahead for allowed patterns + # # blank$ # 1) blank + end + # blank\|s:\d+ # 2) blank|s: + # | blank\|f:\d+ # 3) blank|f: + # | blank\|c: # 4) blank|c: + # | f:\d+ # 5) f: + # | s:\d+ # 6) s: + # | c: # 7) c: + # | blank\|blank\| # 8) blank|s: + # ) + # /x, + # $saved_data_split_2[1] + # ); + + + # my $day_cnt = 0 ; + # foreach my $b (@saved_data_split_3) { + # $day_cnt++ ; + # next if !$b || $b eq 'blank' ; + # $b =~ s/\|/\pipe_in_comment_to_be_removed/g ; + # $saved_field_hash{$id}{$event_sys_id}{$day_cnt} = $b ; + # } + # } + # } + + # foreach my $field_name (keys %i) { + + # next if ($field_name =~ /update_event/ && !$i{$field_name}) || $field_name !~ /update_event/ ; + + # my @fields = split(/\_/,$field_name) ; + + # my $system_id = substr($fields[-3],5) ; + # my $day_cnt = $fields[-2] ; + # my $event_id = $fields[-1] ; + + # my $fixture_field = "fixture_check_event$system_id\_$day_cnt\_$event_id" ; + # my $status_field = "status_event$system_id\_$day_cnt\_$event_id" ; + # my $comments_field = "comments_event$system_id\_$day_cnt\_$event_id" ; + + # $saved_field_hash{$event_id}{$system_id}{$day_cnt} = qq~~ ; + # $saved_field_hash{$event_id}{$system_id}{$day_cnt} = ($i{$fixture_field}) ? qq~f:$i{$fixture_field};~ : qq~~ ; + # $saved_field_hash{$event_id}{$system_id}{$day_cnt} .= ($i{$status_field}) ? qq~s:$i{$status_field};~ : qq~~ ; + # $saved_field_hash{$event_id}{$system_id}{$day_cnt} =~ s/;+$//g unless $i{$comments_field} ; + # $i{$comments_field} =~ s/\|/\pipe_in_comment_to_be_removed/g ; + # $saved_field_hash{$event_id}{$system_id}{$day_cnt} .= qq~c:$i{$comments_field}~ if $i{$comments_field} ; + + # } + + # %ii = %i ; + # %i = () ; + + # foreach my $event_id (keys %saved_field_hash) { + + # $i{monitor_report_saved_data} = qq~~ ; + + # foreach my $system_id (sort { $a <=> $b } keys %{$saved_field_hash{$event_id}}) { + + # # $i{monitor_report_saved_data} .= qq~$system_id\=~ ; + # my $saved_by_system = qq~~ ; + + # foreach my $day_max (sort { $b <=> $a } keys %{$saved_field_hash{$event_id}{$system_id}}) { + + # for my $day_cnt (1 .. $day_max) { + # # $saved_field_hash{$event_id}{$system_id}{$day_cnt} =~ s/;+$//g ; + # $saved_by_system .= qq~$saved_field_hash{$event_id}{$system_id}{$day_cnt}|~ ; + # } + # # chop $saved_by_system if $day_max ; + # $saved_by_system =~ s/\|+$//g ; + # last ; + # } + + # if ($saved_by_system =~ /\||/) { + # $saved_by_system =~ s/\|(?=\|)/|blank/g ; + # } + + # if ($saved_by_system =~ /^\|/) { + # $saved_by_system =~ s/^\|/blank|/g ; + # } + + # # if ($saved_by_system =~ /\|$/) { + # # $saved_by_system =~ s/\|$/|blank/; + # # } + + # $saved_by_system =~ s/pipe_in_comment_to_be_removed/\|/g ; + + # $i{monitor_report_saved_data} .= qq~$system_id\=$saved_by_system\-~ if $saved_by_system ; + # } + + # chop $i{monitor_report_saved_data} if $i{monitor_report_saved_data} ; + + # next if ($i{monitor_report_saved_data} eq $db{$table}{$event_id}{monitor_report_saved_data}) || (!$i{monitor_report_saved_data} && !$db{$table}{$event_id}{monitor_report_saved_data}) ; + + # &db_min_upd($table,"id='$event_id'") ; + + # } + + # %i = %ii ; + +} #------------------------------------------------------------------------------------------ + +sub report_ifields { + + &load_search_vars ; + + # if ($i{date}) { # check dates + # push @report_sql, " `date_from` <= '$i{date} 23:59:59' AND '$i{date} 00:00:00' <= `date_to` " ; + # push @report_results, "DATE IS '$i{date}'" ; + # } else { + # $error = qq~PLEASE ENTER A DATE!~ ; + # &report_screen; + # } + + if ($i{client_id}) { + push @report_sql, "`quote_to`='$i{client_id}'" ; + &db_min_ro('customers','id,name',"`id`='$i{client_id}'") ; + push @report_results,"`CLIENT` = '$db{customers}{$i{client_id}}{name}'" ; + } + + my $date_from_val = $i{date_from} ; my $date_to_val = $i{date_to} ; + + $date_from_val =~ s/\-//g ; $date_to_val =~ s/\-//g ; + + if ($i{date_from} && $i{date_to} && $date_from_val > $date_to_val) { + $error = qq~THE START MUST BE BEFORE THE END DATE!!!~ ; + &report_screen; + } elsif ($i{date_from} && $i{date_to}) { # check dates + push @report_sql, "(('$i{date_from} 00:00:00' <= `date_from` AND `date_from` <= '$i{date_to} 23:59:59') OR ('$i{date_from} 00:00:00' <= `date_to` AND `date_to` <= '$i{date_to} 23:59:59') OR (`date_from` <= '$i{date_from} 00:00:00' AND '$i{date_to} 23:59:59' <= `date_to`))" ; ############################################### > OR >= + push @report_results, "(EVENT BETWEEN '$i{date_from}' AND '$i{date_to}')" ; + } else { + $error = qq~PLEASE ENTER A START AND END DATE!!!~ ; + &report_screen; + } + + if ($i{monitor_id} and $i{monitor_id} ne 'all') { + push @report_results,"`MONITOR` = '$db{users}{1}{name}'" ; + push @report_sql, " `monitor_ids` LIKE '%$i{monitor_id}%' " ; + } elsif ($i{monitor_id} and $i{monitor_id} eq 'all') { + push @report_results,"`MONITORS` = 'ALL'" ; + } else { + # push @report_sql, "(`user_id` = '')" ; + } + + $report_results_msg = uc join(', ', @report_results) ; + + if ($iaction eq 'save') { + $isaved = qq(SUCCESSFULLY SAVED!) ; + } elsif (not $report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); + &report_screen; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + + our $srch_where_sql = join(' AND ',@report_sql) ; + + my @date = split(/ /,$i{date}) ; + + my ($year_inp,$month_inp,$day_inp) = split(/\-/,$date[0]) ; + + our $date_inp_val = int("$year_inp$month_inp$day_inp") ; + our $today_val = int("$now_year$now_mm$now_dd") ; + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + if ($i{monitor_id} and $i{monitor_id} ne 'all') { + &db_min_ro('users','1,name',"`id` = '$i{monitor_id}'",'','') ; + } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + $print_box_content_rows .= &common_min_forms_start("$lcpage") ; + + our $monitoring_report = 1 ; + + our $extra_column = ",monitor_report_saved_data" ; + + &schedule_load_list_vars("$srch_where_sql") ; + + $fcol = 12 ; + + my $report = 1 ; + + our $xlsxdir = "monitoring_report" ; + + our $xlsxreportname = "Monitor_Allocations" ; + + my $date = &common_write_date_interval($i{date_from},$i{date_to}) ; + + our $xlsx_title_heading = "Monitor Allocations $date" ; + + my $field_name = "shift_monitor" ; + my $uc_field_name = ucfirst $field_name ; + + our $print_tbody_extra = qq~~ ; + + # our @sql_col_display_extra = ("date","shift_1_(07:00-10:00)","shift_2_(10:00-13:00)","shift_3_(13:00-16:00)","shift_4_(16:00-19:00)") ; + our @sql_col_display_extra = ("date","shift_1_(08:00-11:00)","shift_2_(11:00-14:00)","shift_3_(14:00-17:00)","shift_4_(17:00-21:00)","notes") ; + push @sql_col_display_extra,"update" ; + # if $date_inp_val >= $today_val ; + + our @sql_col_display = ("count","event","date","day","start_date","start_time","end_time","region","sport","system","club_name","operator","fixture_check","status","comments") ; + + # push @sql_col_display,"update" if ($monitoring_report || $temp_calibrator_report) && $date_inp_val >= $today_val ; + + &report_xlsx_export_header("$xlsxreportname",$xlsxdir,'',$xlsx_title_heading) ; + + &schedule_build_extra_table("shift_monitor","shift_operator_ids","monitor_ids","monitor_notes","select_monitors") ; + + # &common_min_table_update_checkbox_col("3") ; + + push @sql_col_display,"update" ; + + my $table_col_name = "monitor_ids" ; + + $xlsxrow-- ; + + my @rev_sql_col_display = reverse @sql_col_display ; + + foreach (@rev_sql_col_display) { $lastchild++ ; $last_child{$_} = $lastchild ; } + + &schedule_get_monitor_reports_default_values ; + + # our %default_values = () ; + # # 12=f:;s:|s:1;t:1|f:2;s:2-13=|f:3;s:3|f:4;s:4 + # foreach my $id (keys %{$db{$table}}) { + + # # $db{$table}{$id}{monitor_report_saved_data} = "12=f:1;s:1|s:1;t:1|f:2;s:2;c:1|-23-123=f2-13=blank|f:3;s:3|f:4;s:4-133=blank|blank|f:3;s:3|f:4;s:4-1232=c:as" ; + + # # next if $id eq '5136' ; + + # # my @saved_data_split_1 = split /\-(?=\d+=[\f:\d+|\s:\d+|\c:|blank\|])/x, $db{$table}{$id}{monitor_report_saved_data}; + # my @saved_data_split_1 = split /-(?=\d+=(?:blank\||f:\d+|s:\d+|c:))/, $db{$table}{$id}{monitor_report_saved_data}; ## split on "-" if and only if it it is followed by an integer = blank or f:integer or s:integer or c: + + # foreach my $a (@saved_data_split_1) { + + # # my @saved_data_split_2 = split /(?<=^(\d+))=/, $a; + # my @saved_data_split_2 = () ; + + # if ($a =~ /^(\d+|none)=(.*)$/) { + # @saved_data_split_2 = ($1, $2); + # } else { + # @saved_data_split_2 = ($a); + # } + + # # my @saved_data_split_2 = split(/(?<=^\d+)=/,$a) ; + + # my $event_sys_id = $saved_data_split_2[0] ; + # # my $remaining_data = join(";", @saved_data_split_3[3 .. $#saved_data_split_3]) ; + # # my @saved_data_split_3 = split(/\|/,$saved_data_split_2[1]) ; + # # my @saved_data_split_3 = split /(?<=^(?:f:(\d+)|s:(\d+)|f:|s:|c:|blank))\|(?=(?:f:|s:|c:|blank))/x, $saved_data_split_2[1]; + + # my @saved_data_split_3 = () ; + + # # while ($saved_data_split_2[1] =~ /\G((?:f:(\d+)|s:(\d+)|f:|s:|c:|blank)?)\|(?=(?:f:|s:|c:|blank|$))/xg) { + # # push @saved_data_split_3, $1; + # # } + + # # my $final_element = $saved_data_split_2[1] ; + + # # foreach (@saved_data_split_3) { + # # $final_element =~ s/^$_\|//g ; + # # } + + # # push @saved_data_split_3, $final_element ; + + # # $saved_data_split_2[1] = "blank|s:3|s:3|s:3|blank|blank" ; + + # # my @saved_data_split_3 = split(/\|(?=(?:+$|blank\|+$|blank\|blank|blank\|f:\d+|blank\|s:\d+|blank\|c:|f:\d+|s:\d+|c:))/, "$saved_data_split_2[1]") ; + # my @saved_data_split_3 = split( + # /\| + # (?= # Look ahead for allowed patterns + # # blank$ # 1) blank + end + # blank\|s:\d+ # 2) blank|s: + # | blank\|f:\d+ # 3) blank|f: + # | blank\|c: # 4) blank|c: + # | f:\d+ # 5) f: + # | s:\d+ # 6) s: + # | c: # 7) c: + # | blank\|blank\| # 8) blank|s: + # ) + # /x, + # $saved_data_split_2[1] + # ); + + # my $day_cnt = 0 ; + # foreach my $b (@saved_data_split_3) { + # $day_cnt++ ; + + # next if !$b || $b eq 'blank' ; + + # # $b =~ s/\;+$//g ; + + # my @saved_data_split_3 = split(/\;/,$b) ; + # my @saved_data_split_4 = ($saved_data_split_3[0]) ? split(/\:/,$saved_data_split_3[0]) : () ; + # my @saved_data_split_5 = ($saved_data_split_3[1]) ? split(/\:/,$saved_data_split_3[1]) : () ; + # my @saved_data_split_6 = ($saved_data_split_3[2]) ? split(/\:/,$saved_data_split_3[2]) : () ; + + # if ($saved_data_split_3[0] =~ /^f:\d+/) { + # $default_values{$sql_col_display[-4]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_4[1] ; + # } + + # if ($saved_data_split_3[0] =~ /^s:\d+/) { + # $default_values{$sql_col_display[-3]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_4[1] ; + # } elsif ($saved_data_split_3[1] =~ /^s:\d+/ && $saved_data_split_3[0] =~ /^f:\d+/) { + # $default_values{$sql_col_display[-3]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_5[1] ; + # } + + # my $comments_after_semicolon = "" ; ## In case the comments contain a ; when we split on ; + + # if ($saved_data_split_3[0] =~ /^c:/) { + # $comments_after_semicolon = join(";", @saved_data_split_3[1 .. $#saved_data_split_3]) ; + # $default_values{$sql_col_display[-2]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_4[1] . join(":", @saved_data_split_4[2 .. $#saved_data_split_4]) ; + # } elsif ($saved_data_split_3[1] =~ /^c:/ && ($saved_data_split_3[0] =~ /^f:\d+/ || $saved_data_split_3[0] =~ /^s:\d+/)) { + # $comments_after_semicolon = join(";", @saved_data_split_3[2 .. $#saved_data_split_3]) ; + # $default_values{$sql_col_display[-2]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_5[1] . join(":", @saved_data_split_5[2 .. $#saved_data_split_5]) ; + # } elsif ($saved_data_split_3[2] =~ /^c:/ && $saved_data_split_3[1] =~ /^s:\d+/ && $saved_data_split_3[0] =~ /^f:\d+/) { + # $comments_after_semicolon = join(";", @saved_data_split_3[3 .. $#saved_data_split_3]) ; + # $default_values{$sql_col_display[-2]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_6[1] . join(":", @saved_data_split_6[2 .. $#saved_data_split_6]) ; + # } + + # $default_values{$sql_col_display[-2]}{$event_sys_id}{$day_cnt}{$id} .= ";$comments_after_semicolon" if $comments_after_semicolon || $b =~ /c:;+$/ ; + + # } + # } + # } + + &common_min_select_opts("status","monitor_status","status") ; + + our @default_javascript_by_id_2 = () ; + + &schedule_build_table("monitor_ids") ; + + # if ($date_inp_val >= $today_val) { + # $trigger_jquery_raw .= qq~ + # \$("#itv-table tr th:nth-last-child(5)").css("width","10%") ; + # \$("#itv-table tr th:nth-last-child(4)").css("width","10%") ; + # \$("#itv-table tr th:nth-last-child(3)").css("width","10%") ; + # \$("#itv-table tr th:nth-last-child(2)").css("width","10%") ; + # ~ ; + + # } else { + # $trigger_jquery_raw .= qq~ + # \$("#select_monitors tr th:nth-last-child(1)").css("width","23%") ; + # \$("#select_monitors tr th:nth-last-child(4)").css("width","23%") ; + # \$("#select_monitors tr th:nth-last-child(3)").css("width","23%") ; + # \$("#select_monitors tr th:nth-last-child(2)").css("width","23%") ; + # ~ ; + # } + + # &calibration_build_table_and_or_excel(1) ; + + # if ($found_after_date) { + + + + # } else { + # $trigger_jquery_raw .= qq~ + # \$("#itv-table tr th:nth-last-child(2)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(3)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(4)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(5)").css("width", "7.5%") ; + + # ~ ; + # } + + + # my $first_table_multi_select_table_cells_str = join(",",@first_table_multi_select_table_cells) ; + + # &common_min_table_select_fixed_width_jquery($first_table_multi_select_table_cells_str ) ; + + # &common_min_table_select_default_values_jquery ; + + # &common_min_table_update_checkbox_col("3") ; + + + my $first_table_multi_select_table_cells_str = join(",",@first_table_multi_select_table_cells) ; + # $useropts{table_id} + &common_min_table_select_fixed_width_jquery($first_table_multi_select_table_cells_str) ; + + &common_min_table_select_prevent_dropdown_overlap_jquery ; + + &common_min_table_select_default_values_jquery ; + + &common_min_table_update_checkbox_col("3","content","[id^='textareaComments_'],[id^='selectFixture_check_'],[id^='selectStatus_'],[id^='selectShift_monitor_1_'],[id^='selectShift_monitor_2_'],[id^='selectShift_monitor_3_'],[id^='selectShift_monitor_4_'],[id^='textareaShift_monitor_notes_1_'],[id^='textareaShift_monitor_notes_2_'],[id^='textareaShift_monitor_notes_3_'],[id^='textareaShift_monitor_notes_4_']") ; + + # my $default_javascript_by_id_str = join (",",@default_javascript_by_id) ; + + # $trigger_jquery_raw .= qq~ + + # all_def_vals = {$default_javascript_by_id_str} ; + + # \$("#$useropts{table_id}").on("change","[id^='selectFixture_check_'],[id^='selectStatus_']", function (event) { + # event.preventDefault(); + # console.log("2 update : "+this.id) ; + # check_whether_to_update(this.id); + # }); + + # ~ ; + + # &common_min_table_update_checkbox_col("3") ; + + $fnsortorder = 'asc' ; + + &common_min_extra_crumb("$lcpage","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + # &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + # our $lcpage = 'monitor-allocations' ; + our $lcpage = 'monitoring-report' ; + + &common_page_name ; + + our $table = 'event_quotes' ; + $page_title = 'Monitor Allocations' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + &common_min_select_opts('client_id','customers','name','','','',"events='1'") ; + + $allow_deselect{client_id} = 1 ; + $opts{client_id} =~ s/value="$i{client_id}"/value="$i{client_id}" SELECTED/g if $i{client_id} ; + $print_box_content_rows .= &common_min_form_select('client_id','') ; + + my ($sql_next_day) = &common_add_delta_days(1) ; + my ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-$now_mm-$now_dd") ; #unless $i{date_from} ; + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$next_year-$next_month-$next_day") ; #unless $i{date_from} ; + + push @date_value_ids,"input[name='date_from']" ; + push @date_value_ids,"input[name='date_to']" ; + + &common_min_table_validate_date_inputs_jquery ; + + $preferred_title{monitor_id} = "Monitor" ; + + # &db_min_ro('users',"id,name","`user_type` = 'support' OR `user_type` = 'casual_calibrator'",'','') ; + # &db_min_ro('users',"id,name,username","`name` NOT LIKE 'Rory%'",'','') ; + + $selected{monitor_id}{all} = 'SELECTED' ; + + # if ($i{monitor_id}) { + # $selected{monitor_id}{$i{monitor_id}} = 'SELECTED' ; + # $selected{monitor_id}{all} = '' ; + # } + + # foreach (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + # next if $useropts{it}{$db{users}{$_}{username}} ; + # $opts{monitor_id} .= qq~~ ; + # } + $opts{monitor_id} .= qq~~ ; + + $print_box_content_rows .= &common_min_form_select('monitor_id','') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# my $page = "$lcpage\s" ; + +my $page = "event-quotes" ; + +if ($s{no}) { $page = $lcpage ; } + +# &db_min_ro('daily_monitor_ids','date,monitor_ids') ; + +my @sql_col_display_2 = @sql_col_display ; + +@sql_col_display = @sql_col_display_extra ; + +our %custom_column_styles = () ; + +$custom_column_styles{fixture_check} = qq~style="width:7%;min-width:150px;"~ ; +$custom_column_styles{status} = qq~style="width:7%;min-width:150px;"~ ; +$custom_column_styles{comments} = qq~style="width:7%;min-width:150px;"~ ; + +&common_min_thead ; + +$print_box_content_rows .= qq~ + + $print_thead + + + $print_tbody_extra + + +
    ~ ; + +@sql_col_display = @sql_col_display_2 ; + +&common_min_thead ; + +&common_min_table('id',$page,'list') ; + +our $savjqy = 1 ; + +$extra_form_fields .= qq~ + + + + + +~; + +for (1 .. $date_cnt) { + + $extra_form_fields .= qq~ + + + + + ~ ; + +} + + +# $print_box_content_rows .= &common_min_forms_end('','','save') if $date_inp_val >= $today_val ; +$print_box_content_rows .= &common_min_forms_end('','','save') ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub redirect_screen { + +&common_min_alert_type ; + +print < + + + + $useropts{title} + + + + + + +
    + + + + + +
    + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +use common ; +use report ; +use xlsxcreator ; +use today ; +# use calibration_test ; +use schedule ; +1; \ No newline at end of file diff --git a/scripts/_FromProd/XXX-troubleshoot_report.pl b/scripts/_FromProd/XXX-troubleshoot_report.pl new file mode 100644 index 0000000..611c4a7 --- /dev/null +++ b/scripts/_FromProd/XXX-troubleshoot_report.pl @@ -0,0 +1,628 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +# unless ($useropts{it}{$username}) { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; +use Time::Piece ; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $no_dates_in_table = 1 ; + +# our $debug = 1 ; +# our $testing = 1 ; + +# if ($username ne 'handre') { + # print "<< MAINTENANCE IN PROGRESS >>" ; exit ; +# } + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $srchscr = 1 ; + +if ($iaction eq 'save') { + &db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &common_min_load_params ; + &report_ifields ; + &update ; + &list_screen ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + # exit if $username eq 'handre' && $testing ; + &screen3 ; + # &redirect_screen; +} + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + &report_screen if $iaction eq '' ; + + if ($iaction eq 'report') { + &common_min_load_params ; + &report_ifields ; + &list_screen ; + &screen3 ; + } + + &common_min_action ; + + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub hidden_fields { + + # $ignore{id} = 1 ; + $ignore{iaction} = 1 ; + $ignore{date} = 1 ; + $ignore{troubleshoot_monitor_id} = 1 ; + + for my $d_cnt (1 .. $date_counter) { + for my $shift_cnt (1 .. 4) { + $ignore{"shifttroubleshootmonitorid_$shift_cnt\_$d_cnt"} = 1 ; + $ignore{"shift_troubleshoot_monitor_$shift_cnt\_$d_cnt"} = 1 ; + } + } + # $ignore{monitor_ids} = 1 ; + $ignore{update_table_1} = 1 ; + $ignore{update} = 1 ; + $ignore{"itv-table_length"} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + &schedule_update("shift_operator_ids","troubleshoot_monitor_ids","shifttroubleshootmonitorid","troubleshoot_monitor_notes") ; +# 12=f:;s:|s:1;t:1|f:2;s:2-13=|f:3;s:3|f:4;s:4 + + &schedule_update_monitor_reports ; + + # my @table_sql_where = () ; + + # if ($i{client_id}) { + # push @table_sql_where, "`quote_to`='$i{client_id}'" ; + # } + # if ($i{date_from} && $i{date_to}) { # check dates + # push @table_sql_where, "(('$i{date_from} 00:00:00' <= `date_from` AND `date_from` <= '$i{date_to} 23:59:59') OR ('$i{date_from} 00:00:00' <= `date_to` AND `date_to` <= '$i{date_to} 23:59:59') OR (`date_from` <= '$i{date_from} 00:00:00' AND '$i{date_to} 23:59:59' <= `date_to`))" ; ############################################### > OR >= + + # } + + # # if ($i{monitor_id} and $i{monitor_id} ne 'all') { + # # push @table_sql_where,"`TROUBLESHOOT MONITOR` = '$db{users}{1}{name}'" ; + # # } + + # my $table_sql_where_str = join(" AND ",@table_sql_where) ; + + # &db_min_ro($table,"id,monitor_report_saved_data","$table_sql_where_str",'','') ; + + # my %saved_field_hash = () ; + + # foreach my $id (keys %{$db{$table}}) { + + # my @saved_data_split_1 = split(/\-/,$db{$table}{$id}{monitor_report_saved_data}) ; + + # foreach my $a (@saved_data_split_1) { + # my @saved_data_split_2 = split(/\=/,$a) ; + # my $event_sys_id = $saved_data_split_2[0] ; + # my @saved_data_split_3 = split(/\|/,$saved_data_split_2[1]) ; + # my $day_cnt = 0 ; + # foreach my $b (@saved_data_split_3) { + # $day_cnt++ ; + # next unless $b =~ /(\d+)/g ; + # $saved_field_hash{$id}{$event_sys_id}{$day_cnt} = $b ; + # } + # } + # } + + # foreach my $field_name (keys %i) { + + # next if ($field_name =~ /update_event/ && !$i{$field_name}) || $field_name !~ /update_event/ ; + + # my @fields = split(/\_/,$field_name) ; + + # my $system_id = substr($fields[-3],5) ; + # my $day_cnt = $fields[-2] ; + # my $event_id = $fields[-1] ; + + # my $fixture_field = "fixture_check_event$system_id\_$day_cnt\_$event_id" ; + # my $status_field = "status_event$system_id\_$day_cnt\_$event_id" ; + + # $saved_field_hash{$event_id}{$system_id}{$day_cnt} = qq~~ ; + # $saved_field_hash{$event_id}{$system_id}{$day_cnt} = qq~f:$i{$fixture_field};~ if $i{$fixture_field} ; + # $saved_field_hash{$event_id}{$system_id}{$day_cnt} .= qq~s:$i{$status_field}~ if $i{$status_field} ; + + # } + + # %ii = %i ; + # %i = () ; + + # foreach my $event_id (keys %saved_field_hash) { + + # $i{monitor_report_saved_data} = qq~~ ; + + # foreach my $system_id (sort { $a <=> $b } keys %{$saved_field_hash{$event_id}}) { + + # # $i{monitor_report_saved_data} .= qq~$system_id\=~ ; + # my $saved_by_system = qq~~ ; + + # foreach my $day_max (sort { $b <=> $a } keys %{$saved_field_hash{$event_id}{$system_id}}) { + # for my $day_cnt (1 .. $day_max) { + # $saved_by_system .= qq~$saved_field_hash{$event_id}{$system_id}{$day_cnt}|~ ; + # } + # chop $saved_by_system if $day_max ; + # last ; + # } + # $i{monitor_report_saved_data} .= qq~$system_id\=$saved_by_system\-~ if $saved_by_system =~ /(\d+)/g ; + # } + + # chop $i{monitor_report_saved_data} if $i{monitor_report_saved_data} ; + + # next if ($i{monitor_report_saved_data} eq $db{$table}{$event_id}{monitor_report_saved_data}) || (!$i{monitor_report_saved_data} && !$db{$table}{$event_id}{monitor_report_saved_data}) ; + + # &db_min_upd($table,"id='$event_id'") ; + + # } + + # %i = %ii ; + +} #------------------------------------------------------------------------------------------ + +sub report_ifields { + + &load_search_vars ; + + # if ($i{date}) { # check dates + # push @report_sql, " `date_from` <= '$i{date} 23:59:59' AND '$i{date} 00:00:00' <= `date_to` " ; + # push @report_results, "DATE IS '$i{date}'" ; + # } else { + # $error = qq~PLEASE ENTER A DATE!~ ; + # &report_screen; + # } + + if ($i{client_id}) { + push @report_sql, "`quote_to`='$i{client_id}'" ; + &db_min_ro('customers','id,name',"`id`='$i{client_id}'") ; + push @report_results,"`CLIENT` = '$db{customers}{$i{client_id}}{name}'" ; + } + + my $date_from_val = $i{date_from} ; my $date_to_val = $i{date_to} ; + + $date_from_val =~ s/\-//g ; $date_to_val =~ s/\-//g ; + + if ($i{date_from} && $i{date_to} && $date_from_val > $date_to_val) { + $error = qq~THE START MUST BE BEFORE THE END DATE!!!~ ; + &report_screen ; + } elsif ($i{date_from} && $i{date_to}) { # check dates + push @report_sql, "(('$i{date_from} 00:00:00' <= `date_from` AND `date_from` <= '$i{date_to} 23:59:59') OR ('$i{date_from} 00:00:00' <= `date_to` AND `date_to` <= '$i{date_to} 23:59:59') OR (`date_from` <= '$i{date_from} 00:00:00' AND '$i{date_to} 23:59:59' <= `date_to`))" ; ############################################### > OR >= + push @report_results, "(EVENT BETWEEN '$i{date_from}' AND '$i{date_to}')" ; + } else { + $error = qq~PLEASE ENTER A START AND END DATE!!!~ ; + &report_screen; + } + + if ($i{monitor_id} and $i{monitor_id} ne 'all') { + push @report_results,"`TROUBLESHOOT MONITOR` = '$db{users}{1}{name}'" ; + push @report_sql, " `troubleshoot_monitor_ids` LIKE '%$i{troubleshoot_monitor_id}%' " ; + } elsif ($i{monitor_id} and $i{monitor_id} eq 'all') { + push @report_results,"`TROUBLESHOOT MONITORS` = 'ALL'" ; + } else { + # push @report_sql, "(`user_id` = '')" ; + } + + $report_results_msg = uc join(', ', @report_results) ; + + if ($iaction eq 'save') { + $isaved = qq(SUCCESSFULLY SAVED!) ; + } elsif (not $report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER) ; + &report_screen; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + + our $srch_where_sql = join(' AND ',@report_sql) ; + + my @date = split(/ /,$i{date}) ; + + my ($year_inp,$month_inp,$day_inp) = split(/\-/,$date[0]) ; + + our $date_inp_val = int("$year_inp$month_inp$day_inp") ; + our $today_val = int("$now_year$now_mm$now_dd") ; + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + if ($i{monitor_id} and $i{monitor_id} ne 'all') { + &db_min_ro('users','1,name',"`id` = '$i{troubleshoot_monitor_id}'",'','') ; + } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + $print_box_content_rows .= &common_min_forms_start("$lcpage") ; + + # our $monitoring_report = 1 ; + + our $troubleshoot_monitoring_report = 1 ; + + our $extra_column = ",monitor_report_saved_data" ; + + &schedule_load_list_vars("$srch_where_sql") ; + + $fcol = 12 ; + + my $report = 1 ; + + our $xlsxdir = "troubleshoot_report" ; + + our $xlsxreportname = "Troubleshoot_Report" ; + + my $date = &common_write_date_interval($i{date_from},$i{date_to}) ; + + our $xlsx_title_heading = "Troubleshoot Allocations $date" ; + + my $field_name = "troubleshoot_shift_monitor" ; + + my $uc_field_name = ucfirst $field_name ; + + our $print_tbody_extra = qq~~ ; + + # our @sql_col_display_extra = ("date","shift_1_(07:00-10:00)","shift_2_(10:00-13:00)","shift_3_(13:00-16:00)","shift_4_(16:00-19:00)") ; + our @sql_col_display_extra = ("date","shift_1_(08:00-11:00)","shift_2_(11:00-14:00)","shift_3_(14:00-17:00)","shift_4_(17:00-21:00)","notes") ; + push @sql_col_display_extra,"update" ; + # if $date_inp_val >= $today_val ; + + our @sql_col_display = ("count","event","date","day","start_date","start_time","end_time","region","sport","system","club_name","operator","fixture_check","status","comments") ; + + # push @sql_col_display,"update" if ($monitoring_report || $temp_calibrator_report) && $date_inp_val >= $today_val ; + + &report_xlsx_export_header("$xlsxreportname",$xlsxdir,'',$xlsx_title_heading) ; + # troubleshoot_monitoring_report + + &schedule_build_extra_table("shift_troubleshoot_monitor","shift_operator_ids","troubleshoot_monitor_ids","troubleshoot_monitor_notes","select_troubleshoot_monitors") ; + + # &common_min_table_update_checkbox_col("3") ; + + push @sql_col_display,"update" ; + + my $table_col_name = "troubleshoot_monitor_ids" ; + + $xlsxrow-- ; + + my @rev_sql_col_display = reverse @sql_col_display ; + + foreach (@rev_sql_col_display) { $lastchild++ ; $last_child{$_} = $lastchild ; } + + &schedule_get_monitor_reports_default_values ; + + # our %default_values = () ; + # # 12=f:;s:|s:1;t:1|f:2;s:2-13=|f:3;s:3|f:4;s:4 + # foreach my $id (keys %{$db{$table}}) { + + # my @saved_data_split_1 = split(/\-/,$db{$table}{$id}{monitor_report_saved_data}) ; + # # $sql_col_display[-2] + # # $default_vals{}{$event_sys_id}{$sys_day_cnt}{$id} + + # foreach my $a (@saved_data_split_1) { + # my @saved_data_split_2 = split(/\=/,$a) ; + # my $event_sys_id = $saved_data_split_2[0] ; + # my @saved_data_split_3 = split(/\|/,$saved_data_split_2[1]) ; + # my $day_cnt = 0 ; + # foreach my $b (@saved_data_split_3) { + # $day_cnt++ ; + # next unless $b =~ /(\d+)/g ; + # my @saved_data_split_3 = split(/\;/,$b) ; + # my @saved_data_split_4 = split(/\:/,$saved_data_split_3[0]) ; + # my @saved_data_split_5 = split(/\:/,$saved_data_split_3[1]) ; + + # if ($saved_data_split_4[0] =~ /f/) { + # $default_values{$sql_col_display[-3]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_4[1] ; + # } + # if ($saved_data_split_5[0] =~ /s/) { + # $default_values{$sql_col_display[-2]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_5[1] ; + # } elsif ($saved_data_split_4[0] =~ /s/) { + # $default_values{$sql_col_display[-2]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_4[1] ; + # } + # } + # } + # } + + &common_min_select_opts("status","monitor_status","status") ; + + our @default_javascript_by_id_2 = () ; + + &schedule_build_table("troubleshoot_monitor_ids") ; + + # if ($date_inp_val >= $today_val) { + # $trigger_jquery_raw .= qq~ + # \$("#itv-table tr th:nth-last-child(5)").css("width","10%") ; + # \$("#itv-table tr th:nth-last-child(4)").css("width","10%") ; + # \$("#itv-table tr th:nth-last-child(3)").css("width","10%") ; + # \$("#itv-table tr th:nth-last-child(2)").css("width","10%") ; + # ~ ; + + # } else { + # $trigger_jquery_raw .= qq~ + # \$("#select_monitors tr th:nth-last-child(1)").css("width","23%") ; + # \$("#select_monitors tr th:nth-last-child(4)").css("width","23%") ; + # \$("#select_monitors tr th:nth-last-child(3)").css("width","23%") ; + # \$("#select_monitors tr th:nth-last-child(2)").css("width","23%") ; + # ~ ; + # } + + # &calibration_build_table_and_or_excel(1) ; + + # if ($found_after_date) { + + + + # } else { + # $trigger_jquery_raw .= qq~ + # \$("#itv-table tr th:nth-last-child(2)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(3)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(4)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(5)").css("width", "7.5%") ; + + # ~ ; + # } + + + # my $first_table_multi_select_table_cells_str = join(",",@first_table_multi_select_table_cells) ; + + # &common_min_table_select_fixed_width_jquery($first_table_multi_select_table_cells_str ) ; + + # &common_min_table_select_default_values_jquery ; + + # &common_min_table_update_checkbox_col("3") ; + + + my $first_table_multi_select_table_cells_str = join(",",@first_table_multi_select_table_cells) ; + # $useropts{table_id} + &common_min_table_select_fixed_width_jquery($first_table_multi_select_table_cells_str) ; + + &common_min_table_select_prevent_dropdown_overlap_jquery ; + + &common_min_table_select_default_values_jquery ; + + &common_min_table_update_checkbox_col("3","content","[id^='textareaComments_'],[id^='selectFixture_check_'],[id^='selectStatus_'],[id^='selectShift_troubleshoot_monitor_1_'],[id^='selectShift_troubleshoot_monitor_2_'],[id^='selectShift_troubleshoot_monitor_3_'],[id^='selectShift_troubleshoot_monitor_4_'],[id^='textareaShift_troubleshoot_monitor_notes_1_'],[id^='textareaShift_troubleshoot_monitor_notes_2_'],[id^='textareaShift_troubleshoot_monitor_notes_3_'],[id^='textareaShift_troubleshoot_monitor_notes_4_']") ; + + # my $default_javascript_by_id_str = join (",",@default_javascript_by_id) ; + + # print "\n default_javascript_by_id_str : $default_javascript_by_id_str" ; + + # $trigger_jquery_raw .= qq~ + + # all_def_vals = {$default_javascript_by_id_str} ; + + # \$("#$useropts{table_id}").on("change","[id^='selectFixture_check_'],[id^='selectStatus_']", function (event) { + # event.preventDefault(); + # console.log("2 update : "+this.id) ; + # check_whether_to_update(this.id); + # }); + + # ~ ; + + # &common_min_table_update_checkbox_col("3") ; + + $fnsortorder = 'asc' ; + + &common_min_extra_crumb("$lcpage","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + # &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + # our $lcpage = 'monitor-allocations' ; + our $lcpage = 'troubleshoot-report' ; + + &common_page_name ; + + our $table = 'event_quotes' ; + $page_title = 'Troubleshoot Allocations' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + &common_min_select_opts('client_id','customers','name','','','',"events='1'") ; + + $allow_deselect{client_id} = 1 ; + $opts{client_id} =~ s/value="$i{client_id}"/value="$i{client_id}" SELECTED/g if $i{client_id} ; + $print_box_content_rows .= &common_min_form_select('client_id','') ; + + my ($sql_next_day) = &common_add_delta_days(1) ; + my ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-$now_mm-$now_dd") ; #unless $i{date_from} ; + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$next_year-$next_month-$next_day") ; #unless $i{date_from} ; + + push @date_value_ids,"input[name='date_from']" ; + push @date_value_ids,"input[name='date_to']" ; + + &common_min_table_validate_date_inputs_jquery ; + + $preferred_title{troubleshoot_monitor_id} = "Troubleshoot Monitor" ; + + # &db_min_ro('users',"id,name","`user_type` = 'support' OR `user_type` = 'casual_calibrator'",'','') ; + # &db_min_ro('users',"id,name,username","`name` NOT LIKE 'Rory%'",'','') ; + + $selected{troubleshoot_monitor_id}{all} = 'SELECTED' ; + + # if ($i{monitor_id}) { + # $selected{monitor_id}{$i{monitor_id}} = 'SELECTED' ; + # $selected{monitor_id}{all} = '' ; + # } + + # foreach (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + # next if $useropts{it}{$db{users}{$_}{username}} ; + # $opts{monitor_id} .= qq~~ ; + # } + $opts{troubleshoot_monitor_id} .= qq~~ ; + + $print_box_content_rows .= &common_min_form_select('troubleshoot_monitor_id','') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# my $page = "$lcpage\s" ; + +my $page = "event-quotes" ; + +if ($s{no}) { $page = $lcpage ; } + +# &db_min_ro('daily_monitor_ids','date,monitor_ids') ; + +my @sql_col_display_2 = @sql_col_display ; + +@sql_col_display = @sql_col_display_extra ; + +our %custom_column_styles = () ; + +$custom_column_styles{fixture_check} = qq~style="width:7%;min-width:150px;"~ ; +$custom_column_styles{status} = qq~style="width:7%;min-width:150px;"~ ; + +&common_min_thead ; + +$print_box_content_rows .= qq~ + + $print_thead + + + $print_tbody_extra + + +
    ~ ; + +@sql_col_display = @sql_col_display_2 ; + +&common_min_thead ; + +&common_min_table('id',$page,'list') ; + +our $savjqy = 1 ; + +$extra_form_fields .= qq~ + + + + + +~; + +for (1 .. $date_cnt) { + + $extra_form_fields .= qq~ + + + + + ~ ; + +} + + +# $print_box_content_rows .= &common_min_forms_end('','','save') if $date_inp_val >= $today_val ; +$print_box_content_rows .= &common_min_forms_end('','','save') ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub redirect_screen { + +&common_min_alert_type ; + +print < + + + + $useropts{title} + + + + + + +
    + + + + + +
    + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +use common ; +use report ; +use xlsxcreator ; +use today ; +# use calibration_test ; +use schedule ; +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/admin/oneoff/build_poc_table.pl b/scripts/_FromProd/v1.0/admin/oneoff/build_poc_table.pl new file mode 100644 index 0000000..070a92d --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/build_poc_table.pl @@ -0,0 +1,328 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser) ; +# use Date::Calc qw(:all); +# use DBI; + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/build_poc_table.pl?1&poc +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/build_poc_table.pl?1&recipient + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0] ; +our $poc_or_recipient = $ARGV[1] ; +# our $username = 'rory' ; + +if ($debug) { print "Content-type: text/html\n\n"; } + +#------------------------------------------------------------------------------------------ + +&today ; + +&db_open_upd ; +# &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &load_vars ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +if ($debug) { print "Done."; } + +exit; + +#------------------------------------------------------------------------------------------ + +sub load_vars { + + + # $poc_or_recipient = "poc" ; + + exit unless $poc_or_recipient ; + # my $poc_or_recipient = "poc" ; + my $id_field = "$poc_or_recipient\_id" ; + my $table_ = "event_quotes_$poc_or_recipient" ; + my $name_field = "$poc_or_recipient\_name" ; + my $nr_field = ($poc_or_recipient eq 'poc') ? "$poc_or_recipient\_contact_nr" : "$poc_or_recipient\_nr" ; + + &db_min_ro('event_quotes aisa',"id,$name_field,$nr_field","$name_field <> '' AND $name_field IS NOT NULL","","") ; + &db_min_ro($table_,'id,name,contact_nr',"","","") ; + &db_switch_conn('sss') ; + &db_min_ro('event_quotes sss',"id,$name_field,$nr_field","$name_field <> '' AND $name_field IS NOT NULL","","") ; + my %seen_poc = () ; + &db_switch_conn('aisa') ; + + foreach (keys %{$db{$table_}}) { + $seen_poc{$db{$table_}{$_}{name}}{$db{$table_}{$_}{contact_nr}} = 1 ; + } + + my %seen_name = () ; my %seen_name_with_blank_number = () ; my %seen_name_with_non_blank_number = () ; my %seen_number_with_complete_name = () ; my %seen_number_cnt = () ; my %seen_name_cnt = () ; + + my %unique_number_linked_to_name = () ; + + my $cnt = 0 ; + use utf8; + + foreach (sort { lc $db{"event_quotes aisa"}{$a}{$name_field} cmp lc $db{"event_quotes aisa"}{$b}{$name_field} } keys %{$db{"event_quotes aisa"}}) { + + my $number = &common_fix_poc_numbers($db{"event_quotes aisa"}{$_}{$nr_field}) ; + my $name = &common_fix_poc_name($db{"event_quotes aisa"}{$_}{$name_field}) ; + + $db{"event_quotes aisa"}{$_}{$nr_field} = $number ; + $db{"event_quotes aisa"}{$_}{$name_field} = $name ; + + if ($unique_number_linked_to_name{$name} && $unique_number_linked_to_name{$name} ne $number && $number) { + $unique_number_linked_to_name{$name} = "NA" ; + } elsif ($number) { + $unique_number_linked_to_name{$name} = $number ; + } + + $seen_name{$name}{$number} = 1 ; + $seen_name_with_non_blank_number{$name} = 1 if $number ; + } + + foreach (sort { lc $db{"event_quotes sss"}{$a}{$name_field} cmp lc $db{"event_quotes sss"}{$b}{$name_field} } keys %{$db{"event_quotes sss"}}) { + + my $number = &common_fix_poc_numbers($db{"event_quotes sss"}{$_}{$nr_field}) ; + my $name = &common_fix_poc_name($db{"event_quotes sss"}{$_}{$name_field}) ; + # $number = "" if !$number || length($number) <= 5 ; + $db{"event_quotes sss"}{$_}{$nr_field} = $number ; + $db{"event_quotes sss"}{$_}{$name_field} = $name ; + if ($unique_number_linked_to_name{$name} && $unique_number_linked_to_name{$name} ne $number && $number) { + $unique_number_linked_to_name{$name} = "NA" ; + } elsif ($number) { + $unique_number_linked_to_name{$name} = $number ; + } + + $seen_name{$name}{$number} = 1 ; + $seen_name_with_non_blank_number{$name} = 1 if $number ; + } + + my %poc_id = () ; my %final_names_numbers = () ; my %names_seen_with_number = () ; my %skip_name_number = () ; + + foreach my $lc_name (sort { $seen_name{$a} cmp $seen_name{$b} } keys %seen_name) { + foreach my $nr (sort { $seen_name{$lc_name}{$a} cmp $seen_name{$lc_name}{$b} } keys %{$seen_name{$lc_name}}) { + # next if $seen_poc{$lc_name}{$nr} ; + + next if $seen_poc{$lc_name}{$nr} || (!$nr && $seen_name_with_non_blank_number{$lc_name} && $unique_number_linked_to_name{$lc_name} ne 'NA') || $seen_name{$lc_name}{$nr} < 0 ; + # next if $seen_name_with_non_blank_number{$lc_name} ; + # $cnt++ ; + # $poc_id{$lc_name}{$nr} = $cnt ; + $seen_number_cnt{$nr}++ if $nr ; + $seen_number_cnt{$nr} = 0 unless $nr ; + $names_seen_with_number{$nr}{$seen_number_cnt{$nr}} = $lc_name ; + $final_names_numbers{$lc_name}{$nr} = 1 ; + + } + } + + $cnt = 0 ; + + our %skip_name_number = () ; #our %skip_name_number_because_of = () ; + + foreach my $nr (keys %names_seen_with_number) { + + my $seen_cnt = 0 ; + + foreach my $number_cnt (sort {$b <=> $a} keys %{$names_seen_with_number{$nr}}) { + + next if $number_cnt <= 1 && !$seen_cnt ; + $seen_cnt++ ; + + for my $cnt1 (1 .. $number_cnt) { + + my @name_split = split(/ /,$names_seen_with_number{$nr}{$cnt1}) ; + my $first_name1 = $name_split[0] ; + my $rest_of_name1 = join(" ", @name_split[1..$#name_split]); + + for my $cnt2 (1 .. $number_cnt) { + + next if $cnt1 eq $cnt2 ; + + # print "\n MAWND $names_seen_with_number{$nr}{$cnt2} =~ /\b$names_seen_with_number{$nr}{$cnt1}b/" ; + + if ($names_seen_with_number{$nr}{$cnt2} =~ /\b$names_seen_with_number{$nr}{$cnt1}\b/) { + # print "\n SKIP : $nr : $names_seen_with_number{$nr}{$cnt1}" ; + $skip_name_number{$names_seen_with_number{$nr}{$cnt1}}{$nr} = "$names_seen_with_number{$nr}{$cnt2}\_:_$nr" ; + # $skip_name_number_because_of{$names_seen_with_number{$nr}{$cnt1}}{$nr} = "$names_seen_with_number{$nr}{$cnt2}\_:_$nr" ; + } else { + + @name_split = split(/ /,$names_seen_with_number{$nr}{$cnt2}) ; + my $first_name2 = $name_split[0] ; + my $rest_of_name2 = join(" ", @name_split[1..$#name_split]); + if ($first_name2 =~ /$first_name1/ && $rest_of_name2 =~ /$rest_of_name1/) { + $skip_name_number{$names_seen_with_number{$nr}{$cnt1}}{$nr} = "$names_seen_with_number{$nr}{$cnt2}\_:_$nr" ; + # $skip_name_number_because_of{$names_seen_with_number{$nr}{$cnt1}}{$nr} = "$names_seen_with_number{$nr}{$cnt2}\_:_$nr" ; + } + } + } + } + last ; + } + } + + &skip_names_numbers ; + # sort { $seen_name{$lc_name}{$a} cmp $seen_name{$lc_name}{$b} } + + $cnt = 0 ; + + foreach my $lc_name (sort { $seen_name{$a} cmp $seen_name{$b} } keys %final_names_numbers) { + foreach my $nr ( keys %{$final_names_numbers{$lc_name}}) { + # next if $seen_poc{$lc_name}{$nr} ; + # next if $seen_name_with_non_blank_number{$lc_name} ; + + next if $skip_name_number{$lc_name}{$nr} || !$lc_name || $lc_name eq '1' || $lc_name eq '123' ; + # next if $lc_name =~ /Iren/ && $lc_name ne 'Irene' && $nr eq '27832524894' ; + # next if $lc_name =~ /Handr/ && $lc_name ne 'Handro Le Roux' && $nr eq '27766215100' ; + $cnt++ ; + $poc_id{$lc_name}{$nr} = $cnt ; + print "\n INSERT INTO $table_ (id,name,contact_nr) VALUES ($cnt,\"$lc_name\",'$nr') ; " ; + } + } + + my %event_quotes_ = () ; + + foreach (sort { lc $db{"event_quotes aisa"}{$a}{$name_field} cmp lc $db{"event_quotes aisa"}{$b}{$name_field} } keys %{$db{"event_quotes aisa"}}) { + + my $number = &common_fix_poc_numbers($db{"event_quotes aisa"}{$_}{$nr_field}) ; + my $name = &common_fix_poc_name($db{"event_quotes aisa"}{$_}{$name_field}) ; + + if (!$number) { + $number = $unique_number_linked_to_name{$name} ; + $number = "" if $number eq 'NA' ; + # print "\n unique_numbers_linked_to_name : $name : $unique_numbers_linked_to_name{$name}" ; + } + if ($skip_name_number{$name}{$number}) { + ($name,$number) = split(/\_:_/,$skip_name_number{$name}{$number}) ; + ($name,$number) = split(/\_:_/,$skip_name_number{$name}{$number}) if $skip_name_number{$name}{$number} ; + ($name,$number) = split(/\_:_/,$skip_name_number{$name}{$number}) if $skip_name_number{$name}{$number} ; + ($name,$number) = split(/\_:_/,$skip_name_number{$name}{$number}) if $skip_name_number{$name}{$number} ; + ($name,$number) = split(/\_:_/,$skip_name_number{$name}{$number}) if $skip_name_number{$name}{$number} ; + } + + if ($poc_id{$name}{$number}) { + # print "\n ID : $name,$number ,$poc_id{$name}{$number}" ; + } else { + # print "\n 3 NO ID : $name,$number" ; + } + + $event_quotes_{$poc_id{$name}{$number}}{$_} = 1 if $poc_id{$name}{$number} ; + } + + foreach my $pid (keys %event_quotes_) { + my $sql_where = join (" OR ", map { "id='$_'" } keys %{$event_quotes_{$pid}} ) ; + print "\n UPDATE event_quotes aisa SET $poc_or_recipient\_id = '$pid' WHERE $sql_where ; " if $sql_where ; + } + + &db_switch_conn('sss') ; + + %event_quotes_ = () ; + + foreach (sort { lc $db{"event_quotes sss"}{$a}{$name_field} cmp lc $db{"event_quotes sss"}{$b}{$name_field} } keys %{$db{"event_quotes sss"}}) { + my $number = &common_fix_poc_numbers($db{"event_quotes sss"}{$_}{$nr_field}) ; + my $name = &common_fix_poc_name($db{"event_quotes sss"}{$_}{$name_field}) ; + + if (!$number) { + $number = $unique_number_linked_to_name{$name} ; + $number = "" if $number eq 'NA' ; + # print "\n unique_numbers_linked_to_name : $name : $unique_numbers_linked_to_name{$name}" ; + } + + if ($skip_name_number{$name}{$number}) { + ($name,$number) = split(/\_:_/,$skip_name_number{$name}{$number}) ; + ($name,$number) = split(/\_:_/,$skip_name_number{$name}{$number}) if $skip_name_number{$name}{$number} ; + ($name,$number) = split(/\_:_/,$skip_name_number{$name}{$number}) if $skip_name_number{$name}{$number} ; + ($name,$number) = split(/\_:_/,$skip_name_number{$name}{$number}) if $skip_name_number{$name}{$number} ; + ($name,$number) = split(/\_:_/,$skip_name_number{$name}{$number}) if $skip_name_number{$name}{$number} ; + } + + $event_quotes_{$poc_id{$name}{$number}}{$_} = 1 if $poc_id{$name}{$number} ; + # print "\n UPDATE event_quotes SET poc_id = '$poc_id{$name}{$number}' WHERE id = '$_'" if $poc_id{$name}{$number} ; + } + + foreach my $pid (keys %event_quotes_) { + my $sql_where = join (" OR ", map { "id='$_'" } keys %{$event_quotes_{$pid}} ) ; + print "\n UPDATE event_quotes sss SET $poc_or_recipient\_id = '$pid' WHERE $sql_where ; " if $sql_where ; + } + +} #------------------------------------------------------------------------------- + +sub skip_names_numbers { + + # $skip_name_number{"Klye Reddy"}{"27716057436"} = "Kyle Reddy_:_27716057436" ; + # $skip_name_number{"Adi"}{"27828831558"} = "Adrian Norris_:_27828831558" ; + # $skip_name_number{"Monwabisi ( Mo)"}{"27791349494"} = "Monwabisi (mo)_:_27791349494" ; + # $skip_name_number{"Patrick"}{"073286160"} = "Patrick_:_27732876160" ; + # $skip_name_number{"Wikus"}{"27766969301"} = "Wickus Coetzer_:_27766969301" ; + # $skip_name_number{"Werner Jv Rensburg"}{"27714103925"} = "Werner Jansen van Rensburg_:_27714103925" ; + # $skip_name_number{"Werener"}{"27714103925"} = "Werner Jansen van Rensburg_:_27714103925" ; + # $skip_name_number{"Warner"}{"27714103925"} = "Werner Jansen van Rensburg_:_27714103925" ; + # $skip_name_number{"Warren Tanner Ellis"}{"27832124379"} = "Warren Tanner-Ellis_:_27832124379" ; + # $skip_name_number{"Shaun Labscher"}{"27847751762"} = "Shaun Laubscher_:_27847751762" ; + # $skip_name_number{"Andrew Nel Skool"}{"27822186009"} = "Andrew Nel-Skool_:_27822186009" ; + # $skip_name_number{"Anna Marie - Pmbghs"}{"27829293432"} = "Anna-Marie Snyman_:_27829293432" ; + # $skip_name_number{"Willem vd Merwe"}{"27844028276"} = "Willem van De Merwe_:_27844028276" ; + # $skip_name_number{"Wanri Venter"}{"07780195566"} = "Wanri Venter_:_27780195566" ; + # $skip_name_number{"Willem van De Merwe"}{"844028276"} = "Willem van De Merwe_:_27844028276" ; + # $skip_name_number{"Wayne Philips"}{"27827832211"} = "Wayne Phillips_:_27827832211" ; + # $skip_name_number{"Martin Vw"}{"27737466628"} = "Martin van Wyngaardt_:_27737466628" ; + # $skip_name_number{"Max ,mohale"}{"27824974244"} = "Max Mohale_:_27824974244" ; + # $skip_name_number{"Greg"}{"27746011640"} = "Gregg Von Molendorf_:_27746011640" ; + # $skip_name_number{"Greg"}{"27746011640"} = "Gregg Von Molendorf_:_27746011640" ; + # $skip_name_number{"Hendo Le Rouz"}{"27766215100"} = "Hendo Le Roux_:_27766215100" ; + # $skip_name_number{"Henrich Kruger"}{"27825024824"} = "Heinrich Kruger_:_27825024824" ; + # $skip_name_number{"Ilse Davds"}{"27605017896"} = "Ilse Davids_:_27605017896" ; + # $skip_name_number{"Renee van Wayk"}{"27847039138"} = "Renee van Wyk_:_27847039138" ; + # $skip_name_number{"Cathrine Mccreesh"}{"27825673044"} = "Catherine Mccreesh_:_27825673044" ; + +} #------------------------------------------------------------------------------- + +sub common_fix_poc_numbers { + + my ($number) = @_ ; + + # use utf8; Make sure this is called + + $number =~ s/\-//g ; + $number =~ s/\p{Space}//g; + $number = &common_fix_cell($number) ; + $number = "" if !$number || length($number) <= 5 ; + + if ($number =~ /\//) { + $number = join ("/",map{ &common_fix_cell($_) } split(/\//,$number)) ; + } elsif (length ($number) == 10 && substr($number,0,1) eq '7') { + $number = '2' . $number ; + } + return $number ; + +} #------------------------------------------------------------------------------- + +sub common_fix_poc_name { + + my ($name) = @_ ; + $name = lc $name ; + $name = join(" ", map { ($_ eq 'v' || $_ eq 'van' || $_ eq 'der' || $_ eq 'vd') ? $_ : ucfirst $_ } split(/ /,$name)) ; + $name = join("-", map { ucfirst $_ } split(/\-/,$name)) ; + $name = join(":", map { ucfirst $_ } split(/\:/,$name)) ; + $name =~ s/ / /g ; + if ($name =~ /\b- \b/ ) { + $name =~ s/- /-/g ; + } elsif ($name =~ /\b -\b/) { + $name =~ s/ -/-/g ; + } + + $name =~ s/:(?=\S)/: /g; + $name =~ s/^\s+|\s+$//g; + + return $name ; + +} #------------------------------------------------------------------------------- + +use db ; +use today ; +use common ; +use common_min ; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/change_event_cost_items.pl b/scripts/_FromProd/v1.0/admin/oneoff/change_event_cost_items.pl new file mode 100644 index 0000000..c9ebf72 --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/change_event_cost_items.pl @@ -0,0 +1,92 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser); +# use Date::Calc qw(:all); +# use DBI; + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/change_event_cost_items.pl?1 + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0] ; +# our $username = 'rory' ; + +if ($debug) { print "Content-type: text/html\n\n"; } + +#------------------------------------------------------------------------------------------ + +&today ; + +&db_open_upd ; +# &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &load_vars ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +if ($debug) { print "Done."; } + +exit; + +#------------------------------------------------------------------------------------------ + +sub load_vars { + + &db_min_ro('event_quotes_min','id,item_costing_event,description_workings_event',"",'','') ; + + # my $cnt = 0 ; + + foreach (sort keys %{$db{event_quotes_min}}) { + + # last if $cnt > 100 ; + + my $costing1 = $db{event_quotes_min}{$_}{item_costing_event} ; + my $costing2 = $db{event_quotes_min}{$_}{description_workings_event} ; + + $costing1 =~ s/11/22/g if $costing1 =~ /11/ ; # Mobile Camera Operation - SSS [11] >>> Mobile S1 System - SSS[22] + $costing1 =~ s/18/23/g if $costing1 =~ /18/ ; # Mobile Camera Operation - AISA [18] >>> Mobile S1 System - AISA [23] + $costing1 =~ s/10/26/g if $costing1 =~ /10/ ; # Fixed Camera Operation [10] >>> Fixed System - SSS [26] + $costing1 =~ s/12/21/g if $costing1 =~ /12/ ; # Cricket Camera Operation [12] >>> Mobile Cricket System - SSS [21] + $costing1 =~ s/19/27/g if $costing1 =~ /19/ ; # Fixed Camera Operation - Linear [19] >>>> Fixed System - Linear - SSS [27] + $costing1 =~ s/20/28/g if $costing1 =~ /20/ ; # Mobile Camera Operation - Linear [20] >>> Mobile S1 System - Linear - SSS [28] + + $costing2 =~ s/11/22/g if $costing2 =~ /11/ ; # + $costing2 =~ s/18/23/g if $costing2 =~ /18/ ; # + $costing2 =~ s/10/26/g if $costing2 =~ /10/ ; # + $costing2 =~ s/12/21/g if $costing2 =~ /12/ ; # + $costing2 =~ s/19/27/g if $costing2 =~ /19/ ; # + $costing2 =~ s/20/28/g if $costing2 =~ /20/ ; # + + %i = () ; + + $ignore{item_costing_event} = ($costing1 eq $db{event_quotes_min}{$_}{item_costing_event}) ? 1 : 0 ; + $ignore{description_workings_event} = ($costing2 eq $db{event_quotes_min}{$_}{description_workings_event}) ? 1 : 0 ; + + $costing1 =~ s/;+$//g unless $ignore{item_costing_event} ; + $costing2 =~ s/;+$//g unless $ignore{description_workings_event} ; + + # if ($costing1 ne $db{event_quotes_min}{$_}{item_costing_event} || $costing2 ne $db{event_quotes_min}{$_}{description_workings_event}) { + if ($costing1 ne $db{event_quotes_min}{$_}{item_costing_event} || $costing2 ne $db{event_quotes_min}{$_}{description_workings_event}) { + + $i{item_costing_event} = $costing1 ; + $i{description_workings_event} = $costing2 ; + # print "\n UPDATE event_quotes_min SET item_costing_event = '$i{item_costing_event} FROM $db{event_quotes_min}{$_}{item_costing_event}', description_workings_event = '$i{description_workings_event} FROM $db{event_quotes_min}{$_}{description_workings_event}' WHERE id='$_'" ; + &common_debug("WAS item_costing_event=$db{event_quotes_min}{$_}{item_costing_event}, description_workings_event=$db{event_quotes_min}{$_}{description_workings_event}") ; + # &db_min_upd('event_quotes_min',"id='$_'") ; + + # $cnt++ ; + + } + } + +} #------------------------------------------------------------------------------- + +use db ; +use today ; +use common ; +use common_min ; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/cities_fix_db.pl b/scripts/_FromProd/v1.0/admin/oneoff/cities_fix_db.pl new file mode 100644 index 0000000..34e2e36 --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/cities_fix_db.pl @@ -0,0 +1,57 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser); +# use Date::Calc qw(:all); +# use DBI; + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/cities_fix_db.pl?1 + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0] ; +# our $username = 'rory' ; + +if ($debug) { print "Content-type: text/html\n\n"; } + +#------------------------------------------------------------------------------------------ + +&today ; + +&db_open_upd ; +# &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &load_vars ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +if ($debug) { print "Done."; } + +exit; + +#------------------------------------------------------------------------------------------ + +sub load_vars { + + &db_min_ro('event_quotes','id,city_id',"city_id > 0",'','') ; + + foreach my $_id (sort {$a <=> $b} keys %{$db{event_quotes}}) { + $got_city{$db{event_quotes}{$_id}{city_id}} .= $_id . '|' ; + } + + &db_min_ro('cities','id,city','','','') ; + foreach my $_id (sort {$a <=> $b} keys %{$db{cities}}) { + # print $db{cities}{$_id}{city} . "[$got_city{$_id}]" . '
    ' unless $got_city{$_id} ; + &db_min_delete('cities',"id = '$_id'") unless $got_city{$_id} ; + } + +} #------------------------------------------------------------------------------- + +use db ; +use today ; +use common ; +use common_min ; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/compare_sss_aisa_poc.pl b/scripts/_FromProd/v1.0/admin/oneoff/compare_sss_aisa_poc.pl new file mode 100644 index 0000000..3e15132 --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/compare_sss_aisa_poc.pl @@ -0,0 +1,68 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser) ; + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/compare_sss_aisa_poc.pl?1&poc +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/compare_sss_aisa_poc.pl?1&recipient + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0] ; +our $poc_or_recipient = $ARGV[1] ; +# our $username = 'rory' ; + +if ($debug) { print "Content-type: text/html\n\n"; } + +#------------------------------------------------------------------------------------------ + +&today ; + +&db_open_upd ; +# &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &load_vars ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +if ($debug) { print "Done."; } + +exit; + +#------------------------------------------------------------------------------------------ + +sub load_vars { + + # $poc_or_recipient = "poc" ; + + exit unless $poc_or_recipient ; + # my $poc_or_recipient = "poc" ; + my $id_field = "$poc_or_recipient\_id" ; + my $table_ = "event_quotes_$poc_or_recipient" ; + my $name_field = "$poc_or_recipient\_name" ; + my $nr_field = ($poc_or_recipient eq 'poc') ? "$poc_or_recipient\_contact_nr" : "$poc_or_recipient\_nr" ; + + my $table_aisa = 'event_quotes aisa' ; + my $table_sss = 'event_quotes sss' ; + + &db_min_ro($table_aisa,"id,$id_field","sss_quote_nr <> '0'","","") ; + # foreach (keys %{$db{$table_aisa}}) { + # $aisa_poc_id{$_} = $db{$table_aisa}{$_}{$id_field} ; + # } + &db_switch_conn('sss') ; + &db_min_ro($table_sss,"id,aisa_quote_nr,$id_field","aisa_quote_nr <> '0'","","") ; + foreach (keys %{$db{$table_sss}}) { + print "\n sss_poc_id : $db{$table_sss}{$_}{$id_field} , aisa_poc_id : $db{$table_aisa}{$db{$table_sss}{$_}{aisa_quote_nr}}{$id_field}" if $db{$table_sss}{$_}{$id_field} ne $db{$table_aisa}{$db{$table_sss}{$_}{aisa_quote_nr}}{$id_field} ; + } + +} #------------------------------------------------------------------------------- + + +use db ; +use today ; +use common ; +use common_min ; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/compare_sss_aisa_synking.pl b/scripts/_FromProd/v1.0/admin/oneoff/compare_sss_aisa_synking.pl new file mode 100644 index 0000000..54a6893 --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/compare_sss_aisa_synking.pl @@ -0,0 +1,83 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser) ; +# use Date::Calc qw(:all); +# use DBI; + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/compare_sss_aisa_synking.pl?1 +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/compare_sss_aisa_synking.pl?1 + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0] ; +# our $username = 'rory' ; + +if ($debug) { print "Content-type: text/html\n\n"; } + +#------------------------------------------------------------------------------------------ + +&today ; + +&db_open_upd ; +# &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &load_vars ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +if ($debug) { print "Done."; } + +exit; + +#------------------------------------------------------------------------------------------ + +sub load_vars { + + my $table_aisa = 'event_quotes aisa' ; + my $table_sss = 'event_quotes sss' ; + + &db_min_ro($table_aisa,"*","sss_quote_nr <> '0'","","") ; + foreach my $id1 (keys %{$db{$table_aisa}}) { + foreach my $col (keys %{$db{$table_aisa}{$id1}}) { + $aisa_col{$col} = 1 ; + } + last ; + } + + + &db_switch_conn('sss') ; + &db_min_ro($table_sss,"*","aisa_quote_nr <> '0'","","") ; + + # foreach my $id2 (sort {$b <=> $a} keys %{$db{$table_sss}}) { + # next unless $db{$table_sss}{$id2}{supplier_ids} =~ /\b63\b/ ; + # foreach my $col (keys %{$db{$table_sss}{$id2}}) { + # print "\n col : $col" ; + # } + # last ; + # } + + foreach my $id (sort {$b <=> $a} keys %{$db{$table_sss}}) { + # print "\n SSS ID : $id , AISA ID : $db{$table_sss}{$id}{aisa_quote_nr} \n" ; + next unless $db{$table_sss}{$id}{supplier_ids} =~ /\b63\b/ ; + foreach my $col (keys %{$db{$table_sss}{$id}}) { + next if !$aisa_col{$col} || $col eq 'poc_name' || $col eq 'poc_contact_nr' || $col eq 'user_id' || $col eq 'id' || $col eq 'quote_nr' || $col eq 'excl_3_payment_terms' ; + $db{$table_sss}{$id}{$col} =~ s/;+$// ; + $db{$table_aisa}{$db{$table_sss}{$id}{aisa_quote_nr}}{$col} =~ s/;+$// ; + + + print "\n SSS ID : $id , AISA ID : $db{$table_sss}{$id}{aisa_quote_nr} , $col SSS : $db{$table_sss}{$id}{$col} , AISA : $db{$table_aisa}{$db{$table_sss}{$id}{aisa_quote_nr}}{$col} " if $db{$table_sss}{$id}{$col} ne $db{$table_aisa}{$db{$table_sss}{$id}{aisa_quote_nr}}{$col} ; + } + } + +} #------------------------------------------------------------------------------- + + +use db ; +use today ; +use common ; +use common_min ; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/correct_event_quotes_min_table.pl b/scripts/_FromProd/v1.0/admin/oneoff/correct_event_quotes_min_table.pl new file mode 100644 index 0000000..ede7f4e --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/correct_event_quotes_min_table.pl @@ -0,0 +1,430 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser); +# use Date::Calc qw(:all); +# use DBI; + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/correct_event_quotes_min_table.pl?1 + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0] ; +# our $username = 'rory' ; + +if ($debug) { print "Content-type: text/html\n\n"; } + +#------------------------------------------------------------------------------------------ + +&today ; + +&db_open_upd ; +# &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &load_vars ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +if ($debug) { print "Done."; } + +exit; + +#------------------------------------------------------------------------------------------ + +# sub load_vars { + + # &db_min_ro('event_quotes','id',"",'','') ; + + # &db_min_ro('event_quotes_min','id',"",'','') ; + + # foreach (keys %{$db{event_quotes}}) { + + # print "\n INSERT INTO event_quotes_min (id,quote_nr) VALUES ($_,$_) ;" if !$db{event_quotes_min}{$_}{id} ; + + # } + +# } #------------------------------------------------------------------------------- + +sub load_vars { + + &db_min_ro('event_quotes_min','id,quote_nr',"id != quote_nr",'','') ; + + foreach (keys %{$db{event_quotes_min}}) { + + # print "\n $_ , $db{event_quotes_min}{$_}{quote_nr}" ; + + print "\nUPDATE event_quotes_min SET quote_nr='$_' where id = $_ ;" ; + + } + + # print "\n $_ , $db{event_quotes_min}{$_}{quote_nr}" ; + + # 9613 , 9573 + # 8378 , 8026 + # 10167 , 9839 + # 8427 , 8422 + # 9383 , 9382 + # 9045 , 8942 + # 10445 , 9839 + # 9217 , 9194 + # 9002 , 8950 + # 9683 , 9538 + # 9696 , 8605 + # 8155 , 8154 + # 9591 , 9578 + # 9841 , 9839 + # 10115 , 10114 + # 10112 , 9918 + # 9112 , 8928 + # 9043 , 8942 + # 8543 , 8030 + # 8476 , 8154 + # 8487 , 8030 + # 11098 , 11081 + # 7604 , 7549 + # 10909 , 10906 + # 8851 , 8805 + # 11033 , 10905 + # 10793 , 10677 + # 8852 , 8805 + # 8488 , 8030 + # 9238 , 9226 + # 9743 , 9678 + # 9154 , 9117 + # 8471 , 8026 + # 8649 , 8614 + # 9562 , 9491 + # 9088 , 8928 + # 8423 , 8026 + # 8544 , 8030 + # 10102 , 9926 + # 9705 , 9581 + # 9147 , 8805 + # 7849 , 7784 + # 9046 , 8942 + # 9592 , 9582 + # 10218 , 10217 + # 9773 , 9491 + # 9511 , 9510 + # 11258 , 10861 + # 8149 , 8026 + # 9563 , 9491 + # 8542 , 8451 + # 7900 , 7895 + # 9315 , 8605 + # 4725 , 472 + # 7603 , 7577 + # 8478 , 8154 + # 11118 , 11085 + # 9314 , 8605 + # 9145 , 8805 + # 8528 , 8026 + # 10858 , 10836 + # 8997 , 8926 + # 8533 , 8030 + # 9560 , 9491 + # 8499 , 8026 + # 10609 , 10498 + # 10726 , 10717 + # 8945 , 8805 + # 10166 , 9839 + # 7676 , 7656 + # 11213 , 11212 + # 8612 , 8518 + # 8526 , 8026 + # 8853 , 8805 + # 10391 , 10383 + # 9564 , 9491 + # 8258 , 8153 + # 9742 , 9553 + # 8327 , 8026 + # 10360 , 9839 + # 8205 , 8135 + # 9512 , 9496 + # 9001 , 8950 + # 8859 , 8605 + # 9236 , 8605 + # 9686 , 9542 + # 10070 , 9839 + # 9458 , 9457 + # 9078 , 8805 + # 8425 , 8026 + # 8464 , 8026 + # 9688 , 9574 + # 7756 , 7755 + # 9079 , 8805 + # 8549 , 8030 + # 10921 , 10906 + # 9657 , 9654 + # 8522 , 8452 + # 8248 , 8154 + # 8158 , 8154 + # 8530 , 8026 + # 8531 , 8026 + # 11020 , 11003 + # 8534 , 8030 + # 9218 , 9170 + # 10165 , 9839 + # 9843 , 8605 + # 8148 , 8026 + # 10908 , 10906 + # 8915 , 8908 + # 9711 , 9582 + # 9380 , 9378 + # 9492 , 9491 + # 8201 , 8196 + # 7702 , 7701 + # 9295 , 9261 + # 9115 , 8928 + # 9516 , 9495 + # 9697 , 8605 + # 10920 , 10831 + # 10385 , 10383 + # 8860 , 8605 + # 8386 , 8314 + # 8539 , 8454 + # 8812 , 8805 + # 7703 , 7701 + # 8944 , 8805 + # 9114 , 8928 + # 8032 , 8030 + # 8609 , 8605 + # 9729 , 9582 + # 8489 , 8030 + # 8545 , 8030 + # 9698 , 8605 + # 9235 , 8605 + # 9153 , 9117 + # 9566 , 8605 + # 9044 , 8942 + # 8139 , 8074 + # 9493 , 9491 + # 7999 , 7993 + # 10071 , 9839 + # 9461 , 9385 + # 9589 , 9575 + # 8073 , 8059 + # 10119 , 10013 + # 10389 , 10387 + # 9370 , 9357 + # 7995 , 7994 + # 9588 , 9582 + # 9084 , 8928 + # 9152 , 9117 + # 9840 , 9839 + # 9616 , 9545 + # 9462 , 9385 + # 7991 , 7990 + # 8850 , 8805 + # 9587 , 9582 + # 8202 , 8196 + # 8561 , 8553 + # 8529 , 8026 + # 8482 , 8385 + # 8465 , 8026 + # 9715 , 9712 + # 10746 , 10744 + # 8249 , 8154 + # 10447 , 9839 + # 9077 , 8805 + # 9179 , 8605 + # 8328 , 8026 + # 10911 , 10906 + # 9856 , 9854 + # 9083 , 8928 + # 8204 , 8142 + # 9997 , 9916 + # 8527 , 8026 + # 9685 , 9505 + # 8606 , 8605 + # 9388 , 9385 + # 8607 , 8605 + # 9687 , 9542 + # 11102 , 11101 + # 9593 , 9579 + # 8806 , 8805 + # 9905 , 9875 + # 8862 , 8605 + # 10072 , 9839 + # 8550 , 8030 + # 9845 , 8605 + # 8551 , 8030 + # 9842 , 9839 + # 8027 , 8026 + # 8865 , 8605 + # 7977 , 7975 + # 9387 , 9385 + # 9726 , 9550 + # 8479 , 8030 + # 7685 , 7683 + # 9846 , 8605 + # 9781 , 9776 + # 8947 , 8805 + # 8552 , 8030 + # 7968 , 7810 + # 9709 , 9582 + # 9768 , 9491 + # 8854 , 8605 + # 9708 , 9581 + # 9158 , 9120 + # 10950 , 10816 + # 8608 , 8605 + # 5069 , 5066 + # 9027 , 8805 + # 8252 , 8154 + # 7647 , 7634 + # 9682 , 9538 + # 8535 , 8030 + # 9454 , 9438 + # 8490 , 8030 + # 7637 , 7608 + # 9080 , 8805 + # 7646 , 7609 + # 9509 , 9456 + # 9707 , 9581 + # 9025 , 8805 + # 8949 , 8805 + # 9570 , 8605 + # 8613 , 8569 + # 11047 , 11046 + # 8505 , 8030 + # 10446 , 9839 + # 8486 , 8030 + # 9076 , 8805 + # 8861 , 8605 + # 9681 , 9584 + # 9844 , 8605 + # 9558 , 9495 + # 9517 , 9494 + # 8541 , 8452 + # 8251 , 8154 + # 8508 , 8154 + # 10907 , 10906 + # 8424 , 8026 + # 9755 , 9556 + # 11255 , 11212 + # 8946 , 8805 + # 8507 , 8154 + # 8811 , 8805 + # 8596 , 8578 + # 8810 , 8805 + # 10011 , 9902 + # 10910 , 10906 + # 7589 , 7578 + # 7979 , 7978 + # 9706 , 9581 + # 8250 , 8154 + # 9772 , 9491 + # 8506 , 8030 + # 10101 , 9922 + # 9148 , 8805 + # 8470 , 8026 + # 9515 , 9495 + # 9049 , 9008 + # 8641 , 8578 + # 8157 , 8154 + # 10113 , 10055 + # 10782 , 10723 + # 8379 , 8026 + # 9561 , 9491 + # 10103 , 9915 + # 9782 , 9775 + # 10377 , 10337 + # 9612 , 9573 + # 8033 , 8030 + # 8948 , 8805 + # 9396 , 9392 + # 8150 , 8030 + # 9586 , 9582 + # 9710 , 9582 + # 8610 , 8605 + # 9569 , 8605 + # 11097 , 11081 + # 8809 , 8805 + # 9237 , 8605 + # 10361 , 9839 + # 10390 , 10387 + # 7967 , 7934 + # 10392 , 10383 + # 9003 , 8950 + # 9774 , 9491 + # 9730 , 9676 + # 7643 , 7642 + # 8232 , 8231 + # 9868 , 9867 + # 8548 , 8536 + # 9847 , 8605 + # 9615 , 9536 + # 9087 , 9086 + # 10069 , 9839 + # 8640 , 8578 + # 8647 , 8554 + # 9028 , 8805 + # 9771 , 9491 + # 8849 , 8805 + # 9029 , 8805 + # 8500 , 8026 + # 9176 , 9175 + # 8523 , 8026 + # 9178 , 8605 + # 9203 , 9194 + # 8546 , 8030 + # 8807 , 8805 + # 9590 , 9577 + # 11004 , 11003 + # 9684 , 9505 + # 8152 , 8030 + # 9535 , 9411 + # 9180 , 9135 + # 7757 , 7755 + # 10118 , 10093 + # 8858 , 8605 + # 9146 , 8805 + # 7874 , 7833 + # 8532 , 8030 + # 9594 , 9579 + # 9567 , 8605 + # 9026 , 8805 + # 9651 , 9649 + # 9202 , 9194 + # 9294 , 9263 + # 9614 , 9575 + # 9293 , 9264 + # 8485 , 8030 + # 9316 , 8673 + # 8312 , 8227 + # 8477 , 8154 + # 10745 , 10744 + # 8547 , 8537 + # 9695 , 8605 + # 9744 , 9678 + # 8448 , 8443 + # 10104 , 9918 + # 10164 , 9839 + # 10731 , 10649 + # 7997 , 7994 + # 8034 , 8030 + # 8808 , 8805 + # 7996 , 7994 + # 11117 , 11116 + # 8498 , 8030 + # 9463 , 9385 + # 9857 , 9855 + # 8031 , 8030 + # 9082 , 8928 + # 8863 , 8605 + # 10912 , 10906 + # 8206 , 8108 + # 8524 , 8026 + + +} #------------------------------------------------------------------------------- + +use db ; +use today ; +use common ; +use common_min ; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/correct_linked_vpu_id.pl b/scripts/_FromProd/v1.0/admin/oneoff/correct_linked_vpu_id.pl new file mode 100644 index 0000000..4f8ad6d --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/correct_linked_vpu_id.pl @@ -0,0 +1,99 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +&today ; + +#------------------------------------------------------------------------------------------ + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); + +foreach $ARG (@ARGV) { ($par,$val) = split(/\=/,$ARG) ; $param{$par} = $val ; } + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/correct_linked_vpu_id.pl?1 + +our $debug = $ARGV[0] ; +our $username = 'rory' ; + +# print "\n debug : $debug \n" ; + +if ($debug) { print "Content-type: text/html\n\n"; } + +&common_debug("\n 1. START") ; + +#------------------------------------------------------------------------------------------ + +&today ; +&common_debug("\n 2. START") ; +# &set_delete_date ; +&read_sessions ; + +if ($debug) { print "Done."; } + +exit; + + +#------------------------------------------------------------------------------------------ + +sub read_sessions { + +&db_open_ro ; + +# my $sql = qq( +# SELECT id,c2.id2 FROM `cameras` c1 +# LEFT JOIN ( + # SELECT id AS 'id2',substr(camera_nr,4,7) AS 'sub_cam_nr', camera_nr AS 'camera_nr_2' FROM `cameras` WHERE camera_nr LIKE 'vpu%' AND (camera_nr LIKE '%s1%' OR camera_nr LIKE '%s2%') +# ) c2 ON c2.sub_cam_nr = c1.camera_nr +# WHERE c1.camera_nr NOT LIKE 'vpu%' AND (c1.camera_nr LIKE '%s1%' OR c1.camera_nr LIKE '%s2%') AND linked_vpu_id = 0 +# ) ; + +my $sql = qq~ +SELECT c2.id,c1.id FROM `cameras` c1 +left join ( + SELECT id,camera_nr,event_linked_vpu FROM `cameras` WHERE camera_nr NOT LIKE 'vpu%' AND (camera_nr LIKE '%s1%' OR camera_nr LIKE '%s2%') +) c2 on c2.event_linked_vpu = c1.serial_nr +WHERE c1.camera_nr LIKE 'vpu%' AND (c1.camera_nr LIKE '%s1%' OR c1.camera_nr LIKE '%s2%') and linked_vpu_id = 0 and c2.id is not null ; +~ ; + +&common_debug("\n 3 . START "); + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +$id_array_ref = $sth->fetchall_arrayref(); +$sth->finish(); +# my $cnt = 0 ; + +foreach my $row (@$id_array_ref) { + next unless @$row[1] ; + # last if $cnt ; + # $cnt++ ; + # &common_debug("\n UPDATE cameras SET linked_vpu_id = @$row[1] WHERE id = @$row[0] \n") ; + $sql = qq~UPDATE cameras SET linked_vpu_id = @$row[1] WHERE id = @$row[0] ; ~ ; + &common_debug("$sql") ; + $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + + # foreach (@a_session) { + # my ($param,$val) = split(/=>/) ; + # if ($param =~ /timestamp/) { + # my $date_ccyy_mm_dd = substr($val,2,10); + # my ($sccyy,$smm,$sdd) = split(/\-/,$date_ccyy_mm_dd); + # my $sdate = $sccyy . $smm . $sdd ; + # if ($sdate < $delete_date) { + # print "
    ($sdate < $delete_date)" ; + # # &delete_session($id) ; + # } + # } + # } +} + +&db_close_conn ; + +} #------------------------------------------------------------------------------- + +use db ; +use today ; +use common ; +use common_min ; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/dcb_create_waybill_test.pl b/scripts/_FromProd/v1.0/admin/oneoff/dcb_create_waybill_test.pl new file mode 100644 index 0000000..65d9821 --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/dcb_create_waybill_test.pl @@ -0,0 +1,199 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser); + +print "Content-type: text/html\n\n"; + +use LWP::UserAgent; +# use HTTP::Request; +use XML::Simple ; +use DBI; +# use SOAP::Lite ; + + +#------------------------------------------------------------------------------- + + @ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0]; +our $from_to = $ARGV[1]; +our $event_id = $ARGV[2]; +our $logistics_dcb_waybill = $ARGV[3]; +# my $suburb = $ARGV[1]; + +# $suburb =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/dcb_create_waybill_test.pl?1 + +#------------------------------------------------------------------------------- + +&today; +&db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &send_it ; + &parse_it ; + &read_it ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +# &dcd_set_parameters ; +# &dcb_send_xml ; + +exit; + +#------------------------------------------------------------------------------- + +sub send_it { + + my $message = qq~ + + + + + + + + + + + +27 (79) 888 7121 + CLINT SLIEDRECHT + + 2024-05-31 + AMERICAN INTERNATIONAL SCHOOL CAPE TOWN + ITVTEST123 + ITV CPT + 1619 + DEV SERVICE + JNBKMPE + HelloWOrld!!!dfsdfdfsdfasdfasdfasdfdsfasdfasdfasdf sf sdf asdf + 1 + + + + ~ ; + + if ($debug) { + # print $message; + } + + my $userAgent = LWP::UserAgent->new(); + my $request = HTTP::Request->new(POST => 'https://dcboms.co.za/APIUAT/OMSIntegrate.svc'); + $request->header(SOAPAction => '"http://tempuri.org/IOMSIntegrate/savewabill"'); + $request->content($message); + $request->content_type("text/xml; charset=utf-8"); + my $response = $userAgent->request($request); + + # Check response + my $response_code = $response -> code ; + my $response_content = $response -> content ; + + $returnxml = $response_content ; + + # print $returnxml ; + +} #------------------------------------------------------------------------------- + +sub parse_it { + + # use Data::Dumper; + # print Dumper(\$returnxml); + # exit; + + $returnxml =~ s/[\x80-\xFF]/?/g ; + my $xml = new XML::Simple or die "Cant instantiate object XML::Simple $!" ; + # my $xmldata = $xml->XMLin($returnxml) or die "Cant open xmldata $!" ; + $xmldata = $xml->XMLin($returnxml, forcearray => 1) or die "Cant open xmldata $!"; + + if ($debug) { + use Data::Dumper; + print Dumper(\$xmldata); + # exit ; + } + +} #------------------------------------------------------------------------------- + +sub read_it { + + print "\n" . $xmldata->{'s:Body'}->[0]->{'savewabillResponse'}->[0]->{'savewabillResult'}->[0] ; + + return unless $event_id ; + return unless $from_to ; + + # &db_min_ro("event_quotes","1,logistics_dcb_waybill","`id`='$event_id'","","") ; + + # my @waybill_nrs = split(/\-/,$db{event_quotes}{1}{logistics_waybill_nrs}) ; + my @dcb_waybill = split(/\-/,$logistics_dcb_waybill) ; + + %i = () ; + + $i{logistics_dcb_waybill} = ($from_to eq 'to') ? "$dcb_waybill[0]-1" : "1-$dcb_waybill[1]" ; + + # our $testing = 1 ; + + # &db_min_upd('event_quotes',"`id`='$event_id'") ; + &db_min_upd('event_quotes',"`id`='5136'") ; + +} #------------------------------------------------------------------------------- + + + +sub dcd_set_parameters { + +# use SOAP::Lite ; + # +trace => [ transport => sub { print $_[0]->as_string } ]; + +$dcb_param{'uri'} = 'https://dcboms.co.za/APIUAT/OMSIntegrate.svc' ; +$dcb_param{'proxy'} = 'https://dcboms.co.za/APIUAT/OMSIntegrate.svc' ; +# $dcb_param{'username'} = 'res@followme2africa.com' ; +# $dcb_param{'password'} = 'moby602' ; + +} #---------------------------------------------------------------------------------------------------- + +sub dcb_send_xml { + +$dcb_param{'method'} = 'PostalCode' ; + +&dcb_create_soap ; + +# if (lc $username eq 'groz000'){ + # print "Content-type: text/html\n\n"; + # use Data::Dumper; + # print Dumper(\$xml_out_save_itinerary); + # } + +$xml_out = qq~ + + + POMONA + +~ ; + +$xml_out_dcb_soap = SOAP::Data->type('xml' => $xml_out); + +$dcb_response = $dcb_soap -> call ($dcb_method => $xml_out_dcb_soap) ; + +&common_debug ("dcb_send_xml : dcb_response [ $dcb_response ]") ; + +} #---------------------------------------------------------------------------------------------------- + +sub dcb_create_soap { + +$dcb_soap = SOAP::Lite + ->proxy( $dcb_param{'proxy'} ) + ->autotype(0) + ->outputxml(1) + ->on_action( sub { join '/', @_ } ) + ; + +$dcb_method = SOAP::Data -> name( $dcb_param{'method'} ) -> attr({ 'xmlns' => $dcb_param{'uri'} } ) ; + +} #---------------------------------------------------------------------------------------------------- + +use common ; +use today ; + +1; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/dcb_postalcode_lookup.pl b/scripts/_FromProd/v1.0/admin/oneoff/dcb_postalcode_lookup.pl new file mode 100644 index 0000000..524bf63 --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/dcb_postalcode_lookup.pl @@ -0,0 +1,195 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser); + +print "Content-type: text/html\n\n"; + +use LWP::UserAgent; +use HTTP::Request; +use XML::Simple ; +use DBI; +use SOAP::Lite ; + +#------------------------------------------------------------------------------- + + @ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0]; +my $suburb = $ARGV[1]; +my $postalcode = $ARGV[2]; + +$suburb =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/dcb_postalcode_lookup.pl?1&Morningside&4001 + +#------------------------------------------------------------------------------- + +&today; + +&send_it ; +&parse_it ; +&read_it ; + +# &dcd_set_parameters ; +# &dcb_send_xml ; + +exit; + +#------------------------------------------------------------------------------- + +sub send_it { + + my $message = qq~ + + + + + $postalcode + $suburb + + + + ~ ; + + if ($debug) { + print $message; + } + + my $userAgent = LWP::UserAgent->new(); + # my $request = HTTP::Request->new(POST => 'https://dcboms.co.za/APIUAT/OMSIntegrate.svc'); + my $request = HTTP::Request->new(POST => 'https://dcboms.co.za/API/OMSIntegrate.svc'); + $request->header(SOAPAction => '"http://tempuri.org/IOMSIntegrate/PostalCode"'); + $request->content($message); + $request->content_type("text/xml; charset=utf-8"); + my $response = $userAgent->request($request); + + # Check response + my $response_code = $response -> code ; + my $response_content = $response -> content ; + + $returnxml = $response_content ; + + # print $returnxml ; + +} #------------------------------------------------------------------------------- + +sub parse_it { + + # use Data::Dumper; + # print Dumper(\$returnxml); + # exit; + + $returnxml =~ s/[\x80-\xFF]/?/g ; + my $xml = new XML::Simple or die "Cant instantiate object XML::Simple $!" ; + # my $xmldata = $xml->XMLin($returnxml) or die "Cant open xmldata $!" ; + $xmldata = $xml->XMLin($returnxml, forcearray => 1) or die "Cant open xmldata $!"; + + if ($debug) { + use Data::Dumper; + print Dumper(\$xmldata); + # exit ; + } + +} #------------------------------------------------------------------------------- + +sub read_it { + + foreach my $hashref ( @{$xmldata->{'s:Body'}->[0]->{'PostalCodeResponse'}->[0]->{'PostalCodeResult'}->[0]->{'a:ArrayOfpostalCode'} } ) { + # unless (lc ${$hashref}{'Name'}->[0] eq lc $search) { next ; } + # print ${$hashref}{'ContentEntityId'}->[0] ; + + # unless (exists $exists{${$hashref}{'a:postalCode'}->[0]}) { + foreach $address ( @{$hashref}{'a:postalCode'}) { + # print $address . "
    " ; + # print Dumper(\$address); + # print Dumper(\$address{'a:city'}->[0]); + print 'a:city=' . ${$hashref}{'a:postalCode'}->[0]->{'a:city'}->[0] . "\n" ; + print 'a:suburb=' . ${$hashref}{'a:postalCode'}->[0]->{'a:suburb'}->[0] . "\n" ; + print 'a:code=' . ${$hashref}{'a:postalCode'}->[0]->{'a:code'}->[0] . "\n" ; + print 'a:routeCode=' . ${$hashref}{'a:postalCode'}->[0]->{'a:routeCode'}->[0] . "\n" ; + # print ${$address}->[0] . "\n" ; + # print 'a:city=' . ${$address}{'a:city'}->[0] . "
    " ; + # print 'a:routeCode=' . ${$address}{'a:routeCode'}->[0] . "
    " ; + # print 'a:suburb=' . ${$address}{'a:suburb'}->[0] . "
    " ; + # print 'a:code=' . ${$address}{'a:code'}->[0] . "
    " ; + + # $i{dcb_id} = ${$hashref}{'ContentEntityId'}->[0] ; + # $i{latitude} = ${$hashref}{'Latitude'}->[0] ; + # $i{longitude} = ${$hashref}{'Longitude'}->[0] ; + # $i{country} = ${$hashref}{'Country'}->[0] ; + # $i{area} = ${$hashref}{'Area'}->[0] ; + + # # unless (ref(${$hashref}{'Area'}->[0] eq 'HASH')) { $i{area} = ${$hashref}{'Area'}->[0] ; } + # # unless (ref(${$hashref}{'Location'}->[0] eq 'HASH')) { $i{location} = ${$hashref}{'Location'}->[0] ; } + + # $i{location} = ${$hashref}{'Location'}->[0] unless (ref(${$hashref}{'Location'}->[0]) eq 'HASH'); + + # $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + # &common_db_insert('dcb_places') ; + } + # last ; + } + +} #------------------------------------------------------------------------------- + + + +sub dcd_set_parameters { + +# use SOAP::Lite ; + # +trace => [ transport => sub { print $_[0]->as_string } ]; + +$dcb_param{'uri'} = 'https://dcboms.co.za/APIUAT/OMSIntegrate.svc' ; +$dcb_param{'proxy'} = 'https://dcboms.co.za/APIUAT/OMSIntegrate.svc' ; +# $dcb_param{'username'} = 'res@followme2africa.com' ; +# $dcb_param{'password'} = 'moby602' ; + +} #---------------------------------------------------------------------------------------------------- + +sub dcb_send_xml { + +$dcb_param{'method'} = 'PostalCode' ; + +&dcb_create_soap ; + +# if (lc $username eq 'groz000'){ + # print "Content-type: text/html\n\n"; + # use Data::Dumper; + # print Dumper(\$xml_out_save_itinerary); + # } + +$xml_out = qq~ + + + POMONA + +~ ; + +$xml_out_dcb_soap = SOAP::Data->type('xml' => $xml_out); + +$dcb_response = $dcb_soap -> call ($dcb_method => $xml_out_dcb_soap) ; + +&common_debug ("dcb_send_xml : dcb_response [ $dcb_response ]") ; + +} #---------------------------------------------------------------------------------------------------- + +sub dcb_create_soap { + +$dcb_soap = SOAP::Lite + ->proxy( $dcb_param{'proxy'} ) + ->autotype(0) + ->outputxml(1) + ->on_action( sub { join '/', @_ } ) + ; + +$dcb_method = SOAP::Data -> name( $dcb_param{'method'} ) -> attr({ 'xmlns' => $dcb_param{'uri'} } ) ; + +} #---------------------------------------------------------------------------------------------------- + +use common ; +use today ; + +1; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/dcb_soap_test.pl b/scripts/_FromProd/v1.0/admin/oneoff/dcb_soap_test.pl new file mode 100644 index 0000000..2312787 --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/dcb_soap_test.pl @@ -0,0 +1,194 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser); + +print "Content-type: text/html\n\n"; + +use LWP::UserAgent; +use HTTP::Request; +use XML::Simple ; +use DBI; +use SOAP::Lite ; + +#------------------------------------------------------------------------------- + + @ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0]; +my $suburb = $ARGV[1]; + +$suburb =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/dcb_soap_test.pl?1 + +#------------------------------------------------------------------------------- + +&today; + +&send_it ; +&parse_it ; +&read_it ; + +# &dcd_set_parameters ; +# &dcb_send_xml ; + +exit; + +#------------------------------------------------------------------------------- + +sub send_it { + + my $message = qq~ + + + + + + $suburb + + + + ~ ; + + if ($debug) { + print $message; + } + + my $userAgent = LWP::UserAgent->new(); + my $request = HTTP::Request->new(POST => 'https://dcboms.co.za/APIUAT/OMSIntegrate.svc'); + # $request->header(SOAPAction => '"https://dcboms.co.za/APIUAT/OMSIntegrate.svc"'); + $request->header(SOAPAction => '"http://tempuri.org/IOMSIntegrate/PostalCode"'); + $request->content($message); + $request->content_type("text/xml; charset=utf-8"); + my $response = $userAgent->request($request); + + # Check response + my $response_code = $response -> code ; + my $response_content = $response -> content ; + + $returnxml = $response_content ; + + # print $returnxml ; + +} #------------------------------------------------------------------------------- + +sub parse_it { + + # use Data::Dumper; + # print Dumper(\$returnxml); + # exit; + + $returnxml =~ s/[\x80-\xFF]/?/g ; + my $xml = new XML::Simple or die "Cant instantiate object XML::Simple $!" ; + # my $xmldata = $xml->XMLin($returnxml) or die "Cant open xmldata $!" ; + $xmldata = $xml->XMLin($returnxml, forcearray => 1) or die "Cant open xmldata $!"; + + if ($debug) { + use Data::Dumper; + print Dumper(\$xmldata); + # exit ; + } + +} #------------------------------------------------------------------------------- + +sub read_it { + + foreach my $hashref ( @{$xmldata->{'s:Body'}->[0]->{'PostalCodeResponse'}->[0]->{'PostalCodeResult'}->[0]->{'a:ArrayOfpostalCode'} } ) { + # unless (lc ${$hashref}{'Name'}->[0] eq lc $search) { next ; } + # print ${$hashref}{'ContentEntityId'}->[0] ; + + # unless (exists $exists{${$hashref}{'a:postalCode'}->[0]}) { + foreach $address ( @{$hashref}{'a:postalCode'}) { + # print $address . "
    " ; + # print Dumper(\$address); + # print Dumper(\$address{'a:city'}->[0]); + print 'a:city=' . ${$hashref}{'a:postalCode'}->[0]->{'a:city'}->[0] . "\n" ; + print 'a:suburb=' . ${$hashref}{'a:postalCode'}->[0]->{'a:suburb'}->[0] . "\n" ; + print 'a:code=' . ${$hashref}{'a:postalCode'}->[0]->{'a:code'}->[0] . "\n" ; + print 'a:routeCode=' . ${$hashref}{'a:postalCode'}->[0]->{'a:routeCode'}->[0] . "\n" ; + # print ${$address}->[0] . "\n" ; + # print 'a:city=' . ${$address}{'a:city'}->[0] . "
    " ; + # print 'a:routeCode=' . ${$address}{'a:routeCode'}->[0] . "
    " ; + # print 'a:suburb=' . ${$address}{'a:suburb'}->[0] . "
    " ; + # print 'a:code=' . ${$address}{'a:code'}->[0] . "
    " ; + + # $i{dcb_id} = ${$hashref}{'ContentEntityId'}->[0] ; + # $i{latitude} = ${$hashref}{'Latitude'}->[0] ; + # $i{longitude} = ${$hashref}{'Longitude'}->[0] ; + # $i{country} = ${$hashref}{'Country'}->[0] ; + # $i{area} = ${$hashref}{'Area'}->[0] ; + + # # unless (ref(${$hashref}{'Area'}->[0] eq 'HASH')) { $i{area} = ${$hashref}{'Area'}->[0] ; } + # # unless (ref(${$hashref}{'Location'}->[0] eq 'HASH')) { $i{location} = ${$hashref}{'Location'}->[0] ; } + + # $i{location} = ${$hashref}{'Location'}->[0] unless (ref(${$hashref}{'Location'}->[0]) eq 'HASH'); + + # $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + # &common_db_insert('dcb_places') ; + } + # last ; + } + +} #------------------------------------------------------------------------------- + + + +sub dcd_set_parameters { + +# use SOAP::Lite ; + # +trace => [ transport => sub { print $_[0]->as_string } ]; + +$dcb_param{'uri'} = 'https://dcboms.co.za/APIUAT/OMSIntegrate.svc' ; +$dcb_param{'proxy'} = 'https://dcboms.co.za/APIUAT/OMSIntegrate.svc' ; +# $dcb_param{'username'} = 'res@followme2africa.com' ; +# $dcb_param{'password'} = 'moby602' ; + +} #---------------------------------------------------------------------------------------------------- + +sub dcb_send_xml { + +$dcb_param{'method'} = 'PostalCode' ; + +&dcb_create_soap ; + +# if (lc $username eq 'groz000'){ + # print "Content-type: text/html\n\n"; + # use Data::Dumper; + # print Dumper(\$xml_out_save_itinerary); + # } + +$xml_out = qq~ + + + POMONA + +~ ; + +$xml_out_dcb_soap = SOAP::Data->type('xml' => $xml_out); + +$dcb_response = $dcb_soap -> call ($dcb_method => $xml_out_dcb_soap) ; + +&common_debug ("dcb_send_xml : dcb_response [ $dcb_response ]") ; + +} #---------------------------------------------------------------------------------------------------- + +sub dcb_create_soap { + +$dcb_soap = SOAP::Lite + ->proxy( $dcb_param{'proxy'} ) + ->autotype(0) + ->outputxml(1) + ->on_action( sub { join '/', @_ } ) + ; + +$dcb_method = SOAP::Data -> name( $dcb_param{'method'} ) -> attr({ 'xmlns' => $dcb_param{'uri'} } ) ; + +} #---------------------------------------------------------------------------------------------------- + +use common ; +use today ; + +1; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/dcb_waybill_test.pl b/scripts/_FromProd/v1.0/admin/oneoff/dcb_waybill_test.pl new file mode 100644 index 0000000..0b90369 --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/dcb_waybill_test.pl @@ -0,0 +1,308 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser); + +print "Content-type: text/html\n\n"; + +use LWP::UserAgent; +use HTTP::Request; +use XML::Simple ; +use DBI; +use SOAP::Lite ; + +#------------------------------------------------------------------------------- + + @ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0]; +my $suburb = $ARGV[1]; + +$suburb =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/dcb_soap_test.pl?1 + +#------------------------------------------------------------------------------- + +&today; + +&send_it ; +&parse_it ; +&read_it ; + +# &dcd_set_parameters ; +# &dcb_send_xml ; + +exit; + +#------------------------------------------------------------------------------- + +sub send_it { + + +# + # + # + # + # + # DCBDEVLP + # 15 SIM ROAD + # , + # POMONA + # GAUTENG + # 0 + # DEV + # DEV + # 2023-01-26 + # JNB + # APITEST23 + # JNB + # 1619 + # DEV SERVICE + # JNBKMPE + # + # 1 + # + # + # + # + # + # + # + # + # 0 + # + # + # + # + # + # + # STD + # G + # 0 + # 40 + # DEV + # 32 + # 32 + # 32 + # 1 + # + # + # + # + # +# + + +# + # + # + # + # + # DCBDEVLP + # 15 SIM ROAD + # , + # POMONA + # GAUTENG + # 0 + # DEV + # DEV + # 2023-01-26 + # JNB + # APITEST23 + # JNB + # 1619 + # DEV SERVICE + # JNBKMPE + # + # 1 + # + # + # + # + # + # + # + # + # 0 + # + # + # + # + # + # + # STD + # G + # 0 + # 40 + # DEV + # 32 + # 32 + # 32 + # 1 + # + # + # + # + # +# + # + # + # + # $suburb + # + # + + my $message = qq~ + + + + + + $suburb + + + + ~ ; + + if ($debug) { + # print $message; + } + + my $userAgent = LWP::UserAgent->new(); + my $request = HTTP::Request->new(POST => 'https://dcboms.co.za/APIUAT/OMSIntegrate.svc'); + # $request->header(SOAPAction => '"https://dcboms.co.za/APIUAT/OMSIntegrate.svc"'); + $request->header(SOAPAction => '"http://tempuri.org/IOMSIntegrate/PostalCode"'); + $request->content($message); + $request->content_type("text/xml; charset=utf-8"); + my $response = $userAgent->request($request); + + # Check response + my $response_code = $response -> code ; + my $response_content = $response -> content ; + + $returnxml = $response_content ; + + # print $returnxml ; + +} #------------------------------------------------------------------------------- + +sub parse_it { + + # use Data::Dumper; + # print Dumper(\$returnxml); + # exit; + + $returnxml =~ s/[\x80-\xFF]/?/g ; + my $xml = new XML::Simple or die "Cant instantiate object XML::Simple $!" ; + # my $xmldata = $xml->XMLin($returnxml) or die "Cant open xmldata $!" ; + $xmldata = $xml->XMLin($returnxml, forcearray => 1) or die "Cant open xmldata $!"; + + if ($debug) { + use Data::Dumper; + print Dumper(\$xmldata); + # exit ; + } + +} #------------------------------------------------------------------------------- + +sub read_it { + + foreach my $hashref ( @{$xmldata->{'s:Body'}->[0]->{'PostalCodeResponse'}->[0]->{'PostalCodeResult'}->[0]->{'a:ArrayOfpostalCode'} } ) { + # unless (lc ${$hashref}{'Name'}->[0] eq lc $search) { next ; } + # print ${$hashref}{'ContentEntityId'}->[0] ; + + # unless (exists $exists{${$hashref}{'a:postalCode'}->[0]}) { + foreach $address ( @{$hashref}{'a:postalCode'}) { + # print $address . "
    " ; + # print Dumper(\$address); + # print Dumper(\$address{'a:city'}->[0]); + # print 'a:city=' . ${$hashref}{'a:postalCode'}->[0]->{'a:city'}->[0] . "\n" ; + # print 'a:suburb=' . ${$hashref}{'a:postalCode'}->[0]->{'a:suburb'}->[0] . "\n" ; + # print 'a:code=' . ${$hashref}{'a:postalCode'}->[0]->{'a:code'}->[0] . "\n" ; + # print 'a:routeCode=' . ${$hashref}{'a:postalCode'}->[0]->{'a:routeCode'}->[0] . "\n" ; + # print ${$address}->[0] . "\n" ; + # print 'a:city=' . ${$address}{'a:city'}->[0] . "
    " ; + # print 'a:routeCode=' . ${$address}{'a:routeCode'}->[0] . "
    " ; + # print 'a:suburb=' . ${$address}{'a:suburb'}->[0] . "
    " ; + # print 'a:code=' . ${$address}{'a:code'}->[0] . "
    " ; + + # $i{dcb_id} = ${$hashref}{'ContentEntityId'}->[0] ; + # $i{latitude} = ${$hashref}{'Latitude'}->[0] ; + # $i{longitude} = ${$hashref}{'Longitude'}->[0] ; + # $i{country} = ${$hashref}{'Country'}->[0] ; + # $i{area} = ${$hashref}{'Area'}->[0] ; + + # # unless (ref(${$hashref}{'Area'}->[0] eq 'HASH')) { $i{area} = ${$hashref}{'Area'}->[0] ; } + # # unless (ref(${$hashref}{'Location'}->[0] eq 'HASH')) { $i{location} = ${$hashref}{'Location'}->[0] ; } + + # $i{location} = ${$hashref}{'Location'}->[0] unless (ref(${$hashref}{'Location'}->[0]) eq 'HASH'); + + # $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + # &common_db_insert('dcb_places') ; + } + # last ; + } + +} #------------------------------------------------------------------------------- + + + +sub dcd_set_parameters { + +# use SOAP::Lite ; + # +trace => [ transport => sub { print $_[0]->as_string } ]; + +$dcb_param{'uri'} = 'https://dcboms.co.za/APIUAT/OMSIntegrate.svc' ; +$dcb_param{'proxy'} = 'https://dcboms.co.za/APIUAT/OMSIntegrate.svc' ; +# $dcb_param{'username'} = 'res@followme2africa.com' ; +# $dcb_param{'password'} = 'moby602' ; + +} #---------------------------------------------------------------------------------------------------- + +sub dcb_send_xml { + +$dcb_param{'method'} = 'PostalCode' ; + +&dcb_create_soap ; + +# if (lc $username eq 'groz000'){ + # print "Content-type: text/html\n\n"; + # use Data::Dumper; + # print Dumper(\$xml_out_save_itinerary); + # } + +$xml_out = qq~ + + + POMONA + +~ ; + +$xml_out_dcb_soap = SOAP::Data->type('xml' => $xml_out); + +$dcb_response = $dcb_soap -> call ($dcb_method => $xml_out_dcb_soap) ; + +&common_debug ("dcb_send_xml : dcb_response [ $dcb_response ]") ; + +} #---------------------------------------------------------------------------------------------------- + +sub dcb_create_soap { + +$dcb_soap = SOAP::Lite + ->proxy( $dcb_param{'proxy'} ) + ->autotype(0) + ->outputxml(1) + ->on_action( sub { join '/', @_ } ) + ; + +$dcb_method = SOAP::Data -> name( $dcb_param{'method'} ) -> attr({ 'xmlns' => $dcb_param{'uri'} } ) ; + +} #---------------------------------------------------------------------------------------------------- + +use common ; +use today ; + +1; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/event_quotes_fix_db.pl b/scripts/_FromProd/v1.0/admin/oneoff/event_quotes_fix_db.pl new file mode 100644 index 0000000..6a0279e --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/event_quotes_fix_db.pl @@ -0,0 +1,245 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser); +use Date::Calc qw(:all); +# use DBI; + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/event_quotes_fix_db.pl?1 + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0] ; +# our $username = 'rory' ; + +if ($debug) { print "Content-type: text/html\n\n"; } + +#------------------------------------------------------------------------------------------ + +&today ; + +&load_hash ; + +&db_open_upd ; +# &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &load_vars ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +if ($debug) { print "Done."; } + +exit; + +#------------------------------------------------------------------------------------------ + +sub load_vars { + + &db_min_ro('cities','*','','','') ; + foreach my $_id (sort {$a <=> $b} keys %{$db{cities}}) { + $city_id{lc $db{cities}{$_id}{city}} = $_id ; + } + + &db_min_ro('event_quotes','id,city',"id",'','') ; + + foreach my $_id (sort {$a <=> $b} keys %{$db{event_quotes}}) { + next unless $db{event_quotes}{$_id}{city} ; + + my $lc_city = lc $db{event_quotes}{$_id}{city} ; + $lc_city =~ s/^\s+|\s+$//g; + + $i{city_id} = ($city_id{$lc_city}) ? $city_id{$lc_city} : 0 ; + + &db_min_upd(event_quotes,"id='$_id'") ; + # &common_min_debug("UPDATE event_quotes SET city_id = '$i{city_id}' WHERE id = '$_id' [$lc_city]") ; + + } + +} #------------------------------------------------------------------------------- + +sub load_hash { + + $school_id_hash{"jeppe's high"} = 45 ; + $school_id_hash{"jeppe"} = 45 ; + # $school_id_hash{"st stithians college"} = 56 ; + $school_id_hash{"st stithians"} = 56 ; + $school_id_hash{"st stithians"} = 56 ; + $school_id_hash{"st stithian's"} = 56 ; + $school_id_hash{"st stithians + st andrew's"} = '56,53' ; + $school_id_hash{"cornwall college"} = 61 ; + $school_id_hash{"cornwall hill"} = 61 ; + $school_id_hash{"cornwall"} = 61 ; + $school_id_hash{"cornwall hill college"} = 61 ; + $school_id_hash{"st andrew's school for girls"} = 53 ; + $school_id_hash{"st andrew's college"} = 53 ; + $school_id_hash{"st andrew's"} = 53 ; + $school_id_hash{"st alban's college"} = 52 ; + $school_id_hash{"st albans"} = 52 ; + $school_id_hash{"st albans college"} = 52 ; + $school_id_hash{"st alban's rugby"} = 52 ; + $school_id_hash{"parktown high"} = 47 ; + $school_id_hash{"parktown"} = 47 ; + $school_id_hash{"st anne's college"} = 13 ; + $school_id_hash{"kes"} = 46 ; + $school_id_hash{"kes + parktown"} = '46,47' ; + $school_id_hash{"st joh's"} = 54 ; + $school_id_hash{"st john's"} = 54 ; + $school_id_hash{"st john's college"} = 54 ; + $school_id_hash{"pretoria boys high school"} = 49 ; + $school_id_hash{"clarendon all girls"} = 97 ; + $school_id_hash{"clarendon school for girls"} = 97 ; + $school_id_hash{"kimberley boys high"} = 37 ; + $school_id_hash{"selbourne college"} = 108 ; + $school_id_hash{"selborne"} = 108 ; + $school_id_hash{"dsg"} = 100 ; + $school_id_hash{"stellenbosch"} = 109 ; + $school_id_hash{"riverside"} = 12 ; + $school_id_hash{"waterkloof hs"} = 58 ; + $school_id_hash{"waterkloof + cornwall"} = '58,61' ; + $school_id_hash{"hs alberton"} = 41 ; + $school_id_hash{"st john's dsg"} = 15 ; + $school_id_hash{"keps"} = 154 ; + $school_id_hash{"grey high"} = 101 ; + $school_id_hash{"grey hs"} = 101 ; + $school_id_hash{"grey + eunice"} = 101 ; + $school_id_hash{"woodbridge"} = 155 ; + $school_id_hash{"saccs & wpcc"} = '107,111' ; + $school_id_hash{"wpcc"} = 111 ; + $school_id_hash{"northwood high school"} = 10 ; + $school_id_hash{"heron bridge"} = 38 ; + $school_id_hash{"herronbridge"} = 38 ; + $school_id_hash{"heronbridge college"} = 38 ; + $school_id_hash{"danville"} = 156 ; + $school_id_hash{"christ church"} = 57 ; + $school_id_hash{"christ church soccer"} = 57 ; + $school_id_hash{"st davids"} = 73 ; + $school_id_hash{"st david's"} = 73 ; + $school_id_hash{"st dunstans"} = 158 ; + $school_id_hash{"maties"} = 109 ; + $school_id_hash{"maties + bloemhof"} = '109,95' ; + $school_id_hash{"hs bloemhof"} = 95 ; + $school_id_hash{"bloemhof"} = 95 ; + $school_id_hash{"bloemhof + rhenish"} = '95,134' ; + $school_id_hash{"paul roos gimnasium"} = 104 ; + $school_id_hash{"alexandra"} = 17 ; + $school_id_hash{"alexander hs"} = 17 ; + $school_id_hash{"alex high school"} = 17 ; + $school_id_hash{"pbhs"} = 102 ; + $school_id_hash{"roedean"} = 51 ; + $school_id_hash{"roedean school"} = 51 ; + $school_id_hash{"roedean senior high"} = 51 ; + $school_id_hash{"roedean school (sa)"} = 51 ; + $school_id_hash{"maritzburg college + pmbgh"} = '8,11' ; + $school_id_hash{"eldoraigne"} = 43 ; + $school_id_hash{"hs waterkloof"} = 58 ; + $school_id_hash{"st mary's waverly"} = 55 ; + $school_id_hash{"st mary's waverley"} = 55 ; + $school_id_hash{"pretoria girls"} = 70 ; + $school_id_hash{"pretoria girls high school"} = 70 ; + $school_id_hash{"hs oosterlig"} = 40 ; + $school_id_hash{"pretoria high school for boys"} = 49 ; + $school_id_hash{"pretoria boys"} = 49 ; + $school_id_hash{"rondebosch high school"} = 106 ; + $school_id_hash{"rondebosh boys"} = 106 ; + $school_id_hash{"rondebosh"} = 106 ; + $school_id_hash{"rondebosch"} = 106 ; + $school_id_hash{"rbhs"} = 106 ; + $school_id_hash{"glenwood"} = 5 ; + $school_id_hash{"dhs"} = 4 ; + $school_id_hash{"beaulieu college"} = 59 ; + $school_id_hash{"st mary's"} = 15 ; + $school_id_hash{"st mary's kloof"} = 15 ; + $school_id_hash{"rhenish"} = 134 ; + $school_id_hash{"rhenish hs"} = 134 ; + $school_id_hash{"klerksdorp"} = 88 ; + $school_id_hash{"hs menlopark"} = 44 ; + $school_id_hash{"menlo park"} = 44 ; + $school_id_hash{"menlo + cornwall"} = '44,61' ; + $school_id_hash{"menlo"} = 44 ; + $school_id_hash{"benoni hs"} = 159 ; + $school_id_hash{"kloof hs"} = 161 ; + $school_id_hash{"bosmansdam"} = 112 ; + $school_id_hash{"lyttleton high"} = 162 ; + $school_id_hash{"hs transvalia"} = 75 ; + $school_id_hash{"noordheuwel"} = 66 ; + $school_id_hash{"westville"} = 16 ; + $school_id_hash{"westville hs"} = 16 ; + $school_id_hash{"stelleberg"} = 138 ; + $school_id_hash{"stellenberg"} = 138 ; + $school_id_hash{"reddam waterfall"} = 163 ; + $school_id_hash{"monnas hs"} = 42 ; + $school_id_hash{"hs noordheuwel + hs monument"} = '66,42' ; + $school_id_hash{"noordheuwel + monnas"} = '66,42' ; + $school_id_hash{"noordheuwel + monument"} = '66,42' ; + $school_id_hash{"st martins"} = 164 ; + $school_id_hash{"worcester gym"} = 141 ; + $school_id_hash{"st anne's"} = 13 ; + $school_id_hash{"paark boys high"} = 47 ; + $school_id_hash{"kearsney + st mary's kloof"} = '7,15' ; + $school_id_hash{"la rochelle + paarl girls + paarl boys"} = '128,131,102' ; + $school_id_hash{"pghs"} = 131 ; + $school_id_hash{"pmbgh"} = 11 ; + $school_id_hash{"curro thatchfield"} = 165 ; + $school_id_hash{"dphs"} = 2 ; + $school_id_hash{"waterstone college"} = 166 ; + $school_id_hash{"glenwood hs"} = 5 ; + $school_id_hash{"hugenote hs"} = 167 ; + $school_id_hash{"cloetesville"} = 168 ; + $school_id_hash{"thomas moore"} = 170 ; + $school_id_hash{"eg jansens"} = 62 ; + $school_id_hash{"hs hans moore"} = 63 ; + $school_id_hash{"crawford la lucia"} = 172 ; + $school_id_hash{"riverside + crawford la lucia"} = '12,172' ; + $school_id_hash{"riverside rugby"} = 12 ; + $school_id_hash{"randburg astro"} = 71 ; + $school_id_hash{"crawford north coast"} = 174 ; + $school_id_hash{"panorama sports ground"} = 175 ; + $school_id_hash{"uj"} = 177 ; + $school_id_hash{"tut + tuks"} = '178,179' ; + $school_id_hash{"tut + nwu"} = '178,180' ; + $school_id_hash{"hartleyvale + paarl"} = '181,102' ; + $school_id_hash{"trinity house"} = 76 ; + $school_id_hash{"garsfontein"} = 39 ; + $school_id_hash{"crawford sandton"} = 182 ; + $school_id_hash{"sol plaaitjie university"} = 185 ; + $school_id_hash{"st charles"} = 14 ; + $school_id_hash{"saheti bedfordview"} = 187 ; + $school_id_hash{"epworth"} = 20 ; + $school_id_hash{"sutherland"} = 189 ; + $school_id_hash{"alberton"} = 41 ; + + $region_id{"cape town"} = 9 ; + $region_id{"langa"} = 9 ; + $region_id{"grahamstown"} = 1 ; + $region_id{"mitchells plein"} = 9 ; + $region_id{"durban"} = 4 ; + $region_id{"pretoria"} = 3 ; + $region_id{"johannesburg"} = 3 ; + $region_id{"bloemfontein"} = 2 ; + + $sport_types_id_hash{'hockey & netball'} = '2,3' ; + $sport_types_id_hash{'netball + hockey'} = '2,3' ; + $sport_types_id_hash{'hockey + netball'} = '2,3' ; + $sport_types_id_hash{'hockey + rugby'} = '1,2' ; + $sport_types_id_hash{'rugby + hockey'} = '1,2' ; + $sport_types_id_hash{'hockey & rugby'} = '1,2' ; + $sport_types_id_hash{'rugby + netball'} = '1,3' ; + $sport_types_id_hash{'netball + rugby'} = '1,3' ; + $sport_types_id_hash{'football'} = 7 ; + $sport_types_id_hash{'rugby + rugby'} = 1 ; + $sport_types_id_hash{'hokcey'} = 2 ; + $sport_types_id_hash{'waterpolo + basketball'} = '4,5' ; + $sport_types_id_hash{'basketball + waterpolo'} = '4,5' ; + $sport_types_id_hash{'hockey + football + waterpolo'} = '2,7,4' ; + $sport_types_id_hash{'football + netball'} = '7,3' ; + +} #------------------------------------------------------------------------------- + +# use db ; +use today ; +use common ; +use common_min ; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/link_event_cost_items_to_event_systems.pl b/scripts/_FromProd/v1.0/admin/oneoff/link_event_cost_items_to_event_systems.pl new file mode 100644 index 0000000..870b9f4 --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/link_event_cost_items_to_event_systems.pl @@ -0,0 +1,133 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser); +# use Date::Calc qw(:all); +# use DBI; + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/link_event_cost_items_to_event_systems.pl?1 + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0] ; +# our $username = 'rory' ; + +if ($debug) { print "Content-type: text/html\n\n"; } + +#------------------------------------------------------------------------------------------ + +&today ; + +&db_open_upd ; +# &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &load_vars ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +if ($debug) { print "Done."; } + +exit; + +#------------------------------------------------------------------------------------------ + +sub load_vars { + + &db_min_ro('event_cost_items','id,name,excl_from_expenses',"name LIKE 'Fixed%' OR name LIKE 'Mobile%' OR name LIKE 'Cricket%'",'','') ; + + # UPDATE event_systems SET event_cost_item_id = '0' WHERE event_cost_item_id != '0' AND id != '396' AND id != '109' AND id != '398' AND id != '400' AND id != '104' AND id != '399' AND id != '397' ; + + &db_min_ro('event_systems','id,name,description,system_type,event_cost_item_id',"id != '396' AND id != '109' AND id != '398' AND id != '400' AND id != '104' AND id != '399' AND id != '397'",'','') ; + + foreach my $sys_id (sort {$db{event_systems}{$a}{system_type} cmp $db{event_systems}{$b}{system_type}} keys %{$db{event_systems}}) { + + my $system_type = $db{event_systems}{$sys_id}{system_type} ; + my $system_name = $db{event_systems}{$sys_id}{name} ; + my $system_desc = $db{event_systems}{$sys_id}{description} ; + my $cost_ids = "" ; + + print "\n excl_from_expenses : $db{event_systems}{$sys_id}{event_cost_item_id} , $db{event_cost_items}{$db{event_systems}{$sys_id}{event_cost_item_id}}{name} , SYSTEM : $system_name [$system_desc] ($system_type)" if $db{event_cost_items}{$db{event_systems}{$sys_id}{event_cost_item_id}}{excl_from_expenses} ; + + foreach my $cost_id (keys %{$db{event_cost_items}}) { + + next if $db{event_cost_items}{$cost_id}{excl_from_expenses} ; + + my $cost_name = $db{event_cost_items}{$cost_id}{name} ; + + unless (($cost_name =~ /- AISA/ && $system_desc !~ /\bAISA\b/) || ($cost_name =~ /- SSS/ && $system_desc !~ /\bSSS\b/) || ($cost_name !~ /- SSS/ && $system_desc =~ /\bSSS\b/) || ($cost_name !~ /- AISA/ && $system_desc =~ /\bAISA\b/ && $system_desc !~ /- SSS/)) { + + if ($system_type eq 'mobile' && $cost_name =~ /\bMobile\b/ && $cost_name !~ /\bCricket\b/) { + if ($system_name =~ /\bPXLS1\b/ && $cost_name =~ /\bS1\b/) { + $cost_ids .= "$cost_id," ; + } elsif (($system_name =~ /\bPXLS3\b/ || $system_name =~ /PXLS3_/) && $cost_name =~ /\bS3\b/) { + $cost_ids .= "$cost_id," ; + } elsif ($system_name !~ /PXLS3_/ && $system_name !~ /\bPXLS3\b/ && $cost_name !~ /\bS3\b/ && $system_name !~ /\bPXLS1\b/ && $cost_name !~ /\bS1\b/) { + $cost_ids .= "$cost_id," ; + } + } elsif ($system_type eq 'fixed' && $cost_name =~ /\bFixed\b/ && $cost_name !~ /\bCricket\b/) { + $cost_ids .= "$cost_id," ; + } elsif ($system_type eq 'solo' && ($cost_name =~ /\bSolo\b/ || $cost_name =~ /\bCricket\b/)) { + if ($cost_name =~ /\bCricket\b/ && $system_desc =~ /\bCricket\b/) { + $cost_ids .= "$cost_id," ; + } elsif ($cost_name =~ /\bSolo\b/ && ($system_desc =~ /\bSOLO\b/ || $system_desc =~ /\bSolo\b/)) { + $cost_ids .= "$cost_id," ; + } + } + + } elsif ($system_desc =~ /\bSports AI\b/ && $cost_name =~ /- AISA/) { + + # print "\n 2 \n " ; + + if ($system_type eq 'mobile' && $cost_name =~ /\bMobile\b/ && $cost_name !~ /\bCricket\b/) { + if (($system_name =~ /\bPXLS3\b/ || $system_name =~ /PXLS3_/) && $cost_name =~ /\bS3\b/) { + $cost_ids .= "$cost_id," ; + } + } + } elsif ($system_desc =~ /\bAISA\b/ && $system_desc =~ /- SSS/ && ($cost_name =~ /- SSS/ || $cost_name =~ /\bAISA\b/)) { + + if ($system_type eq 'mobile' && $cost_name =~ /\bMobile\b/ && $cost_name !~ /\bCricket\b/) { +; + + if (($system_name =~ /\bPXLS3\b/ || $system_name =~ /PXLS3_/) && $cost_name =~ /\bS3\b/) { + + $cost_ids .= "$cost_id," ; + # $cost_ids .= "$cost_id," ; + + } + } + } + } + + chop $cost_ids if $cost_ids; + + $cost_ids = "10" if $cost_ids eq '19,10' || $cost_ids eq '10,19' ; + $cost_ids = "22" if $cost_ids eq '28,22' || $cost_ids eq '22,28' ; + $cost_ids = "24" if $cost_ids eq '29,24' || $cost_ids eq '24,29' ; + + # print "\n UPDATE event_systems SET event_cost_item_id='$cost_ids' WHERE id = '$sys_id' ; " if $cost_ids && $cost_ids !~ /,/ ; ; + # print "\n UPDATE event_systems SET event_cost_item_id='$cost_ids' WHERE id = '$sys_id' ; " if !$cost_ids || $cost_ids =~ /,/ ; + + # print "\n cost_ids : $cost_ids" ; + # print "\n $sys_id $cost_ids CHANGED TO $db{event_systems}{$sys_id}{event_cost_item_id}" if $cost_ids && $db{event_systems}{$sys_id}{event_cost_item_id} && $cost_ids ne $db{event_systems}{$sys_id}{event_cost_item_id} ; + + + # print "\n CHANGE TO $db{event_cost_items}{$cost_ids}{name} ($cost_ids) FROM $db{event_cost_items}{$db{event_systems}{$sys_id}{event_cost_item_id}}{name} ($db{event_cost_items}{$db{event_systems}{$sys_id}{event_cost_item_id}}{excl_from_expenses})" if $db{event_systems}{$sys_id}{event_cost_item_id} ne $cost_ids ; + + $cost_ids = join(",", map { "$db{event_cost_items}{$_}{name}" } split (/\,/,$cost_ids)) ; + + # print "\n $sys_id : $system_name [$system_desc] ($system_type) ---> $cost_ids\n" if !$cost_ids || $cost_ids =~ /,/ ; + # print "\n $sys_id : $system_name [$system_desc] ($system_type) ---> $cost_ids\n" if $cost_ids && $cost_ids !~ /,/ ; + + } + +} #------------------------------------------------------------------------------- + + +use db ; +use today ; +use common ; +use common_min ; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/match_team_to_region.pl b/scripts/_FromProd/v1.0/admin/oneoff/match_team_to_region.pl new file mode 100644 index 0000000..fa0c538 --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/match_team_to_region.pl @@ -0,0 +1,337 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser) ; +use Text::CSV ; +# use Date::Calc qw(:all); +# use DBI; + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/match_team_to_region.pl?1 + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0] ; +# our $username = 'rory' ; + +if ($debug) { print "Content-type: text/html\n\n"; } + +#------------------------------------------------------------------------------------------ + +&today ; + +&db_open_upd ; +# &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &load_vars ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +if ($debug) { print "Done."; } + +exit; + +#------------------------------------------------------------------------------------------ + +sub load_vars { + + my $folder = '/home/libs/data/logs/schools_csv' ; # change this to your folder path + my $filename = 'South_Africa_Schools.csv' ; # change this to your CSV file name + + my $filepath = "$folder/$filename"; + + open my $fh, '<', $filepath or die "Could not open file '$filepath': $!"; + + my $csv = Text::CSV->new({ + binary => 1, # required for binary mode + auto_diag => 1, # report irregularities immediately + }) or die "Cannot use CSV: " . Text::CSV->error_diag(); + + use utf8; + my %seen_school_name = () ; my %multiple_region_names = () ; + while (my $row = $csv->getline($fh)) { + + next if @$row[7] eq 'Institution_Name' ; + my $school_name = @$row[7] ; + my $school_type = @$row[11] ; + + + + $school_name =~ s/\b$school_type\b//g ; + $school_name =~ s/HIGH SCHOOL//g ; + $school_name =~ s/High School//g ; + $school_name =~ s/INTERMEDIATE SCHOOL//g ; + $school_name =~ s/HOëRSKOOL//g ; + $school_name =~ s/PRIMÊRE SKOOL//g ; + $school_name =~ s/HOËRSKOOL//g ; + $school_name =~ s/PRIMARY SCHOOL//g ; + $school_name =~ s/PRIVAATSKOOL//g ; + $school_name =~ s/PRIVATE SCHOOL//g ; + $school_name =~ s/PRIMÊRE SKOOL//g ; + $school_name =~ s/SCHOOL//g ; + $school_name =~ s/SCHOOL//g ; + $school_name =~ s/\(PTY\) LTD//g ; + $school_name =~ s/\'//g ; + $school_name =~ s/\'//g ; + $school_name =~ s/\ LAERSKOOL//g ; + $school_name =~ s/Secondary School//g ; + $school_name =~ s/PRIMARY//g ; + $school_name =~ s/INTERMEDIATE//g ; + $school_name =~ s/COMBINED//g ; + $school_name =~ s/Preparatory School//g ; + $school_name =~ s/SENIOR//g ; + $school_name =~ s/HIGHER//g ; + $school_name =~ s/SECONDARY//g ; + $school_name =~ s/Primary School//g ; + $school_name =~ s/JUNIOR//g ; + $school_name =~ s/PUBLIC//g ; + $school_name =~ s/PRIAMARY//g ; + $school_name =~ s/PRIMÊRE SKOOL//g ; + $school_name =~ s/Combined School//g ; + $school_name =~ s/MIDDLE SCOOL//g ; + $school_name =~ s/High school//g ; + $school_name =~ s/Primary School//g ; + $school_name =~ s/Intermediate School//g ; + $school_name =~ s/LAERSKOOL//g ; + $school_name =~ s/Middle School//g ; + $school_name =~ s/Primary school//g ; + $school_name =~ s/Primary//g ; + $school_name =~ s/Gereformeerde Akademie//g ; + $school_name =~ s/INDEPENDENT//g ; + $school_name =~ s/Christian Academy//g ; + $school_name =~ s/Christian College//g ; + $school_name =~ s/Christian School//g ; + $school_name =~ s/Secondary School//g ; + $school_name =~ s/GEKOMBINEERDE SKOOL//g ; + $school_name =~ s/CHRISTELIKE VOLKSKOOL//g ; + $school_name =~ s/COLLEGE//g ; + $school_name =~ s/ACADEMIA//g ; + $school_name =~ s/SEKONDÊRE SKOOL//g ; + $school_name =~ s/SEKONDÊR//g ; + $school_name =~ s/GIMNASIUM//g ; + $school_name =~ s/SEKONDÊR//g ; + $school_name =~ s/VOORBEREIDINGSKOOL//g ; + $school_name =~ s/CHRISTELIKE //g ; + $school_name =~ s/NGK//g ; + $school_name =~ s/PREPARATORY//g ; + $school_name =~ s/COMPREHENSIVE//g ; + $school_name =~ s/Middle school//g ; + $school_name =~ s/Laerskool//g ; + $school_name =~ s/HOËR TEGNIESE SKOOL//g ; + $school_name =~ s/Akademie\/Academy//g ; + $school_name =~ s/Hoërskool//g ; + $school_name =~ s/Intermediate School//g ; + $school_name =~ s/SKOOL GEKOMBINEERD//g ; + $school_name =~ s/LEARNING SITE//g ; + $school_name =~ s/Muslim School//g ; + $school_name =~ s/Technical and Commercial//g ; + $school_name =~ s/PRIMERE SKOOL//g ; + $school_name =~ s/TECHNICAL HIGH//g ; + $school_name =~ s/S P//g ; + $school_name =~ s/STATE AIDED//g ; + $school_name =~ s/& TECHNICAL INSTITUTE//g ; + $school_name =~ s/& TECHNICAL//g ; + $school_name =~ s/\s*MIDDLE\s*$//; + $school_name =~ s/\s*LOWER\s*$//; + $school_name =~ s/\s*TECHNICAL\s*$//; + $school_name =~ s/^\s+|\s+$//g; + + # print "\n schools_region |$school_name| , @$row[5] , $multiple_region_names{$school_name}" if lc $school_name eq 'langalibalele' ; + + $multiple_region_names{$school_name} = 1 if @$row[5] && !$multiple_region_names{$school_name} && $seen_school_name{$school_name} && $seen_school_name{$school_name} ne @$row[5] ; + + $seen_school_name{$school_name} = @$row[5] ; + + $schools_region{$school_name}{$school_type} = @$row[5] ; + + + + } + + # my %seen_school_name = () ; my %multiple_region_names = () ; + + # foreach my $school_name (sort { $schools_region{$a} cmp $schools_region{$b} } keys %schools_region) { + # foreach my $school_type (keys %{$schools_region{$school_name}}) { + # $multiple_region_names{$school_name} = 1 if $seen_school_name{$seen_school_name} && $schools_region{$school_name}{$school_type} && $seen_school_name{$seen_school_name} ne $schools_region{$school_name}{$school_type} ; + # $seen_school_name{$seen_school_name} = $schools_region{$school_name}{$school_type} ; + # } + # } + + $csv->eof or $csv->error_diag(); + close $fh; + + $region_id{"MP"} = 6 ; + $region_id{"EC"} = 1 ; + $region_id{"GT"} = 3 ; + $region_id{"KZN"} = 4 ; + $region_id{"WC"} = 9 ; + $region_id{"LP"} = 5 ; + $region_id{"NC"} = 8 ; + $region_id{"NW"} = 7 ; + $region_id{"FS"} = 2 ; + + &db_switch_conn('sss'); + + &db_min_ro('teams',"id,name","region_id = '0' AND matched_region_id = '0' AND (name like '% senior %' OR name like 'senior %' OR name like '% senior' OR name like '% junior %' OR name like 'junior %' OR name like '% junior' OR name like '% PS' OR name like 'PS %' OR name like '% HS' OR name like 'HS %' OR name like '% Primary' OR name like '% SECONDARY' OR name like 'SECONDARY%' OR name like 'SENIOR SECONDARY%' OR name like 'PS%' OR name like '%college%' OR name like '%school%' OR name like '%skool%' OR name like '%gimnasium%' OR name like '%akademia%' OR name like '%academy%' OR name like '%akademie%')",'','') ; + + foreach my $school_name (sort { $seen_school_name{$a} cmp $seen_school_name{$b} } keys %schools_region) { + + next if $multiple_region_names{$school_name} || length($school_name) < 5 || lc $school_name eq 'christian' || lc $school_name eq 'elite' || lc $school_name eq 'global' || lc $school_name eq 'curro' || lc $school_name eq 'northern' ; + # next if length($school_name) < 5 || lc $school_name eq 'christian' || lc $school_name eq 'elite' || lc $school_name eq 'global' || lc $school_name eq 'curro' || lc $school_name eq 'northern' ; + foreach my $type (keys %{$schools_region{$school_name}}) { + my $region = $schools_region{$school_name}{$type}; + foreach my $team (keys %{$db{teams}}) { + my $team2 = lc $db{teams}{$team}{name} ; + $team2 =~ s/\'//g ; + my $school_name2 = lc $school_name ; + if ($team2 =~ /\b$school_name2\b/) { + print "\n UPDATE teams SET matched_region_id = '$region_id{$region}' WHERE id = '$team';" ; + } + } + } + } + + $region_id{"Mpumalanga"} = 6 ; + $region_id{"Eastern Cape"} = 1 ; + $region_id{"Gauteng"} = 3 ; + $region_id{"KwaZulu-Natal"} = 4 ; + $region_id{"KwaZulu Natal"} = 4 ; + $region_id{"Western Cape"} = 9 ; + $region_id{"Limpopo"} = 5 ; + $region_id{"Northern Cape"} = 8 ; + $region_id{"North West"} = 7 ; + $region_id{"Free State"} = 2 ; + + # $filename = 'South_African_cities.csv' ; # change this to your CSV file name + + # my $filepath = "$folder/$filename"; + + # open my $fh, '<', $filepath or die "Could not open file '$filepath': $!"; + + # my $csv = Text::CSV->new({ + # binary => 1, # required for binary mode + # auto_diag => 1, # report irregularities immediately + # }) or die "Cannot use CSV: " . Text::CSV->error_diag(); + + # while (my $row = $csv->getline($fh)) { + # next if @$row[0] eq 'city' ; + # my $school_name = @$row[0] ; + # $city_name{$school_name} = $region_id{@$row[5]} ; + # } + + # $csv->eof or $csv->error_diag(); + # close $fh; + + # # # $filename = 'South_African_cities_2.csv' ; # change this to your CSV file name + + # # # my $filepath = "$folder/$filename"; + + # # # open my $fh, '<', $filepath or die "Could not open file '$filepath': $!"; + + # # # my $csv = Text::CSV->new({ + # # # binary => 1, # required for binary mode + # # # auto_diag => 1, # report irregularities immediately + # # # }) or die "Cannot use CSV: " . Text::CSV->error_diag(); + + # # # my %seen_city_name = () ; + + # # # while (my $row = $csv->getline($fh)) { + # # # next if @$row[0] eq 'City' ; + # # # my $cityname = lc @$row[1] ; + # # # if ($seen_city_name{$cityname} && $seen_city_name{$cityname} ne $region_id{@$row[2]}) { + # # # $city_name{$cityname} = 0 ; + # # # next ; + # # # } + # # # $seen_city_name{$cityname} = $region_id{@$row[2]} ; + # # # $city_name{$cityname} = $region_id{@$row[2]} ; + # # # } + + # # # $csv->eof or $csv->error_diag(); + # # # close $fh; + + + # # # &db_switch_conn('sss'); + + # # # &db_min_ro('teams',"id,name","region_id = '0' AND matched_region_id = '0' AND id > 5000 AND name not like '%school%' AND name not like '%skool%'",'','') ; + + # # # # &db_switch_conn('aisa'); + + # # # my %prev_match = () ; + + # # # foreach my $team_id (keys %{$db{teams}}) { + + # # # my $team_name = lc $db{teams}{$team_id}{name} ; + # # # $team_name =~ s/\'//g ; + + # # # foreach my $cityname (keys %city_name) { + + # # # my $regionid = $city_name{$cityname} ; + # # # next unless $regionid ; + # # # $cityname = lc $cityname ; + + # # # $cityname =~ s/\'//g ; + + + # # # if ($team_name =~ /\b$cityname\b/) { + # # # if ($team_name =~ /\bst $cityname\b/) { + # # # $city_name{"st $cityname"} = $region_id{$cityname} ; + # # # $cityname = "st $cityname" ; + # # # } + # # # if ($team_name =~ /\b$cityname park\b/ && $cityname !~ /\bpark\b/ && length($cityname) < 10) { + # # # next ; + # # # } + # # # if ($prev_match{$team_id} && length($prev_match{$team_id}) > length($cityname)) { + # # # print "\n Do NOT MATCH $cityname WITH $team_name" ; + # # # next ; + # # # } + # # # $prev_match{$team_id} = $cityname ; + # # # # print "\n , $team_name , $city_name , $regionid, UPDATE `teams` SET `matched_region_id`='$regionid' WHERE `id`=' $team_id';" ; + # # # # print "\n city_name,$city_name : team_name,$team_name" ; + # # # } + # # # } + # # # } + + # # # foreach (keys %prev_match) { + # # # next if length($prev_match{$_}) < 5 || !$city_name{$prev_match{$_}} ; + # # # print "\n UPDATE teams SET matched_region_id = '$city_name{$prev_match{$_}}' WHERE id = '$_' ; " ; + # # # } + + # &db_min_ro('cities','id,name,region_id','','','') ; + + # &db_min_ro('regions','id,name','','','') ; + + # foreach my $team_id (keys %{$db{teams}}) { + + # my $team_name = lc $db{teams}{$team_id}{name} ; + + # next unless lc $team_name =~ /kimberly/ ; + + # foreach my $city_id (keys %{$db{cities}}) { + + + + # my $city_name = lc $db{cities}{$city_id}{name} ; + + + # print "\n team_name : $team_name , city_name : $city_name" ; + + # # $city_name =~ s/\'//g ; + # # $team_name =~ s/\'//g ; + + # if ($team_name =~ /\b$city_name\b/) { + + # print "\n $team_name UPDATE teams SET matched_region_id='$db{cities}{$city_id}{region_id}' WHERE id = '$team_id' ; " ; + + # } + # } + # } + +} #------------------------------------------------------------------------------- + +use db ; +use today ; +use common ; +use common_min ; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/pixellot_api.pl b/scripts/_FromProd/v1.0/admin/oneoff/pixellot_api.pl new file mode 100644 index 0000000..f683674 --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/pixellot_api.pl @@ -0,0 +1,165 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser); + +print "Content-type: text/html\n\n"; + +use LWP::UserAgent; +use HTTP::Request; +use XML::Simple ; +use DBI; +use SOAP::Lite ; + +#------------------------------------------------------------------------------- + + @ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0]; + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/pixellot_api.pl?1 + +#------------------------------------------------------------------------------- + +&today; + +&send_it ; +&parse_it ; +&read_it ; + +exit; + +#------------------------------------------------------------------------------- + +sub send_it { + + my $url = "https://api.stage.pixellot.tv/v1/login"; + # my $url = "https://api.pixellot.tv/v1/login"; + my $json = '{ +"username" : "rory@kre8it.co.za", +"password" : "13centreP1x3110T" +}'; + + &common_debug("url=$url") ; + &common_debug("json=$json") ; + + # my $request = HTTP::Request->new(POST => $url) or die "Error: Cannot create GET request \n" ; + my $request = HTTP::Request->new(POST => $url) or print "Error: Cannot create GET request \n" ; + $request -> header('content-length' => length($json)) ; + $request -> content($json); + $request -> content_type("application/json; charset=UTF-8"); + + my $ua = LWP::UserAgent->new; + my $response = $ua->request($request); + + my $response_code = $response -> code ; + my $response_content = $response -> content ; + + &common_debug("response_content=$response_content") ; + + eval { + my $decoded_json = decode_json $response_content ; + $token = $decoded_json->{'token'} ; + } or do { + # print("Something went wrong: $@\n"); + }; + + &common_debug("token=$token") ; + + # # return unless $token ; + # if (!$token) { + # &common_cms_send_mail('','','',"[.102 ERROR] post_to_world_to_africa_logistics","NO TOKEN") if $now_mm == 15 || $now_mm == 45 ; + # return ; + # } + + # my $url = "http://102.219.138.34:8000/api/kreateit/positions"; + # my $json = &read_file($fh); + + # &common_debug("url=$url") ; + # &common_debug("json=$json") ; + + # my $request = HTTP::Request->new(POST => $url) or print "Error: Cannot create GET request \n" ; + # $request -> header(Authorization => "Bearer $token"); + # $request -> header('content-length' => length($json)) ; + # $request -> content($json); + # $request -> content_type("application/json; charset=UTF-8"); + + # my $ua = LWP::UserAgent->new; + # my $response = $ua->request($request); + + # my $response_code = $response -> code ; + # my $response_content = $response -> content ; + + # &common_debug("response_code=$response_code") ; + # &common_debug("response_content=$response_content") ; + + # &common_cms_time_log("world_to_africa_response.txt","response_code=$response_code\nresponse_content=$response_content",$apipath) ; + # unlink ($fh) or &common_cms_send_mail('','','',$err_subj,$!) ; + +} #------------------------------------------------------------------------------- + +sub parse_it { + + # # use Data::Dumper; + # # print Dumper(\$returnxml); + # # exit; + + # $returnxml =~ s/[\x80-\xFF]/?/g ; + # my $xml = new XML::Simple or die "Cant instantiate object XML::Simple $!" ; + # # my $xmldata = $xml->XMLin($returnxml) or die "Cant open xmldata $!" ; + # $xmldata = $xml->XMLin($returnxml, forcearray => 1) or die "Cant open xmldata $!"; + + # if ($debug) { + # use Data::Dumper; + # print Dumper(\$xmldata); + # # exit ; + # } + +} #------------------------------------------------------------------------------- + +sub read_it { + + # foreach my $hashref ( @{$xmldata->{'s:Body'}->[0]->{'PostalCodeResponse'}->[0]->{'PostalCodeResult'}->[0]->{'a:ArrayOfpostalCode'} } ) { + # # unless (lc ${$hashref}{'Name'}->[0] eq lc $search) { next ; } + # # print ${$hashref}{'ContentEntityId'}->[0] ; + + # # unless (exists $exists{${$hashref}{'a:postalCode'}->[0]}) { + # foreach $address ( @{$hashref}{'a:postalCode'}) { + # # print $address . "
    " ; + # # print Dumper(\$address); + # # print Dumper(\$address{'a:city'}->[0]); + # print 'a:city=' . ${$hashref}{'a:postalCode'}->[0]->{'a:city'}->[0] . "\n" ; + # print 'a:suburb=' . ${$hashref}{'a:postalCode'}->[0]->{'a:suburb'}->[0] . "\n" ; + # print 'a:code=' . ${$hashref}{'a:postalCode'}->[0]->{'a:code'}->[0] . "\n" ; + # print 'a:routeCode=' . ${$hashref}{'a:postalCode'}->[0]->{'a:routeCode'}->[0] . "\n" ; + # # print ${$address}->[0] . "\n" ; + # # print 'a:city=' . ${$address}{'a:city'}->[0] . "
    " ; + # # print 'a:routeCode=' . ${$address}{'a:routeCode'}->[0] . "
    " ; + # # print 'a:suburb=' . ${$address}{'a:suburb'}->[0] . "
    " ; + # # print 'a:code=' . ${$address}{'a:code'}->[0] . "
    " ; + + # # $i{dcb_id} = ${$hashref}{'ContentEntityId'}->[0] ; + # # $i{latitude} = ${$hashref}{'Latitude'}->[0] ; + # # $i{longitude} = ${$hashref}{'Longitude'}->[0] ; + # # $i{country} = ${$hashref}{'Country'}->[0] ; + # # $i{area} = ${$hashref}{'Area'}->[0] ; + + # # # unless (ref(${$hashref}{'Area'}->[0] eq 'HASH')) { $i{area} = ${$hashref}{'Area'}->[0] ; } + # # # unless (ref(${$hashref}{'Location'}->[0] eq 'HASH')) { $i{location} = ${$hashref}{'Location'}->[0] ; } + + # # $i{location} = ${$hashref}{'Location'}->[0] unless (ref(${$hashref}{'Location'}->[0]) eq 'HASH'); + + # # $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + # # &common_db_insert('dcb_places') ; + # } + # # last ; + # } + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/sendmail.pl b/scripts/_FromProd/v1.0/admin/oneoff/sendmail.pl new file mode 100644 index 0000000..a6f01ac --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/sendmail.pl @@ -0,0 +1,536 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use MIME::Lite; +use Mail::Sendmail; + +require cfg ; + +print "Content-type: text/html\n\n"; + +&today ; + +our $debug = 1 ; + +#------------------------------------------------------------------------------------------ + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/sendmail.pl + +use CGI::Carp qw(fatalsToBrowser); + +$email_add{'reply-to'} = 'info@telemedia.co.za' ; + +# &mailsend('','rory@mathew.za.net',"mailsend ffwaybill Test $now_year-$now_mm-$now_dd",'test email') ; + +# &common_mailsend_sendgrid('text','rory@kre8it.co.za','TEST - Tue 30-Apr-2024','Hi Rory Mathew

    TEST AT 14:00








    Please let me know if you need anything.

    Thanks,
    Rory Mathew','/var/www/html/pdf/feed_details','Feed_Details-1003.pdf','Test Events','events@interactivetvafrica.com','','rory@kre8it.co.za','','') ; +# &common_mailsend_sendgrid('text','rory@kre8it.co.za','TEST - Tue 30-Apr-2024','testing 123','/var/www/html/pdf/event_details','Event_Details-5136.pdf','ITV Africa Events','events@itvadmin.co.za','','','',0) ; +&mailsend_sendgrid('text','rory@kre8it.co.za','TEST - Tue 30-Apr-2024','testing 123','/var/www/html/pdf/event_details','Event_Details-5136.pdf','Telemedia Events','website@bookingtelemedia.co.za','','','',0) ; +# &common_send_mail('rory@kre8it.co.za','','','','','test msg','TEST - Tue 30-Apr-2024') ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub mailsend_sendgrid { + + local ($qtype,$qemail,$qsubject,$qbody,$qattachfilepath,$qattachfilename,$qfromname,$qfromemail,$qccemail,$qbccemail,$uploaded_doc,$operator_email) = @_; + + $qccemail =~ s/\;/\,/g ; + $qbccemail =~ s/\;/\,/g ; + + use Email::SendGrid::V3; + + &common_debug("common_mailsend_sendgrid [$qtype,$qemail,$qsubject,$qbody,$qattachfilepath,$qattachfilename,$qfromname,$qfromemail,$qccemail,$qbccemail,$uploaded_doc,$operator_email]") ; + + #======================= + #REF1: https://docs.sendgrid.com/for-developers/sending-email/curl-examples + #REF2: https://github.com/GrantStreetGroup/Email-SendGrid-V3 + #To Install: + #cpan -i Email::SendGrid::V3 + #cd /root/perl5/lib/perl5 + #cp -R Email /usr/local/lib64/perl5 + #======================= + + my $sg = Email::SendGrid::V3->new(api_key => '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'); + + $qbody =~ s/'/`/gi; + $qbody =~ s/\r//gi; + $qbody =~ s/\n//gi; + + #------------------------------------------------ + #SEND TEXT ONLY MAIL + if ($qtype eq "text") { + + # , cc => [ $qccemail ], bcc => [ $qbccemail ] + + my %cc_args = ($qccemail) ? (cc => [ "$qccemail" ]) : () ; + my %bcc_args = ($qbccemail) ? (bcc => [ "$qbccemail" ]) : () ; + + my $result = $sg->from($qfromemail,$qfromname) + ->reply_to($email_add{'reply-to'}, "$useropts{short} Events") + ->subject($qsubject) + ->add_content('text/plain', $qbody) + ->add_envelope( to => [ "$qemail" ], %cc_args, %bcc_args) + ->send; + + $qres = $result->{success} ? "success" : "error: " . $result->{reason}; + + } + + #------------------------------------------------ + #SEND HTML ONLY MAIL + if ($qtype eq "html") { + + $qbody = qq~ + + + +Film Freight + + + +

    + +

    +

    +$qbody +

    +
    +
    + + +~; + my %cc_args = ($qccemail) ? (cc => [ "$qccemail" ]) : () ; + my %bcc_args = ($qbccemail) ? (bcc => [ "$qbccemail" ]) : () ; + + my $result = $sg->from($qfromemail,$qfromname) + ->reply_to($email_add{'reply-to'}, "$useropts{short} Feeds") + ->subject($qsubject) + ->add_content('text/html', $qbody) + ->add_envelope( to => [ "$qemail" ], %cc_args, %bcc_args) + ->send; + + $qres = $result->{success} ? "success" : "error: " . $result->{reason}; + + } + + #------------------------------------------------ + #SEND HTML WITH ATTACHMENT MAIL + if ($qtype eq "htmlattach") { + + my $encodedcontent = &encode_attachment("$qattachfilepath/$qattachfilename"); + + my %args = ( + type => 'AUTO', + disposition => 'attachment' + ); + + $qbody = qq~ + + + +Film Freight + + + +

    + +

    +

    +$qbody +

    +
    +
    + + +~; + + my @attachments = ($qattachfilename, $encodedcontent, %args) ; + + if ($uploaded_doc) { + my $encodedcontent = &encode_attachment("$uploaded_doc") ; + push @attachments, ($uploaded_doc, $encodedcontent, %args) ; + } + + # if ($operator_email) { + # my $encodedcontent = &encode_attachment("$htmlpath/pdf/operator_flyer") ; + # push @attachments, ("operator_email_attach.pdf", $encodedcontent, %args) ; + # } + + + my %cc_args = ($qccemail) ? (cc => [ "$qccemail" ]) : () ; + my %bcc_args = ($qbccemail) ? (bcc => [ "$qbccemail" ]) : () ; + + my $result = $sg->from($qfromemail,$qfromname) + ->reply_to($email_add{'reply-to'}, "$useropts{short} Feeds") + ->subject($qsubject) + ->add_content('text/html', $qbody) + ->add_attachment(@attachments) + ->add_envelope( to => [ "$qemail" ], %cc_args, %bcc_args) + ->send; + + $qres = $result->{success} ? "success" : "error: " . $result->{reason}; + + #NOTE: Cannot use command line cURL here as the body (base64 pdf) is too large - below works for smaller content + #$qres = `/usr/bin/curl --request POST --url https://api.sendgrid.com/v3/mail/send --header 'authorization: Bearer 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' --header 'Content-Type: application/json' --data '{"personalizations": [{"to": [{"email": "$qemail"}]}],"from": {"email": "no-reply\@myappointment.co.za"},"subject":"$qsubject","content": [{"type": "text/html","value": "$qbody"}], "attachments": [{"content": "$encodedcontent", "type": "text/plain", "filename": "$qattachfilename"}]}'`; + } + #------------------------------------------------ + + &common_debug("common_mailsend_sendgrid [$qres]") ; + + return "$qres"; + +} #------------------------------------------------------------------------------------------ + +# sub SendEmailSendgrid { + + # local($qtype,$qemail,$qsubject,$qbody,$qattachfilepath,$qattachfilename,$qfromname,$qfromemail) = @_; + + # use Email::SendGrid::V3; + + # #======================= + # #REF1: https://docs.sendgrid.com/for-developers/sending-email/curl-examples + # #REF2: https://github.com/GrantStreetGroup/Email-SendGrid-V3 + # #To Install: + # #cpan -i Email::SendGrid::V3 + # #cd /root/perl5/lib/perl5 + # #cp -R Email /usr/local/lib64/perl5 + # #======================= + + # my $sg = Email::SendGrid::V3->new(api_key => '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'); + + # $qbody =~ s/'/`/gi; + # #$qbody =~ s/"/\\\"/gi; + # $qbody =~ s/\r//gi; + # $qbody =~ s/\n//gi; + + # #------------------------------------------------ + # #SEND TEXT ONLY MAIL + # if ($qtype eq "text") { + + # my $result = $sg->from($qfromemail,$qfromname) + # ->reply_to('filmfreight@filmfreight.co.za', 'Film Freight') + # ->subject($qsubject) + # ->add_content('text/plain', $qbody) + # ->add_envelope( to => [ $qemail ] ) + # ->send; + + # $qres = $result->{success} ? "success" : "error: " . $result->{reason}; + + # } + + # #------------------------------------------------ + # #SEND HTML ONLY MAIL + # if ($qtype eq "html") { + + # $qbody = qq~ +# +# +# +# Untitled Document +# +# +# +#

    +# +#

    +#

    +# $qbody +#

    +#
    +#
    +# +# +# ~; + + # my $result = $sg->from($qfromemail,$qfromname) + # ->reply_to('filmfreight@filmfreight.co.za', 'Film Freight') + # ->subject($qsubject) + # ->add_content('text/html', $qbody) + # ->add_envelope( to => [ $qemail ] ) + # ->send; + + # $qres = $result->{success} ? "success" : "error: " . $result->{reason}; + + # } + + # #------------------------------------------------ + # #SEND HTML WITH ATTACHMENT MAIL + # if ($qtype eq "htmlattach") { + + # use MIME::Base64 qw(encode_base64); + + # open (infile, "$qattachfilepath/$qattachfilename"); + # binmode infile; + # while () { + # #$_ =~ s/\r//gi; + # #$_ =~ s/\n//gi; + # $myfilecontents .= "$_"; + # } + # close(infile); + + # $encodedcontent = encode_base64($myfilecontents); + + # $encodedcontent =~ s/'/`/gi; + # #$encodedcontent =~ s/"/\\\"/gi; + # $encodedcontent =~ s/\r//gi; + # $encodedcontent =~ s/\n//gi; + + # my %args = ( + # type => 'text/plain', + # disposition => 'attachment' + # ); + + # my $result = $sg->from($qfromemail,$qfromname) + # ->reply_to('filmfreight@filmfreight.co.za', 'Film Freight') + # ->subject($qsubject) + # ->add_content('text/html', $qbody) + # ->add_attachment($qattachfilename, $encodedcontent, %args) + # ->add_envelope( to => [ $qemail ] ) + # ->send; + + # $qres = $result->{success} ? "success" : "error: " . $result->{reason}; + + # #NOTE: Cannot use command line cURL here as the body (base64 pdf) is too large - below works for smaller content + # #$qres = `/usr/bin/curl --request POST --url https://api.sendgrid.com/v3/mail/send --header 'authorization: Bearer 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' --header 'Content-Type: application/json' --data '{"personalizations": [{"to": [{"email": "$qemail"}]}],"from": {"email": "no-reply\@myappointment.co.za"},"subject":"$qsubject","content": [{"type": "text/html","value": "$qbody"}], "attachments": [{"content": "$encodedcontent", "type": "text/plain", "filename": "$qattachfilename"}]}'`; + # } + # #------------------------------------------------ + + # #log all mail sends here + + # # $datetime = `date "+%Y-%m-%d %H:%M"`; + # # chop($datetime); + + # # open (logfile, ">> $basedir/admin/SendGrid.log"); + # # print logfile "$datetime $qtype $qemail $qsubject $qattachfilename $qfromname $qfromemail $qres\n"; + # # close(logfile); + + + # return "$qres"; + +# } #------------------------------------------------------------------------------------------ + +# sub smtp_mail_auth { + +# my ($to,$cc,$email_bcc,$email_subject,$email_message,$html,$thead) = @_ ; + +# return unless $email_message ; +# return unless $email_subject ; + +# use Time::HiRes qw( gettimeofday ); +# use MIME::Lite; +# use Net::SMTP_auth; + +# my $email_from = $user ; + +# $email_to = ($to) ? $to : $email_from ; +# $email_to =~ s/\s+//; # Strip out any whitespace + +# my ($s, $usec) = gettimeofday(); + +# my $email_message_id = "<$s$usec\@mailserver.filmfreight.co.za>" ; +# my $email_mailed_by = "filmfreight.co.za" ; +# my $email_from_display = qq("$sig ($email_from_prefix) ($ibookref)" <$email_from>) ; + +# $msg = MIME::Lite -> new( + # 'Message-ID' => $email_message_id, + # 'Mailed-By:' => $email_mailed_by, + # 'From' => $email_from_display, + # 'To' => $email_to, + # 'Bcc' => $email_bcc, + # 'Subject' => $email_subject, + # 'Type' => 'multipart/mixed' +# ); + +# $msg -> attach( + # 'Type' => 'text/plain', + # 'Data' => $email_message +# ); + +# my $email = $msg -> as_string(); + +# my $smtp_host = 'filmfreight-co-za.mail.protection.outlook.com'; +# my $smtp_port = 25; + +# my $smtp = Net::SMTP_auth -> new ($smtp_host, Port=>$smtp_port) or die "Can't connect"; + +# # $smtp->auth('NORMAL', $email_from, 'Roq80545') or die "Error:" . $smtp->message(); +# $smtp->auth('OAuth2', $email_from, 'Roq80545') or die "Error:" . $smtp->message(); +# # $smtp->auth('AUTH', $user, $pass) or die "Error:" . $smtp->message(); + +# # die "Couldn't login: $!" unless \&auth; + +# $smtp->mail($email_from) or die "Error:" . $smtp->message(); +# $smtp->recipient(split(/;/, $email_to)); +# $smtp->data() or die "Error:" . $smtp->message(); +# $smtp->datasend($email) or die "Error:" . $smtp->message(); +# $smtp->dataend() or die "Error:" . $smtp->message(); +# $smtp->quit or die "Error:" . $smtp->message(); + +# } #------------------------------------------------------------------------------------------ + +# sub auth { + + # my $sasl; + # my $mechanisms = ['AUTH', 500]; + + # my $sasl = Authen::SASL->new( + # mechanism => $mechanisms, + # debug => 1, + # callback => { + # user => $user, + # pass => $pass, + # authname => $user, + # } + # ); + +# } #------------------------------------------------------------------------------------------ + +# sub smtp_mail { + +# my ($to,$cc,$bcc,$subj,$msg,$html,$thead) = @_ ; + +# return unless $msg ; +# return unless $subj ; + +# # use Mail::Sendmail; + +# $to = $user unless $to ; + +# # use Net::SMTP 3.0; +# # Force use of Authen::SASL::Perl - it may fix problems with other alternatives +# # use Authen::SASL qw(Perl); + +# # Port => "587", +# # doSSL => "starttls", +# # SSL_version => "TLSv1_1", +# # Debug => 4 + +# use Net::SMTPS; + +# my $smtp = Net::SMTPS->new("filmfreight-co-za.mail.protection.outlook.com", Port => 25); die "Initialization failed: $!" if !defined $smtp; + +# my $sender = $user ; +# print "Trying to authenticate.."; +# # $smtp->auth('OAuth2', $user, $pass) or die "could not authenticate : $!\n"; + +# &auth or die "Couldn't login: $!" ; + +# my $receiver = $to; +# $smtp->mail( $sender ); +# $smtp->to( $receiver ); +# $smtp->data() or die "Error:" . $smtp->message(); +# $smtp->datasend( "To: $receiver\n" ) or die "Error:" . $smtp->message(); +# $smtp->datasend( "From: $sender\n" ) or die "Error:" . $smtp->message(); +# $smtp->datasend( "Content-Type: text/html\n" ) or die "Error:" . $smtp->message(); +# $smtp->datasend( "Subject: Testing Net::SMTP" ) or die "Error:" . $smtp->message(); +# $smtp->datasend( "\n" ) or die "Error:" . $smtp->message(); +# $smtp->datasend( 'The body of the email' ) or die "Error:" . $smtp->message(); +# $smtp->dataend() or die "Error:" . $smtp->message(); +# $smtp->quit() or die "Error:" . $smtp->message(); + +# } #------------------------------------------------------------------------------------------ + + +# sub smtp_tls_mail { + +# my ($to,$cc,$bcc,$subj,$msg,$html,$thead) = @_ ; + +# return unless $msg ; +# return unless $subj ; + +# my $user = 'pod@filmfreight.co.za' ; + +# $to = $user unless $to ; + +# use Net::SMTP::TLS; + +# my $mailer = new Net::SMTP::TLS( + # # 'smtp.office365.com', + # # 'mail.protection.outlook.com', + # # 'o365info-com.mail.protection.outlook.com', + # 'filmfreight-co-za.mail.protection.outlook.com', + # # Port => 587, + # Port => 25, + # Hello => '', + # User => "$user", + # # SSL_version => "TLSv1_2", + # Password => 'Roq80545', + # Debug => 1) || die "Cannot connect to smtp server"; + +# $mailer->mail($user); +# $mailer->to($to); +# $mailer->data; +# $mailer->datasend("\n"); +# $mailer->datasend("Sent from perl!"); +# $mailer->dataend; +# $mailer->quit; + +# } #------------------------------------------------------------------------------------------ + +# sub smtp_mail_1 { + +# my ($to,$cc,$bcc,$subj,$msg,$html,$thead) = @_ ; + +# use Mail::Sendmail; + +# $to = $user unless $to ; + +# my %mail = () ; + +# %mail = ( + # smtp => 'localhost', + # From => $user, + # To => $to, + # Cc => $cc, + # Bcc => $bcc, + # Subject => $subj + # ); + +# $mail{smtp} = "smtp.afrihost.co.za"; +# $mail{port} = 25; +# $mail{Auth} = {user => $user, pass => 'PvB{Da{8($ow'}; +# $mail{body} = < +# +# +# +# +# +# +#

    +# +#

    +#

    +# $msg +#

    +# +# + +# $boundary-- + +# END_OF_BODY + +# } + +# sendmail(%mail) ; + +# } #------------------------------------------------------------------------------------------ + +use today ; +use common ; +# use mailsend ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/admin/oneoff/sendmailv2.pl b/scripts/_FromProd/v1.0/admin/oneoff/sendmailv2.pl new file mode 100644 index 0000000..931cb27 --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/sendmailv2.pl @@ -0,0 +1,478 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use MIME::Lite; +use Mail::Sendmail; + +require cfg ; + +print "Content-type: text/html\n\n"; + +&today ; + +our $debug = 1 ; + +#------------------------------------------------------------------------------------------ + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/sendmailv2.pl + +use CGI::Carp qw(fatalsToBrowser); + +# $email_add{'reply-to'} = 'events@aisport.africa' ; + +# &mailsend_sendgrid('text','rory@kre8it.co.za','TEST - Tue 30-Apr-2024','testing 123','/var/www/html/pdf/event_details','Event_Details-5136.pdf','Telemedia Events','website@bookingtelemedia.co.za','','','',0) ; + +&common_v2_send_smtp_mail('','rory@kre8it.co.za','rory@mathew.za.net,admin@kre8it.co.za','k@re8it.com',"Calibration : $now_ccyy_mm_dd $now_hh_min_sec","Please see attached calibration...",'','html','',"$htmlpath/pdf/operator_flyer",'operator_email_attach.pdf','pdf',0,0) ; +# &common_v2_send_smtp_mail('','rory@kre8it.co.za','rory@mathew.za.net','',"Calibration : $now_ccyy_mm_dd $now_hh_min_sec","Please see attached calibration...",'','','','','','',0,0) ; +# &common_v2_send_smtp_mail('','rory@kre8it.co.za','rory@mathew.za.net','',"Calibration : $now_ccyy_mm_dd $now_hh_min_sec","Please see attached calibration...",'','','','','','',0,0) ; +# &common_send_mail('rory@kre8it.co.za','rory@mathew.za.net','k@re8it.com','html','',"Please see attached calibration...","Calibration : $now_ccyy_mm_dd $now_hh_min_sec") ; +# &common_send_mail('rory@kre8it.co.za','rory@mathew.za.net','k@re8it.com','','',"Please see attached calibration...","Calibration : $now_ccyy_mm_dd $now_hh_min_sec") ; +# &common_send_mail('rory@kre8it.co.za','rory@mathew.za.net,k@re8it.com','','','',"Please see attached calibration...","Calibration : $now_ccyy_mm_dd $now_hh_min_sec") ; + + +exit ; + +#------------------------------------------------------------------------------------------ + +sub common_v2_send_smtp_mail { + + my ($from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication,$uploaded_doc,$operator_email) = @_ ; + + # &common_debug("common_send_smtp_mail [$from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication,$uploaded_doc,$operator_email]") ; + + return unless $msg ; + return unless $subj ; + + # my $htype = (-f "$attachpath/$attachname" || $uploaded_doc || $operator_email) ? 'htmlattach' : ($html eq 'html') ? $html : 'text' ; + + # my $res = &common_mailsend_sendgrid($htype,$to,$subj,$msg,$attachpath,$attachname,"$useropts{short} Events",'events@itvadmin.co.za',$cc,$bcc,$uploaded_doc,$operator_email); + + # return if $res eq 'success' ; # carry on if mailsend_sendgrid failed + + my $main_email = $email_add{'events'} ; + + $to = $main_email unless $to ; + $from = $afrihost_from unless $from ; + + my $mail_body = ($html) ? &common_get_mail_body($msg,$table_msg,$thead) : $msg ; + + if ($html) { + if ($attachname && -f "$attachpath/$attachname") { + &common_debug("common_send_smtp_mail attach : $attachpath/$attachname [$attachapplication]") ; + &common_email_with_attachments($from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication) ; + return ; + } + if ($uploaded_doc) { + my @parts = split(/\//,$uploaded_doc) ; + $attachname = $parts[-1] ; + pop @parts ; + $attachpath = join("/",@parts) ; + &common_email_with_attachments($from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,$attachpath,$attachname,'') ; + return ; + } + if ($operator_email) { + &common_email_with_attachments($from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,"$htmlpath/pdf/operator_flyer/operator_email_attach.pdf",'operator_email_attach.pdf','pdf') ; + return ; + } + &common_send_mail($to,$cc,$bcc,$html,$thead,$msg,$subj,$table_msg) ; + } else { + &common_send_mail($to,$cc,$bcc,$html,$thead,$msg,$subj,$table_msg) ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_email_with_attachments { + + my ($from,$to,$cc,$bcc,$subj,$text_msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication) = @_ ; + + use MIME::Lite; + use Net::SMTP_auth; + + # SMTP configuration + my $smtp_host = $afrihost_smtp ; + my $smtp_port = $afrihost_port ; + my $smtp_user = $afrihost_from ; + my $smtp_pass = $afrihost_psw ; + my $from = $afrihost_from ; + + # HTML body part + my $mail_body = &common_get_mail_body($text_msg,$table_msg) ; + + my $fullattachpath = "$attachpath/$attachname"; + die "Attachment file not found: $fullattachpath" unless -e $fullattachpath; + + # === build the MulitPart MIME Message === + + # Create the Message + my $msg = MIME::Lite::->new( + 'From' => "$useropts{short} Events <$from>", + 'Reply-To' => $email_reply_to, + 'To' => $to, + 'Cc' => $cc, + 'Bcc' => $bcc, + 'Subject' => $subj, + 'Type' => 'multipart/mixed', + ); + + # Create the HTML part + my $html_part = MIME::Lite::->new( + 'Type' => 'multipart/related', + ); + + $html_part->attach( + 'Type' => 'text/html', + 'Data' => $mail_body, + ) ; + + # === Attachments === + + my $attachtype = ($attachapplication) ? "application/$attachapplication" : 'AUTO' ; + my $attach_part = MIME::Lite::->new( + 'Type' => 'multipart/mixed', + ); + $attach_part->attach ( + Type => "$attachtype", + Encoding => 'base64', + Path => "$fullattachpath", + Filename => $attachname, + Disposition => 'attachement' + ) ; + + $msg->attach($attach_part); + $msg->attach($html_part); + + my $email = $msg->as_string(); + + my $smtp_msg = Net::SMTP_auth->new($smtp_host, Port=>587) or die "Can't connect"; + $smtp_msg->auth('PLAIN', $smtp_user, $smtp_pass) or die "Can't authenticate:" . $smtp_msg->message(); + + $smtp_msg->mail($from) or die "Error:" . $smtp_msg->message(); + + $smtp_msg->to($_) for split(/\s*,\s*/, join(',', $to, $cc, $bcc)); + + # $smtp_msg->recipient($to) or die "Error:".$smtp_msg->message(); + $smtp_msg->data() or die "Error:".$smtp_msg->message(); + $smtp_msg->datasend($email) or die "Error:".$smtp_msg->message(); + $smtp_msg->dataend() or die "Error:".$smtp_msg->message(); + $smtp_msg->quit or die "Error:".$smtp_msg->message(); + +} #---------------------------------------------------------------------------------------- + +# sub common_email_with_attachments { + + # my ($from,$to,$cc,$bcc,$subj,$text_msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication) = @_ ; + + # use MIME::Lite; + # use Net::SMTPS; + + # # SMTP configuration + # my $smtp_host = $afrihost_smtp ; + # my $smtp_port = $afrihost_port ; + # my $smtp_user = $afrihost_from ; + # my $smtp_pass = $afrihost_psw ; + # my $from = $afrihost_from ; + + # # HTML body part + # my $mail_body = &common_get_mail_body($text_msg,$table_msg) ; + + # my $fullattachpath = "$attachpath/$attachname"; + # die "Attachment file not found: $fullattachpath" unless -e $fullattachpath; + + # # ################################################################# + # # Lets build the MulitPart MIME Message + # # ################################################################# + # # Create the Message + # my $msg = MIME::Lite::->new( + # 'From' => "$useropts{short} Events <$from>", + # 'Reply-To' => $email_reply_to, + # 'To' => $to, + # 'Cc' => $cc, + # 'Bcc' => $bcc, + # 'Subject' => $subj, + # 'Type' => 'multipart/mixed', + # ); + + # # Create the HTML part + # my $html_part = MIME::Lite::->new( + # 'Type' => 'multipart/related', + # ); + + # $html_part->attach( + # 'Type' => 'text/html', + # 'Data' => $mail_body, + # ) ; + + # # === Attachments === + + # my $attachtype = ($attachapplication) ? "application/$attachapplication" : 'AUTO' ; + # my $attach_part = MIME::Lite::->new( + # 'Type' => 'multipart/mixed', + # ); + # $attach_part->attach ( + # Type => "$attachtype", + # Encoding => 'base64', + # Path => "$fullattachpath", + # Filename => $attachname, + # Disposition => 'attachement' + # ) or &common_send_mail('rory@kre8it.co.za','','','',"$useropts{short} ERROR : common.pm","common_send_smtp_mail cant attach $attachpath/$attachname : $!") ; + + # $msg->attach($attach_part); + # $msg->attach($html_part); + + # my $email = $msg->as_string(); + + # # # === Send via SMTPS (port 465) === + + # my $smtp = Net::SMTPS->new( + # $smtp_host, + # Port => 587, + # doSSL => 'starttls', + # Timeout => 30, + # Debug => 1, + # ) or die "Failed to connect to SMTP server"; + + # $smtp->auth($smtp_user, $smtp_pass) or die "SMTP Auth failed: $!"; + + # # Send the email + # $smtp->mail($from) or die "MAIL FROM failed"; + # # $smtp->to($_) for split(/\s*,\s*/, join(',', $to, $cc, $bcc)); + + # $smtp->to($to) or die "Error:".$smtp->message(); + # # $smtp->recipient($to) or die "Error:".$smtp->message(); + + # # &common_debug("common_send_smtp_mail attach : $attachpath/$attachname [$attachapplication]") ; + + # # # Send the message + # # $smtp->data(); + # # $smtp->datasend($msg->as_string); + # # my $response = $smtp->dataend(); + # # $smtp->quit; + + # eval { + # $smtp->data() or die "Error:" . $smtp->message(); + # $smtp->datasend($email) or die "Error:" . $smtp->message(); + # $smtp->dataend() or die "Error:" . $smtp->message(); + # $smtp->quit; + # }; + # if ($@ || $!) { + # print "Email sending failed: $@ $!\n"; + # } else { + # print "Email sent successfully.\n"; + # } + + + # # my $smtp_msg = Net::SMTP_auth->new($smtp_host, Port=>587) or die "Can't connect"; + # # $smtp_msg->auth('PLAIN', $smtp_user, $smtp_pass) or die "Can't authenticate:" . $smtp_msg->message(); + + # # $smtp_msg->mail($from) or die "Error:".$smtp_msg->message(); + + # # # $smtp->to($_) for split(/\s*,\s*/, join(',', $to, $cc, $bcc)); + + # # $smtp_msg->recipient($to) or die "Error:".$smtp_msg->message(); + # # $smtp_msg->data() or die "Error:".$smtp_msg->message(); + # # $smtp_msg->datasend($email) or die "Error:".$smtp_msg->message(); + # # $smtp_msg->dataend() or die "Error:".$smtp_msg->message(); + # # $smtp_msg->quit or die "Error:".$smtp_msg->message(); + +# } #---------------------------------------------------------------------------------------- + +# sub common_email_with_attachments { + + # my ($from,$to,$cc,$bcc,$subj,$text_msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication) = @_ ; + + # use MIME::Lite; + # use Net::SMTPS; + + # # SMTP configuration + # my $smtp_host = $afrihost_smtp ; + # my $smtp_port = $afrihost_port ; + # my $smtp_user = $afrihost_from ; + # my $smtp_pass = $afrihost_psw ; + # my $from = $afrihost_from ; + + # # HTML body part + # my $html_body = &common_get_mail_body($text_msg,$table_msg) ; + + # my $fullpath = "$attachpath/$attachname"; + # die "Attachment file not found: $fullpath" unless -e $fullpath; + + # # Create MIME::Lite message + # my $msg = MIME::Lite->new( + # From => $from, + # To => $to, + # Cc => $cc, + # Bcc => $bcc, + # Subject => $subj, + # Type => 'multipart/mixed', + # ); + + # $msg->attach( + # Type => 'text/html', + # Data => $html_body, + # ); + + # # === Attachments === + + # my $attachtype = ($attachapplication) ? "application/$attachapplication" : 'application/octet-stream' ; # application/pdf or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet + # $msg->attach( + # Type => "$attachtype", + # # Encoding => 'base64', + # Path => "$fullpath", + # Filename => "$attachname", + # Disposition => 'attachment', + # ); + + # # # JPG + # # $msg->attach( + # # Type => 'image/jpeg', + # # Path => 'photo.jpg', + # # Filename => 'photo.jpg', + # # Disposition => 'attachment', + # # ); + + # # === Send via SMTPS (port 465) === + + # my $smtp = Net::SMTPS->new( + # $smtp_host, + # Port => $smtp_port, + # doSSL => 'ssl', + # Timeout => 30, + # Debug => 1, + # ) or die "Failed to connect to SMTP server"; + + # $smtp->auth($smtp_user, $smtp_pass) or die "SMTP Auth failed: $!"; + + # # Send the email + # $smtp->mail($from) or die "MAIL FROM failed"; + # $smtp->to($_) for split(/\s*,\s*/, join(',', $to, $cc, $bcc)); + + # # &common_debug("common_send_smtp_mail attach : $attachpath/$attachname [$attachapplication]") ; + + # # # Send the message + # # $smtp->data(); + # # $smtp->datasend($msg->as_string); + # # my $response = $smtp->dataend(); + # # $smtp->quit; + + # eval { + # $smtp->data() or die "DATA command failed : $@ $!"; + # $smtp->datasend($msg->as_string) or die "DATASEND failed : $@ $!"; + # $smtp->dataend() or die "DATAEND failed : $@ $!"; + # $smtp->quit; + # }; + # if ($@ || $!) { + # print "Email sending failed: $@ $!\n"; + # } else { + # print "Email sent successfully.\n"; + # } + +# } #---------------------------------------------------------------------------------------- + +# sub common_v2_send_smtp_mail { + + # my ($from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication,$uploaded_doc,$operator_email) = @_ ; + + # use Net::SMTPS; + + # # SMTP configuration + # my $smtp_host = $afrihost_smtp ; + # my $smtp_port = $afrihost_port ; + # my $smtp_user = $afrihost_from ; + # my $smtp_pass = $afrihost_psw ; + + # $from = $afrihost_from unless $from ; + + # # Create SMTPS object + # my $smtp = Net::SMTPS->new( + # $smtp_host, + # Port => $smtp_port, + # doSSL => 'ssl', # Ensure SSL from start (port 465) + # Timeout => 30, + # Debug => 1, # Optional: for debug output + # ); + + # # Authenticate + # $smtp->auth($smtp_user, $smtp_pass) or die "SMTP Auth failed: $!"; + + # # Send the email + # $smtp->mail($from); + # $smtp->to($to); + + # my $body = ($html) ? &common_get_mail_body($msg,$table_msg) : $msg ; + + # $smtp->data(); + # $smtp->datasend("From: $from\n"); + # $smtp->datasend("To: $to\n"); + # $smtp->datasend("Subject: $subj\n"); + # $smtp->datasend("MIME-Version: 1.0\n") if $html ; + # $smtp->datasend("Content-Type: text/html; charset=UTF-8\n") if $html ; + # $smtp->datasend("\n"); # empty line between headers and body + # $smtp->datasend("$body\n"); + # $smtp->dataend(); + + # $smtp->quit; + + # # print "Email sent successfully.\n"; + +# } #---------------------------------------------------------------------------------------- + +# sub common_get_mail_body { + + # my ($email_msg,$table_msg) = @_ ; + + # my $mail_body = < + # + # + # + # + + # + + # + # + + #
    + + # $useropts{short} + #

    + # $email_msg + #

    + # + # $thead + # + # $table_msg + # + #
    + + #
    + #

    $display_notif_msg + # Best regards, + #
    + #
    + # The $useropts{short} Team. + #

    + #
    + # + # +# END_OF_BODY + + # return ($mail_body) ; + +# } #---------------------------------------------------------------------------------------- + +use today ; +use common ; +# use mailsend ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/admin/oneoff/sendmailv3.pl b/scripts/_FromProd/v1.0/admin/oneoff/sendmailv3.pl new file mode 100644 index 0000000..9194bd9 --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/sendmailv3.pl @@ -0,0 +1,146 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use MIME::Lite; +use Mail::Sendmail; + +require cfg ; + +print "Content-type: text/html\n\n"; + +&today ; + +our $debug = 1 ; + +#------------------------------------------------------------------------------------------ + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/sendmailv3.pl + +use CGI::Carp qw(fatalsToBrowser); + +&common_v3_send_smtp_mail('','rory@kre8it.co.za','rory@mathew.za.net,admin@kre8it.co.za','k@re8it.com',"Calibration : $now_ccyy_mm_dd $now_hh_min_sec","Please see attached calibration...",'','html','',"$htmlpath/pdf/operator_flyer",'operator_email_attach.pdf','pdf',0,0) ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub common_v3_send_smtp_mail { + + my ($from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication,$uploaded_doc,$operator_email) = @_ ; + + # &common_debug("common_send_smtp_mail [$from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication,$uploaded_doc,$operator_email]") ; + + return unless $msg ; + return unless $subj ; + + # my $htype = (-f "$attachpath/$attachname" || $uploaded_doc || $operator_email) ? 'htmlattach' : ($html eq 'html') ? $html : 'text' ; + + # my $res = &common_mailsend_sendgrid($htype,$to,$subj,$msg,$attachpath,$attachname,"$useropts{short} Events",'events@itvadmin.co.za',$cc,$bcc,$uploaded_doc,$operator_email); + + # return if $res eq 'success' ; # carry on if mailsend_sendgrid failed + + my $main_email = $email_add{'events'} ; + + $to = $main_email unless $to ; + $from = $afrihost_from unless $from ; + + my $mail_body = ($html) ? &common_get_mail_body($msg,$table_msg,$thead) : $msg ; + + if ($html) { + if ($attachname && -f "$attachpath/$attachname") { + &common_debug("common_send_smtp_mail attach : $attachpath/$attachname [$attachapplication]") ; + &common_v3_email_with_attachments($from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication) ; + return ; + } + if ($uploaded_doc) { + my @parts = split(/\//,$uploaded_doc) ; + $attachname = $parts[-1] ; + pop @parts ; + $attachpath = join("/",@parts) ; + &common_v3_email_with_attachments($from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,$attachpath,$attachname,'') ; + return ; + } + if ($operator_email) { + &common_v3_email_with_attachments($from,$to,$cc,$bcc,$subj,$msg,$table_msg,$html,$thead,"$htmlpath/pdf/operator_flyer/operator_email_attach.pdf",'operator_email_attach.pdf','pdf') ; + return ; + } + # &common_send_mail($to,$cc,$bcc,$html,$thead,$msg,$subj,$table_msg) ; + } else { + # &common_send_mail($to,$cc,$bcc,$html,$thead,$msg,$subj,$table_msg) ; + } + +} #------------------------------------------------------------------------------------------ + +sub common_v3_email_with_attachments { + my ($from, $to, $cc, $bcc, $subj, $text_msg, $table_msg, $html, $thead, $attachpath, $attachname, $attachapplication) = @_; + + use MIME::Lite; + use Net::SMTP::SSL; + + # === Gmail SMTP configuration === + my $smtp_host = $gmail_smtp; # e.g. "smtp.gmail.com" + my $smtp_port = 465; + my $smtp_user = $gmail_from; + my $smtp_pass = $gmail_psw; + + # HTML body + my $mail_body = common_get_mail_body($text_msg, $table_msg); + + # Attachment + my $fullattachpath = "$attachpath/$attachname"; + die "Attachment file not found: $fullattachpath\n" unless -e $fullattachpath; + + # === Create top-level message === + my $msg = MIME::Lite->new( + From => "$useropts{short} Events <$from>", + 'Reply-To' => $email_reply_to, + To => $to, + Cc => $cc || '', + Bcc => $bcc || '', + Subject => $subj, + Type => 'multipart/mixed', + ); + + # Add HTML part + $msg->attach( + Type => 'text/html', + Data => $mail_body + ); + + # Add attachment + my $attachtype = ($attachapplication) ? "application/$attachapplication" : 'AUTO'; + $msg->attach( + Type => $attachtype, + Path => $fullattachpath, + Filename => $attachname, + Disposition => 'attachment', + Encoding => 'base64', + ); + + # === Send via Gmail === + my $smtp = Net::SMTP::SSL->new($smtp_host, Port => $smtp_port, Timeout => 20) + or die "Cannot connect to $smtp_host: $!"; + + $smtp->auth($smtp_user, $smtp_pass) + or die "SMTP auth failed: " . $smtp->message(); + + $smtp->mail($from) + or die "MAIL FROM failed: " . $smtp->message(); + + for my $recipient (split /\s*,\s*/, join(',', grep { $_ } ($to, $cc, $bcc))) { + $smtp->to($recipient) + or die "RCPT TO <$recipient> failed: " . $smtp->message(); + } + + $smtp->data(); + $smtp->datasend($msg->as_string); + $smtp->dataend(); + $smtp->quit; + +} #---------------------------------------------------------------------------------------- + +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/admin/oneoff/sendmailv4.pl b/scripts/_FromProd/v1.0/admin/oneoff/sendmailv4.pl new file mode 100644 index 0000000..f54212f --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/sendmailv4.pl @@ -0,0 +1,215 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use MIME::Lite; +use Mail::Sendmail; + +require cfg ; + +print "Content-type: text/html\n\n"; + +&today ; + +our $debug = 1 ; + +#------------------------------------------------------------------------------------------ + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/sendmailv4.pl + +use CGI::Carp qw(fatalsToBrowser); + +# &common_send_localhost_mail('rory@kre8it.co.za','rory@mathew.za.net,admin@kre8it.co.za','k@re8it.com','','',"Calibration : $now_ccyy_mm_dd $now_hh_min_sec","Please see attached calibration...") ; +&common_v4_send_mail('rory@kre8it.co.za','rory@mathew.za.net,admin@kre8it.co.za','k@re8it.com','','',"Calibration : $now_ccyy_mm_dd $now_hh_min_sec","Please see attached calibration...") ; + +# &common_v4_email_with_attachments('events@itvadmin.co.za','rory@kre8it.co.za','rory@mathew.za.net,admin@kre8it.co.za','k@re8it.com',"Calibration : $now_ccyy_mm_dd $now_hh_min_sec","Please see attached calibration...",$table_msg,1,$thead,"$htmlpath/pdf/operator_flyer",'operator_email_attach.pdf','pdf') ; + +#------------------------------------------------------------------------------------------ + +sub common_v4_send_mail { + + my ($to,$cc,$bcc,$html,$thead,$msg,$subj,$tmsg) = @_ ; + + return unless $msg ; + return unless $subj ; + + # my $cc = 'cc1@example.com, cc2@example.com'; # multiple cc's + # $smtp->to(split(/\s*,\s*/, $cc)); # split and add each + + use Net::SMTPS; + + # # SMTP configuration + # my $smtp_host = $afrihost_smtp ; + # my $smtp_port = $afrihost_port ; + # my $smtp_user = $afrihost_from ; + # my $smtp_pass = $afrihost_psw ; + my $from = $afrihost_from ; + + # # Create SMTPS object + # my $smtp = Net::SMTPS->new( + # $smtp_host, + # Port => $smtp_port, + # doSSL => 'ssl', # Ensure SSL from start (port 465) + # Timeout => 30, + # Debug => 1, # Optional: for debug output + # ); + + # # Authenticate + # $smtp->auth($smtp_user, $smtp_pass) or die "SMTP Auth failed: $!"; + + my $smtp = Net::SMTPS->new('localhost') or die "Can't connect"; + + # Send the email + $smtp->mail($from); + $smtp->to($to); + # $smtp->to($cc) if $cc ; + $cc =~ s/\;/\,/g ; + $smtp->to(split(/\s*,\s*/, $cc)) if $cc ; # split and add each + $bcc =~ s/\;/\,/g ; + $smtp->to(split(/\s*,\s*/, $bcc)) if $bcc; + + my $body = ($html) ? &common_get_mail_body($msg,$tmsg,$thead) : $msg ; + + $smtp->data(); + $smtp->datasend("From: $useropts{short} Events <$from>\n"); + $smtp->datasend("To: $to\n"); + $smtp->datasend("Cc: $cc\n") if $cc ; # visible + # Do NOT include Bcc in headers + $smtp->datasend("Subject: $subj\n"); + $smtp->datasend("MIME-Version: 1.0\n") if $html ; + $smtp->datasend("Content-Type: text/html; charset=UTF-8\n") if $html ; + $smtp->datasend("\n"); # empty line between headers and body + $smtp->datasend("$body\n"); + $smtp->dataend(); + + $smtp->quit; + +} #------------------------------------------------------------------------------------------ + +sub common_v4_email_with_attachments { + + my ($from,$to,$cc,$bcc,$subj,$text_msg,$table_msg,$html,$thead,$attachpath,$attachname,$attachapplication) = @_ ; + + use MIME::Lite; + use Net::SMTP_auth; + + # # SMTP configuration + # my $smtp_host = $afrihost_smtp ; + # my $smtp_port = $afrihost_port ; + # my $smtp_user = $afrihost_from ; + # my $smtp_pass = $afrihost_psw ; + my $from = $afrihost_from ; + + # HTML body part + my $mail_body = &common_get_mail_body($text_msg,$table_msg) ; + + my $fullattachpath = "$attachpath/$attachname"; + die "Attachment file not found: $fullattachpath" unless -e $fullattachpath; + + # === build the MulitPart MIME Message === + + # Create the Message + my $msg = MIME::Lite::->new( + 'From' => "$useropts{short} Events <$from>", + 'Reply-To' => $email_reply_to, + 'To' => $to, + 'Cc' => $cc, + 'Bcc' => $bcc, + 'Subject' => $subj, + 'Type' => 'multipart/mixed', + ); + + # Create the HTML part + my $html_part = MIME::Lite::->new( + 'Type' => 'multipart/related', + ); + + $html_part->attach( + 'Type' => 'text/html', + 'Data' => $mail_body, + ) ; + + # === Attachments === + + my $attachtype = ($attachapplication) ? "application/$attachapplication" : 'AUTO' ; # application/pdf or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet + my $attach_part = MIME::Lite::->new( + 'Type' => 'multipart/mixed', + ); + $attach_part->attach ( + Type => "$attachtype", + Encoding => 'base64', + Path => "$fullattachpath", + Filename => $attachname, + Disposition => 'attachement' + ) ; + + $msg->attach($attach_part); + $msg->attach($html_part); + + my $email = $msg->as_string(); + + # my $smtp_msg = Net::SMTP_auth->new($smtp_host, Port=>587) or die "Can't connect"; + # $smtp_msg->auth('PLAIN', $smtp_user, $smtp_pass) or die "Can't authenticate:" . $smtp_msg->message(); + + my $smtp_msg = Net::SMTP_auth->new('localhost') or die "Can't connect"; + + $smtp_msg->mail($from) or die "Error:" . $smtp_msg->message(); + + $smtp_msg->to($_) for split(/\s*,\s*/, join(',', $to, $cc, $bcc)); + + # $smtp_msg->recipient($to) or die "Error:".$smtp_msg->message(); + $smtp_msg->data() or die "Error:".$smtp_msg->message(); + $smtp_msg->datasend($email) or die "Error:".$smtp_msg->message(); + $smtp_msg->dataend() or die "Error:".$smtp_msg->message(); + $smtp_msg->quit or die "Error:".$smtp_msg->message(); + +} #---------------------------------------------------------------------------------------- + +exit ; + +#------------------------------------------------------------------------------------------ + +sub common_send_localhost_mail { + + my ($to,$cc,$bcc,$html,$thead,$msg,$subj) = @_ ; + + return unless $msg ; + return unless $subj ; + + use Mail::Sendmail; + + $to = $main_email unless $to ; + + my %mail = () ; + + %mail = ( + smtp => 'localhost', + From => "$useropts{short} Events ", + To => $to, + Cc => $cc, + Bcc => $bcc, + Subject => $subj + ); + + # $mail{smtp} = "smtp.interactivetvafrica.com"; + # $mail{Debug} = 6; + # $mail{port} = 587; + # $mail{port} = 465; + # $mail{Auth} = {user => $main_email, pass => $send_mail_psw, method => "LOGIN", required => 1}; + + $mail{body} = < $a} keys %{$db{$changes_table}}) { + $seen_changes{$db{$changes_table}{$_}{changes}} = 1 ; + $saved_line_max_id = $_ if $saved_line_max_id < $_ ; + + if ($cnt_line == 1) { + $cnt_line++ ; + my @abc = split(/\|/,$db{$changes_table}{$_}{changes}) ; + $most_recent_saved_line = $abc[0] ; + } + + } + + my $logfile = "/home/libs/data/logs/events/$changes_script.dat"; + + open(my $fh, "<", $logfile) or die "Can't open $logfile: $!"; + + my @lines = <$fh> ; # Slurp all lines into an array + + # 202520250528164733|2025-05-28 16:47:33|event_quote_id='10427'|user_id=84|changed_from|last_update='2025-05-28 16:45:34',additional_notes='COURT 2 AND 3 Nkululeko 305 Aletia 31 5 COURT 2 Emihle 305 Nkululeko 31 5 COURT 3' + # 202520250528164733|2025-05-28 16:47:33|event_quote_id='10427'|user_id=84|changed_from|last_update='2025-05-28 16:45:34',additional_notes='COURT 2 AND 3 Nkululeko 305 Aletia 315 COURT 2 Emihle 305 Nkululeko 315 COURT 3' + + my $line_count = scalar @lines ; + # my $line_count = $saved_line_max_id ; + $line_count += $saved_line_max_id ; + + my %lines_ = () ; + + + + foreach my $line (@lines) { + chomp $line ; + + my @abc = split(/\|/,$line) ; + $seen_changes{$line} = 1 if $most_recent_saved_line && $abc[0] <= $most_recent_saved_line ; + + $line_count-- if $seen_changes{$line} ; + $lines_{$line} = 1 ; + } + + foreach my $line (@lines) { + chomp $line ; + next if $seen_changes{$line} ; + print "INSERT INTO $changes_table (id,changes) VALUES ($line_count,\"$line\") ; \n"; + $line_count-- ; + } + + close($fh); + +} #------------------------------------------------------------------------------- + +use db ; +use today ; +use common ; +use common_min ; diff --git a/scripts/_FromProd/v1.0/admin/oneoff/update_user_password_from_excel.pl b/scripts/_FromProd/v1.0/admin/oneoff/update_user_password_from_excel.pl new file mode 100644 index 0000000..bbb9bae --- /dev/null +++ b/scripts/_FromProd/v1.0/admin/oneoff/update_user_password_from_excel.pl @@ -0,0 +1,102 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Crypt::PasswdMD5; + + +&today ; + +#------------------------------------------------------------------------------------------ + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); + +foreach $ARG (@ARGV) { ($par,$val) = split(/\=/,$ARG) ; $param{$par} = $val ; } + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/update_user_password_from_excel.pl?1 + +our $debug = $ARGV[0] ; +our $username = 'rory' ; + +# print "\n debug : $debug \n" ; + +if ($debug) { print "Content-type: text/html\n\n"; } + +&common_debug("\n 1. START") ; + +#------------------------------------------------------------------------------------------ + +&today ; +&common_debug("\n 2. START") ; +# &set_delete_date ; +&read_csv ; + +if ($debug) { print "Done."; } + +exit; + + +#------------------------------------------------------------------------------------------ + +sub read_csv { + + + # my $crypted_password = apache_md5_crypt($i{password},$useropts{salt}) ; + + my $file_path = "$htmlpath/csv/operator_list_csv.csv" ; + + &common_debug("file_path : $file_path") if -f $file_path ; + + # Open the file for reading + + unless (open(CSV_FILE, '<', $file_path)) { + die "Unable to open the file '$file_path' for reading: $!"; + } + + my $header_line = ; my @fields = () ; + + while (my $line = ) { + + @fields = () ; @fields = split(',',$line) ; + + my $id = $fields[0] ; + my $password = $fields[5] ; + $password =~ s/\n//g; $password =~ s/ //g; + my $length = length ($password) ; + $password = substr($password,0,$length-1) ; + + my $crypted_password = apache_md5_crypt($password,$useropts{salt}) ; + + &common_debug("UPDATE `users` SET `password` = '$crypted_password' WHERE `id` = '$id' ;") ; + + # # $fields[4] =~ s\/'\\gi ; + # $fields[0] =~ s\/'\\gi ; + + # $fields[3] =~ s/\n//g; + + # my $region_id = 0 ; my $city_id = 0 ; + # $region_id = 4 if $fields[3] eq 'KZN' ; + # $region_id = 9 if $fields[3] eq 'CPT' ; + # $region_id = 2 if $fields[3] eq 'Bloem' ; + # $region_id = 3 if $fields[3] eq 'JHB' ; + + # $city_id = 1 if $fields[3] eq 'JHB' ; + # $city_id = 10 if $fields[3] eq 'CPT' ; + # $city_id = 20 if $fields[3] eq 'Bloem' ; + + # print "\n;UPDATE `users` SET `region_ids` = '$region_id', `city_id` = '$city_id' WHERE region_ids = '0' AND `name` LIKE '$fields[0]%' AND `name` LIKE '%$fields[1]'" ; + + # print "\n ;UPDATE `users` SET email = '$fields[2]' WHERE region_ids = '0' AND name LIKE '$fields[0]%' AND name LIKE '%$fields[1]' AND (`email` = '' OR `email` IS NULL) ;" ; + + } + +} #------------------------------------------------------------------------------- + +use db ; +use today ; +use common ; +use common_min ; diff --git a/scripts/live_reacon.pl b/scripts/_FromProd/v1.0/allocate_credits.pl similarity index 100% rename from scripts/live_reacon.pl rename to scripts/_FromProd/v1.0/allocate_credits.pl diff --git a/scripts/_FromProd/v1.0/analytics_clients.pl b/scripts/_FromProd/v1.0/analytics_clients.pl new file mode 100644 index 0000000..8c4de04 --- /dev/null +++ b/scripts/_FromProd/v1.0/analytics_clients.pl @@ -0,0 +1,124 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Crypt::PasswdMD5; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +# unless ($username eq 'rory') { print ">>>> DEVELOPMENT IN PROGRESS <<<<" ; exit ; } + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + + &users_validate; + +} #------------------------------------------------------------------------------------------ + +sub insert { + + &users_insert ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + &users_update ; + +} #------------------------------------------------------------------------------------------ + +sub process_multi_select { + + &users_process_multi_select ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + &users_list_screen ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + &users_sort_fields ; + +} #------------------------------------------------------------------------------- + +sub add_db_fields { + + &users_add_db_fields ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &users_edit_db_fields ; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + + # called from common_add_screen + &users_add_screen ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + &users_edit_screen ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &users_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'user' ; + our $lcpage = 'analytics-client' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'users' ; + our $user_type = 'analytics_client' ; + + &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; +use users ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/analytics_event_bookings.pl b/scripts/_FromProd/v1.0/analytics_event_bookings.pl new file mode 100644 index 0000000..90bd328 --- /dev/null +++ b/scripts/_FromProd/v1.0/analytics_event_bookings.pl @@ -0,0 +1,1839 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); + +require cfg ; + +print header; # CGI.pm method + +# unless ($username eq 'handre'or $username eq 'rory') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#---------------- ----------------------------------------------------------------------------------------------------------------------------------------------------- + +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX ; +use LWP::Simple qw($ua get); +use JSON ; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +# our $redirtype = 'search' ; + +# our $testing = 1 ; +# our $debug = 1 ; +# &common_debug("glod_user_level = $glod_user_level [$usertype]") ; + +# unless ($username eq 'rory') { print ">>>> DEVELOPMENT IN PROGRESS <<<<" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +# my $string = '3;;1;u16;a;;1;;s;s;;|5;;1;u17;a;;1;;s;s;;|5;;1;open;a;;1;;p;s;;'; + +# print "\n MAINTENANCE IN PROGRESS !" ; +# exit if $username ne 'handre'; + +if ($is_operator && $glod_user_level == 2) { $glod_user_level = 3 ; } # upgrade operators level 2&3 to 3&4 + +our $nr_of_system_names_and_clubs = 15 ; our @all_select_ids = () ; our $minify_jquery = 1 ; + +&db_open_ro ; + $db_ignore_open_close = 1 ; + + &page_opts ; + + if ($iaction eq 'filter' || $iaction eq 'search' || $iaction eq 'report') { + our $srchscr = 1 ; + our $savjqy = 0 ; + } + + #------------------------------------------------------------------------------------------------------------------------------------------------------------------ + + our @fixture_headers = ("Fixture Date/Time From","Sport","Age Group","Team","Home Team","HT Colour","Away Team","Coding Type","Footage Type"); + our @analytics_headers = ("Fixture Date/Time From","Sport","Age Group","Team","Home Team","HT Colour","Away Team","Coding Type","Footage Type","Service Type"); + our %service_types = (1 => "Live Coding",2 => "Post Coding 12 hrs",3 => "Post Coding 24 hrs") ; + our %coding_type = ("s" => "Standard","p" => "Premium") ; + our %footage_type = ("s" => "SSS","r" => "Raw") ; + + if ($iaction eq 'add') { + &add_screen ; + &common_min_screen1 ; + } elsif ($iaction eq 'edit') { + &common_min_load_params ; + &edit_screen ; + &common_min_screen1 ; + } elsif ($iaction eq 'save') { + &common_min_load_params ; + &insert ; + # &log_changes ; + &edit_or_list ; + } elsif ($iaction eq 'update') { + &common_min_load_params ; + &update ; + # &log_changes ; + &edit_or_list ; + } elsif ($iaction eq 'copy') { + &common_min_load_params ; + &duplicate ; + &edit_screen ; + &common_min_screen1 ; + } elsif ($iaction eq 'delete') { + &common_min_load_params ; + &report_ifields ; + &delete ; + &common_min_screen2 ; + } + + &common_min_action ; + + $db_ignore_open_close = 0 ; +&db_close_conn ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub edit_or_list { + + exit if $testing && substr($username,0,4) eq 'rory' ; + + &edit_screen ; + &common_min_screen1; + +} #------------------------------------------------------------------------------------------ + +sub process_fixtures_tab { + + my ($id) = @_ ; + + &db_min_ro($table,"id,fixtures_saved_values,analytics_saved_values","id='$id'",'','') if $id ; + + $i{fixtures_saved_values} = qq~~ ; + + my $suffix = "fixtures" ; + + my @changed_field_keys = ("age_group","team","home_team","ht_colour","away_team","coding_type","footage_type") ; + + my @fixtures_saved_values_split = ($id) ? split(/\|/,$db{$table}{$id}{fixtures_saved_values}) : () ; + + for my $row_nr (1 .. 100) { + + # last if $row_nr > $i{total_fixtures} ; + + my $input_vals = qq~~ ; + + my @fixtures_saved_values_split_2 = ($id) ? split(/\;/,$fixtures_saved_values_split[$row_nr - 1]) : () ; + + foreach (@changed_field_keys) { + $input_vals .= qq~;$i{"$_\_$suffix\_$row_nr"}~ ; + $ignore{"$_\_$suffix\_$row_nr"} = 1 ; + } + $input_vals .= qq~;$fixtures_saved_values_split_2[9];$fixtures_saved_values_split_2[10]~ ; + + my $changed_fixtures_date_field = "changed_fixtures_date_$row_nr" ; + + my $date_field = "start_date_time_$suffix\_$row_nr" ; + + my $changed_sport_field = "sport_fixtures_$row_nr" ; + + if ($input_vals =~ /[a-zA-Z]/ || $input_vals =~ /(\d+)/g || $i{$changed_sport_field} || $i{$changed_fixtures_date_field}) { + $i{fixtures_saved_values} .= ($i{$changed_fixtures_date_field}) ? qq~$i{$date_field};$i{$changed_sport_field}~ : qq~;$i{$changed_sport_field}~ ; + $i{fixtures_saved_values} .= qq~$input_vals~ ; + } + + $i{fixtures_saved_values} .= qq~|~ ; + + $ignore{"start_date_time_$suffix\_$row_nr"} = 1 ; + $ignore{"readonly_sport_$suffix\_$row_nr"} = 1 ; + $ignore{"sport_$suffix\_$row_nr"} = 1 ; + + } + # 1;;;u14;a;;1;;s;s|2;;;u14;a;;1;;s;s|3;;2;u15;a;;1;;s;s|4;;1;u15;a;;1;;s;s|5;;2;u16;a;;1;;s;s|6;;1;u16;a;;1;;s;s|7;;2;open;b;;1;;s;s|8;;1;open;b;;1;;s;s|9;;2;open;a;;1;;p;s|10;;1;open;a;;1;;p;s + # 1;;;u14;a;;1;;s;s;;|2;;;u14;a;;1;;s;s;;|3;;2;u15;a;;1;;s;s;;|4;;1;u15;a;;1;;s;s;;|5;;2;u16;a;;1;;s;s;;|6;;1;u16;a;;1;;s;s;;|7;;2;open;b;;1;;s;s;;|8;;1;open;b;;1;;s;s;;|9;;2;open;a;;1;;p;s;;|10;;1;open;a;;1;;p;s;; 1005 + + + # 1;;;open;a;7495;1;6684;s;s;;|2;;;u19;b;845;1;778;p;r;;|3;2025-06-18 06:00:00;8;u17;c;54;1;3975;s;s;; 1000 + + # 1;;;u14;a;;1;;s;s;;|2;;1;u15;a;;1;;s;s;;|3;;1;u16;a;;1;;s;s;;|4;;1;u17;a;;1;;s;s;;|5;;1;open;a;;1;;p;s;; + # 1;;;u14;a;;1;;s;s|2;;1;u15;a;;1;;s;s|3;;1;u16;a;;1;;s;s|4;;1;u17;a;;1;;s;s|5;;1;open;a;;1;;p;s + + chop $i{fixtures_saved_values} if $i{fixtures_saved_values} ; + + $i{fixtures_saved_values} =~ s/([a-zA-Z0-9]);+(\|)/$1$2/g; + $i{fixtures_saved_values} =~ s/([a-zA-Z0-9])\|+$/$1/; + + $ignore{fixtures_saved_values} = (($id && $i{fixtures_saved_values} eq $db{$table}{$id}{fixtures_saved_values}) || (!$i{fixtures_saved_values} && !$db{$table}{$id}{fixtures_saved_values})) ? 1 : 0 ; + +} #------------------------------------------------------------------------------------------ + +sub process_analytics_tab { + + $i{analytics_saved_values} = qq~~ ; + + my $suffix = "analytics" ; + + my @changed_field_keys = ("stream_forwarding","stream_key","stream_URL") ; + + for my $row_nr (1 .. 100) { + + foreach (@changed_field_keys) { + $i{analytics_saved_values} .= ($i{"$_\_$suffix\_$row_nr"}) ? qq~$i{"$_\_$suffix\_$row_nr"};~ : ($i{"$_\_fixtures_$row_nr"}) ? qq~$i{"$_\_fixtures_$row_nr"};~ : qq~;~ ; + $ignore{"$_\_$suffix\_$row_nr"} = 1 ; + $ignore{"$_\_fixtures_$row_nr"} = 1 ; + } + + $i{analytics_saved_values} =~ s/;+$// ; + $i{analytics_saved_values} .= qq~|~ ; + + } + + $i{analytics_saved_values} =~ s/\|+$// ; + + $ignore{analytics_saved_values} = (($id && $i{analytics_saved_values} eq $db{$table}{$id}{analytics_saved_values}) || (!$i{analytics_saved_values} && !$db{$table}{$id}{analytics_saved_values})) ? 1 : 0 ; + +} #------------------------------------------------------------------------------------------ + +sub insert { + + my $quote_cancelled = $i{quote_cancelled} ; my $quote_accepted = $i{quote_accepted} ; my $quote_rejected = $i{quote_rejected} ; + + &add_db_fields ; + + $i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{date_created} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{created_by} = $userid ; + $i{last_changed_by} = $userid ; + + $i{id} = &db_min_get_max($table,'id') ; + $i{id} = 1000 if !$i{id} || $i{id} < 1000 ; + + &process_fixtures_tab('') ; + + &process_analytics_tab('') ; + + &set_default_i_vals ; + + &process_multi_select ; + + &process_client_id ; + + $ignore{country_id} = 1 ; + + &db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + unless ($i{id}) { + $error = qq(NO ID) ; + return ; + } + + $i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{last_changed_by} = $userid ; + + &edit_db_fields ; + + &set_default_i_vals ; + + &process_fixtures_tab($i{id}) ; + + &process_analytics_tab($i{id}) ; + + &process_multi_select ; + + &process_client_id ; + + # &log_changes($i{id}) ; + + # &db_min_upd($table,"id='$i{id}'") ; + + our $line = qq~~ ; + + $ignore{country_id} = 1 ; + + &common_shared_log_update_changes($table,"analytics_changes","changes_analytics") ; + +} #------------------------------------------------------------------------------------------ + +# sub log_changes { + + # my ($id) = @_ ; + + # &db_min_ro($table,"*","`id`='$id'",'','') ; + + # my $line = qq~~ ; + + # my %col_to_be_updated = () ; + + # foreach (keys %i) { + # $col_to_be_updated{$_} = 1 ; + # } + + # foreach my $col (keys %{$db{$table}{$id}}) { + + # next if $ignore{$col} || $hidden{$col} == 1 || substr($col,0,3) eq 'new' || !$col_to_be_updated{$col} || $col eq 'last_updated' ; + # if (($i{$col} || $db{$table}{$id}{$col}) && $db{$table}{$id}{$col} ne $i{$col}) { + # $line .= qq~$col='$db{$table}{$id}{$col}',~ ; + # } elsif ((!$i{$col} && !$db{$table}{$id}{$col}) || (($i{$col} || $db{$table}{$id}{$col}) && $db{$table}{$id}{$col} eq $i{$col})) { + # $ignore{$col} = 1 ; + # } + # } + + # $line = qq~$now_year$now_year$now_mm$now_dd$now_hour$now_min$now_sec|$now_year-$now_mm-$now_dd $now_hour:$now_min:$now_sec|event_quote_id='$id'|user_id=$userid|changed_from|~ . $line if $line ; + + # return unless $line ; + + # chop $line ; + + # &common_log_changes("events/changes_analytics.dat",$line) ; + + + +# } #------------------------------------------------------------------------------------------ + +# sub process_event_to { +sub process_client_id { + + my @abc = split(/\:/,$i{client_id}) ; + $i{client_id} = $abc[0] ; + +} #------------------------------------------------------------------------------------------ + +sub process_multi_select { + + local @sporttypeids = split(/\,/,$i{sporttypeids}) ; + my $sporttypeids = join(";",@sporttypeids) ; + $sporttypeids =~ s/\s//g; # remove white space + $ignore{sporttypeids} = 1 ; + $i{sport_type_ids} = $sporttypeids ; + $i{sport_type_ids} = 0 unless $i{sport_type_ids} ; + +} #------------------------------------------------------------------------------------------ + +sub duplicate { + + unless ($i{id}) { + $error = qq~NO ID~ ; + return ; + } + + &db_min_copy($table,$i{id}) ; + +} #------------------------------------------------------------------------------------------ + +sub delete { + + unless ($i{id}) { $error = uc "NO ID" ; return ; } + + &db_min_delete($table,"`id`='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub set_default_i_vals { + + $i{created_by} = '0' unless $i{created_by} ; + $i{event_completed} = '0' unless $i{event_completed} ; + $i{event_accepted} = '0' unless $i{event_accepted} ; + $i{event_pending} = '0' unless $i{event_pending} ; + $i{event_cancelled} = '0' unless $i{event_cancelled} ; + $i{event_rejected} = '0' unless $i{event_rejected} ; + $i{event_created} = '0' unless $i{event_created} ; + $i{country_id} = '0' unless $i{country_id} ; + $i{total_fixtures} = '1' unless $i{total_fixtures} ; + $i{service_type_id} = '0' unless $i{service_type_id} ; + $i{event_quote_id} = '0' unless $i{event_quote_id} ; + $i{region_id} = '0' unless $i{region_id} ; + $i{home_teams_built_on_regions} = '0' unless $i{home_teams_built_on_regions} ; + $i{derby_day_weekly_fixture_id} = '0' unless $i{derby_day_weekly_fixture_id} ; + $i{tournament_festival_id} = '0' unless $i{tournament_festival_id} ; + +} #---------------------------------------------------------------------------------------- + +sub list_screen { + + $trigger_jquery_raw .= qq~ + function deleteMinItem_custom (name,id) { + BootstrapDialog.confirm({ + title: 'Confirm Delete', + message: 'Are you sure you want to delete '+name+'?', + type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + callback: function(result) { + if (result) { + let delete_url = "$useropts{scripts}/get/get_delete_event_quote.pl?"+id+"&$table" ; + \$.get(delete_url) ; + \$("#analytics_event_row_"+id).html("") ; + } + } + }) ; + } + ~ ; + + &db_min_ro('users','id,username,name,email','','','') ; + foreach my $_id (keys %{$db{users}}) { + $username{$_id} = $db{users}{$_id}{username} ; + $name{$_id} = $db{users}{$_id}{name} ; + $email{$_id} = $db{users}{$_id}{email} ; + } + + &db_min_ro('sport_types','*','','','') ; + foreach my $_id (keys %{$db{sport_types}}) { $sport_type{$_id} = $db{sport_types}{$_id}{name} ; } + + if ($iaction eq 'completed' or $i{options} eq 'completed') { push @report_sql, "q.event_completed='1'" ; } + if ($iaction eq 'accepted' or $i{options} eq 'accepted') { push @report_sql, "q.event_accepted='1'" ; } + if ($iaction eq 'rejected' or $i{options} eq 'rejected') { push @report_sql, "q.event_rejected='1'" ; } + if ($iaction eq 'closed' or $i{options} eq 'closed') { push @report_sql, "(q.event_cancelled='1' OR (q.event_expiry<'$now_year-$now_mm-$now_dd' AND q.event_accepted<>'1'))" ; } + if ($iaction eq 'pending' or $i{options} eq 'pending') { push @report_sql, "q.event_pending='1'" ; } + if ($iaction eq 'list' or $i{options} eq 'list') { push @report_sql, "q.event_cancelled<>'1'" ; } + + my $t1 = $table ; + my $t2 = 'countries' ; + my $t3 = 'customers' ; + my $t4 = 'event_quotes' ; + our $tables = "$t1,$t2,$t3,$t4" ; + + if ($is_schools_manager || $is_operator) { + @report_sql_or = () ; + foreach $_reg_id (keys %{$glob_regids{$userid}}) { + push @report_sql_or, "q.region_id = '$_reg_id'" + } + my $sql_or = join(' OR ',@report_sql_or) ; + push @report_sql, "($sql_or)" if $sql_or ; + push @report_sql, "(q.event_created='1')" if $is_schools_manager ; + # push @report_sql, "(q.user_id='$userid')" if $is_schools_manager ; + push @report_sql, "(q.event_accepted='1')" if $is_operator && !$i{options} ; + } + + push @report_sql, "(q.event_completed <> '1')" if $iaction eq 'list' ; + + my $srch_where_sql = join(' AND ', @report_sql) ; my $sql_where = ($srch_where_sql) ? "WHERE $srch_where_sql" : '' ; + + &db_min_raw("SELECT q.id AS 'quote_id', + q.sport_type_ids, + q.start_date_time, + q.event_name, + q.event_expiry, + q.client_id, + q.event_date, + q.date_created, + q.country_id, + q.event_cancelled, + q.event_accepted, + q.event_completed, + q.event_pending, + q.event_created, + q.event_rejected, + q.created_by, + q.additional_notes, + q.total_fixtures, + q.service_type_id, + q.event_quote_id, + q.fixtures_saved_values, + q.analytics_saved_values, + c.name AS 'country', + t.name AS 'customer', + eq.event_system_id_multiple + FROM $t1 q LEFT JOIN $t2 c ON q.country_id = c.id + LEFT JOIN $t3 t ON q.client_id = t.id + LEFT JOIN $t4 eq ON q.event_quote_id = eq.id + $sql_where;"); + + foreach $row (@$rows_array_ref) { + for (0 .. $col_cnt){ + # &common_debug("[$_] $col_name{$_} -> @$row[$_]") ; + $db{$tables}{@$row[0]}{$col_name{$_}} = @$row[$_] ; + } + } + + &db_min_ro('event_systems','id,name,description','','','') ; + + &db_min_ro('customers','id,name','','','') ; + + &db_min_ro('sport_types','id,name','','','') ; + + &analytics_event_bookings_tabs_hash ; # load for PDF links + "e_list ; # load for PDF links + + if ($iaction eq 'update' or $iaction eq 'save'){ + &common_min_extra_crumb("list-$lcpage\s","List $ucfirstpage\s") ; + } + +} #------------------------------------------------------------------------------------------ + +sub quote_list { + + # our @sql_col_display = ("nr","date","customer","user","event","venue","location","sports_type","date_from","date_to","days","type") ; + # our @sql_col_display = ("nr","event_start","event_end","date_added","customer","user","event","venue","location","sports_type","days","type") ; + + our @sql_col_display = ("nr","event_start","event_end","date_added","customer","event","sport","total_fixtures","service_type") ; + + our @col_display_excel = @sql_col_display ; + + push @sql_col_display, "" ; + + &report_xlsx_export_header("Analytics-Events",'analytics_events') ; + + our $ws2 = 'Individual Games' ; + + &xlsxcreator_add_worksheet($ws2) ; + + my %individual_games = () ; + + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) { + + next unless $id ; + + my $quote_expiry = $db{$tables}{$id}{event_expiry} ; $quote_expiry =~ s/\-//iog ; + our $quote_accepted = $db{$tables}{$id}{event_accepted} ; + our $quote_pending = $db{$tables}{$id}{event_pending} ; + our $quote_cancelled = $db{$tables}{$id}{event_cancelled} ; + our $quote_completed = $db{$tables}{$id}{event_completed} ; + our $quote_created = $db{$tables}{$id}{event_created} ; + our $quote_rejected = $db{$tables}{$id}{event_rejected} ; + + if ($quote_completed) { + $sortprefix = 'd' ; + } elsif ($quote_accepted) { + $sortprefix = 'c' ; + } elsif ($quote_rejected) { + $sortprefix = 'x' ; + } elsif ($quote_cancelled) { + $sortprefix = 'z' ; + } elsif ($quote_created) { # create by schools_manager + $sortprefix = 'a' ; + } elsif ($quote_pending) { + $sortprefix = 'b' ; + } + + if ($usertype eq 'support') { + next unless $quote_accepted && !$quote_completed ; + } + + # if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all') { next ; } + + my $quote_date = $db{$tables}{$id}{event_date} ; $quote_date =~ s/\-//iog ; + + $yr = substr($quote_date,0,4) ; + $mm = substr($quote_date,4,2) ; + $dd = substr($quote_date,6,2) ; + + my ($yr2,$mm2,$dd2) = Add_Delta_Days($yr,$mm,$dd,60); # + + $mm2 = sprintf("%02s",$mm2) ; + $dd2 = sprintf("%02s",$dd2) ; + + $quote_date = "$yr2$mm2$dd2" ; + + if ($quote_date && $quote_date < "$now_year$now_mm$now_dd" && $quote_accepted!=1 && + $iaction ne 'report' && $iaction ne 'accepted' && $iaction ne 'closed' && $iaction ne 'all' && + $i{options} ne 'accepted' && $i{options} ne 'closed' && $i{options} ne 'all') { next ; } + + $print_tbody .= qq~~ ; + + $xlsxcol = 0 ; + + my $quote_nr = $db{$tables}{$id}{quote_nr} ; + + my @fixtures_saved_values = split(/\|/,$db{$tables}{$id}{fixtures_saved_values}) ; + my @analytics_saved_values = split(/\|/,$db{$tables}{$id}{analytics_saved_values}) ; + + my $row_cnt = 0 ; + foreach (@fixtures_saved_values) { + my $date = (substr($_,0,1) eq ';') ? substr($db{$tables}{$id}{start_date_time},0,10) : substr($_,0,10) ; + my $time = (substr($_,0,1) eq ';') ? substr($db{$tables}{$id}{start_date_time},11,5) : substr($_,11,5) ; + $individual_games{$date}{$time}{$id}{fixtures} .= qq~$_\|~ ; + $individual_games{$date}{$time}{$id}{analytics} .= qq~$analytics_saved_values[$row_cnt]\|~ ; + $row_cnt++ ; + } + + foreach (@sql_col_display) { + + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$tables}{$id}{$_} ; + my $align = qq~ class="dt-center"~ ; + my $nowrap = '' ; + my $val_xlsx = '' ; + + if ($_ eq 'nr') { + + $nowrap = 'nowrap' ; + $sort_val = sprintf("%06d",$id) ; + $sort_val = ($quote_accepted) ? qq~5~ . $sort_val : ($quote_completed) ? qq~4~ . $sort_val : ($quote_pending) ? qq~3~ . $sort_val : ($quote_rejected) ? qq~2~ . $sort_val : ($quote_cancelled) ? qq~1~ . $sort_val : qq~0~ . $sort_val ; + $val = qq~$sort_val~ . &common_min_get_event_quote_button($id,$tables,"analytics-event-bookings") ; + $val .= qq~~ if $db{$tables}{$id}{event_quote_id} ; + $val_xlsx = $id ; + # javascript:editMinItem('10922','event-quotes'); + if ($quote_completed) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format80) ; + } elsif ($quote_accepted) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format77) ; + } elsif ($quote_created) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format78) ; # yellow + } elsif ($quote_pending) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format79) ; # orange + } elsif ($quote_cancelled) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format81) ; # red + } + + } elsif ($_ eq 'event_start') { + my $sort_val = $db{$tables}{$id}{start_date_time} =~ s/[\-:\s]//gr; + $val_xlsx = &common_min_date_as_string(substr($db{$tables}{$id}{start_date_time},0,16)) ; + $val = qq~$sort_val~ . $val_xlsx ; + $nowrap = 'nowrap' ; + } elsif ($_ eq 'event_end') { + + if ($db{$tables}{$id}{end_date_time}) { + my $sort_val = $db{$tables}{$id}{end_date_time} =~ s/[- :]//g ; + $val_xlsx = &common_min_date_as_string(substr($db{$tables}{$id}{end_date_time},0,16)) ; + $val = qq~$sort_val~ . $val_xlsx ; + } elsif ($db{$tables}{$id}{fixtures_saved_values}) { + my $latest_date = "" ; my $latest_date_val = "" ; + foreach (split(/\|/,$db{$tables}{$id}{fixtures_saved_values})) { + next unless $_ ; + my @saved_vals = split(/\;/,$_) ; + next unless $saved_vals[0] ; + my $date_val = $saved_vals[0] ; + $date_val =~ s/[- :]//g ; + $latest_date = $saved_vals[0] if !$latest_date_val || ($latest_date_val && $latest_date_val < $date_val) ; + $latest_date_val = $latest_date ; + $latest_date_val =~ s/[- :]//g ; + } + $val = substr($latest_date,0,10) ; + if ($val) { + my $sort_val = $val ; + $sort_val =~ s/[- :]//g ; + $val_xlsx = &common_min_date_as_string($val) ; + $val = qq~$sort_val~ . &common_min_date_as_string($val) ; + } + } + + $nowrap = 'nowrap' ; + } elsif ($_ eq 'date_added') { + my $sort_val = $db{$tables}{$id}{date_created} =~ s/[\-:\s]//gr; + $val_xlsx = &common_min_date_as_string($db{$tables}{$id}{date_created}) ; + $val = qq~$sort_val~ . $val_xlsx ; + $val_xlsx .= qq~ [Added By: $username{$db{$tables}{$id}{created_by}}]~ ; + $val = qq~$val~ ; + $nowrap = 'nowrap' ; + } elsif ($_ eq 'event') { + $val = $db{$tables}{$id}{event_name} ; + $nowrap = '' ; + } elsif ($_ eq 'customer') { + $nowrap = 'nowrap' ; + } elsif ($_ eq 'country_id') { + $val = $db{$tables}{$id}{country} ; + } elsif ($_ eq 'sport') { + $val = join("
    ", map { $sport_type{$_} } split(/\;/,$db{$tables}{$id}{sport_type_ids})) ; + $val_xlsx = $val ; + $val_xlsx =~ s/\
    /\;/g ; + } elsif ($_ eq 'total_fixtures') { + $val = ($db{$tables}{$id}{total_fixtures}) ? $db{$tables}{$id}{total_fixtures} : 1 ; + } elsif ($_ eq 'service_type') { + $db{$tables}{$id}{service_type_id} = ($db{$tables}{$id}{service_type_id}) ? $db{$tables}{$id}{service_type_id} : 2 ; + $val = $service_types{$db{$tables}{$id}{service_type_id}} ; + } + $print_tbody .= qq~$val~ ; + + if ($_ ne 'nr') { + $val_xlsx = $val unless $val_xlsx ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format82) ; + } + $xlsxcol++ ; + + } + + $xlsxrow++ ; + + my $quote_nr = $quote_nr ; $quote_nr =~ s/'//iog; unless ($quote_nr) { $quote_nr = $id ; } + + my $edit_butt = qq~~ ; + my $delete_butt = qq~~ ; + # ($glod_user_level < 3 || $quote_accepted || $quote_completed || $quote_rejected || $quote_pending) ? '' : + my $copy_butt = qq~~ ; + + $edit_butt = qq~$edit_butt ~ if $edit_butt ; + $copy_butt = qq~$copy_butt ~ if $copy_butt ; + $delete_butt = qq~$delete_butt ~ if $delete_butt ; + + $print_tbody .= qq~ $edit_butt$copy_butt$delete_butt~ ; + } + + my @day_name = ("","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday") ; + my @month_name = ("","January","February","March","April","May","June","July","August","September","October","November","December") ; + + my $xlsxrow2 = 0 ; my $xlsxcol2 = 0 ; + + my %team_ids = () ; + + foreach my $a (keys %individual_games) { + foreach my $b (keys %{$individual_games{$a}}) { + foreach my $c (keys %{$individual_games{$a}{$b}}) { + my @abc = split(/\|/,$individual_games{$a}{$b}{$c}{fixtures}) ; + foreach (@abc) { + my @abcd = split(/\;/,$_) ; + $team_ids{$abcd[4]} = 1 ; + $team_ids{$abcd[6]} = 1 ; + } + } + } + } + + my $team_sql = join(" OR ", map{ "id='$_'" } keys %team_ids) ; + + &db_switch_conn('sss') ; + + &db_min_ro('teams','id,name',$team_sql,'','') ; + + &db_switch_conn('aisa') ; + + my $heading_count = 0 ; my %seen_event_sport = () ; + + foreach my $date (sort {$a cmp $b} keys %individual_games) { + + my ($year,$month,$day) = split(/\-/,$date) ; + my $day_of_week = Day_of_Week($year,$month,$day) ; + my $day_add = ($day eq '1') ? "st" : ($day eq '2') ? "nd" : ($day eq '3') ? "rd" : "th" ; + my $date_name = "$day_name[$day_of_week] $day$day_add $month_name[$month]" ; + + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"$date_name",$format109) ; + + my $first_game = 1 ; + + my $contain_tbc_events = 0 ; + my $contain_confired_events = 0 ; + + foreach my $time (sort {$a cmp $b} keys %{$individual_games{$date}}) { + + foreach my $a_id (sort { $a <=> $b } keys %{$individual_games{$date}{$time}}) { + + $individual_games{$date}{$time}{$a_id}{fixtures} =~ s/\|+$// ; + $individual_games{$date}{$time}{$a_id}{analytics} =~ s/\|+$// ; + my @individual_games_fixtures = split(/\|/,$individual_games{$date}{$time}{$a_id}{fixtures}) ; + my @individual_games_analytics= split(/\|/,$individual_games{$date}{$time}{$a_id}{analytics}) ; + + my $row_cnt = scalar @individual_games_fixtures ; + $row_cnt = scalar @individual_games_analytics if scalar @individual_games_analytics > scalar @individual_games_fixtures ; + $row_cnt = 0 unless $row_cnt ; + + next unless $row_cnt ; + + my $tbc_game = 1 ; + + foreach my $row_nr (0 .. $row_cnt - 1) { + + my @data_split = split(/\;/,$individual_games_fixtures[$row_nr]) ; + + my $customer_name = uc $db{customers}{$db{$tables}{$a_id}{client_id}}{name} ; + my $sport_name = ($db{$tables}{$a_id}{sport_type_ids} && $db{$tables}{$a_id}{sport_type_ids} !~ /;/) ? $db{sport_types}{$db{$tables}{$a_id}{sport_type_ids}}{name} : $db{sport_types}{$data_split[1]}{name} ; + $sport_name = uc $sport_name ; + + $heading_count++ unless $seen_cleint_sport{$db{$tables}{$a_id}{client_id}}{$sport_name} ; + $heading_count = $heading_count%3 ; + $seen_cleint_sport{$db{$tables}{$a_id}{client_id}}{$sport_name} = 1 ; + + my $heading_format = ($heading_count == 1) ? $format110 : ($heading_count == 2) ? $format111 : ($heading_count == 0) ? $format112 : $format112 ; + + if (!$data_split[6]) { + $tbc_games{$date}{$db{$tables}{$a_id}{client_id}}{$sport_name}++ ; + $contain_tbc_events = 1 ; + next ; + } else { + $contain_confired_events = 1 ; + $tbc_game = 0 ; + } + + $xlsxrow2++ if $first_game ; + $first_game = 0 ; + $xlsxrow2++ ; + + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," $customer_name $sport_name ANALYTICS",$heading_format) ; + $xlsxrow2++ ; + + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," $db{teams}{$data_split[4]}{name} vs $db{teams}{$data_split[6]}{name}",$format1) ; + $xlsxrow2++ ; + + if ($data_split[0]) { + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," " . substr($data_split[0],11,5),$format1) ; + } else { + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," " . substr($db{$tables}{$a_id}{start_date_time},11,5),$format1) ; + } + + if ($db{$tables}{$a_id}{event_system_id_multiple}) { + $db{$tables}{$a_id}{event_system_id_multiple} =~ s/f-//g ; + my $systems = join(";", map { "$db{event_systems}{$_}{name} ($db{event_systems}{$_}{description})" } split(/\;/,$db{$tables}{$a_id}{event_system_id_multiple})) ; + $systems =~ s/ ()//g ; + + foreach (split(/\;/,$systems)) { + next unless $_ ; + $xlsxrow2++ ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," $_",$format115) ; + } + } + + if ($individual_games_analytics[$row_nr]) { + + my @data_split_2 = split(/\;/,$individual_games_analytics[$row_nr]) ; + + if ($data_split_2[0] eq '1' && $data_split_2[1]) { + $xlsxrow2++ ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," " . $data_split_2[1],$format1) ; + } + if ($data_split_2[0] eq '1' && $data_split_2[2]) { + $xlsxrow2++ ; + &xlsxcreator_write_url($ws2,$xlsxrow2,$xlsxcol2,$data_split_2[2],"$data_split_2[2]") ; + } + + } + + } + $xlsxrow2++ unless $tbc_game ; + } + } + + my $abcbc = 0 ; + + $xlsxrow2++ if $contain_tbc_events && !$contain_confired_events ; + + foreach my $client_id (sort { $a <=> $b } keys %{$tbc_games{$date}}) { + foreach my $sport_name (sort { $a <=> $b } keys %{$tbc_games{$date}{$client_id}}) { + $xlsxrow2++ ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"$db{customers}{$client_id}{name} $sport_name ANALYTICS",$format116) ; + $xlsxrow2++ ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"Other $tbc_games{$date}{$client_id}{$sport_name} games still to be confirmed",$format113) ; + $abcbc = 1 ; + } + } + + $xlsxrow2++ if $abcbc ; + $xlsxrow2++ ; + } + + $worksheet{$ws2}->set_column(0,0,75) ; + $worksheet{$ws}->set_column(0,0,10) ; + $worksheet{$ws}->set_column(1,5,30) ; + $worksheet{$ws}->set_column(6,8,20) ; + + &report_xlsx_export_footer('L',15,'analytics_events') ; + + if ($usertype eq 'support') { + $fnsortcol = 1 ; # start date + $fnsortorder = 'asc' ; + } + + # &common_min_extra_crumb("search-$lcpage\s","Search Screen") if $glod_user_level > 3 ; + &common_min_extra_crumb("filter-$lcpage\s","Search Screen") if $glod_user_level > 3 ; + + # 12~yBf-w0xwLJcY7rY49dFy6Fw0tohiEHDUOw.png:Screenshot_2025-10-24_082334.png:Screenshot_2025-10-24_082804.png:32482_F.jpg|134~File_-_2025-10-08T074305.322.jpg:File_-_2025-10-09T080750.400.jpg:File_-_2025-10-10T091621.052.jpg:30729_F.jpg|309~Screenshot_2025-10-24_083010.png::Screenshot_2025-10-24_083250.png:31023vF.jpg + # 11685 + # |309~;;;08:02:50 + + + + + # 12~2025-10-08 07:59:14;2025-10-09 08:22:14;2025-10-10 09:35:18;2025-10-11 08:49:36|309~2025-10-08 08:15:26;;2025-10-10 08:56:42;2025-10-11 08:41:10|134~2025-10-08 07:43:03;2025-10-09 08:07:59;2025-10-10 09:14:17;2025-10-11 08:33:47 + # 161 + # 2025-10-24 09:29:09 + + +} #------------------------------------------------------------------------------- + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub add_db_fields { + + &hidden_fields ; + $hidden{id} = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &hidden_fields ; + $hidden{id} = 1 ; + # $readonly{ref} = 'READONLY' ; + +} #------------------------------------------------------------------------------------------ + +sub view_db_fields { + + &hidden_fields ; + $hidden{id} = 1 ; + $label{event_name} = 1 ; + $label{qty} = 1 ; + $label{start_date_time} = 1 ; + $label{sport_type_ids} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub hidden_fields { + + # if ($glod_user_level < 4) { + if ($glod_user_level < 3) { + + $ignore{type_of_system} = 1 ; + $ignore{system_details} = 1 ; + $ignore{system_name} = 1 ; + $ignore{operators} = 1 ; + # $ignore{operator_ids} = 1 ; + } + + $ignore{quote_nr} = 1 ; + $ignore{iaction} = 1 ; + $ignore{sport_type_ids_readonly} = 1 ; + $ignore{datetime} = 1 ; + $ignore{custom_selected_region} = 1 ; + $ignore{custom_selected_country} = 1 ; + + # $ignore{home_teams_built_on_regions} = 1 ; + + for (1 .. 100) { + $ignore{"changed_fixtures_date_$_"} = 1 ; + $ignore{"changed_home_team_$_"} = 1 ; + } + + $hidden{event_date} = 2 ; + $hidden{last_updated} = 2 ; + $hidden{created_by} = 2 ; + + # $required{event_to} = 1 ; + # $required{country_id} = 1 ; + # $required{region_id} = 1 ; + $required{client_id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + + $selected{max_cams}{10} = 'SELECTED'; + &select_opts('') ; + %col_name = () ; + &db_min_ro($table,'*',"id > 1 AND id < 10",'','') ; + + $page_title = substr($page_title,0,-1) ; + $db{$table}{''}{quote_nr} = &db_min_get_max($table,'id') ; + $db{$table}{''}{quote_nr} = 1000 if $db{$table}{''}{quote_nr} < 1000 ; + + # if ($username eq 'rory') { $db{$table}{''}{quote_nr} = 1000 ; } + + &add_db_fields ; + + &build_boxes('','save') ; + + local $all_select_ids_string = join(",",@all_select_ids) ; + $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true });~ ; + +} #------------------------------------------------------------------------------------------ + +sub view_screen { + + &edit_screen ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + unless ($i{id}) { $warning = qq(NO ID) ; return ; } + + # my $users_cols = "id,name,user_type" ; $users_cols = "id,name,user_type,region_ids" if $glod_user_level < 4 ; + my $users_cols = "id,name,user_type" ; $users_cols = "id,name,user_type,region_ids" if $glod_user_level < 3 ; + + &db_min_ro('users',$users_cols,"`user_type` LIKE 'casual%' OR `user_type` = 'schools_manager'",'','') ; + foreach (keys %{$db{users}}) { + next if $db{users}{$_}{user_type} eq 'schools_manager' ; + $casual_name{$_} = $db{users}{$_}{name} ; + $casual_type{$_} = uc substr($db{users}{$_}{user_type},-1,1) ; + $casuals{$_} = 1 if substr($db{users}{$_}{user_type},0,6) eq 'casual' ; + } + + &db_min_ro($table,'*',"id='$i{id}'",'','') ; + + $db{$table}{$i{id}}{quote_nr} = $i{id} ; + + my $cnt_rows = 0 ; + for (1 .. $nr_of_system_names_and_clubs) { + $cnt_rows = $_ if $system_name_ids[$_ - 1] or $club_ids[$_ - 1] ; + } + + our @table_op_ids = () ; + our @multi_select_op_ids = () ; + + for (1 .. $cnt_rows) { + push @table_op_ids,$op_ids[$_ - 1] if $op_ids[$_ - 1] ; + push @table_op_ids,0 unless $op_ids[$_ - 1] ; + } + for ($cnt_rows+1 .. $nr_of_system_names_and_clubs) { + push @multi_select_op_ids,$op_ids[$_ - 1] if $op_ids[$_ - 1] ; + } + + our $quote_completed = $db{$table}{$i{id}}{event_completed} ; + our $quote_accepted = $db{$table}{$i{id}}{event_accepted} ; + our $quote_pending = $db{$table}{$i{id}}{event_pending} ; + our $quote_cancelled = $db{$table}{$i{id}}{event_cancelled} ; + our $quote_rejected = $db{$table}{$i{id}}{event_rejected} ; + + # our $cancel_butt = ($d_check[2] > $now_ccyymmddhrmnsc && $iaction eq 'edit' && ($quote_completed || $quote_accepted || $quote_pending) && ($glod_user_level > 2 || $is_schools_manager)) ? 1 : 0 ; + our $cancel_butt = ($iaction eq 'edit' && ($quote_completed || $quote_accepted || $quote_pending) && ($glod_user_level > 2 || $is_schools_manager)) ? 1 : 0 ; + + # if ($is_schools_manager) { + if ($is_schools_manager || $glod_user_level < 4) { + my @ed_from = &common_split_sql_time($db{$table}{$i{id}}{start_date_time}) ; + my @d_check = &common_add_delta_dhms($ed_from[0],$ed_from[1],$ed_from[2],$ed_from[3],$ed_from[4],$ed_from[5],0,-18,0,0) ; # go 18 hours back from event start + + if ($d_check[2] < $now_ccyymmddhrmnsc) { + $cancel_butt = 0 ; + } + } + + $page_title = substr($page_title,0,-1) ; + $page_title .= " : $i{id}" ; + + $custom_back_button = qq~ ~ ; + # $custom_back_button = qq~$val~ ; + + # our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + &common_min_footer('id',"$lcpage\s"); + + &edit_db_fields ; + + &select_opts($i{id}) ; + + our $saveandexit = 1 ; + + &build_boxes($i{id},'update') ; + + &common_min_extra_crumb("filter-$lcpage\s","Search $ucfirstpage\s") if $glod_user_level > 3 ; + + local $all_select_ids_string = join(",",@all_select_ids) ; + $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true });~ ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes { + + my ($id,$action) = @_ ; + + our @jquery_trigger_fields = () ; + our @jquery_custom_vat_ids = () ; + our @jquery_duty_ids = () ; + our @jquery_workings_trigger_fields = () ; + + push @jquery_trigger_fields, 'inputRoe' ; + push @jquery_workings_trigger_fields, 'inputRoe' ; + + for (1 .. 15) { + push @jquery_workings_trigger_fields, "checkboxVat_workings_event_$_" ; + push @jquery_workings_trigger_fields, "checkboxExcl_workings_event_$_" ; + # push @jquery_workings_trigger_fields, "checkboxVat_$_\_workings_casual_users" ; + # push @jquery_workings_trigger_fields, "checkboxExcl_$_\_workings_casual_users" ; + } + &analytics_event_bookings_tabs_curr_symbols; + + foreach $col(keys %required) { + &common_min_forms_required ; + } + + our $tab_cnt = 0 ; + + &analytics_event_bookings_tabs_load_vars; + + $print_box_content_rows .= &common_min_forms_start($table) ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq~ +
    +
    ~ ; + &build_boxes_top($id); + $print_box_content_rows .= qq~ +
    +
    + ~ ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq~
    ~ ; + + &analytics_event_bookings_tabs_cnt ; + + $print_box_content_rows .= qq(
    + +
    ); + + our %tab_sections = () ; + + foreach (sort {$a <=> $b} keys %cntxt) { + + my $tab_name = &analytics_event_bookings_tabs_names($_) ; my $active = '' ; + + $active = ($_==2) ? 'active' : '' ; + + my $colsleft = 12 ; my $showright = '' ; + + if ($cntxt{$_} eq 'one' or $cntxt{$_} eq 'seven') { + $colsleft = 12 ; + $showright = 1 ; + } + + $print_box_content_rows .= qq~
    ~; + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_left($id,$_); + $print_box_content_rows .= qq~
    ~ ; + + if ($showright) { + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_right($id,$_); + $print_box_content_rows .= qq~
    ~ ; + } + + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~
    ~ ; + } + + $print_box_content_rows .= qq~ +
    +
    + ~ ; + + $print_box_content_rows .= qq~
    ~ ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_bottom($id); + $print_box_content_rows .= qq~
    ~ ; + + #-------------------------------------------------------------------------- + + our $skip_save_btn = ($quote_completed && $glod_user_level <= 3) ? 1 : 0 ; + + $print_box_content_rows .= &common_min_forms_end($id,$table,$action,$skip) ; + + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_top { + + my ($id) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(3,6) ; + + $add_form_fields = '' ; + + $fcol=8 ; + + $add_form_fields .= qq~
    ~ ; + $preferred_title{quote_nr} = "Nr" ; + $readonly{quote_nr} = "READONLY" ; + $add_form_fields .= &common_min_form_input('quote_nr',$db{$table}{$id}{quote_nr},'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + if (($db{$table}{$id}{event_date} eq '') or ($db{$table}{$id}{event_date} eq '0000-00-00')) { + $db{$table}{$id}{event_date} = $now_ccyy_mm_dd ; + } + $preferred_title{event_date} = "Date" ; + $readonly{event_date} = "READONLY" ; + $add_form_fields .= &common_min_form_datepicker('event_date',$db{$table}{$id}{event_date}) ; + my $plus_n_days_ccyy_mm_dd = &common_add_delta_days(14) ; + + # $trigger_jquery_raw .= qq~\$('#datepickerEvent_date').datepicker({format:'yyyy-MM-dd'})~ ; + # $trigger_jquery_raw .= qq~\$('#datepickerEvent_date').datepicker({language: 'pt-BR'})~ ; + # $trigger_jquery_raw .= qq~\$('#datepickerEvent_date_fixtures_'+i).datepicker({language: 'pt-BR'})~ ; + + # $required{event_to} = 1 ; + # $required{region_id} = 1 ; + + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $preferred_title{event_to} = "Client" ; + # $add_form_fields .= &common_min_form_select('event_to',$db{$table}{$id}{event_to},'') ; + # $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + # $dlg{event_to} = qq~ + # ~ ; + $fcol = 7; + # &common_min_select_opts('sport_type_ids','sport_types','name','','','','') ; + + $sql_limit_user_regions = ($is_schools_manager || $is_operator) ? join(' OR ', map { "id = '$_'" } keys %{$glob_regids{$userid}}) : '' ; + + # our $debug = 1 ; + + $allow_deselect{region_id} = 1 ; + + &common_min_select_opts('region_id','regions','name','','','code',$sql_limit_user_regions) ; + + $add_form_fields .= qq~~ ; + + $db{$table}{$id}{country_id} = $db{regions}{$db{$table}{$id}{region_id}}{country_id} ; + + $add_form_fields .= qq~~ ; + + # $db{$table}{$id}{country_id} = "242" unless $db{$table}{$id}{country_id} ; + + &common_min_select_opts('country_id','countries','name','','','','') ; + + my %home_teams = () ; + + foreach my $data (split(/\|/,$db{$table}{$id}{fixtures_saved_values})) { + my @abc = split(/\;/,$data) ; + $home_teams{$abc[4]} = 1 ; + } + + my $home_teams_str = join(" OR ", map{ "id='$_'" } keys %home_teams) ; + + if ($db{$table}{$id}{client_id} || $home_teams_str) { + + &db_switch_conn('sss') ; + + # my $region_filter = $db{$table}{$id}{region_id} ; + my $region_filter = '' ; + my $client_filter = $db{$table}{$id}{client_id} ; + + $db{$table}{$id}{home_teams_built_on_regions} = ($iaction eq 'add' || (!$region_filter && !$client_filter)) ? 1 : $db{$table}{$id}{home_teams_built_on_regions} ; + + my $home_teams_built_on_regions = $db{$table}{$id}{home_teams_built_on_regions} ; + + my $teams_sql = ($region_filter) ? qq~(`region_id`='$region_filter' OR (`region_id`='0' AND `matched_region_id`='$region_filter'))~ : qq~(`region_id`='0' AND `matched_region_id`='0')~ ; #(`region_id`='0' AND `matched_region_id`='0') + + if ($client_filter && !$home_teams_built_on_regions) { + $teams_sql .= qq~ OR ~ if $teams_sql ; + $teams_sql .= qq~(`aisa_client_id`='$client_filter')~ ; + } + + if ($home_teams_str) { + $teams_sql .= qq~ OR ~ if $teams_sql ; + $teams_sql .= qq~($home_teams_str)~ ; + } + + $opts{teams_id} = qq~~ ; + $opts{client_teams_id} = qq~~ ; + + if ($teams_sql) { + &db_min_ro('teams','*',"$teams_sql",'','') ; + foreach (sort { $db{teams}{$a}{name} cmp $db{teams}{$b}{name} } keys %{$db{teams}}) { + my $region_id = $db{teams}{$_}{region_id} ; + my $matched_region_id = $db{teams}{$_}{matched_region_id} ; + my $client_id = $db{teams}{$_}{aisa_client_id} ; + $opts{teams_id} .= qq~~ if ($region_filter && (($region_id eq $region_filter) || (!$region_id && $matched_region_id eq $region_filter))) || (!$region_filter && !$client_filter && !$region_id && !$matched_region_id) ; + next if $home_teams_built_on_regions || !$client_filter ; + $opts{client_teams_id} .= qq~~ if $client_filter eq $client_id || $home_teams{$_} ; + } + } + + # # # &db_min_ro('teams','*',"",'','') ; + # # # foreach (sort { $db{teams}{$a}{name} cmp $db{teams}{$b}{name} } keys %{$db{teams}}) { + # # # $opts{away_team} .= qq~~ ; + # # # } + + # &common_min_select_opts('teams_id','teams','name','','','',"`region_id`='$db{$table}{$id}{region_id}' OR (`region_id`='0' AND `matched_region_id`='$db{$table}{$id}{region_id}')") if $db{$table}{$id}{region_id} ; + # &common_min_select_opts('client_teams_id','teams','name','','','',"`aisa_client_id`='$db{$table}{$id}{client_id}'") if $db{$table}{$id}{client_id} && !$db{$table}{$id}{home_teams_built_on_regions} ; + + &db_switch_conn('aisa') ; + + } + + my %away_teams = () ; my %home_teams = () ; my %home_and_away_teams = () ; + + foreach (split(/\|/,$db{$table}{$id}{fixtures_saved_values})) { + my @abc = split(/\;/,$_) ; + $home_teams{$abc[4]} = 1 if $abc[4] ; + $away_teams{$abc[6]} = 1 if $abc[6] ; + $home_and_away_teams{$abc[4]} = 1 if $abc[4] ; + $home_and_away_teams{$abc[6]} = 1 if $abc[6] ; + } + + my $away_teams_sql = qq~~ ; + $away_teams_sql = join (" OR ",map{"id='$_'"} keys %home_and_away_teams) ; + if ($away_teams_sql) { + &db_switch_conn('sss') ; + &db_min_ro('teams','id,name',"$away_teams_sql",'','') ; + foreach (sort { $db{teams}{$a}{name} cmp $db{teams}{$b}{name} } keys %{$db{teams}}) { + next if $home_teams{$_} && !$away_teams{$_} ; + $opts{away_team} .= qq~~ ; + } + &db_switch_conn('aisa') ; + } + + # $db{$table}{$id}{country_id} = 242 unless $db{$table}{$id}{country_id} ; + $opts{region_id} =~ s/value="$db{$table}{$id}{region_id}"/value="$db{$table}{$id}{region_id}" SELECTED/g if $db{$table}{$id}{region_id} ; + $opts{country_id} =~ s/value="$db{$table}{$id}{country_id}"/value="$db{$table}{$id}{country_id}" SELECTED/g if $db{$table}{$id}{country_id} ; + + # $required{country_id} = qq~data-validation="required"~ ; + # $required{region_id} = qq~data-validation="required"~ ; + + $allow_deselect{country_id} = 1 ; + + $add_form_fields .= &common_min_form_select('country_id',$db{$table}{$id}{country_id},'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= &common_min_form_select('region_id',$db{$table}{$id}{region_id},'') ; + $add_form_fields .= qq~
    ~ ; + + $fcol = 8; + + $print_box_content_rows .= &common_min_box_top('qrcode',"Quote",'BABEC2'); + + $print_box_content_rows .= qq~ +
    +
    + $add_form_fields +
    +
    + ~; + + $print_box_content_rows .= qq~ +
    +
    +   +
    +
    + ~ ; + + $print_box_content_rows .= &common_min_box_foot; + + $print_box_content_rows .= qq~~ ; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_left { + + my ($id,$tab) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(3,6) ; + + &analytics_event_bookings_tabs_build_qt_left($id,$tab); + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_right { + + my ($id,$tab) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(3,6) ; + + &analytics_event_bookings_tabs_build_qt_right($id,$tab); + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_bottom { + + my ($id) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(2,2) ; + + $add_form_fields = '' ; + + # --------------- START GRAND TOTAL ---------------------------------------------------------------------------------------------------------------------- + + # $print_box_content_rows .= &common_min_form_input('activetab',$db{$table}{$id}{activetab},'hidden') ; + + # --------------- END RAND TOTAL ------------------------------------------------------------------------------------------------------------------------ + +} #---------------------------------------------------------------------------------------- + +sub fix_options_for_javascript { + + my ($options) = @_ ; + $options =~ s/\SELECTED//g ; + $options =~ s/\"/\'/g ; + return $options ; + +} #---------------------------------------------------------------------------------------- + +sub q_get_val { + + my ($val) = @_ ; + + my $disp_val = $val ; + + if ($val eq '0.00') { + $disp_val = '' ; + } + + return ($disp_val); + +} #------------------------------------------------------------------------------------------ + +sub set_check_boxes_checked { + + my ($id,$rcnt,$prefix,$suffix) = @_ ; + + for (1 .. $rcnt) { + + my $ifield = $prefix . '_' . "$_$suffix" ; + my $val = $db{$table}{$id}{$ifield} ; + # &common_debug("set_check_boxes_checked: [prefix=$prefix] [suffix=$suffix] ifield=$ifield, val=$val") ; + + $checkit{$ifield} = $val ; + } + +} #---------------------------------------------------------------------------------------- + +sub select_opts { + + my ($id) = @_ ; + + our $savjqy = 1 ; + + %filter_val = () ; %filter_select_opts = () ; + # if ($is_schools_manager) { + # if ($glod_user_level < 4) { + if ($glod_user_level < 3) { + $filter_select_opts{'regions'} = 1 ; + foreach $_reg_id (keys %{$glob_regids{$userid}}) { + $filter_val{'regions'}{$_reg_id} = 1 ; + } + } + # &common_debug("[$usertype] filter_select_opts = $filter_select_opts{'regions'}") ; + + local $region_id_where = qq~~ ; local @abcd = () ; + + # if ($is_schools_manager) { + # if ($glod_user_level < 4) { + if ($glod_user_level < 3) { + foreach (split(",",$db{users}{$userid}{region_ids})) { + push @abcd , "`id` = '$_'" ; + } + } + + $preferred_title{sport_type_ids} = "Sport Types" ; + %selected_multi = () ; + $multiple{sport_type_ids} = 1; + my @sport_type_ids = split(/\;/,$db{$table}{$id}{sport_type_ids}); + foreach (@sport_type_ids) { + $selected_multi{$_} = 'SELECTED' ; + } + + &common_min_select_opts('sport_type_ids','sport_types','name',$db{$table}{$id}{sport_type_ids},'','','','','name') ; + + $extra_form_fields .= qq~~; + + foreach (@multi_select_op_ids) { + $selected_multi{$_} = 'SELECTED' ; # &common_debug("SELECTED operator_ids [$_] : [selected=$selected_multi{$_}]") ; + } + + &db_min_ro('users',"id,name,region_ids","user_type LIKE 'casual%' AND block <> 1 AND inactive <> 1",'','') ; + + foreach my $op_id (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + my $regions = "" ; + foreach (split(",",$db{users}{$op_id}{region_ids})) { + $regions .= "$db{regions}{$_}{code}," ; + } + chop $regions if $regions ; + my $user_names = $db{users}{$op_id}{name} ; + $user_names = "$db{users}{$op_id}{name} [$regions]" if $regions ; + $opts{operator_ids} .= qq~~ ; + # for (1 .. $nr_of_system_names_and_clubs) { + # $opts{"operator_ids_$_"} .= qq~~ ; + } + + # &common_min_select_opts('operator_ids','users','name',$db{$table}{$i{id}}{operator_ids},'','',"user_type LIKE 'casual%'") ; + + $trigger_jquery .= qq~\$("#selectType\_chosen").css("width","80%");~ ; + + %selected_multi = () ; + + # $db{event_quotes}{''}{event_to} = 5 if $iaction eq 'add' ; # SuperSport Schools (Pty) Ltd + + $extra_css .= qq() ; + + $trigger_jquery .= qq~\$("#selectSport_type_ids_chosen").css("width","100%");~ ; + + $trigger_jquery_raw .= qq~ + + \$("#savebutt").click( async function() { + + let buttonClass = \$(this).attr("class") ; + if (buttonClass == "btn btn-custom") { + return ; + } + + var we_can_save_form = check_before_saving() ; + + let end_date = new Date(\$("input[name='end_date_time']").val()) ; + let start_date = new Date(\$("input[name='start_date_time']").val()) ; + + start_date = new Date(start_date.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours + end_date = new Date(end_date.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours + + let earliest_latest = find_latest_and_earliest_date_in_fixtures() ; + + if (start_date > earliest_latest.earliest_date) { + noty({text:'Please Select an Event Start Date that is before the earliest date on the Fixtures tab!',layout:"center",type:"error",timeout:3000}) ; + we_can_save_form = 0 ; + } + + if (end_date < earliest_latest.latest_date) { + noty({text:'Please Select an Event Start Date that is before the earliest date on the Fixtures tab!',layout:"center",type:"error",timeout:3000}) ; + we_can_save_form = 0 ; + } + + for (let i=1;i<=100;i++) { + + if (!\$("#fixtures_"+i).html() || \$("#fixtures_"+i).css("display") === 'none') { + break ; + } + if (\$("#selectHome_team_fixtures_"+i).val() && !\$("#selectAway_team_fixtures_"+i).val()) { + we_can_save_form = 0 ; + noty({text:'Please Select an Away team when selecting a Home Team on the Fixtures tab!',layout:"center",type:"error",timeout:3000}) ; + break ; + } else if (!\$("#selectHome_team_fixtures_"+i).val() && \$("#selectAway_team_fixtures_"+i).val()) { + we_can_save_form = 0 ; + noty({text:'Please Select an Home team when selecting a Away Team on the Fixtures tab!',layout:"center",type:"error",timeout:3000}) ; + break ; + } + } + + if (\$("#selectEvent_quote_id").val() && we_can_save_form) { + + let date_url = "$useropts{scripts}/get/get_dates_from_event_quote.pl?event_quote_id="+\$("#selectEvent_quote_id").val()+"&start_date_time="+\$("input[name='start_date_time']").val()+"&end_date_time="+\$("input[name='end_date_time']").val() ; + + let dates_json = await fetchJSON(date_url); + + for (const key in dates_json) { + const data = dates_json[key]; + noty({text:'The Start and End date of this Event is from '+data.start_date_time+' to '+data.end_date_time+' Compared to '+data.date_from+' to '+data.date_to+' for the Event Quote.
    Please Ensure the Dates Correspond!',layout:"center",type:"warning",timeout:7500}) ; + await sleep(7500); + } + + // await \$.get(date_url, function(json) { + // \$.each(json, function(key, data) { + // noty({text:'The Start and End date of this Event is from '+data.start_date_time+' to '+data.end_date_time+' Compared to '+data.date_from+' to '+data.date_to+' for the Event Quote',layout:"center",type:"error",timeout:7500}) ; + // // await sleep(10000); + // }); + // } + // ,'json') ; + + } + + if (we_can_save_form) { + \$('#analytics_event_bookings-form').submit() ; + } else { + return ; + } + }) ; + + function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); + } + + \$("#cancelbutt").click( function() { + + let buttonClass = \$(this).attr("class") ; + if (buttonClass == "btn btn-custom") { + return ; + } + + var we_can_save_form = check_before_saving() ; + + if (we_can_save_form) { + cancel_quote() ; + } else { + return ; + } + + }) ; + + function cancel_quote () { + + BootstrapDialog.confirm({ + title: 'Confirm Cancellation', + message: 'Are you sure you want to cancel this event?', + type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + callback: function(result) { + if (result) { + \$("#checkboxQuote_completed").prop("checked", false) ; + \$("#checkboxQuote_accepted").prop("checked", false) ; + \$("#checkboxQuote_pending").prop("checked", false) ; + \$("#checkboxQuote_rejected").prop("checked", false) ; + \$("#checkboxQuote_cancelled").prop("checked", true) ; + \$('#event_quotes-form').submit() ; + } + } + }); + } + + function check_before_saving () { + + $jquery_chosen_sel + + let st_val = \$("#selectSport_type_ids").chosen().val() ; + \$('#sport-type-ids').val(st_val) ; + + return 1 ; + } + + ~ ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'global' ; + our $lcpage = 'analytics-event-booking' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'analytics_event_bookings' ; + + our $cust_cols = 1 ; # display _blank_3.pm + our $savjqy = 1 ; + our $max_cams = 10 ; + + &common_min_add_box_icon ; + + our %casuals = (); + +} #------------------------------------------------------------------------------- + +sub report_ifields { + + if ($i{start_date_from} && $i{start_date_to}) { + push @report_sql, " (('$i{start_date_from}' <= start_date_time AND start_date_time <= '$i{start_date_to}') OR ('$i{start_date_from}' <= end_date_time AND end_date_time <= '$i{start_date_to}' AND end_date_time IS NOT NULL)) " ; + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + my $start_date_from = &common_min_date_as_string($i{start_date_from}) ; + my $start_date_to = &common_min_date_as_string($i{start_date_to}) ; + push @report_results, " (START DATE BETWEEN '$start_date_from' AND '$start_date_to') OR (END DATE BETWEEN '$start_date_from' AND '$start_date_to')" ; + } + + if ($i{country}) { + push @report_sql, "(q.country_id = '$i{country}')" ; + push @report_results, "country_id = `$i{country}`" ; + } + + if ($i{customer_name} && $i{customer_name} ne 'all') { + push @report_sql, "(q.client_id = '$i{customer_name}')" ; + &db_min_ro('customers','id,name',"`id`='$i{customer_name}'",'','') ; + push @report_results, "customer = `$db{customers}{$i{customer_name}}{name}`" ; + } + + if ($i{accepted} || $i{options} eq 'accepted') { + push @report_sql, "(q.event_accepted='1' AND q.event_completed<>'1')" ; + push @report_results, "event_accepted = `Yes`" ; + } + + if ($i{options} eq 'accepted') { + push @report_sql, "(q.event_accepted='1')" ; + push @report_results, "Event is Accepted" ; + } elsif ($i{options} eq 'completed') { + push @report_sql, "(q.event_completed='1')" ; + push @report_results, "Event is Completing" ; + } elsif ($i{options} eq 'pending') { + push @report_sql, "(q.event_pending='1')" ; + push @report_results, "Event is Pending" ; + } elsif ($i{options} eq 'cancelled') { + push @report_sql, "(q.event_cancelled='1' OR (q.event_expiry IS NOT NULL AND q.event_expiry<'$now_year-$now_mm-$now_dd' AND q.event_accepted<>'1'))" ; + push @report_results, "Event is Cancelled" ; + } elsif ($i{options} eq 'rejected') { + push @report_sql, "(q.event_rejected='1')" ; + push @report_results, "Event is Rejecting" ; + } + + $preferred_title{region_id} = "Region" ; + $preferred_title{city_id} = "City" ; + $preferred_title{organisation_ids} = "Venue" ; + $preferred_title{sport_type_ids} = "Sport Type" ; + + if ($i{sport_type_ids} && $i{sport_type_ids} ne 'all') { + &db_min_ro('sport_types',"id,name","id='$i{sport_type_ids}'",'','') ; + push @report_sql, "FIND_IN_SET($i{sport_type_ids},REPLACE(q.sport_type_ids,';',','))" ; + push @report_results, "sport_types INCLUDE `$db{sport_types}{$i{sport_type_ids}}{name}`" ; + } + + if ($usertype eq 'analytics_client') { + push @report_sql, "(q.client_id='$userid')" ; + } + + $report_results_msg = uc join(', ', @report_results) ; + + unless ($report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER) ; + &report_screen ; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + +} #------------------------------------------------------------------------------------------ + +sub report_screen { + + &filter_screen ; + +} #------------------------------------------------------------------------------- + +sub filter_screen { + + our $lcol = 2 ; + our $fcol = 5 ; + + my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-42) ; # 6 weeks back + + $set_month = sprintf("%02s", $set_month) ; + $set_day = sprintf("%02s", $set_day) ; + + my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + # $allow_deselect{customer_name} = 1 ; + $allow_deselect{options} = 1 ; + $allow_deselect{sport_type_ids} = 1 ; + + my $defualt_customer = 0 ; $defualt_customer = 5 if $usertype ne 'school_manager' ; + # &common_min_select_opts('customer_name','customers','name',$defualt_customer,'','',"events='1'") ; + &common_min_select_opts('customer_name','customers','name','','','',"analytics='1'") ; + $opts{customer_name} .= qq~~ ; + my $def_val = ($i{customer_name}) ? $i{customer_name} : "all" ; + $opts{customer_name} =~ s/value='$def_val'/value='$def_val' SELECTED/g ; + $print_box_content_rows .= &common_min_form_select('customer_name','') ; + + $preferred_title{event_from} = 'Event Date From' ; + + my $day_of_week = Day_of_Week($now_year,$now_mm,$now_dd) ; + + my ($def_s_year,$def_s_mm,$def_s_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,1-$day_of_week) ; + my ($def_e_year,$def_e_mm,$def_e_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,7-$day_of_week) ; + + $def_s_mm = sprintf("%02d",$def_s_mm) ; + $def_s_day = sprintf("%02d",$def_s_day) ; + $def_e_mm = sprintf("%02d",$def_e_mm) ; + $def_e_day = sprintf("%02d",$def_e_day) ; + + $i{start_date_from} = qq~$def_s_year-$def_s_mm-$def_s_day 00:00:00~ unless $i{start_date_from} ; + $i{start_date_to} = qq~$def_e_year-$def_e_mm-$def_e_day 23:59:59~ unless $i{start_date_to} ; + + $preferred_title{start_date_from} = "Event Date/Time From" ; + $preferred_title{start_date_to} = "Event Date/Time To" ; + + $print_box_content_rows .= &common_min_form_datetimepicker('start_date_from',$i{start_date_from},720) ; + $print_box_content_rows .= &common_min_form_datetimepicker('start_date_to',$i{start_date_to},720) ; + + $opts{options} = qq~ + + + + + + + ~ ; + + $allow_deselect{options} = 0 ; + + $print_box_content_rows .= &common_min_form_select('options','') ; + + &common_min_select_opts('sport_type_ids','sport_types','name','','','','') ; + + $preferred_title{sport_type_ids} = "Sport Type" ; + + $allow_deselect{sport_type_ids} = 0 ; + + $opts{sport_type_ids} .= qq~~ ; + + $print_box_content_rows .= &common_min_form_select('sport_type_ids','') ; + + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + local $all_select_ids_string = join(",",@all_select_ids) ; + $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true });~ ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +use event_email ; +use analytics_event_booking_tabs ; +use common ; +use common_min ; +use common_shared ; +use today ; +use report ; +use xlsxcreator ; +use csv ; + +1 ; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/analytics_event_credits.pl b/scripts/_FromProd/v1.0/analytics_event_credits.pl new file mode 100644 index 0000000..6ce90ab --- /dev/null +++ b/scripts/_FromProd/v1.0/analytics_event_credits.pl @@ -0,0 +1,1845 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); + +require cfg ; + +print header; # CGI.pm method + +# unless ($username eq 'handre'or $username eq 'rory') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#---------------- ----------------------------------------------------------------------------------------------------------------------------------------------------- + +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX ; +use LWP::Simple qw($ua get); +use JSON ; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +# our $redirtype = 'search' ; + +# our $testing = 1 ; +# our $debug = 1 ; +# &common_debug("glod_user_level = $glod_user_level [$usertype]") ; + +# unless ($username eq 'rory') { print ">>>> DEVELOPMENT IN PROGRESS <<<<" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +# my $string = '3;;1;u16;a;;1;;s;s;;|5;;1;u17;a;;1;;s;s;;|5;;1;open;a;;1;;p;s;;'; + +# print "\n MAINTENANCE IN PROGRESS !" ; +# exit if $username ne 'handre'; + +if ($is_operator && $glod_user_level == 2) { $glod_user_level = 3 ; } # upgrade operators level 2&3 to 3&4 + +our $nr_of_system_names_and_clubs = 15 ; our @all_select_ids = () ; our $minify_jquery = 1 ; + +if ($username ne 'handre') { + print "Development in Progress!!!" ; + exit ; +} + +&db_open_ro ; + $db_ignore_open_close = 1 ; + + &page_opts ; + + if ($iaction eq 'filter' || $iaction eq 'search' || $iaction eq 'report') { + our $srchscr = 1 ; + our $savjqy = 0 ; + } + + #------------------------------------------------------------------------------------------------------------------------------------------------------------------ + + our @fixture_headers = ("Fixture Date/Time From","Sport","Age Group","Team","Home Team","HT Colour","Away Team","Coding Type","Footage Type"); + our @analytics_headers = ("Fixture Date/Time From","Sport","Age Group","Team","Home Team","HT Colour","Away Team","Coding Type","Footage Type","Service Type"); + our %service_types = (1 => "Live Coding",2 => "Post Coding 12 hrs",3 => "Post Coding 24 hrs") ; + our %coding_type = ("s" => "Standard","p" => "Premium") ; + our %footage_type = ("s" => "SSS","r" => "Raw") ; + + if ($iaction eq 'add') { + &add_screen ; + &common_min_screen1 ; + } elsif ($iaction eq 'edit') { + &common_min_load_params ; + &edit_screen ; + &common_min_screen1 ; + } elsif ($iaction eq 'save') { + &common_min_load_params ; + &insert ; + # &log_changes ; + &edit_or_list ; + } elsif ($iaction eq 'update') { + &common_min_load_params ; + &update ; + # &log_changes ; + &edit_or_list ; + } elsif ($iaction eq 'copy') { + &common_min_load_params ; + &duplicate ; + &edit_screen ; + &common_min_screen1 ; + } elsif ($iaction eq 'delete') { + &common_min_load_params ; + &report_ifields ; + &delete ; + &common_min_screen2 ; + } + + &common_min_action ; + + $db_ignore_open_close = 0 ; +&db_close_conn ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub edit_or_list { + + exit if $testing && substr($username,0,4) eq 'rory' ; + + &edit_screen ; + &common_min_screen1; + +} #------------------------------------------------------------------------------------------ + +sub process_fixtures_tab { + + my ($id) = @_ ; + + &db_min_ro($table,"id,fixtures_saved_values,analytics_saved_values","id='$id'",'','') if $id ; + + $i{fixtures_saved_values} = qq~~ ; + + my $suffix = "fixtures" ; + + my @changed_field_keys = ("age_group","team","home_team","ht_colour","away_team","coding_type","footage_type") ; + + my @fixtures_saved_values_split = ($id) ? split(/\|/,$db{$table}{$id}{fixtures_saved_values}) : () ; + + for my $row_nr (1 .. 100) { + + # last if $row_nr > $i{total_fixtures} ; + + my $input_vals = qq~~ ; + + my @fixtures_saved_values_split_2 = ($id) ? split(/\;/,$fixtures_saved_values_split[$row_nr - 1]) : () ; + + foreach (@changed_field_keys) { + $input_vals .= qq~;$i{"$_\_$suffix\_$row_nr"}~ ; + $ignore{"$_\_$suffix\_$row_nr"} = 1 ; + } + $input_vals .= qq~;$fixtures_saved_values_split_2[9];$fixtures_saved_values_split_2[10]~ ; + + my $changed_fixtures_date_field = "changed_fixtures_date_$row_nr" ; + + my $date_field = "start_date_time_$suffix\_$row_nr" ; + + my $changed_sport_field = "sport_fixtures_$row_nr" ; + + if ($input_vals =~ /[a-zA-Z]/ || $input_vals =~ /(\d+)/g || $i{$changed_sport_field} || $i{$changed_fixtures_date_field}) { + $i{fixtures_saved_values} .= ($i{$changed_fixtures_date_field}) ? qq~$i{$date_field};$i{$changed_sport_field}~ : qq~;$i{$changed_sport_field}~ ; + $i{fixtures_saved_values} .= qq~$input_vals~ ; + } + + $i{fixtures_saved_values} .= qq~|~ ; + + $ignore{"start_date_time_$suffix\_$row_nr"} = 1 ; + $ignore{"readonly_sport_$suffix\_$row_nr"} = 1 ; + $ignore{"sport_$suffix\_$row_nr"} = 1 ; + + } + # 1;;;u14;a;;1;;s;s|2;;;u14;a;;1;;s;s|3;;2;u15;a;;1;;s;s|4;;1;u15;a;;1;;s;s|5;;2;u16;a;;1;;s;s|6;;1;u16;a;;1;;s;s|7;;2;open;b;;1;;s;s|8;;1;open;b;;1;;s;s|9;;2;open;a;;1;;p;s|10;;1;open;a;;1;;p;s + # 1;;;u14;a;;1;;s;s;;|2;;;u14;a;;1;;s;s;;|3;;2;u15;a;;1;;s;s;;|4;;1;u15;a;;1;;s;s;;|5;;2;u16;a;;1;;s;s;;|6;;1;u16;a;;1;;s;s;;|7;;2;open;b;;1;;s;s;;|8;;1;open;b;;1;;s;s;;|9;;2;open;a;;1;;p;s;;|10;;1;open;a;;1;;p;s;; 1005 + + + # 1;;;open;a;7495;1;6684;s;s;;|2;;;u19;b;845;1;778;p;r;;|3;2025-06-18 06:00:00;8;u17;c;54;1;3975;s;s;; 1000 + + # 1;;;u14;a;;1;;s;s;;|2;;1;u15;a;;1;;s;s;;|3;;1;u16;a;;1;;s;s;;|4;;1;u17;a;;1;;s;s;;|5;;1;open;a;;1;;p;s;; + # 1;;;u14;a;;1;;s;s|2;;1;u15;a;;1;;s;s|3;;1;u16;a;;1;;s;s|4;;1;u17;a;;1;;s;s|5;;1;open;a;;1;;p;s + + chop $i{fixtures_saved_values} if $i{fixtures_saved_values} ; + + $i{fixtures_saved_values} =~ s/([a-zA-Z0-9]);+(\|)/$1$2/g; + $i{fixtures_saved_values} =~ s/([a-zA-Z0-9])\|+$/$1/; + + $ignore{fixtures_saved_values} = (($id && $i{fixtures_saved_values} eq $db{$table}{$id}{fixtures_saved_values}) || (!$i{fixtures_saved_values} && !$db{$table}{$id}{fixtures_saved_values})) ? 1 : 0 ; + +} #------------------------------------------------------------------------------------------ + +sub process_analytics_tab { + + $i{analytics_saved_values} = qq~~ ; + + my $suffix = "analytics" ; + + my @changed_field_keys = ("stream_forwarding","stream_key","stream_URL") ; + + for my $row_nr (1 .. 100) { + + foreach (@changed_field_keys) { + $i{analytics_saved_values} .= ($i{"$_\_$suffix\_$row_nr"}) ? qq~$i{"$_\_$suffix\_$row_nr"};~ : ($i{"$_\_fixtures_$row_nr"}) ? qq~$i{"$_\_fixtures_$row_nr"};~ : qq~;~ ; + $ignore{"$_\_$suffix\_$row_nr"} = 1 ; + $ignore{"$_\_fixtures_$row_nr"} = 1 ; + } + + $i{analytics_saved_values} =~ s/;+$// ; + $i{analytics_saved_values} .= qq~|~ ; + + } + + $i{analytics_saved_values} =~ s/\|+$// ; + + $ignore{analytics_saved_values} = (($id && $i{analytics_saved_values} eq $db{$table}{$id}{analytics_saved_values}) || (!$i{analytics_saved_values} && !$db{$table}{$id}{analytics_saved_values})) ? 1 : 0 ; + +} #------------------------------------------------------------------------------------------ + +sub insert { + + my $quote_cancelled = $i{quote_cancelled} ; my $quote_accepted = $i{quote_accepted} ; my $quote_rejected = $i{quote_rejected} ; + + &add_db_fields ; + + $i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{date_created} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{created_by} = $userid ; + $i{last_changed_by} = $userid ; + + $i{id} = &db_min_get_max($table,'id') ; + $i{id} = 1000 if !$i{id} || $i{id} < 1000 ; + + &process_fixtures_tab('') ; + + &process_analytics_tab('') ; + + &set_default_i_vals ; + + &process_multi_select ; + + &process_client_id ; + + $ignore{country_id} = 1 ; + + &db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + unless ($i{id}) { + $error = qq(NO ID) ; + return ; + } + + $i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{last_changed_by} = $userid ; + + &edit_db_fields ; + + &set_default_i_vals ; + + &process_fixtures_tab($i{id}) ; + + &process_analytics_tab($i{id}) ; + + &process_multi_select ; + + &process_client_id ; + + # &log_changes($i{id}) ; + + # &db_min_upd($table,"id='$i{id}'") ; + + our $line = qq~~ ; + + $ignore{country_id} = 1 ; + + &common_shared_log_update_changes($table,"analytics_changes","changes_analytics") ; + +} #------------------------------------------------------------------------------------------ + +# sub log_changes { + + # my ($id) = @_ ; + + # &db_min_ro($table,"*","`id`='$id'",'','') ; + + # my $line = qq~~ ; + + # my %col_to_be_updated = () ; + + # foreach (keys %i) { + # $col_to_be_updated{$_} = 1 ; + # } + + # foreach my $col (keys %{$db{$table}{$id}}) { + + # next if $ignore{$col} || $hidden{$col} == 1 || substr($col,0,3) eq 'new' || !$col_to_be_updated{$col} || $col eq 'last_updated' ; + # if (($i{$col} || $db{$table}{$id}{$col}) && $db{$table}{$id}{$col} ne $i{$col}) { + # $line .= qq~$col='$db{$table}{$id}{$col}',~ ; + # } elsif ((!$i{$col} && !$db{$table}{$id}{$col}) || (($i{$col} || $db{$table}{$id}{$col}) && $db{$table}{$id}{$col} eq $i{$col})) { + # $ignore{$col} = 1 ; + # } + # } + + # $line = qq~$now_year$now_year$now_mm$now_dd$now_hour$now_min$now_sec|$now_year-$now_mm-$now_dd $now_hour:$now_min:$now_sec|event_quote_id='$id'|user_id=$userid|changed_from|~ . $line if $line ; + + # return unless $line ; + + # chop $line ; + + # &common_log_changes("events/changes_analytics.dat",$line) ; + + + +# } #------------------------------------------------------------------------------------------ + +# sub process_event_to { +sub process_client_id { + + my @abc = split(/\:/,$i{client_id}) ; + $i{client_id} = $abc[0] ; + +} #------------------------------------------------------------------------------------------ + +sub process_multi_select { + + local @sporttypeids = split(/\,/,$i{sporttypeids}) ; + my $sporttypeids = join(";",@sporttypeids) ; + $sporttypeids =~ s/\s//g; # remove white space + $ignore{sporttypeids} = 1 ; + $i{sport_type_ids} = $sporttypeids ; + $i{sport_type_ids} = 0 unless $i{sport_type_ids} ; + +} #------------------------------------------------------------------------------------------ + +sub duplicate { + + unless ($i{id}) { + $error = qq~NO ID~ ; + return ; + } + + &db_min_copy($table,$i{id}) ; + +} #------------------------------------------------------------------------------------------ + +sub delete { + + unless ($i{id}) { $error = uc "NO ID" ; return ; } + + &db_min_delete($table,"`id`='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub set_default_i_vals { + + $i{created_by} = '0' unless $i{created_by} ; + $i{event_completed} = '0' unless $i{event_completed} ; + $i{event_accepted} = '0' unless $i{event_accepted} ; + $i{event_pending} = '0' unless $i{event_pending} ; + $i{event_cancelled} = '0' unless $i{event_cancelled} ; + $i{event_rejected} = '0' unless $i{event_rejected} ; + $i{event_created} = '0' unless $i{event_created} ; + $i{country_id} = '0' unless $i{country_id} ; + $i{total_fixtures} = '1' unless $i{total_fixtures} ; + $i{service_type_id} = '0' unless $i{service_type_id} ; + $i{event_quote_id} = '0' unless $i{event_quote_id} ; + $i{region_id} = '0' unless $i{region_id} ; + $i{home_teams_built_on_regions} = '0' unless $i{home_teams_built_on_regions} ; + $i{derby_day_weekly_fixture_id} = '0' unless $i{derby_day_weekly_fixture_id} ; + $i{tournament_festival_id} = '0' unless $i{tournament_festival_id} ; + +} #---------------------------------------------------------------------------------------- + +sub list_screen { + + $trigger_jquery_raw .= qq~ + function deleteMinItem_custom (name,id) { + BootstrapDialog.confirm({ + title: 'Confirm Delete', + message: 'Are you sure you want to delete '+name+'?', + type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + callback: function(result) { + if (result) { + let delete_url = "$useropts{scripts}/get/get_delete_event_quote.pl?"+id+"&$table" ; + \$.get(delete_url) ; + \$("#analytics_event_row_"+id).html("") ; + } + } + }) ; + } + ~ ; + + &db_min_ro('users','id,username,name,email','','','') ; + foreach my $_id (keys %{$db{users}}) { + $username{$_id} = $db{users}{$_id}{username} ; + $name{$_id} = $db{users}{$_id}{name} ; + $email{$_id} = $db{users}{$_id}{email} ; + } + + &db_min_ro('sport_types','*','','','') ; + foreach my $_id (keys %{$db{sport_types}}) { $sport_type{$_id} = $db{sport_types}{$_id}{name} ; } + + if ($iaction eq 'completed' or $i{options} eq 'completed') { push @report_sql, "q.event_completed='1'" ; } + if ($iaction eq 'accepted' or $i{options} eq 'accepted') { push @report_sql, "q.event_accepted='1'" ; } + if ($iaction eq 'rejected' or $i{options} eq 'rejected') { push @report_sql, "q.event_rejected='1'" ; } + if ($iaction eq 'closed' or $i{options} eq 'closed') { push @report_sql, "(q.event_cancelled='1' OR (q.event_expiry<'$now_year-$now_mm-$now_dd' AND q.event_accepted<>'1'))" ; } + if ($iaction eq 'pending' or $i{options} eq 'pending') { push @report_sql, "q.event_pending='1'" ; } + if ($iaction eq 'list' or $i{options} eq 'list') { push @report_sql, "q.event_cancelled<>'1'" ; } + + my $t1 = $table ; + my $t2 = 'countries' ; + my $t3 = 'customers' ; + my $t4 = 'event_quotes' ; + our $tables = "$t1,$t2,$t3,$t4" ; + + if ($is_schools_manager || $is_operator) { + @report_sql_or = () ; + foreach $_reg_id (keys %{$glob_regids{$userid}}) { + push @report_sql_or, "q.region_id = '$_reg_id'" + } + my $sql_or = join(' OR ',@report_sql_or) ; + push @report_sql, "($sql_or)" if $sql_or ; + push @report_sql, "(q.event_created='1')" if $is_schools_manager ; + # push @report_sql, "(q.user_id='$userid')" if $is_schools_manager ; + push @report_sql, "(q.event_accepted='1')" if $is_operator && !$i{options} ; + } + + push @report_sql, "(q.event_completed <> '1')" if $iaction eq 'list' ; + + my $srch_where_sql = join(' AND ', @report_sql) ; my $sql_where = ($srch_where_sql) ? "WHERE $srch_where_sql" : '' ; + + &db_min_raw("SELECT q.id AS 'quote_id', + q.sport_type_ids, + q.start_date_time, + q.event_name, + q.event_expiry, + q.client_id, + q.event_date, + q.date_created, + q.country_id, + q.event_cancelled, + q.event_accepted, + q.event_completed, + q.event_pending, + q.event_created, + q.event_rejected, + q.created_by, + q.additional_notes, + q.total_fixtures, + q.service_type_id, + q.event_quote_id, + q.fixtures_saved_values, + q.analytics_saved_values, + c.name AS 'country', + t.name AS 'customer', + eq.event_system_id_multiple + FROM $t1 q LEFT JOIN $t2 c ON q.country_id = c.id + LEFT JOIN $t3 t ON q.client_id = t.id + LEFT JOIN $t4 eq ON q.event_quote_id = eq.id + $sql_where;"); + + foreach $row (@$rows_array_ref) { + for (0 .. $col_cnt){ + # &common_debug("[$_] $col_name{$_} -> @$row[$_]") ; + $db{$tables}{@$row[0]}{$col_name{$_}} = @$row[$_] ; + } + } + + &db_min_ro('event_systems','id,name,description','','','') ; + + &db_min_ro('customers','id,name','','','') ; + + &db_min_ro('sport_types','id,name','','','') ; + + &analytics_event_bookings_tabs_hash ; # load for PDF links + "e_list ; # load for PDF links + + if ($iaction eq 'update' or $iaction eq 'save'){ + &common_min_extra_crumb("list-$lcpage\s","List $ucfirstpage\s") ; + } + +} #------------------------------------------------------------------------------------------ + +sub quote_list { + + # our @sql_col_display = ("nr","date","customer","user","event","venue","location","sports_type","date_from","date_to","days","type") ; + # our @sql_col_display = ("nr","event_start","event_end","date_added","customer","user","event","venue","location","sports_type","days","type") ; + + our @sql_col_display = ("nr","event_start","event_end","date_added","customer","event","sport","total_fixtures","service_type") ; + + our @col_display_excel = @sql_col_display ; + + push @sql_col_display, "" ; + + &report_xlsx_export_header("Analytics-Events",'analytics_events') ; + + our $ws2 = 'Individual Games' ; + + &xlsxcreator_add_worksheet($ws2) ; + + my %individual_games = () ; + + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) { + + next unless $id ; + + my $quote_expiry = $db{$tables}{$id}{event_expiry} ; $quote_expiry =~ s/\-//iog ; + our $quote_accepted = $db{$tables}{$id}{event_accepted} ; + our $quote_pending = $db{$tables}{$id}{event_pending} ; + our $quote_cancelled = $db{$tables}{$id}{event_cancelled} ; + our $quote_completed = $db{$tables}{$id}{event_completed} ; + our $quote_created = $db{$tables}{$id}{event_created} ; + our $quote_rejected = $db{$tables}{$id}{event_rejected} ; + + if ($quote_completed) { + $sortprefix = 'd' ; + } elsif ($quote_accepted) { + $sortprefix = 'c' ; + } elsif ($quote_rejected) { + $sortprefix = 'x' ; + } elsif ($quote_cancelled) { + $sortprefix = 'z' ; + } elsif ($quote_created) { # create by schools_manager + $sortprefix = 'a' ; + } elsif ($quote_pending) { + $sortprefix = 'b' ; + } + + if ($usertype eq 'support') { + next unless $quote_accepted && !$quote_completed ; + } + + # if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all') { next ; } + + my $quote_date = $db{$tables}{$id}{event_date} ; $quote_date =~ s/\-//iog ; + + $yr = substr($quote_date,0,4) ; + $mm = substr($quote_date,4,2) ; + $dd = substr($quote_date,6,2) ; + + my ($yr2,$mm2,$dd2) = Add_Delta_Days($yr,$mm,$dd,60); # + + $mm2 = sprintf("%02s",$mm2) ; + $dd2 = sprintf("%02s",$dd2) ; + + $quote_date = "$yr2$mm2$dd2" ; + + if ($quote_date && $quote_date < "$now_year$now_mm$now_dd" && $quote_accepted!=1 && + $iaction ne 'report' && $iaction ne 'accepted' && $iaction ne 'closed' && $iaction ne 'all' && + $i{options} ne 'accepted' && $i{options} ne 'closed' && $i{options} ne 'all') { next ; } + + $print_tbody .= qq~~ ; + + $xlsxcol = 0 ; + + my $quote_nr = $db{$tables}{$id}{quote_nr} ; + + my @fixtures_saved_values = split(/\|/,$db{$tables}{$id}{fixtures_saved_values}) ; + my @analytics_saved_values = split(/\|/,$db{$tables}{$id}{analytics_saved_values}) ; + + my $row_cnt = 0 ; + foreach (@fixtures_saved_values) { + my $date = (substr($_,0,1) eq ';') ? substr($db{$tables}{$id}{start_date_time},0,10) : substr($_,0,10) ; + my $time = (substr($_,0,1) eq ';') ? substr($db{$tables}{$id}{start_date_time},11,5) : substr($_,11,5) ; + $individual_games{$date}{$time}{$id}{fixtures} .= qq~$_\|~ ; + $individual_games{$date}{$time}{$id}{analytics} .= qq~$analytics_saved_values[$row_cnt]\|~ ; + $row_cnt++ ; + } + + foreach (@sql_col_display) { + + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$tables}{$id}{$_} ; + my $align = qq~ class="dt-center"~ ; + my $nowrap = '' ; + my $val_xlsx = '' ; + + if ($_ eq 'nr') { + + $nowrap = 'nowrap' ; + $sort_val = sprintf("%06d",$id) ; + $sort_val = ($quote_accepted) ? qq~5~ . $sort_val : ($quote_completed) ? qq~4~ . $sort_val : ($quote_pending) ? qq~3~ . $sort_val : ($quote_rejected) ? qq~2~ . $sort_val : ($quote_cancelled) ? qq~1~ . $sort_val : qq~0~ . $sort_val ; + $val = qq~$sort_val~ . &common_min_get_event_quote_button($id,$tables,"analytics-event-bookings") ; + $val .= qq~~ if $db{$tables}{$id}{event_quote_id} ; + $val_xlsx = $id ; + # javascript:editMinItem('10922','event-quotes'); + if ($quote_completed) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format80) ; + } elsif ($quote_accepted) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format77) ; + } elsif ($quote_created) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format78) ; # yellow + } elsif ($quote_pending) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format79) ; # orange + } elsif ($quote_cancelled) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format81) ; # red + } + + } elsif ($_ eq 'event_start') { + my $sort_val = $db{$tables}{$id}{start_date_time} =~ s/[\-:\s]//gr; + $val_xlsx = &common_min_date_as_string(substr($db{$tables}{$id}{start_date_time},0,16)) ; + $val = qq~$sort_val~ . $val_xlsx ; + $nowrap = 'nowrap' ; + } elsif ($_ eq 'event_end') { + + if ($db{$tables}{$id}{end_date_time}) { + my $sort_val = $db{$tables}{$id}{end_date_time} =~ s/[- :]//g ; + $val_xlsx = &common_min_date_as_string(substr($db{$tables}{$id}{end_date_time},0,16)) ; + $val = qq~$sort_val~ . $val_xlsx ; + } elsif ($db{$tables}{$id}{fixtures_saved_values}) { + my $latest_date = "" ; my $latest_date_val = "" ; + foreach (split(/\|/,$db{$tables}{$id}{fixtures_saved_values})) { + next unless $_ ; + my @saved_vals = split(/\;/,$_) ; + next unless $saved_vals[0] ; + my $date_val = $saved_vals[0] ; + $date_val =~ s/[- :]//g ; + $latest_date = $saved_vals[0] if !$latest_date_val || ($latest_date_val && $latest_date_val < $date_val) ; + $latest_date_val = $latest_date ; + $latest_date_val =~ s/[- :]//g ; + } + $val = substr($latest_date,0,10) ; + if ($val) { + my $sort_val = $val ; + $sort_val =~ s/[- :]//g ; + $val_xlsx = &common_min_date_as_string($val) ; + $val = qq~$sort_val~ . &common_min_date_as_string($val) ; + } + } + + $nowrap = 'nowrap' ; + } elsif ($_ eq 'date_added') { + my $sort_val = $db{$tables}{$id}{date_created} =~ s/[\-:\s]//gr; + $val_xlsx = &common_min_date_as_string($db{$tables}{$id}{date_created}) ; + $val = qq~$sort_val~ . $val_xlsx ; + $val_xlsx .= qq~ [Added By: $username{$db{$tables}{$id}{created_by}}]~ ; + $val = qq~$val~ ; + $nowrap = 'nowrap' ; + } elsif ($_ eq 'event') { + $val = $db{$tables}{$id}{event_name} ; + $nowrap = '' ; + } elsif ($_ eq 'customer') { + $nowrap = 'nowrap' ; + } elsif ($_ eq 'country_id') { + $val = $db{$tables}{$id}{country} ; + } elsif ($_ eq 'sport') { + $val = join("
    ", map { $sport_type{$_} } split(/\;/,$db{$tables}{$id}{sport_type_ids})) ; + $val_xlsx = $val ; + $val_xlsx =~ s/\
    /\;/g ; + } elsif ($_ eq 'total_fixtures') { + $val = ($db{$tables}{$id}{total_fixtures}) ? $db{$tables}{$id}{total_fixtures} : 1 ; + } elsif ($_ eq 'service_type') { + $db{$tables}{$id}{service_type_id} = ($db{$tables}{$id}{service_type_id}) ? $db{$tables}{$id}{service_type_id} : 2 ; + $val = $service_types{$db{$tables}{$id}{service_type_id}} ; + } + $print_tbody .= qq~$val~ ; + + if ($_ ne 'nr') { + $val_xlsx = $val unless $val_xlsx ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format82) ; + } + $xlsxcol++ ; + + } + + $xlsxrow++ ; + + my $quote_nr = $quote_nr ; $quote_nr =~ s/'//iog; unless ($quote_nr) { $quote_nr = $id ; } + + my $edit_butt = qq~~ ; + my $delete_butt = qq~~ ; + # ($glod_user_level < 3 || $quote_accepted || $quote_completed || $quote_rejected || $quote_pending) ? '' : + my $copy_butt = qq~~ ; + + $edit_butt = qq~$edit_butt ~ if $edit_butt ; + $copy_butt = qq~$copy_butt ~ if $copy_butt ; + $delete_butt = qq~$delete_butt ~ if $delete_butt ; + + $print_tbody .= qq~ $edit_butt$copy_butt$delete_butt~ ; + } + + my @day_name = ("","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday") ; + my @month_name = ("","January","February","March","April","May","June","July","August","September","October","November","December") ; + + my $xlsxrow2 = 0 ; my $xlsxcol2 = 0 ; + + my %team_ids = () ; + + foreach my $a (keys %individual_games) { + foreach my $b (keys %{$individual_games{$a}}) { + foreach my $c (keys %{$individual_games{$a}{$b}}) { + my @abc = split(/\|/,$individual_games{$a}{$b}{$c}{fixtures}) ; + foreach (@abc) { + my @abcd = split(/\;/,$_) ; + $team_ids{$abcd[4]} = 1 ; + $team_ids{$abcd[6]} = 1 ; + } + } + } + } + + my $team_sql = join(" OR ", map{ "id='$_'" } keys %team_ids) ; + + &db_switch_conn('sss') ; + + &db_min_ro('teams','id,name',$team_sql,'','') ; + + &db_switch_conn('aisa') ; + + my $heading_count = 0 ; my %seen_event_sport = () ; + + foreach my $date (sort {$a cmp $b} keys %individual_games) { + + my ($year,$month,$day) = split(/\-/,$date) ; + my $day_of_week = Day_of_Week($year,$month,$day) ; + my $day_add = ($day eq '1') ? "st" : ($day eq '2') ? "nd" : ($day eq '3') ? "rd" : "th" ; + my $date_name = "$day_name[$day_of_week] $day$day_add $month_name[$month]" ; + + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"$date_name",$format109) ; + + my $first_game = 1 ; + + my $contain_tbc_events = 0 ; + my $contain_confired_events = 0 ; + + foreach my $time (sort {$a cmp $b} keys %{$individual_games{$date}}) { + + foreach my $a_id (sort { $a <=> $b } keys %{$individual_games{$date}{$time}}) { + + $individual_games{$date}{$time}{$a_id}{fixtures} =~ s/\|+$// ; + $individual_games{$date}{$time}{$a_id}{analytics} =~ s/\|+$// ; + my @individual_games_fixtures = split(/\|/,$individual_games{$date}{$time}{$a_id}{fixtures}) ; + my @individual_games_analytics= split(/\|/,$individual_games{$date}{$time}{$a_id}{analytics}) ; + + my $row_cnt = scalar @individual_games_fixtures ; + $row_cnt = scalar @individual_games_analytics if scalar @individual_games_analytics > scalar @individual_games_fixtures ; + $row_cnt = 0 unless $row_cnt ; + + next unless $row_cnt ; + + my $tbc_game = 1 ; + + foreach my $row_nr (0 .. $row_cnt - 1) { + + my @data_split = split(/\;/,$individual_games_fixtures[$row_nr]) ; + + my $customer_name = uc $db{customers}{$db{$tables}{$a_id}{client_id}}{name} ; + my $sport_name = ($db{$tables}{$a_id}{sport_type_ids} && $db{$tables}{$a_id}{sport_type_ids} !~ /;/) ? $db{sport_types}{$db{$tables}{$a_id}{sport_type_ids}}{name} : $db{sport_types}{$data_split[1]}{name} ; + $sport_name = uc $sport_name ; + + $heading_count++ unless $seen_cleint_sport{$db{$tables}{$a_id}{client_id}}{$sport_name} ; + $heading_count = $heading_count%3 ; + $seen_cleint_sport{$db{$tables}{$a_id}{client_id}}{$sport_name} = 1 ; + + my $heading_format = ($heading_count == 1) ? $format110 : ($heading_count == 2) ? $format111 : ($heading_count == 0) ? $format112 : $format112 ; + + if (!$data_split[6]) { + $tbc_games{$date}{$db{$tables}{$a_id}{client_id}}{$sport_name}++ ; + $contain_tbc_events = 1 ; + next ; + } else { + $contain_confired_events = 1 ; + $tbc_game = 0 ; + } + + $xlsxrow2++ if $first_game ; + $first_game = 0 ; + $xlsxrow2++ ; + + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," $customer_name $sport_name ANALYTICS",$heading_format) ; + $xlsxrow2++ ; + + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," $db{teams}{$data_split[4]}{name} vs $db{teams}{$data_split[6]}{name}",$format1) ; + $xlsxrow2++ ; + + if ($data_split[0]) { + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," " . substr($data_split[0],11,5),$format1) ; + } else { + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," " . substr($db{$tables}{$a_id}{start_date_time},11,5),$format1) ; + } + + if ($db{$tables}{$a_id}{event_system_id_multiple}) { + $db{$tables}{$a_id}{event_system_id_multiple} =~ s/f-//g ; + my $systems = join(";", map { "$db{event_systems}{$_}{name} ($db{event_systems}{$_}{description})" } split(/\;/,$db{$tables}{$a_id}{event_system_id_multiple})) ; + $systems =~ s/ ()//g ; + + foreach (split(/\;/,$systems)) { + next unless $_ ; + $xlsxrow2++ ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," $_",$format115) ; + } + } + + if ($individual_games_analytics[$row_nr]) { + + my @data_split_2 = split(/\;/,$individual_games_analytics[$row_nr]) ; + + if ($data_split_2[0] eq '1' && $data_split_2[1]) { + $xlsxrow2++ ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," " . $data_split_2[1],$format1) ; + } + if ($data_split_2[0] eq '1' && $data_split_2[2]) { + $xlsxrow2++ ; + &xlsxcreator_write_url($ws2,$xlsxrow2,$xlsxcol2,$data_split_2[2],"$data_split_2[2]") ; + } + + } + + } + $xlsxrow2++ unless $tbc_game ; + } + } + + my $abcbc = 0 ; + + $xlsxrow2++ if $contain_tbc_events && !$contain_confired_events ; + + foreach my $client_id (sort { $a <=> $b } keys %{$tbc_games{$date}}) { + foreach my $sport_name (sort { $a <=> $b } keys %{$tbc_games{$date}{$client_id}}) { + $xlsxrow2++ ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"$db{customers}{$client_id}{name} $sport_name ANALYTICS",$format116) ; + $xlsxrow2++ ; + &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"Other $tbc_games{$date}{$client_id}{$sport_name} games still to be confirmed",$format113) ; + $abcbc = 1 ; + } + } + + $xlsxrow2++ if $abcbc ; + $xlsxrow2++ ; + } + + $worksheet{$ws2}->set_column(0,0,75) ; + $worksheet{$ws}->set_column(0,0,10) ; + $worksheet{$ws}->set_column(1,5,30) ; + $worksheet{$ws}->set_column(6,8,20) ; + + &report_xlsx_export_footer('L',15,'analytics_events') ; + + if ($usertype eq 'support') { + $fnsortcol = 1 ; # start date + $fnsortorder = 'asc' ; + } + + # &common_min_extra_crumb("search-$lcpage\s","Search Screen") if $glod_user_level > 3 ; + &common_min_extra_crumb("filter-$lcpage\s","Search Screen") if $glod_user_level > 3 ; + + # 12~yBf-w0xwLJcY7rY49dFy6Fw0tohiEHDUOw.png:Screenshot_2025-10-24_082334.png:Screenshot_2025-10-24_082804.png:32482_F.jpg|134~File_-_2025-10-08T074305.322.jpg:File_-_2025-10-09T080750.400.jpg:File_-_2025-10-10T091621.052.jpg:30729_F.jpg|309~Screenshot_2025-10-24_083010.png::Screenshot_2025-10-24_083250.png:31023vF.jpg + # 11685 + # |309~;;;08:02:50 + + + + + # 12~2025-10-08 07:59:14;2025-10-09 08:22:14;2025-10-10 09:35:18;2025-10-11 08:49:36|309~2025-10-08 08:15:26;;2025-10-10 08:56:42;2025-10-11 08:41:10|134~2025-10-08 07:43:03;2025-10-09 08:07:59;2025-10-10 09:14:17;2025-10-11 08:33:47 + # 161 + # 2025-10-24 09:29:09 + + +} #------------------------------------------------------------------------------- + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub add_db_fields { + + &hidden_fields ; + $hidden{id} = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &hidden_fields ; + $hidden{id} = 1 ; + # $readonly{ref} = 'READONLY' ; + +} #------------------------------------------------------------------------------------------ + +sub view_db_fields { + + &hidden_fields ; + $hidden{id} = 1 ; + $label{event_name} = 1 ; + $label{qty} = 1 ; + $label{start_date_time} = 1 ; + $label{sport_type_ids} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub hidden_fields { + + # if ($glod_user_level < 4) { + if ($glod_user_level < 3) { + + $ignore{type_of_system} = 1 ; + $ignore{system_details} = 1 ; + $ignore{system_name} = 1 ; + $ignore{operators} = 1 ; + # $ignore{operator_ids} = 1 ; + } + + $ignore{quote_nr} = 1 ; + $ignore{iaction} = 1 ; + $ignore{sport_type_ids_readonly} = 1 ; + $ignore{datetime} = 1 ; + $ignore{custom_selected_region} = 1 ; + $ignore{custom_selected_country} = 1 ; + + # $ignore{home_teams_built_on_regions} = 1 ; + + for (1 .. 100) { + $ignore{"changed_fixtures_date_$_"} = 1 ; + $ignore{"changed_home_team_$_"} = 1 ; + } + + $hidden{event_date} = 2 ; + $hidden{last_updated} = 2 ; + $hidden{created_by} = 2 ; + + # $required{event_to} = 1 ; + # $required{country_id} = 1 ; + # $required{region_id} = 1 ; + $required{client_id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + + $selected{max_cams}{10} = 'SELECTED'; + &select_opts('') ; + %col_name = () ; + &db_min_ro($table,'*',"id > 1 AND id < 10",'','') ; + + $page_title = substr($page_title,0,-1) ; + $db{$table}{''}{quote_nr} = &db_min_get_max($table,'id') ; + $db{$table}{''}{quote_nr} = 1000 if $db{$table}{''}{quote_nr} < 1000 ; + + # if ($username eq 'rory') { $db{$table}{''}{quote_nr} = 1000 ; } + + &add_db_fields ; + + &build_boxes('','save') ; + + local $all_select_ids_string = join(",",@all_select_ids) ; + $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true });~ ; + +} #------------------------------------------------------------------------------------------ + +sub view_screen { + + &edit_screen ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + unless ($i{id}) { $warning = qq(NO ID) ; return ; } + + # my $users_cols = "id,name,user_type" ; $users_cols = "id,name,user_type,region_ids" if $glod_user_level < 4 ; + my $users_cols = "id,name,user_type" ; $users_cols = "id,name,user_type,region_ids" if $glod_user_level < 3 ; + + &db_min_ro('users',$users_cols,"`user_type` LIKE 'casual%' OR `user_type` = 'schools_manager'",'','') ; + foreach (keys %{$db{users}}) { + next if $db{users}{$_}{user_type} eq 'schools_manager' ; + $casual_name{$_} = $db{users}{$_}{name} ; + $casual_type{$_} = uc substr($db{users}{$_}{user_type},-1,1) ; + $casuals{$_} = 1 if substr($db{users}{$_}{user_type},0,6) eq 'casual' ; + } + + &db_min_ro($table,'*',"id='$i{id}'",'','') ; + + $db{$table}{$i{id}}{quote_nr} = $i{id} ; + + my $cnt_rows = 0 ; + for (1 .. $nr_of_system_names_and_clubs) { + $cnt_rows = $_ if $system_name_ids[$_ - 1] or $club_ids[$_ - 1] ; + } + + our @table_op_ids = () ; + our @multi_select_op_ids = () ; + + for (1 .. $cnt_rows) { + push @table_op_ids,$op_ids[$_ - 1] if $op_ids[$_ - 1] ; + push @table_op_ids,0 unless $op_ids[$_ - 1] ; + } + for ($cnt_rows+1 .. $nr_of_system_names_and_clubs) { + push @multi_select_op_ids,$op_ids[$_ - 1] if $op_ids[$_ - 1] ; + } + + our $quote_completed = $db{$table}{$i{id}}{event_completed} ; + our $quote_accepted = $db{$table}{$i{id}}{event_accepted} ; + our $quote_pending = $db{$table}{$i{id}}{event_pending} ; + our $quote_cancelled = $db{$table}{$i{id}}{event_cancelled} ; + our $quote_rejected = $db{$table}{$i{id}}{event_rejected} ; + + # our $cancel_butt = ($d_check[2] > $now_ccyymmddhrmnsc && $iaction eq 'edit' && ($quote_completed || $quote_accepted || $quote_pending) && ($glod_user_level > 2 || $is_schools_manager)) ? 1 : 0 ; + our $cancel_butt = ($iaction eq 'edit' && ($quote_completed || $quote_accepted || $quote_pending) && ($glod_user_level > 2 || $is_schools_manager)) ? 1 : 0 ; + + # if ($is_schools_manager) { + if ($is_schools_manager || $glod_user_level < 4) { + my @ed_from = &common_split_sql_time($db{$table}{$i{id}}{start_date_time}) ; + my @d_check = &common_add_delta_dhms($ed_from[0],$ed_from[1],$ed_from[2],$ed_from[3],$ed_from[4],$ed_from[5],0,-18,0,0) ; # go 18 hours back from event start + + if ($d_check[2] < $now_ccyymmddhrmnsc) { + $cancel_butt = 0 ; + } + } + + $page_title = substr($page_title,0,-1) ; + $page_title .= " : $i{id}" ; + + $custom_back_button = qq~ ~ ; + # $custom_back_button = qq~$val~ ; + + # our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + &common_min_footer('id',"$lcpage\s"); + + &edit_db_fields ; + + &select_opts($i{id}) ; + + our $saveandexit = 1 ; + + &build_boxes($i{id},'update') ; + + &common_min_extra_crumb("filter-$lcpage\s","Search $ucfirstpage\s") if $glod_user_level > 3 ; + + local $all_select_ids_string = join(",",@all_select_ids) ; + $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true });~ ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes { + + my ($id,$action) = @_ ; + + our @jquery_trigger_fields = () ; + our @jquery_custom_vat_ids = () ; + our @jquery_duty_ids = () ; + our @jquery_workings_trigger_fields = () ; + + push @jquery_trigger_fields, 'inputRoe' ; + push @jquery_workings_trigger_fields, 'inputRoe' ; + + for (1 .. 15) { + push @jquery_workings_trigger_fields, "checkboxVat_workings_event_$_" ; + push @jquery_workings_trigger_fields, "checkboxExcl_workings_event_$_" ; + # push @jquery_workings_trigger_fields, "checkboxVat_$_\_workings_casual_users" ; + # push @jquery_workings_trigger_fields, "checkboxExcl_$_\_workings_casual_users" ; + } + &analytics_event_bookings_tabs_curr_symbols; + + foreach $col(keys %required) { + &common_min_forms_required ; + } + + our $tab_cnt = 0 ; + + &analytics_event_bookings_tabs_load_vars; + + $print_box_content_rows .= &common_min_forms_start($table) ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq~ +
    +
    ~ ; + &build_boxes_top($id); + $print_box_content_rows .= qq~ +
    +
    + ~ ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq~
    ~ ; + + &analytics_event_bookings_tabs_cnt ; + + $print_box_content_rows .= qq(
    + +
    ); + + our %tab_sections = () ; + + foreach (sort {$a <=> $b} keys %cntxt) { + + my $tab_name = &analytics_event_bookings_tabs_names($_) ; my $active = '' ; + + $active = ($_==2) ? 'active' : '' ; + + my $colsleft = 12 ; my $showright = '' ; + + if ($cntxt{$_} eq 'one' or $cntxt{$_} eq 'seven') { + $colsleft = 12 ; + $showright = 1 ; + } + + $print_box_content_rows .= qq~
    ~; + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_left($id,$_); + $print_box_content_rows .= qq~
    ~ ; + + if ($showright) { + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_right($id,$_); + $print_box_content_rows .= qq~
    ~ ; + } + + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~
    ~ ; + } + + $print_box_content_rows .= qq~ +
    +
    + ~ ; + + $print_box_content_rows .= qq~
    ~ ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_bottom($id); + $print_box_content_rows .= qq~
    ~ ; + + #-------------------------------------------------------------------------- + + our $skip_save_btn = ($quote_completed && $glod_user_level <= 3) ? 1 : 0 ; + + $print_box_content_rows .= &common_min_forms_end($id,$table,$action,$skip) ; + + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_top { + + my ($id) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(3,6) ; + + $add_form_fields = '' ; + + $fcol=8 ; + + $add_form_fields .= qq~
    ~ ; + $preferred_title{quote_nr} = "Nr" ; + $readonly{quote_nr} = "READONLY" ; + $add_form_fields .= &common_min_form_input('quote_nr',$db{$table}{$id}{quote_nr},'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + if (($db{$table}{$id}{event_date} eq '') or ($db{$table}{$id}{event_date} eq '0000-00-00')) { + $db{$table}{$id}{event_date} = $now_ccyy_mm_dd ; + } + $preferred_title{event_date} = "Date" ; + $readonly{event_date} = "READONLY" ; + $add_form_fields .= &common_min_form_datepicker('event_date',$db{$table}{$id}{event_date}) ; + my $plus_n_days_ccyy_mm_dd = &common_add_delta_days(14) ; + + # $trigger_jquery_raw .= qq~\$('#datepickerEvent_date').datepicker({format:'yyyy-MM-dd'})~ ; + # $trigger_jquery_raw .= qq~\$('#datepickerEvent_date').datepicker({language: 'pt-BR'})~ ; + # $trigger_jquery_raw .= qq~\$('#datepickerEvent_date_fixtures_'+i).datepicker({language: 'pt-BR'})~ ; + + # $required{event_to} = 1 ; + # $required{region_id} = 1 ; + + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + # $preferred_title{event_to} = "Client" ; + # $add_form_fields .= &common_min_form_select('event_to',$db{$table}{$id}{event_to},'') ; + # $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + # $dlg{event_to} = qq~ + # ~ ; + $fcol = 7; + # &common_min_select_opts('sport_type_ids','sport_types','name','','','','') ; + + $sql_limit_user_regions = ($is_schools_manager || $is_operator) ? join(' OR ', map { "id = '$_'" } keys %{$glob_regids{$userid}}) : '' ; + + # our $debug = 1 ; + + $allow_deselect{region_id} = 1 ; + + &common_min_select_opts('region_id','regions','name','','','code',$sql_limit_user_regions) ; + + $add_form_fields .= qq~~ ; + + $db{$table}{$id}{country_id} = $db{regions}{$db{$table}{$id}{region_id}}{country_id} ; + + $add_form_fields .= qq~~ ; + + # $db{$table}{$id}{country_id} = "242" unless $db{$table}{$id}{country_id} ; + + &common_min_select_opts('country_id','countries','name','','','','') ; + + my %home_teams = () ; + + foreach my $data (split(/\|/,$db{$table}{$id}{fixtures_saved_values})) { + my @abc = split(/\;/,$data) ; + $home_teams{$abc[4]} = 1 ; + } + + my $home_teams_str = join(" OR ", map{ "id='$_'" } keys %home_teams) ; + + if ($db{$table}{$id}{client_id} || $home_teams_str) { + + &db_switch_conn('sss') ; + + # my $region_filter = $db{$table}{$id}{region_id} ; + my $region_filter = '' ; + my $client_filter = $db{$table}{$id}{client_id} ; + + $db{$table}{$id}{home_teams_built_on_regions} = ($iaction eq 'add' || (!$region_filter && !$client_filter)) ? 1 : $db{$table}{$id}{home_teams_built_on_regions} ; + + my $home_teams_built_on_regions = $db{$table}{$id}{home_teams_built_on_regions} ; + + my $teams_sql = ($region_filter) ? qq~(`region_id`='$region_filter' OR (`region_id`='0' AND `matched_region_id`='$region_filter'))~ : qq~(`region_id`='0' AND `matched_region_id`='0')~ ; #(`region_id`='0' AND `matched_region_id`='0') + + if ($client_filter && !$home_teams_built_on_regions) { + $teams_sql .= qq~ OR ~ if $teams_sql ; + $teams_sql .= qq~(`aisa_client_id`='$client_filter')~ ; + } + + if ($home_teams_str) { + $teams_sql .= qq~ OR ~ if $teams_sql ; + $teams_sql .= qq~($home_teams_str)~ ; + } + + $opts{teams_id} = qq~~ ; + $opts{client_teams_id} = qq~~ ; + + if ($teams_sql) { + &db_min_ro('teams','*',"$teams_sql",'','') ; + foreach (sort { $db{teams}{$a}{name} cmp $db{teams}{$b}{name} } keys %{$db{teams}}) { + my $region_id = $db{teams}{$_}{region_id} ; + my $matched_region_id = $db{teams}{$_}{matched_region_id} ; + my $client_id = $db{teams}{$_}{aisa_client_id} ; + $opts{teams_id} .= qq~~ if ($region_filter && (($region_id eq $region_filter) || (!$region_id && $matched_region_id eq $region_filter))) || (!$region_filter && !$client_filter && !$region_id && !$matched_region_id) ; + next if $home_teams_built_on_regions || !$client_filter ; + $opts{client_teams_id} .= qq~~ if $client_filter eq $client_id || $home_teams{$_} ; + } + } + + # # # &db_min_ro('teams','*',"",'','') ; + # # # foreach (sort { $db{teams}{$a}{name} cmp $db{teams}{$b}{name} } keys %{$db{teams}}) { + # # # $opts{away_team} .= qq~~ ; + # # # } + + # &common_min_select_opts('teams_id','teams','name','','','',"`region_id`='$db{$table}{$id}{region_id}' OR (`region_id`='0' AND `matched_region_id`='$db{$table}{$id}{region_id}')") if $db{$table}{$id}{region_id} ; + # &common_min_select_opts('client_teams_id','teams','name','','','',"`aisa_client_id`='$db{$table}{$id}{client_id}'") if $db{$table}{$id}{client_id} && !$db{$table}{$id}{home_teams_built_on_regions} ; + + &db_switch_conn('aisa') ; + + } + + my %away_teams = () ; my %home_teams = () ; my %home_and_away_teams = () ; + + foreach (split(/\|/,$db{$table}{$id}{fixtures_saved_values})) { + my @abc = split(/\;/,$_) ; + $home_teams{$abc[4]} = 1 if $abc[4] ; + $away_teams{$abc[6]} = 1 if $abc[6] ; + $home_and_away_teams{$abc[4]} = 1 if $abc[4] ; + $home_and_away_teams{$abc[6]} = 1 if $abc[6] ; + } + + my $away_teams_sql = qq~~ ; + $away_teams_sql = join (" OR ",map{"id='$_'"} keys %home_and_away_teams) ; + if ($away_teams_sql) { + &db_switch_conn('sss') ; + &db_min_ro('teams','id,name',"$away_teams_sql",'','') ; + foreach (sort { $db{teams}{$a}{name} cmp $db{teams}{$b}{name} } keys %{$db{teams}}) { + next if $home_teams{$_} && !$away_teams{$_} ; + $opts{away_team} .= qq~~ ; + } + &db_switch_conn('aisa') ; + } + + # $db{$table}{$id}{country_id} = 242 unless $db{$table}{$id}{country_id} ; + $opts{region_id} =~ s/value="$db{$table}{$id}{region_id}"/value="$db{$table}{$id}{region_id}" SELECTED/g if $db{$table}{$id}{region_id} ; + $opts{country_id} =~ s/value="$db{$table}{$id}{country_id}"/value="$db{$table}{$id}{country_id}" SELECTED/g if $db{$table}{$id}{country_id} ; + + # $required{country_id} = qq~data-validation="required"~ ; + # $required{region_id} = qq~data-validation="required"~ ; + + $allow_deselect{country_id} = 1 ; + + $add_form_fields .= &common_min_form_select('country_id',$db{$table}{$id}{country_id},'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= &common_min_form_select('region_id',$db{$table}{$id}{region_id},'') ; + $add_form_fields .= qq~
    ~ ; + + $fcol = 8; + + $print_box_content_rows .= &common_min_box_top('qrcode',"Quote",'BABEC2'); + + $print_box_content_rows .= qq~ +
    +
    + $add_form_fields +
    +
    + ~; + + $print_box_content_rows .= qq~ +
    +
    +   +
    +
    + ~ ; + + $print_box_content_rows .= &common_min_box_foot; + + $print_box_content_rows .= qq~~ ; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_left { + + my ($id,$tab) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(3,6) ; + + &analytics_event_bookings_tabs_build_qt_left($id,$tab); + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_right { + + my ($id,$tab) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(3,6) ; + + &analytics_event_bookings_tabs_build_qt_right($id,$tab); + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_bottom { + + my ($id) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(2,2) ; + + $add_form_fields = '' ; + + # --------------- START GRAND TOTAL ---------------------------------------------------------------------------------------------------------------------- + + # $print_box_content_rows .= &common_min_form_input('activetab',$db{$table}{$id}{activetab},'hidden') ; + + # --------------- END RAND TOTAL ------------------------------------------------------------------------------------------------------------------------ + +} #---------------------------------------------------------------------------------------- + +sub fix_options_for_javascript { + + my ($options) = @_ ; + $options =~ s/\SELECTED//g ; + $options =~ s/\"/\'/g ; + return $options ; + +} #---------------------------------------------------------------------------------------- + +sub q_get_val { + + my ($val) = @_ ; + + my $disp_val = $val ; + + if ($val eq '0.00') { + $disp_val = '' ; + } + + return ($disp_val); + +} #------------------------------------------------------------------------------------------ + +sub set_check_boxes_checked { + + my ($id,$rcnt,$prefix,$suffix) = @_ ; + + for (1 .. $rcnt) { + + my $ifield = $prefix . '_' . "$_$suffix" ; + my $val = $db{$table}{$id}{$ifield} ; + # &common_debug("set_check_boxes_checked: [prefix=$prefix] [suffix=$suffix] ifield=$ifield, val=$val") ; + + $checkit{$ifield} = $val ; + } + +} #---------------------------------------------------------------------------------------- + +sub select_opts { + + my ($id) = @_ ; + + our $savjqy = 1 ; + + %filter_val = () ; %filter_select_opts = () ; + # if ($is_schools_manager) { + # if ($glod_user_level < 4) { + if ($glod_user_level < 3) { + $filter_select_opts{'regions'} = 1 ; + foreach $_reg_id (keys %{$glob_regids{$userid}}) { + $filter_val{'regions'}{$_reg_id} = 1 ; + } + } + # &common_debug("[$usertype] filter_select_opts = $filter_select_opts{'regions'}") ; + + local $region_id_where = qq~~ ; local @abcd = () ; + + # if ($is_schools_manager) { + # if ($glod_user_level < 4) { + if ($glod_user_level < 3) { + foreach (split(",",$db{users}{$userid}{region_ids})) { + push @abcd , "`id` = '$_'" ; + } + } + + $preferred_title{sport_type_ids} = "Sport Types" ; + %selected_multi = () ; + $multiple{sport_type_ids} = 1; + my @sport_type_ids = split(/\;/,$db{$table}{$id}{sport_type_ids}); + foreach (@sport_type_ids) { + $selected_multi{$_} = 'SELECTED' ; + } + + &common_min_select_opts('sport_type_ids','sport_types','name',$db{$table}{$id}{sport_type_ids},'','','','','name') ; + + $extra_form_fields .= qq~~; + + foreach (@multi_select_op_ids) { + $selected_multi{$_} = 'SELECTED' ; # &common_debug("SELECTED operator_ids [$_] : [selected=$selected_multi{$_}]") ; + } + + &db_min_ro('users',"id,name,region_ids","user_type LIKE 'casual%' AND block <> 1 AND inactive <> 1",'','') ; + + foreach my $op_id (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + my $regions = "" ; + foreach (split(",",$db{users}{$op_id}{region_ids})) { + $regions .= "$db{regions}{$_}{code}," ; + } + chop $regions if $regions ; + my $user_names = $db{users}{$op_id}{name} ; + $user_names = "$db{users}{$op_id}{name} [$regions]" if $regions ; + $opts{operator_ids} .= qq~~ ; + # for (1 .. $nr_of_system_names_and_clubs) { + # $opts{"operator_ids_$_"} .= qq~~ ; + } + + # &common_min_select_opts('operator_ids','users','name',$db{$table}{$i{id}}{operator_ids},'','',"user_type LIKE 'casual%'") ; + + $trigger_jquery .= qq~\$("#selectType\_chosen").css("width","80%");~ ; + + %selected_multi = () ; + + # $db{event_quotes}{''}{event_to} = 5 if $iaction eq 'add' ; # SuperSport Schools (Pty) Ltd + + $extra_css .= qq() ; + + $trigger_jquery .= qq~\$("#selectSport_type_ids_chosen").css("width","100%");~ ; + + $trigger_jquery_raw .= qq~ + + \$("#savebutt").click( async function() { + + let buttonClass = \$(this).attr("class") ; + if (buttonClass == "btn btn-custom") { + return ; + } + + var we_can_save_form = check_before_saving() ; + + let end_date = new Date(\$("input[name='end_date_time']").val()) ; + let start_date = new Date(\$("input[name='start_date_time']").val()) ; + + start_date = new Date(start_date.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours + end_date = new Date(end_date.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours + + let earliest_latest = find_latest_and_earliest_date_in_fixtures() ; + + if (start_date > earliest_latest.earliest_date) { + noty({text:'Please Select an Event Start Date that is before the earliest date on the Fixtures tab!',layout:"center",type:"error",timeout:3000}) ; + we_can_save_form = 0 ; + } + + if (end_date < earliest_latest.latest_date) { + noty({text:'Please Select an Event Start Date that is before the earliest date on the Fixtures tab!',layout:"center",type:"error",timeout:3000}) ; + we_can_save_form = 0 ; + } + + for (let i=1;i<=100;i++) { + + if (!\$("#fixtures_"+i).html() || \$("#fixtures_"+i).css("display") === 'none') { + break ; + } + if (\$("#selectHome_team_fixtures_"+i).val() && !\$("#selectAway_team_fixtures_"+i).val()) { + we_can_save_form = 0 ; + noty({text:'Please Select an Away team when selecting a Home Team on the Fixtures tab!',layout:"center",type:"error",timeout:3000}) ; + break ; + } else if (!\$("#selectHome_team_fixtures_"+i).val() && \$("#selectAway_team_fixtures_"+i).val()) { + we_can_save_form = 0 ; + noty({text:'Please Select an Home team when selecting a Away Team on the Fixtures tab!',layout:"center",type:"error",timeout:3000}) ; + break ; + } + } + + if (\$("#selectEvent_quote_id").val() && we_can_save_form) { + + let date_url = "$useropts{scripts}/get/get_dates_from_event_quote.pl?event_quote_id="+\$("#selectEvent_quote_id").val()+"&start_date_time="+\$("input[name='start_date_time']").val()+"&end_date_time="+\$("input[name='end_date_time']").val() ; + + let dates_json = await fetchJSON(date_url); + + for (const key in dates_json) { + const data = dates_json[key]; + noty({text:'The Start and End date of this Event is from '+data.start_date_time+' to '+data.end_date_time+' Compared to '+data.date_from+' to '+data.date_to+' for the Event Quote.
    Please Ensure the Dates Correspond!',layout:"center",type:"warning",timeout:7500}) ; + await sleep(7500); + } + + // await \$.get(date_url, function(json) { + // \$.each(json, function(key, data) { + // noty({text:'The Start and End date of this Event is from '+data.start_date_time+' to '+data.end_date_time+' Compared to '+data.date_from+' to '+data.date_to+' for the Event Quote',layout:"center",type:"error",timeout:7500}) ; + // // await sleep(10000); + // }); + // } + // ,'json') ; + + } + + if (we_can_save_form) { + \$('#analytics_event_bookings-form').submit() ; + } else { + return ; + } + }) ; + + function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); + } + + \$("#cancelbutt").click( function() { + + let buttonClass = \$(this).attr("class") ; + if (buttonClass == "btn btn-custom") { + return ; + } + + var we_can_save_form = check_before_saving() ; + + if (we_can_save_form) { + cancel_quote() ; + } else { + return ; + } + + }) ; + + function cancel_quote () { + + BootstrapDialog.confirm({ + title: 'Confirm Cancellation', + message: 'Are you sure you want to cancel this event?', + type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + callback: function(result) { + if (result) { + \$("#checkboxQuote_completed").prop("checked", false) ; + \$("#checkboxQuote_accepted").prop("checked", false) ; + \$("#checkboxQuote_pending").prop("checked", false) ; + \$("#checkboxQuote_rejected").prop("checked", false) ; + \$("#checkboxQuote_cancelled").prop("checked", true) ; + \$('#event_quotes-form').submit() ; + } + } + }); + } + + function check_before_saving () { + + $jquery_chosen_sel + + let st_val = \$("#selectSport_type_ids").chosen().val() ; + \$('#sport-type-ids').val(st_val) ; + + return 1 ; + } + + ~ ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'global' ; + our $lcpage = 'analytics-event-booking' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'analytics_event_bookings' ; + + our $cust_cols = 1 ; # display _blank_3.pm + our $savjqy = 1 ; + our $max_cams = 10 ; + + &common_min_add_box_icon ; + + our %casuals = (); + +} #------------------------------------------------------------------------------- + +sub report_ifields { + + if ($i{start_date_from} && $i{start_date_to}) { + push @report_sql, " (('$i{start_date_from}' <= start_date_time AND start_date_time <= '$i{start_date_to}') OR ('$i{start_date_from}' <= end_date_time AND end_date_time <= '$i{start_date_to}' AND end_date_time IS NOT NULL)) " ; + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + my $start_date_from = &common_min_date_as_string($i{start_date_from}) ; + my $start_date_to = &common_min_date_as_string($i{start_date_to}) ; + push @report_results, " (START DATE BETWEEN '$start_date_from' AND '$start_date_to') OR (END DATE BETWEEN '$start_date_from' AND '$start_date_to')" ; + } + + if ($i{country}) { + push @report_sql, "(q.country_id = '$i{country}')" ; + push @report_results, "country_id = `$i{country}`" ; + } + + if ($i{customer_name} && $i{customer_name} ne 'all') { + push @report_sql, "(q.client_id = '$i{customer_name}')" ; + &db_min_ro('customers','id,name',"`id`='$i{customer_name}'",'','') ; + push @report_results, "customer = `$db{customers}{$i{customer_name}}{name}`" ; + } + + if ($i{accepted} || $i{options} eq 'accepted') { + push @report_sql, "(q.event_accepted='1' AND q.event_completed<>'1')" ; + push @report_results, "event_accepted = `Yes`" ; + } + + if ($i{options} eq 'accepted') { + push @report_sql, "(q.event_accepted='1')" ; + push @report_results, "Event is Accepted" ; + } elsif ($i{options} eq 'completed') { + push @report_sql, "(q.event_completed='1')" ; + push @report_results, "Event is Completing" ; + } elsif ($i{options} eq 'pending') { + push @report_sql, "(q.event_pending='1')" ; + push @report_results, "Event is Pending" ; + } elsif ($i{options} eq 'cancelled') { + push @report_sql, "(q.event_cancelled='1' OR (q.event_expiry IS NOT NULL AND q.event_expiry<'$now_year-$now_mm-$now_dd' AND q.event_accepted<>'1'))" ; + push @report_results, "Event is Cancelled" ; + } elsif ($i{options} eq 'rejected') { + push @report_sql, "(q.event_rejected='1')" ; + push @report_results, "Event is Rejecting" ; + } + + $preferred_title{region_id} = "Region" ; + $preferred_title{city_id} = "City" ; + $preferred_title{organisation_ids} = "Venue" ; + $preferred_title{sport_type_ids} = "Sport Type" ; + + if ($i{sport_type_ids} && $i{sport_type_ids} ne 'all') { + &db_min_ro('sport_types',"id,name","id='$i{sport_type_ids}'",'','') ; + push @report_sql, "FIND_IN_SET($i{sport_type_ids},REPLACE(q.sport_type_ids,';',','))" ; + push @report_results, "sport_types INCLUDE `$db{sport_types}{$i{sport_type_ids}}{name}`" ; + } + + if ($usertype eq 'analytics_client') { + push @report_sql, "(q.client_id='$userid')" ; + } + + $report_results_msg = uc join(', ', @report_results) ; + + unless ($report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER) ; + &report_screen ; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + +} #------------------------------------------------------------------------------------------ + +sub report_screen { + + &filter_screen ; + +} #------------------------------------------------------------------------------- + +sub filter_screen { + + our $lcol = 2 ; + our $fcol = 5 ; + + my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-42) ; # 6 weeks back + + $set_month = sprintf("%02s", $set_month) ; + $set_day = sprintf("%02s", $set_day) ; + + my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + # $allow_deselect{customer_name} = 1 ; + $allow_deselect{options} = 1 ; + $allow_deselect{sport_type_ids} = 1 ; + + my $defualt_customer = 0 ; $defualt_customer = 5 if $usertype ne 'school_manager' ; + # &common_min_select_opts('customer_name','customers','name',$defualt_customer,'','',"events='1'") ; + &common_min_select_opts('customer_name','customers','name','','','',"analytics='1'") ; + $opts{customer_name} .= qq~~ ; + my $def_val = ($i{customer_name}) ? $i{customer_name} : "all" ; + $opts{customer_name} =~ s/value='$def_val'/value='$def_val' SELECTED/g ; + $print_box_content_rows .= &common_min_form_select('customer_name','') ; + + &common_min_select_opts('sport_type_ids','sport_types','name','','','','') ; + + $preferred_title{sport_type_ids} = "Sport Type" ; + + $allow_deselect{sport_type_ids} = 0 ; + + $opts{sport_type_ids} .= qq~~ ; + + $print_box_content_rows .= &common_min_form_select('sport_type_ids','') ; + + $preferred_title{event_from} = 'Event Date From' ; + + my $day_of_week = Day_of_Week($now_year,$now_mm,$now_dd) ; + + my ($def_s_year,$def_s_mm,$def_s_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,1-$day_of_week) ; + my ($def_e_year,$def_e_mm,$def_e_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,7-$day_of_week) ; + + $def_s_mm = sprintf("%02d",$def_s_mm) ; + $def_s_day = sprintf("%02d",$def_s_day) ; + $def_e_mm = sprintf("%02d",$def_e_mm) ; + $def_e_day = sprintf("%02d",$def_e_day) ; + + $i{start_date_from} = qq~$def_s_year-$def_s_mm-$def_s_day 00:00:00~ unless $i{start_date_from} ; + $i{start_date_to} = qq~$def_e_year-$def_e_mm-$def_e_day 23:59:59~ unless $i{start_date_to} ; + + $preferred_title{start_date_from} = "Event Date/Time From" ; + $preferred_title{start_date_to} = "Event Date/Time To" ; + + $print_box_content_rows .= &common_min_form_datetimepicker('start_date_from',$i{start_date_from},720) ; + $print_box_content_rows .= &common_min_form_datetimepicker('start_date_to',$i{start_date_to},720) ; + + # $opts{options} = qq~ + # + # + # + # + # + # + # ~ ; + + # $allow_deselect{options} = 0 ; + + # $print_box_content_rows .= &common_min_form_select('options','') ; + + + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + local $all_select_ids_string = join(",",@all_select_ids) ; + $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true });~ ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +use event_email ; +use analytics_event_booking_tabs ; +use common ; +use common_min ; +use common_shared ; +use today ; +use report ; +use xlsxcreator ; +use csv ; + +1 ; \ No newline at end of file diff --git a/scripts/analytics_eventbookings_test.pl b/scripts/_FromProd/v1.0/analytics_eventbookings_test.pl similarity index 100% rename from scripts/analytics_eventbookings_test.pl rename to scripts/_FromProd/v1.0/analytics_eventbookings_test.pl diff --git a/scripts/_FromProd/v1.0/archive.pl b/scripts/_FromProd/v1.0/archive.pl new file mode 100644 index 0000000..7a40658 --- /dev/null +++ b/scripts/_FromProd/v1.0/archive.pl @@ -0,0 +1,540 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use File::Find; +use File::Path 'rmtree'; +use File::Copy; +use File::Basename; +use MIME::Lite; +use Mail::Sendmail; +use Date::Calc qw(:all); + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +my ($q) = CGI -> new() ; +$iaction = $q -> param('iaction') || '' ; +$idelaction = $q -> param('idelaction') || '' ; +$izip = $q -> param('izip') || '' ; # quote-Sep-2016 + +if ($izip) { our ($ztype,$zmonth,$zyear) = split(/\-/,$izip) ; } + +unless ((lc $username eq 'vivian') or ($username eq 'rory')) { print "<<<<<<<<<<<<<<<< UNAUTHORIZED >>>>>>>>>>>>>>>" ; exit ; } +# unless ($username eq 'rory') { print "<<<<<<<<<<<<<<<< CLOSED FOR MAINTENANCE >>>>>>>>>>>>>>>" ; exit ; } + +my $uploadspath = "$htmlpath/uploads" ; +# my $uploadspath = "$htmlpath/uploads_test" ; +# my $archivezip = "$htmlpath/archives/uploads.zip" ; +my $archivezipdir = "$htmlpath/archives" ; + +# our $debug = 1 ; + +our $to = 'vivian@filmfreight.co.za' ; if ($debug) { $to = 'rory@kre8it.co.za' ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +&today; + +if ($iaction eq ''){ + &get_uploads ; + &server_usage ; + &display_screen1 ; + } + +if ($iaction eq 'zip'){ + &get_uploads ; + &delete_previous_zips ; + &archive_zip ; + &send_email ; + &update_sent ; + &server_usage ; + &display_screen1 ; + } + +if ($iaction eq 'deluploads'){ + &get_uploads ; + &delete_uploads ; + &server_usage ; + &display_screen1 ; + } + +exit ; + +#-------------------------------------------------------------------------------------------- + +sub get_uploads { + +&read_uploads_dir("$uploadspath") ; +# &read_uploads_dir("$uploadspath/journeys") ; +&process_uploads ; + +} #-------------------------------------------------------------------------------------------- + +sub update_sent { + +# if (-e $archivezip) { unlink $archivezip ; } + +unless ($izip) { return ; } + +$i{sent_to} = "$to" ; +$i{send_date} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; +&db_min_upd('uploads_backup',"`month`='$zmonth' AND `year`='$zyear' AND `type`='$ztype'") ; + +} #-------------------------------------------------------------------------------------------- + +sub read_uploads_dir { + +my ($path) = @_ ; + +opendir(DIR,"$path") or die "cant open directory: $path - $!\n"; + +while(defined($folder = readdir(DIR))) { + if (length $folder > 2) { + my ($file,$type) = split(/\./,$folder) ; + + # if ($folder eq 'journeys') { next ; } + + # print "
    $path" ; + + if (-d "$path/$folder"){ # check if directory + &read_uploads_dir_drill_1("$path/$folder") ; + } + + # $ff++; + # if ($ff == 50) { last ; } + } + } + +closedir(DIR) ; + +} #-------------------------------------------------------------------------------------------- + +sub read_uploads_dir_drill_1 { + +my ($path) = @_ ; + +# print "
    $path" ; + +opendir(DIR2, "$path") or die "cant open directory: $path - $!\n"; + +while (defined($folder2 = readdir(DIR2))) { + + if (length $folder2 > 2) { + my ($file,$type) = split(/\./,$folder2) ; + my @file_attributes = stat ("$path/$folder2") ; + my $file_modified_time_readable = localtime ($file_attributes[9]) ; + + # print "
    $folder2 : $file_modified_time_readable" ; + + my @file_name = split(/\_/,$folder2) ; + my @date_data = split(/ /,$file_modified_time_readable) ; + my $year = substr($file_modified_time_readable,-4,4) ; + + if ($izip) { + if (($year eq $zyear) and ($zmonth eq $date_data[1]) and ($ztype eq $file_name[0])) { + push @zip_file_arr, "$path/$folder2" ; + } + } + + # $files_to_zip_hash{$file_name[0]}{$date_data[4]}{$date_data[1]}++ ; + $files_to_zip_hash{$file_name[0]}{$year}{$date_data[1]}++ ; + + # for (1 .. 30) { + # if ($file_attributes[$_]) { print ', ' . $_ . '.' . $file_attributes[$_] ; } + # } + } + } + +closedir(DIR2) ; + +} #-------------------------------------------------------------------------------------------- + +sub process_uploads { + +&db_min_ro('uploads_backup','*','','','') ; + +foreach my $id (sort {$db{uploads_backup}{$a}{year} cmp $db{uploads_backup}{$b}{year}} keys %{$db{uploads_backup}}) { + my $send_date = $db{uploads_backup}{$id}{send_date} ; + my $sent_to = $db{uploads_backup}{$id}{sent_to} ; + my $bak_count = $db{uploads_backup}{$id}{count} ; + my $bak_year = $db{uploads_backup}{$id}{year} ; + my $bak_month = $db{uploads_backup}{$id}{month} ; + my $bak_type = $db{uploads_backup}{$id}{type} ; my $ucf_bak_type = ucfirst $bak_type ; + $db_entry_exists{$bak_year}{$bak_month}{$bak_type} = $bak_count ; + $sent{$bak_year}{$bak_month}{$bak_type} = $sent_to ; + + my $print_sent_to = '' ; if ($sent_to) { $print_sent_to = qq(sent to $sent_to ($send_date)) ; } + + my $selected = '' ; if ($izip eq "$bak_type-$bak_month-$bak_year") { $selected = 'SELECTED' ; } + + if ($bak_type eq 'pod') { next ; } + if ($bak_type eq 'vat') { next ; } + + $opts{zip} .= qq() ; + } + +foreach my $type (keys %files_to_zip_hash) { + foreach my $year (keys %{$files_to_zip_hash{$type}}) { + foreach my $month (keys %{$files_to_zip_hash{$type}{$year}}) { + # print "$type $month $year [$files_to_zip_hash{$type}{$year}{$month}] \n" ; + + %i = () ; + + if ($db_entry_exists{$year}{$month}{$type}) { + unless ($db_entry_exists{$year}{$month}{$type} == $files_to_zip_hash{$type}{$year}{$month}) { + $i{count} = "$files_to_zip_hash{$type}{$year}{$month}" ; + $i{sent_to} = '' ; + &db_min_upd('uploads_backup',"`month`='$month' AND `year`='$year' AND `type`='$type'") ; + } + } + else + { + $i{month} = "$month" ; + $i{type} = "$type" ; + $i{year} = "$year" ; + $i{count} = "$files_to_zip_hash{$type}{$year}{$month}" ; + $i{sent_to} = '' ; + &db_min_insert('uploads_backup') ; + my $ucf_type = ucfirst $type ; + $opts{zip} .= qq() ; + } + + } + } + } + +$archivezip = "$htmlpath/archives/$izip.zip" ; + +our $g_archiveziplink = $archivezip ; $g_archiveziplink =~ s/\/var\/www\/html/https:\/\/www.ffwaybill.co.za/gi ; +our $g_archivezipname = $archivezip ; $g_archivezipname =~ s/\/var\/www\/html//gi ; +our $g_zip_link = qq(DOWNLOAD NOW as it will be deleted if older than a week : $g_archivezipname
    ); + +} #-------------------------------------------------------------------------------------------- + +sub delete_uploads { + +# CHECK ZIP EXISTS THEN OPEN DOWNLOAD LINK AFTER DELETE + +unless (-e $archivezip) { + $alert = qq() ; + return ; + } + +# our $download_zip_after_delete = qq( +# \$(function () { + # window.open("$archiveziplink") +# }); +# ); + +our $download_zip_after_delete = qq( +\$(document).ready(function(){ \$('#open-zip').submit(); }) +); + +my $sent_to = $sent{$zyear}{$zmonth}{$ztype} ; + +unless ($sent_to) { + $alert = qq() ; + return ; + } + +my $deleted = '' ; + +foreach my $filepath (@zip_file_arr) { + # print "unlink $filepath \n" ; + $files_affected .= qq(delete $filepath
    ) ; + unlink ($filepath) ; $deleted = 1 ; + } + +if ($deleted) { + $i{delete_date} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + &db_min_upd('uploads_backup',"`month`='$zmonth' AND `year`='$zyear' AND `type`='$ztype'") ; + } + +$alert = qq() ; + +} #-------------------------------------------------------------------------------------------- + +sub archive_zip { + +use Archive::Zip; +use Archive::Zip::Tree ; + +$archivezip = "$htmlpath/archives/$izip.zip" ; + +if (-e $archivezip) { unlink $archivezip ; } + +my $zip = Archive::Zip->new() ; + +foreach my $filepath (@zip_file_arr) { + # print "$filepath \n" ; + $zip->addTree($filepath,''); + + # my $link = $filepath ; $link =~ s/\\var\\www\\html/https:\/\/www.ffwaybill.co.za/gi ; $link =~ s/\\/\//gi ; + my $name = $filepath ; $name =~ s/\/var\/www\/html//gi ; + my $link = $filepath ; $link =~ s/\/var\/www\/html/https:\/\/www.ffwaybill.co.za/gi ; + $c++; + $emsg .= qq( $c  $name  +) ; + $files_affected .= qq(zipped $name
    ) ; + } + +my $archivezipname = $archivezip ; $archivezipname =~ s/\/var\/www\/html//gi ; +my $archiveziplink = $archivezip ; $archiveziplink =~ s/\/var\/www\/html/https:\/\/www.ffwaybill.co.za/gi ; + +$zip_link = qq(  Download ZIP now as it will be deleted : $archivezipname ); + +$zip->writeToFileNamed($archivezip) ; # or die "could not execute : $!" ; + +if (-e $archivezip) { + $alert = qq() ; + } +else + { + $alert = qq() ; + } + +} #-------------------------------------------------------------------------------------------- + +sub delete_previous_zips { + +opendir(DIR, "$archivezipdir") or die "cant open Directory $archivezipdir: $!\n"; + +while(defined($folder = readdir(DIR))) { + if (length $folder > 2) { + my ($file,$type) = split(/\./,$folder) ; + #only delete if more than a week old + + my ($chk_year,$chk_month,$chk_day,$chk_hour,$chk_min,$chk_sec) = Add_Delta_DHMS($now_year,$now_mm,$now_dd,$now_hour,$now_min,$now_sec,-7,0,0,0); # check n days back + + $chk_month = sprintf("%02s", $chk_month) ; + $chk_day = sprintf("%02s", $chk_day) ; + + my @file_attributes = stat ("$archivezipdir/$file.zip") ; + # my $file_modified_time_readable = localtime ($file_attributes[9]) ; + + ($file_sec,$file_min,$file_hour,$file_dd,$file_mm,$file_year,$file_wday,$file_yday,$isdst)=localtime($file_attributes[9]); + + $file_year += 1900; + + $file_dd = sprintf("%02s", $file_dd) ; + $file_mm = sprintf("%02s", $file_mm + 1) ; + + $file_ccyymmdd = $file_year . $file_mm . $file_dd ; + + if ("$file_ccyymmdd" < "$chk_year$chk_month$chk_day") { + unlink ("$archivezipdir/$file.zip") or print "unable to unlink - $archivezipdir/$folder : $!"; + # print "unlink - $archivezipdir/$folder"; + } + } + } + +closedir(DIR) ; + +} #------------------------------------------------------------------------------------ + +sub archive_unzip { + +# my ($uploadpath,$uploadfile) = @_ ; + +# use Archive::Extract; + +# $ae = Archive::Extract->new(archive => "$uploadpath/$uploadfile.zip") ; +# $ae->extract( to => "$uploadpath"); + +} #-------------------------------------------------------------------------------------------- + +sub server_usage { + +my $size = 0; +find( sub { $size += -f $_ ? -s _ : 0 }, "$htmlpath" ); + +$size = $size / 1000000 ; # convert to MB +$serverspace = 19000 ; # MB (19.00 GB) +$usage = sprintf("%.2f",($size / $serverspace * 100)) ; # % + +if ($alert) { return ; } + +if ($usage > 90) { + $alert = qq() ; + } +elsif ($usage > 80) { + $alert = qq() ; + } +else + { + $alert = qq() ; + } + +} #-------------------------------------------------------------------------------------------- + +sub display_screen1 { + +if ($files_affected) { + $print_files_affected = qq(
    +
    +
    +
    +

    Files

    +
    +
    +
     
    +
    +
    + $g_zip_link + $files_affected +
    +
    +
     
    +
    +
    +
    +
    ); + } + +$print_usage = qq(
    +
    +
    +
    +

    Server Usage

    +
    +
    +
     
    +
    +
    +
    +
    + $usage\% +
    +
    +
    +
    +
    +
    +
    +
    +
     
    +
    +
    +
    +
    +

    Backup Option

    +
    +
    +
     
    +
    +
    +
    +
    + +
    +
    +
    +
    +
     
    +
    +
    +
    +
    +
     
    + $print_files_affected) ; + +$print_buttons = qq( + ) ; + +&screen1 ; + +} #------------------------------------------------------------------------------------------ + +sub screen1 { + +require archive ; + +exit; + +} #------------------------------------------------------------------------------------------ + +sub send_email { + +$msg = MIME::Lite -> new( + From => 'Film Freight ', + To => $to, + Subject => "FF Backup : $izip : $now_year-$now_mm-$now_dd", + Type => 'multipart/mixed' +); + +# my $boundary = "====" . time() . "===="; + +my $email_body = < + + + + + + + + + + +
    + +Film Freight +

    + + + + + $zip_link + $emsg + +
     Link
    + +

    +
    + + +END_OF_BODY + +$msg -> attach( + Type => 'text/html', + Data => $email_body +); + +# $msg -> attach ( + # Type => 'AUTO', + # Path => "$archivezip", + # Filename => "$izip.zip", + # Disposition => 'attachment' + # ) or die "Error adding $path : $attach $!\n"; + +$msg -> send ('smtp','localhost', Debug=>0 ); + +} #------------------------------------------------------------------------------- + +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/audit_trial.pl b/scripts/_FromProd/v1.0/audit_trial.pl similarity index 100% rename from scripts/audit_trial.pl rename to scripts/_FromProd/v1.0/audit_trial.pl diff --git a/scripts/_FromProd/v1.0/bank_transactions_report.pl b/scripts/_FromProd/v1.0/bank_transactions_report.pl new file mode 100644 index 0000000..928e317 --- /dev/null +++ b/scripts/_FromProd/v1.0/bank_transactions_report.pl @@ -0,0 +1,406 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +# unless ($useropts{it}{$username}) { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +# use Excel::Writer::XLSX; + +use Time::Piece; +use Time::Seconds; + +# my $start_time_str = "09:30:00" ; +# my $end_time_str = "17:45:00" ; + +# Create Time::Piece objects for start and end times +# my $start_time = Time::Piece->strptime($start_time_str, "%H:%M:%S"); +# my $end_time = Time::Piece->strptime($end_time_str, "%H:%M:%S"); + +# Calculate the difference in seconds and convert to hours +# my $time_diff_in_hours = (Time::Piece->strptime($end_time_str,"%H:%M:%S") - Time::Piece->strptime($start_time_str,"%H:%M:%S")) / ONE_HOUR; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $open_new_tab = qq~target="_blank"~ ; + +# our $debug = 1 ; our $testing = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $srchscr = 1 ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &report_screen if $iaction eq '' ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +# Create table bank_transaction_categories ( + # id int(5) not null, + # name varchar(100) not null, + # PRIMARY key(id) +# ) + +# create table bank_transactions ( + # id int(10) not null, + # date_time datetime not null, + # transaction_date date not null, + # amount decimal(13,2) default '0.00', + # balance decimal(13,2) default '0.00', + # decription varchar(100) not null, + # account_nr varchar(25) not null, + # category_id int(5) default '0', + # client_id int(10) default '0'. + # invoice_nr varchar(25) not null, + # PRIMARY KEY(id) +# ) + +# if ($iaction eq 'report') { + # &common_min_load_params ; + # &db_open_ro ; + # our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + # &report_ifields ; + # &list_screen ; + # $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + # &db_close_conn ; + # &screen3 ; +# } + +# if ($iaction eq 'save') { + # &common_min_load_params ; + # &db_open_upd ; + # our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + # &update ; + # $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + # &db_close_conn ; + # exit if $username eq 'rory' && $testing ; + # &screen4 ; +# } + +# &common_min_action; + +exit ; + +#------------------------------------------------------------------------------------------ + +# sub update { + + +# } #------------------------------------------------------------------------------------------ + +# sub report_ifields { + + # if ($i{month}) { + # my ($year_input,$month_input) = split(/\-/,$i{month}) ; + # my @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + # push @report_results, "(TRANSACTION DATE IN '$months[$month_input] $year_input')" ; + # push @report_sql, "(transaction_date LIKE '%$i{month}%')" ; + # } + + # $report_results_msg = uc join(', ',@report_results) ; + + # if (not $report_results_msg) { + # } else { + # $isaved = qq(SELECT WHERE $report_results_msg) ; + # } + +# } #------------------------------------------------------------------------------------------ + +# sub list_screen { + + # $print_box_content_rows .= &common_min_forms_start('bank-transactions') ; + + # my $srch_where_sql = join(' AND ', @report_sql) ; + # my $srch_where_sql_2 = join(' AND ', @report_sql_2) ; + + # &load_list_vars("$srch_where_sql","$srch_where_sql_2") ; + + # my ($year_input,$month_input) = split(/\-/,$i{month}) ; + # my @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + # our $xlsxheading = "$months[$month_input] $year_input" ; + # &report_xlsx_export_header("Bank Transactions",'bank_transactions') ; + + # $xlsxrow = 2 ; + + # $xlsxcol = 0 ; + # foreach my $dc (sort { $b cmp $a } keys %bank_transaction_categories) { + # &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,uc $dc,$format117) ; + # $xlsxrow++ ; + # foreach my $cat_id (sort { $bank_transaction_categories{$dc}{$a} cmp $bank_transaction_categories{$dc}{$b} } keys %{$bank_transaction_categories{$dc}}) { + # next if $cat_id == 27 ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$db{bank_transaction_categories}{$cat_id}{name},$format118) ; + # $xlsxrow++ ; + # my $start_row = $xlsxrow ; + # foreach my $trans_id (keys %{$transactions_by_category{$cat_id}}) { + # &xlsxcreator_write_xlsx($ws,$xlsxrow,0,"",$format1) ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,1,substr($db{$table}{$trans_id}{transaction_date},8,2) . "/" . substr($db{$table}{$trans_id}{transaction_date},5,2) . "/" . substr($db{$table}{$trans_id}{transaction_date},0,4),$format1) ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,2,"",$format1) ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,3,$db{$table}{$trans_id}{amount},$format120) ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,4,$db{$table}{$trans_id}{description},$format1) ; + # $xlsxrow++ ; + # } + # $xlsxrow++ ; + # &xlsxcreator_write_formula($ws,$xlsxrow,3,"=SUM(D$start_row:D$xlsxrow)",$format119) ; + # $xlsxrow++ ; + # } + # } + + # my $cat_id = 27 ; + + # for (0 .. 5) { + # &xlsxcreator_write_xlsx($ws,$xlsxrow,$_," ",$format121) ; + # } + + # my $start_row = $xlsxrow ; + + # $xlsxrow++ ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$db{bank_transaction_categories}{$cat_id}{name},$format118) ; + # $xlsxrow++ ; + # my $start_row = $xlsxrow ; + # foreach my $trans_id (keys %{$transactions_by_category{$cat_id}}) { + # &xlsxcreator_write_xlsx($ws,$xlsxrow,0,"",$format1) ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,1,substr($db{$table}{$trans_id}{transaction_date},8,2) . "/" . substr($db{$table}{$trans_id}{transaction_date},5,2) . "/" . substr($db{$table}{$trans_id}{transaction_date},0,4),$format1) ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,2,"",$format1) ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,3,$db{$table}{$trans_id}{amount},$format120) ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,4,$db{$table}{$trans_id}{description},$format1) ; + # $xlsxrow++ ; + # } + # $xlsxrow++ ; + # &xlsxcreator_write_formula($ws,$xlsxrow,3,"=SUM(D$start_row:D$xlsxrow)",$format119) ; + # $xlsxrow++ ; + + # for (0 .. 5) { + # &xlsxcreator_write_xlsx($ws,$xlsxrow,$_," ",$format121) ; + # } + + # for ($start_row - 1 .. $xlsxrow) { + # &xlsxcreator_write_xlsx($ws,$_,6," ",$format122) ; + # } + + # $worksheet{$ws}->set_column(1,3,20) ; + # $worksheet{$ws}->set_column(4,5,30) ; + # &report_xlsx_export_footer('F',15,'bank_transactions') ; + +# } #------------------------------------------------------------------------------------------ + +# sub load_list_vars { + + # my ($where,$where_2) = @_ ; + + # &db_min_ro($table,"*","$where",'','') ; + + # our %transactions_by_category = () ; + + # foreach (keys %{$db{$table}}) { + # $transactions_by_category{$db{$table}{$_}{category_id}}{$_} = 1 ; + # } + + # &db_min_ro('bank_transaction_categories',"*","",'','') ; + + # our %bank_transaction_categories = () ; + + # foreach (keys %{$db{bank_transaction_categories}}) { + + # if ($db{bank_transaction_categories}{$_}{income_source}) { + # $bank_transaction_categories{income}{$_} = $db{bank_transaction_categories}{$_}{name} ; + # } else { + # $bank_transaction_categories{expenses}{$_} = $db{bank_transaction_categories}{$_}{name} ; + # } + # } + +# } #------------------------------------------------------------------------------------------ + +# sub get_events_with_other_costs { + + # my ($where) = @_ ; + +# } #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + our $lcpage = 'bank-transactions-report' ; + + &common_page_name ; + + our $table = 'bank_transactions' ; + $page_title = 'Bank Transactions' ; + + $box_icon .= qq~ +
    + + + +
    +
    + + + +
    +
    + + + +
    + ~ ; + + $trigger_jquery_raw .= qq~ + function importDoc(t,b,a) { + let script = (a == 1) ? "import_bank_trans" : (a ==2) ? "import_bank_trans_cat" : "" ; + dlgMdl("$useropts{'scripts'}/dialog/"+script+".pl?"+t+"&"+b,"Import CSV",'','max-dialog') ; + } + + function build_excel(a,b,c) { + let script = "get_bank_transactions" ; + dlgMdl("$useropts{'scripts'}/dialog/"+script+".pl?"+a+"&"+b+"&"+c,"Get Bank Transactions",'','max-dialog') ; + } + ~; + + $trigger_jquery_raw .= qq~ + console.log("Hello World") ; + \$('#datetimepickerDate_from,#datetimepickerDate_to').on('changeDate', function(e) { + \$("#build_excel_button").html("") ; + }) ; + ~ ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + our $lcol = 1 ; + our $fcol = 3 ; + + # $print_box_content_rows .= &common_min_forms_start('report') ; + + my $event_na_exists = 0 ; my $events_exists = 0 ; my %selected = () ; + + # &get_events_with_other_costs ; + + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-01-01") ; + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$now_dd") ; + + # $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +# sub screen3 { + +# &thead; + +# if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# # my $page = "$lcpage\s" ; + +# my $page = "event-quotes" ; + +# if ($s{no}) { $page = $lcpage ; } + +# &common_min_table('id',$page,'list') ; + +# our $savjqy = 1 ; + +# # &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ; + +# $extra_form_fields .= qq~ + # + # + # + # + # + # +# ~ ; + +# $trigger_jquery_raw .= qq~ + # \$("#savebutt").click( function () { + # \$("#bank-transactions-form").submit() ; + # }) ; +# ~ ; + +# $print_box_content_rows .= &common_min_forms_end('','','save') ; + +# require _blank ; + +# exit ; + +# } #------------------------------------------------------------------------------------------ + +# sub screen4 { + +# &common_min_alert_type ; + +# print < +# +# + # + # $useropts{title} + # +# +# +# +# + +#
    + # + # + # + # + # + # + # + # +#
    + +# +# endoftext + + +# exit ; + +# } #------------------------------------------------------------------------------------------ + +use common ; +use report ; +use xlsxcreator ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/calendar.pl b/scripts/_FromProd/v1.0/calendar.pl new file mode 100644 index 0000000..d0a862d --- /dev/null +++ b/scripts/_FromProd/v1.0/calendar.pl @@ -0,0 +1,73 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +&today ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); + +print "Content-type: text/html\n\n"; + +$title = ucfirst $username; + +&screen1 ; + +#------------------------------------------------------------------------------------------ + +sub screen1 { + +$fullcalendar_events = qq(\$(document).ready(function() { + \$('#calendar').fullCalendar({ + header: { + left: 'prev,next today', + center: 'title', + right: 'month,agendaWeek,agendaDay' + }, + defaultDate: '$now_year-$now_mm-$now_dd', + // defaultView: 'basicDay', + editable: false, + eventLimit: true, // allow "more" link when too many events + events: { + url: '$useropts{'scripts'}/get/get_db_cal_events.pl', + error: function() { + \$('#script-warning').show(); + } + }, + loading: function(bool) { + \$('#loading').toggle(bool); + } + }); + + }); + ); + +# $useropts{'common'}{'css'} = qq(table a:not(.btn), .table a:not(.btn) { + # /* text-decoration: underline; */ +# }); + +# $trigger_jquery = qq(window.setTimeout(function(){location.reload();},300000);); # 300000=5min, 600000=10min, 900000=15min, 10000=10sec + +$useropts{'common'}{'css'} .= qq(table a:not(.btn), .table a:not(.btn) { text-decoration: none; }) ; + +if ($useropts{super}{lc $username}){ + $box_icon = qq(
    + + + +
    ) ; + } + +require calendar ; + +exit; + +} #------------------------------------------------------------------------------------------ + +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/calendar_test.pl b/scripts/_FromProd/v1.0/calendar_test.pl new file mode 100644 index 0000000..d93bc3f --- /dev/null +++ b/scripts/_FromProd/v1.0/calendar_test.pl @@ -0,0 +1,73 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +&today ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); + +print "Content-type: text/html\n\n"; + +$title = ucfirst $username; + +&screen1 ; + +#------------------------------------------------------------------------------------------ + +sub screen1 { + +$fullcalendar_events = qq(\$(document).ready(function() { + \$('#calendar').fullCalendar({ + header: { + left: 'prev,next today', + center: 'title', + right: 'month,agendaWeek,agendaDay' + }, + defaultDate: '$now_year-$now_mm-$now_dd', + // defaultView: 'basicDay', + editable: false, + eventLimit: true, // allow "more" link when too many events + events: { + url: '$useropts{'scripts'}/get/get_db_cal_events_test2.pl', + error: function() { + \$('#script-warning').show(); + } + }, + loading: function(bool) { + \$('#loading').toggle(bool); + } + }); + + }); + ); + +# $useropts{'common'}{'css'} = qq(table a:not(.btn), .table a:not(.btn) { + # /* text-decoration: underline; */ +# }); + +# $trigger_jquery = qq(window.setTimeout(function(){location.reload();},300000);); # 300000=5min, 600000=10min, 900000=15min, 10000=10sec + +$useropts{'common'}{'css'} .= qq(table a:not(.btn), .table a:not(.btn) { text-decoration: none; }) ; + +if ($useropts{super}{lc $username}){ + $box_icon = qq(
    + + + +
    ) ; + } + +require calendar ; + +exit; + +} #------------------------------------------------------------------------------------------ + +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/calibration_report.pl b/scripts/_FromProd/v1.0/calibration_report.pl new file mode 100644 index 0000000..0ddcc9e --- /dev/null +++ b/scripts/_FromProd/v1.0/calibration_report.pl @@ -0,0 +1,722 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +# unless ($useropts{it}{$username}) { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; +use Time::Piece ; +use Image::Size; +use Image::Magick; +use File::Temp qw(tempfile); + +&today; + +# $now_ccyymmdd = "20250321" ; +# $now_dd = "21" ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; +# our $testing = 1 ; + +# if ($username ne 'handre') { + # print "<< MAINTENANCE IN PROGRESS >>" ; exit ; +# } + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $srchscr = 1 ; + + +if ($iaction eq 'save') { + &db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &common_min_load_params ; + &report_ifields; + &update ; + # &list_screen ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + exit if $testing ; + # &screen3; + &redirect_screen; +} + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &report_screen if $iaction eq '' ; + + if ($iaction eq 'report') { + &common_min_load_params ; + &report_ifields; + &list_screen ; + &screen3; + } + + &common_min_action; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + +} #------------------------------------------------------------------------------------------ + +sub insert { + +} #------------------------------------------------------------------------------------------ + +sub update { + + my %seen_event_id = () ; + + foreach (keys %i) { + next if $_ !~ /^update_/ || ($_ =~ /^update_/ && !$i{$_}) ; + local @abc = split("_",$_) ; + $seen_event_id{$abc[-3]} = 1 ; + } + + local $e_q_sql = join (" OR ",map { "id='$_'" } keys %seen_event_id) ; + + &db_min_ro($table,'id,event_system_id_multiple,date_from,date_to,event_system_calibration_ids,event_system_calibration_status',"$e_q_sql",'','') ; + + $e_q_sql =~ s/id/event_quote_id/g ; + + &db_min_ro('calibration_status_report','event_quote_id,id,calibration_done,request_sent',"$e_q_sql",'','') ; + + my %update_calibration_status_report = () ; + foreach (keys %{$db{calibration_status_report}}) { + $update_calibration_status_report{$_} = 1 ; + } + + my %ii = () ; my %iii = %i ; + + my %calibration_done_by_system = () ; my %calibration_ids_hash = () ; my %calibration_status_hash = () ; my %request_sent_hash = () ; + + foreach my $event_id (keys %seen_event_id) { + + my @event_system_ids = split(/\;/,$db{$table}{$event_id}{event_system_id_multiple}) ; + + my @calibration_ids = split(/\;/,$db{$table}{$event_id}{event_system_calibration_ids}) ; + my @event_system_calibration_status = split(/\;/,$db{$table}{$event_id}{event_system_calibration_status}) ; + + my @calibration_done_arr = split(/\|/,$db{calibration_status_report}{$event_id}{calibration_done}) ; + my @request_sent_arr = split(/\|/,$db{calibration_status_report}{$event_id}{request_sent}) ; + + my $system_cnt = 0 ; + + foreach (@event_system_ids) { + $system_cnt++ ; + $calibration_ids_hash{cnt}{$event_id}{$_} = $system_cnt ; + $calibration_status_hash{cnt}{$event_id}{$_} = $system_cnt ; + $calibration_done_by_system{cnt}{$event_id}{$_} = $system_cnt ; + $request_sent_hash{cnt}{$event_id}{$_} = $system_cnt ; + } + + $system_cnt = 0 ; + + foreach my $system_data (@calibration_ids) { + $system_cnt++ ; + next unless $system_data ; + if ($system_data =~ /~/) { + ($system_id,$system_data) = split(/\~/,$system_data) ; + } else { + $system_id = $event_system_ids[$system_cnt - 1] ; + } + next unless $calibration_ids_hash{cnt}{$event_id}{$system_id} ; + my $day_cnt = 0 ; + foreach my $daily_data (split(/\-/,$system_data)) { + $day_cnt++ ; + $ii{$event_id}{$system_id}{$day_cnt}{calibrator_id} = $daily_data ; + } + } + + $system_cnt = 0 ; + + foreach my $system_data (@event_system_calibration_status) { + $system_cnt++ ; + next unless $system_data ; + if ($system_data =~ /~/) { + ($system_id,$system_data) = split(/\~/,$system_data) ; + } else { + $system_id = $event_system_ids[$system_cnt - 1] ; + } + + next unless $calibration_status_hash{cnt}{$event_id}{$system_id} ; + $calibration_status_hash{data}{$event_id}{$system_id} = $system_data ; + my $day_cnt = 0 ; + foreach my $daily_data (split(/\-/,$system_data)) { + $day_cnt++ ; + $ii{$event_id}{$system_id}{$day_cnt}{calibration_status} = $daily_data ; + } + } + + $system_cnt = 0 ; + + foreach my $system_data (@calibration_done_arr) { + $system_cnt++ ; + next unless $system_data ; + my $system_id = 0 ; + my ($system_id,$system_data) = split(/\~/,$system_data) ; + next unless $calibration_done_by_system{cnt}{$event_id}{$system_id} ; + $calibration_done_by_system{data}{$event_id}{$system_id} = $system_data ; + } + + $system_cnt = 0 ; + + foreach my $system_data (@request_sent_arr) { + $system_cnt++ ; + next unless $system_data ; + my ($system_id,$system_data) = split(/\~/,$system_data) ; + next unless $request_sent_hash{cnt}{$event_id}{$system_id} ; + my $day_cnt = 0 ; + foreach my $daily_data (split(/\;/,$system_data)) { + $day_cnt++ ; + $ii{$event_id}{$system_id}{$day_cnt}{request_sent} = $daily_data ; + } + } + + } + + my @col_name = ("calibration_status","calibrator_id","request_sent") ; + + foreach (keys %i) { + + local @a = split(/\_/,$_) ; + + my $upd_field = "update_$a[-3]\_$a[-2]\_$a[-1]" ; + next unless $i{$upd_field} ; + + if (substr($_,0,19) eq 'calibration_status_') { + $ii{$a[-3]}{$a[-2]}{$a[-1]}{calibration_status} = $i{$_} ; + } elsif (substr($_,0,14) eq 'calibrator_id_') { + $ii{$a[-3]}{$a[-2]}{$a[-1]}{calibrator_id} = $i{$_} ; + } elsif (substr($_,0,13) eq 'request_sent_') { + $ii{$a[-3]}{$a[-2]}{$a[-1]}{request_sent} = $i{$_} ; + } elsif (substr($_,0,14) eq 'head_operator_') { + # $ii{$a[-3]}{$a[-2]}{$a[-1]}{head_operator} = $i{$_} ; + } + } + + my %iii = %i ; + + my %iv = () ; + + my $calid_field = 'event_system_calibration_ids' ; + my $calstatus_field = 'event_system_calibration_status' ; + my $request_field = 'request_sent' ; + + foreach my $event_id (keys %ii) { + + %i = () ; %iv = () ; + + my $use_system_id_not_count = 0 ; + + my @ed_from = &common_split_sql_time($db{$table}{$event_id}{date_from}) ; + my @ed_to = &common_split_sql_time($db{$table}{$event_id}{date_to}) ; + + &common_date_array("$ed_from[0]$ed_from[1]$ed_from[2]","$ed_to[0]$ed_to[1]$ed_to[2]") ; + + $sys_cnt = 0; + foreach my $system_id (sort { $request_sent_hash{cnt}{$event_id}{$a} <=> $request_sent_hash{cnt}{$event_id}{$b} } keys %{$request_sent_hash{cnt}{$event_id}}) { + + my $line = qq~~ ; my $sys_day = 0 ; + foreach my $_date (@common_date_array) { + $sys_day++; + # my $upd_field = "update_$event_id\_$system_id\_$sys_day" ; + # $iv{$request_field} .= ($ii{$event_id}{$system_id}{$sys_day}{request_sent}) ? "$ii{$event_id}{$system_id}{$sys_day}{request_sent}-" : ($request_sent_arr[$sys_day-1] && !$iii{$upd_field}) ? "$request_sent_arr[$sys_day-1]-" : '-' ; + $line .= "$ii{$event_id}{$system_id}{$sys_day}{request_sent};" ; + + } + $line =~ s/;+$// ; + + $iv{$request_field} .= qq~$system_id\~$line~ if $line ; + $iv{$request_field} .= qq~|~ ; + + } + $iv{$request_field} =~ s/\|+$// ; + + $sys_cnt = 0 ; + + foreach my $system_id (sort { $calibration_ids_hash{cnt}{$event_id}{$a} <=> $calibration_ids_hash{cnt}{$event_id}{$b} } keys %{$calibration_ids_hash{cnt}{$event_id}}) { + + $sys_cnt++ ; + + my $sys_day = 0 ; + + my $line = qq~~ ; + + foreach my $_date (@common_date_array) { + $sys_day++; + # my $upd_field = "update_$event_id\_$system_id\_$sys_day" ; + # $line .= ($ii{$event_id}{$system_id}{$sys_day}{calibrator_id}) ? "$ii{$event_id}{$system_id}{$sys_day}{calibrator_id}-" : ($calibrator_ids_per_event_day[$sys_day-1] && !$iii{$upd_field}) ? "$calibrator_ids_per_event_day[$sys_day-1]-" : '-' ; + $line .= "$ii{$event_id}{$system_id}{$sys_day}{calibrator_id}-" ; + # print "\n calibrator_id ($event_id,$system_id,$sys_day) : $ii{$event_id}{$system_id}{$sys_day}{calibrator_id}" ; + } + $line =~ s/-+$// ; + $i{$calid_field} .= qq~$system_id\~$line~ if $line ; + $i{$calid_field} .= qq~;~ ; + } + $i{$calid_field} =~ s/;+$// ; + + $sys_cnt = 0; + + foreach my $system_id (sort { $calibration_status_hash{cnt}{$event_id}{$a} <=> $calibration_status_hash{cnt}{$event_id}{$b} } keys %{$calibration_status_hash{cnt}{$event_id}}) { + + $sys_cnt++ ; + + my @calibrator_statuses_per_event_day = split(/\-/,$calibration_status_hash{data}{$event_id}{$system_id}) ; + + my $sys_day = 0 ; + + my $calibration_done_str = qq~~ ; + + my @calibration_done_arr = split(/\;/,$calibration_done_by_system{data}{$event_id}{$system_id}) ; + + my $line = qq~~ ; + + # $i{$calstatus_field} .= qq~$system_id\~~ ; + + foreach my $_date (@common_date_array) { + $sys_day++; + my $upd_field = "update_$event_id\_$system_id\_$sys_day" ; + # $line .= ($ii{$event_id}{$system_id}{$sys_day}{calibration_status}) ? "$ii{$event_id}{$system_id}{$sys_day}{calibration_status}-" : ($calibrator_statuses_per_event_day[$sys_day-1] && !$iii{$upd_field}) ? "$calibrator_statuses_per_event_day[$sys_day-1]-" : '-' ; + $line .= "$ii{$event_id}{$system_id}{$sys_day}{calibration_status}-" ; + $calibration_done_str .= ($iii{$upd_field} && $ii{$event_id}{$system_id}{$sys_day}{calibration_status} eq '3' && $calibrator_statuses_per_event_day[$sys_day-1] ne '3') ? qq~$now_year-$now_mm-$now_dd $now_hour:$now_min:$now_sec;~ : ($iii{$upd_field} && $ii{$event_id}{$system_id}{$sys_day}{calibration_status} ne '3') ? qq~;~ : qq~$calibration_done_arr[$sys_day - 1];~ ; + } + + $line =~ s/\-+$// ; + + $i{$calstatus_field} .= qq~$system_id\~$line~ if $line ; + $i{$calstatus_field} .= qq~;~ ; + + $calibration_done_str =~ s/;+$// ; + + $iv{calibration_done} .= qq~$system_id\~$calibration_done_str~ if $calibration_done_str ; + $iv{calibration_done} .= qq~|~ ; + + } + + $i{$calstatus_field} =~ s/;+$// ; + + $iv{calibration_done} =~ s/\|+$// ; + + $ignore{$calid_field} = (!$i{$calid_field} && !$db{$table}{$event_id}{$calid_field} || ($i{$calid_field} eq $db{$table}{$event_id}{$calid_field})) ? 1 : 0 ; + $ignore{$calstatus_field} = ((!$i{$calstatus_field} && !$db{$table}{$event_id}{$calstatus_field}) || ($i{$calstatus_field} eq $db{$table}{$event_id}{$calstatus_field})) ? 1 : 0 ; + + &db_min_upd($table,"`id`='$event_id'") if !$ignore{$calid_field} || !$ignore{$calstatus_field} ; + + %i = %iv ; + + $ignore{$request_field} = ((!$i{$request_field} && !$db{calibration_status_report}{$event_id}{$request_field}) || ($i{$request_field} eq $db{calibration_status_report}{$event_id}{$request_field})) ? 1 : 0 ; + $ignore{calibration_done} = ((!$i{calibration_done} && !$db{calibration_status_report}{$event_id}{calibration_done}) || ($i{calibration_done} eq $db{calibration_status_report}{$event_id}{calibration_done})) ? 1 : 0 ; + + next if $ignore{$request_field} && $ignore{calibration_done} ; + + $i{user_id} = $userid ; + $i{last_updated} = "$now_year-$now_mm-$now_dd $now_hour:$now_min:$now_sec" ; + + if ($update_calibration_status_report{$event_id}) { + &db_min_upd('calibration_status_report',"event_quote_id='$event_id'") ; + } else { + $i{id} = &db_min_get_max('calibration_status_report','id') ; + $i{id} = 1 unless $i{id} ; + $i{event_quote_id} = $event_id ; + &db_min_insert('calibration_status_report') ; + } + } + + %i = %iii ; + +} #------------------------------------------------------------------------------------------ + +sub report_ifields { + + &load_search_vars ; + + if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { + $error = qq~'$i{date_from}' > '$i{date_to}'~ ; &report_screen ; + } + + my @srch_ed_from = &common_split_sql_time($i{date_from}) ; + my @srch_ed_to = &common_split_sql_time($i{date_to}) ; + + &common_date_array("$srch_ed_from[0]$srch_ed_from[1]$srch_ed_from[2]","$srch_ed_to[0]$srch_ed_to[1]$srch_ed_to[2]") ; + + @report_sql_or = () ; + + foreach my $_srch_date (@common_date_array) { + my $srch_ccyy_mm_dd = substr($_srch_date,0,4) . '-' . substr($_srch_date,4,2) . '-' . substr($_srch_date,6,2) ; + push @report_sql_or, "('$srch_ccyy_mm_dd 23:59:59' >= date_from AND '$srch_ccyy_mm_dd 00:00:00' <= date_to)" + } + + my $sql_or = join(' OR ',@report_sql_or) ; + push @report_sql, "($sql_or)" if $sql_or ; + + # push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` >= '$i{date_from} 00:00:00' AND `date_to` <= '$i{date_to} 23:59:59'))" ; + push @report_results, "(BETWEEN '$i{date_from}' AND '$i{date_to}')" ; + } elsif (not $i{date_from}) { + $error = qq~PLEASE ENTER A START DATE!~ ; + &report_screen; + } elsif (not $i{date_to}) { + $error = qq~PLEASE ENTER AN END DATE!~ ; + &report_screen; + } + + if ($i{calibrator_id} and $i{calibrator_id} ne 'all') { + push @report_results,"`CALIBRATOR` = '$db{users}{1}{name}'" ; + push @report_sql, " + ( + `event_system_calibration_ids` LIKE '%;$i{calibrator_id};%' OR + `event_system_calibration_ids` LIKE '%;$i{calibrator_id}' OR + `event_system_calibration_ids` LIKE '$i{calibrator_id};%' OR + `event_system_calibration_ids` LIKE '%-$i{calibrator_id};%' OR + `event_system_calibration_ids` LIKE '%;$i{calibrator_id}-%' OR + `event_system_calibration_ids` LIKE '%-$i{calibrator_id}-%' OR + `event_system_calibration_ids` LIKE '$i{calibrator_id}-%' OR + `event_system_calibration_ids` LIKE '%-$i{calibrator_id}' OR + `event_system_calibration_ids` LIKE '%~$i{calibrator_id}' OR + `event_system_calibration_ids` LIKE '%~$i{calibrator_id}-%' OR + `event_system_calibration_ids` LIKE '%~$i{calibrator_id};%' + ) + " ; + } elsif ($i{calibrator_id} and $i{calibrator_id} eq 'all') { + push @report_results,"`CALIBRATORS` = 'ALL'" ; + } else { + # push @report_sql, "(`user_id` = '')" ; + } + + if ($i{calibration_status} and $i{calibration_status} ne 'all') { + push @report_sql, " + ( + `event_system_calibration_status` LIKE '%;$i{calibration_status};%' OR + `event_system_calibration_status` LIKE '%;$i{calibration_status}' OR + `event_system_calibration_status` LIKE '$i{calibration_status};%' OR + `event_system_calibration_status` LIKE '%-$i{calibration_status};%' OR + `event_system_calibration_status` LIKE '%;$i{calibration_status}-%' OR + `event_system_calibration_status` LIKE '%-$i{calibration_status}-%' OR + `event_system_calibration_status` LIKE '$i{calibration_status}-%' OR + `event_system_calibration_status` LIKE '%-$i{calibration_status}' OR + `event_system_calibration_status` LIKE '%~$i{calibration_status}' OR + `event_system_calibration_status` LIKE '%~$i{calibration_status}-%' OR + `event_system_calibration_status` LIKE '%~$i{calibration_status};%' + ) + " ; + push @report_results,"`STATUS` = '$db{calibration_status}{$i{calibration_status}}{status}'" ; + } + + $report_results_msg = uc join(', ', @report_results) ; + + if (not $report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); + &report_screen; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + + our $srch_where_sql = join(' AND ',@report_sql) ; + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + if ($i{calibrator_id} and $i{calibrator_id} ne 'all') { + &db_min_ro('users','1,name',"`id` = '$i{calibrator_id}'",'','') ; + } + + &db_min_ro('calibration_status','id,status','','','') ; + + our $calibration_status = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + $print_box_content_rows .= &common_min_forms_start("$lcpage") ; + + our $calibration_report = 1 ; + + &calibration_load_list_vars("$srch_where_sql") ; + + $fcol = 12 ; + + my $report = 1 ; + + our $xlsxdir = "calibration_report" ; + + our $xlsxreportname = "Calibration_Report" ; + + my $date = &common_write_date_interval($i{date_from},$i{date_to}) ; + + our $xlsx_title_heading = "Calibration Report $date" ; + + my $found_after_date = 0 ; + my $today_val = int("$now_year$now_mm$now_dd") ; + + my @date_from_inp = split(/ /,$i{date_from}) ; + my ($year_inp1,$month_inp1,$day_inp1) = split(/\-/,$date_from_inp[0]) ; + my $date_inp_val1 = int("$year_inp1$month_inp1$day_inp1") ; + + my @date_to_inp = split(/ /,$i{date_to}) ; + my ($year_inp2,$month_inp2,$day_inp2) = split(/\-/,$date_to_inp[0]) ; + my $date_inp_val2 = int("$year_inp2$month_inp2$day_inp2") ; + + foreach (keys %{$db{$table}}) { + my @date_from = split(/ /,$db{$table}{$_}{date_from}) ; + my ($year_1,$month_1,$day_1) = split(/\-/,$date_from[0]) ; + my $date_val1 = int("$year_1$month_1$day_1") ; + my @date_to = split(/ /,$db{$table}{$_}{date_to}) ; + my ($year_2,$month_2,$day_2) = split(/\-/,$date_to[0]) ; + my $date_val2 = int("$year_2$month_2$day_2") ; + $found_after_date = 1 if ($today_val <= $date_val1 && $today_val <= $date_inp_val1) || ($today_val <= $date_val2 && $today_val <= $date_inp_val2) ; + } + + my $table2 = 'calibration_status_report' ; + + &db_min_ro($table2,'event_quote_id,request_sent,upload_names','','','') ; + + foreach my $event_id (keys %{$db{$table2}}) { + + my @request_sent = split(/\|/,$db{$table2}{$event_id}{request_sent}) ; + + my $max_cnt = 0 ; + $max_cnt = scalar @request_sent ; + + if ($max_cnt > 0) { + + foreach my $sys_cnt (0 .. $max_cnt-1) { + + my ($system_id1,$data1) = split(/\~/,$request_sent[$sys_cnt]) ; + my $event_sys_id = $system_id1 ; + my @request_sent_day_splt = split(/\;/,$data1) ; + my $max_nr_days = 0 ; + $max_nr_days = scalar @request_sent_day_splt ; + + foreach my $day_cnt (1 .. $max_nr_days) { + $default_vaules{request_sent}{$event_id}{$event_sys_id}{$day_cnt} = $request_sent_day_splt[$day_cnt-1] ; + } + } + } + } + + &calibration_build_table_and_or_excel(1) ; + + $custom_column_styles{request_sent} = qq~style="width:105px;min-width:105px;max-width:105px;"~ ; + + $fnsortorder = 'asc' ; + + &common_min_extra_crumb("$lcpage","Search Screen") ; + + $trigger_jquery_raw .= qq~ + \$("#savebutt").click(function() { + \$("#$lcpage-form").submit() ; + }) ; + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub set_tick { + + my ($color,$tooltip) = @_ ; + + $tick{green} = qq~2~ ; + $tick{orange} = qq~1~ ; + $tick{red} = qq~0~ ; + + return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub set_cross { + + my ($color,$tooltip) = @_ ; + + $tick{green} = qq~2~ ; + $tick{orange} = qq~1~ ; + $tick{red} = qq~0~ ; + + return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + our $lcpage = 'calibration-report' ; + + &common_page_name ; + + our $table = 'event_quotes' ; + $page_title = 'Calibration Report' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + my ($sql_next_day) = &common_add_delta_days(1) ; + my ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$next_year-$next_month-$next_day") ; #unless $i{date_from} ; + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$next_year-$next_month-$next_day") ; + + $selected{calibration_status}{all} = 'SELECTED' ; + if ($i{calibration_status}) { + $selected{calibration_status}{$i{calibration_status}} = 'SELECTED' ; + $selected{calibration_status}{all} = '' ; + } + + &db_min_ro('calibration_status','id,status','','','') ; + + # $opts{calibration_status} .= qq~~ ; + foreach (keys %{$db{calibration_status}}) { + $opts{calibration_status} .= qq~~ ; + } + $opts{calibration_status} .= qq~~ ; + + $preferred_title{calibration_status} = "Status" ; + + $preferred_title{calibrator_id} = "Calibrator" ; + + &db_min_ro('users',"id,name,username","(user_type = 'support' OR user_type = 'manager' OR user_type = 'casual_calibrator') AND name NOT LIKE 'Rory%'",'','') ; + + $selected{calibrator_id}{all} = 'SELECTED' ; + + if ($i{calibrator_id}) { + $selected{calibrator_id}{$i{calibrator_id}} = 'SELECTED' ; + $selected{calibrator_id}{all} = '' ; + } + + foreach (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + next if $useropts{it}{$db{users}{$_}{username}} ; + $opts{calibrator_id} .= qq~~ ; + } + $opts{calibrator_id} .= qq~~ ; + + $print_box_content_rows .= &common_min_form_select('calibration_status','') ; + $print_box_content_rows .= &common_min_form_select('calibrator_id','') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# my $page = "$lcpage\s" ; + +my $page = "event-quotes" ; + +if ($s{no}) { $page = $lcpage ; } + +&common_min_table('id',$page,'list') ; + +our $savjqy = 1 ; + +$extra_form_fields .= qq~ + + + +~; + +$print_box_content_rows .= &common_min_forms_end('','','save') ; + +$useropts{'common'}{'css'} .= qq~tbody tr td { font-size: 10px; } ~ ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub redirect_screen { + +&common_min_alert_type ; + +print < + + + + $useropts{title} + + + + + + +
    + + + + + + +
    + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +use common ; +use common_min ; +use report ; +use xlsxcreator ; +use today ; +use calibration ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/calibration_status_report.pl b/scripts/_FromProd/v1.0/calibration_status_report.pl new file mode 100644 index 0000000..f9e43ea --- /dev/null +++ b/scripts/_FromProd/v1.0/calibration_status_report.pl @@ -0,0 +1,1215 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +# unless ($useropts{it}{$username}) { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; +use Time::Piece ; +use Image::Size; +use File::Temp qw(tempfile); +use Image::Magick; +# use GD::Image; + +&today; + +# $now_ccyymmdd = "20250321" ; +# $now_dd = "21" ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; +# our $testing = 1 ; + +# if ($username ne 'handre') { + # print "<< MAINTENANCE IN PROGRESS >>" ; exit ; +# } + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $srchscr = 1 ; + +if ($iaction eq 'save') { + &db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &common_min_load_params ; + &report_ifields; + &update ; + # &list_screen ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + exit if $testing ; + # &screen3; + &redirect_screen ; +} + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &report_screen if $iaction eq '' ; + if ($iaction eq 'report') { + &common_min_load_params ; + &report_ifields ; + &list_screen ; + &screen3 ; + } + &common_min_action ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + +} #------------------------------------------------------------------------------------------ + +sub insert { + +} #------------------------------------------------------------------------------------------ + +sub update { + + my %ii = () ; my %iii = %i ; my %can_update = () ; my %update = () ; + + &db_min_ro($table,'id,event_system_id_multiple','','','') ; + + my %changed_events = () ; + + foreach my $field (keys %i) { + next if $field !~ /^update_/ || ($field =~ /^update_/ && !$i{$field}) ; + my @field_split = split(/\_/,$field) ; + $changed_events{$field_split[-3]} = 1 ; + } + + my $table2_sql = join(" OR ",map { "event_quote_id='$_'" } keys %changed_events ) ; + + &db_min_ro($table2,'event_quote_id,request_sent,late_start,reason_ids,comments',$table2_sql,'','') ; + + foreach my $event_id (keys %{$db{$table2}}) { + $can_update{$event_id} = 1 ; + } + + my %field_arr = ('request_sent' => 'request_sent','live' => 'live','late_start' => 'late_start','reason' => 'reason_ids','comments' => 'comments') ; + + foreach my $e_id (keys %{$db{$table2}}) { + $can_update{$e_id} = 1 ; + + foreach my $col (keys %{$db{$table2}{$e_id}}) { + + next if $col eq 'event_quote_id' || !$db{$table2}{$e_id}{$col} ; + + my $delim = ($col eq 'comments') ? qr/\|\|/ : qr/\|/ ; + + foreach my $system_data (split $delim,$db{$table2}{$e_id}{$col}) { + + next unless $system_data ; + my ($system_id,$data) = split(/\~/,$system_data) ; + next if !$system_id || $db{$table}{$e_id}{event_system_id_multiple} !~ /\b$system_id\b/ ; + my $delim = ($col eq 'comments') ? qr/\;\;/ : qr/;/ ; + + my $day_cnt = 0 ; + foreach my $daily_data (split $delim,$data) { + $day_cnt++ ; + $ii{$e_id}{$system_id}{$day_cnt}{$col} = $daily_data ; + } + } + } + } + + foreach (keys %i) { + + local @a = split(/\_/,$_) ; + + my $upd_field = "update_$a[-3]\_$a[-2]\_$a[-1]" ; + next unless $i{$upd_field} ; + + $update{$a[-3]} = 1 ; + + if (substr($_,0,13) eq 'request_sent_') { + $ii{$a[-3]}{$a[-2]}{$a[-1]}{request_sent} = $i{$_} ; + } elsif (substr($_,0,11) eq 'late_start_') { + $ii{$a[-3]}{$a[-2]}{$a[-1]}{late_start} = $i{$_} ; + } elsif (substr($_,0,7) eq 'reason_') { + $ii{$a[-3]}{$a[-2]}{$a[-1]}{reason_ids} = $i{$_} ; + } elsif (substr($_,0,9) eq 'comments_') { + $ii{$a[-3]}{$a[-2]}{$a[-1]}{comments} = $i{$_} ; + } + } + + foreach my $event_id (keys %ii) { + + %i = () ; + + foreach my $system_id (sort {$a <=> $b} keys %{$ii{$event_id}}) { + # $i{event_system_ids} .= qq~$system_id;~ ; + my $day_cnt_exists = 0 ; my %system_data = () ; + my $prev_day_cnt = 0 ; + + foreach my $day_cnt (sort {$a <=> $b} keys %{$ii{$event_id}{$system_id}}) { + if ($day_cnt - $prev_day_cnt > 1) { + for my $a (1 .. $day_cnt - $prev_day_cnt - 1) { + foreach (keys %field_arr) { + $system_data{$field_arr{$_}} .= ($_ eq 'comments') ? qq~;;~ : qq~;~ ; + } + } + } + + $prev_day_cnt = $day_cnt ; + $day_cnt_exists = 1 ; + foreach (keys %field_arr) { + $system_data{$field_arr{$_}} .= ($_ eq 'comments') ? qq~$ii{$event_id}{$system_id}{$day_cnt}{$field_arr{$_}};;~ : qq~$ii{$event_id}{$system_id}{$day_cnt}{$field_arr{$_}};~ ; + } + + my $field1 = qq~late_start_$event_id\_$system_id\_$day_cnt~ ; + my $field2 = qq~reason_$event_id\_$system_id\_$day_cnt~ ; + my $field3 = qq~comments_$event_id\_$system_id\_$day_cnt~ ; + + } + foreach (keys %field_arr) { + $system_data{$field_arr{$_}} =~ s/;+$// ; + $i{$field_arr{$_}} .= qq~$system_id\~$system_data{$field_arr{$_}}~ if $system_data{$field_arr{$_}} ; + $i{$field_arr{$_}} .= ($_ eq 'comments') ? qq~||~ : qq~|~ ; + } + } + + foreach (keys %i) { + $i{$_} =~ s/\|+$// ; + $ignore{$_} = ($i{$_} eq $db{$table2}{$event_id}{$_} || (!$i{$_} && !$db{$table2}{$event_id}{$_})) ? 1 : 0 ; + } + + $i{user_id} = $userid ; + $i{last_updated} = "$now_year-$now_mm-$now_dd $now_hour:$now_min:$now_sec" ; + + our $testing = 1 ; + + if ($can_update{$event_id} && $update{$event_id}) { + $ignore{event_quote_id} = 1 ; + &db_min_upd($table2,"event_quote_id='$event_id'") ; + } elsif ($update{$event_id}) { + $i{id} = &db_min_get_max($table2,'id') ; + $i{id} = 1 unless $i{id} ; + $i{event_quote_id} = $event_id ; + &db_min_insert($table2) ; + } + } + + %i = %iii ; + + exit ; + +} #------------------------------------------------------------------------------------------ + +sub report_ifields { + + &load_search_vars ; + + if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { + $error = qq~'$i{date_from}' > '$i{date_to}'~ ; &report_screen ; + } + + my @srch_ed_from = &common_split_sql_time($i{date_from}) ; + my @srch_ed_to = &common_split_sql_time($i{date_to}) ; + + &common_date_array("$srch_ed_from[0]$srch_ed_from[1]$srch_ed_from[2]","$srch_ed_to[0]$srch_ed_to[1]$srch_ed_to[2]") ; + + @report_sql_or = () ; + + foreach my $_srch_date (@common_date_array) { + my $srch_ccyy_mm_dd = substr($_srch_date,0,4) . '-' . substr($_srch_date,4,2) . '-' . substr($_srch_date,6,2) ; + push @report_sql_or, "('$srch_ccyy_mm_dd 23:59:59' >= date_from AND '$srch_ccyy_mm_dd 00:00:00' <= date_to)" + } + + my $sql_or = join(' OR ',@report_sql_or) ; + push @report_sql, "($sql_or)" if $sql_or ; + + # push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` >= '$i{date_from} 00:00:00' AND `date_to` <= '$i{date_to} 23:59:59'))" ; + push @report_results, "(BETWEEN '$i{date_from}' AND '$i{date_to}')" ; + } elsif (not $i{date_from}) { + $error = qq~PLEASE ENTER A START DATE!~ ; + &report_screen; + } elsif (not $i{date_to}) { + $error = qq~PLEASE ENTER AN END DATE!~ ; + &report_screen; + } + + if ($i{calibrator_id} and $i{calibrator_id} ne 'all') { + push @report_results,"`CALIBRATOR` = '$db{users}{1}{name}'" ; + push @report_sql, " + ( + `event_system_calibration_ids` LIKE '%;$i{calibrator_id};%' OR + `event_system_calibration_ids` LIKE '%;$i{calibrator_id}' OR + `event_system_calibration_ids` LIKE '$i{calibrator_id};%' OR + `event_system_calibration_ids` LIKE '%-$i{calibrator_id};%' OR + `event_system_calibration_ids` LIKE '%;$i{calibrator_id}-%' OR + `event_system_calibration_ids` LIKE '%-$i{calibrator_id}-%' OR + `event_system_calibration_ids` LIKE '$i{calibrator_id}-%' OR + `event_system_calibration_ids` LIKE '%-$i{calibrator_id}' OR + `event_system_calibration_ids` LIKE '%~$i{calibrator_id}' OR + `event_system_calibration_ids` LIKE '%~$i{calibrator_id}-%' OR + `event_system_calibration_ids` LIKE '%~$i{calibrator_id};%' + ) + " ; + } elsif ($i{calibrator_id} and $i{calibrator_id} eq 'all') { + push @report_results,"`CALIBRATORS` = 'ALL'" ; + } else { + # push @report_sql, "(`user_id` = '')" ; + } + + if ($i{calibration_status} and $i{calibration_status} ne 'all') { + push @report_sql, " + ( + `event_system_calibration_status` LIKE '%;$i{calibration_status};%' OR + `event_system_calibration_status` LIKE '%;$i{calibration_status}' OR + `event_system_calibration_status` LIKE '$i{calibration_status};%' OR + `event_system_calibration_status` LIKE '%-$i{calibration_status};%' OR + `event_system_calibration_status` LIKE '%;$i{calibration_status}-%' OR + `event_system_calibration_status` LIKE '%-$i{calibration_status}-%' OR + `event_system_calibration_status` LIKE '$i{calibration_status}-%' OR + `event_system_calibration_status` LIKE '%-$i{calibration_status}' OR + `event_system_calibration_status` LIKE '%~$i{calibration_status}' OR + `event_system_calibration_status` LIKE '%~$i{calibration_status}-%' OR + `event_system_calibration_status` LIKE '%~$i{calibration_status};%' + ) + " ; + push @report_results,"`STATUS` = '$db{calibration_status}{$i{calibration_status}}{status}'" ; + } + + $report_results_msg = uc join(', ', @report_results) ; + + if (not $report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); + &report_screen; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + + our $srch_where_sql = join(' AND ',@report_sql) ; + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + if ($i{calibrator_id} and $i{calibrator_id} ne 'all') { + &db_min_ro('users','1,name',"`id` = '$i{calibrator_id}'",'','') ; + } + + &db_min_ro('calibration_status','id,status','','','') ; + + our $calibration_status = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub load_list_vars { + + my ($where) = @_ ; + + our %quote_status = () ; + + our %calibrator_users = () ; + + &db_min_ro('regions','*','','','') ; + + &db_min_ro('users','id,name,user_type,username,region_ids',"name NOT LIKE 'Rory%' AND name NOT LIKE 'Handre%'",'','') ; + + my @event_quote_ids = () ; our %calibration_status_hash = () ; + + &db_min_ro($table,"id,ref,organisation_ids,quote_accepted,event_system_id_multiple,event_system_calibration_status,region_id,sport_type_ids,operator_ids,date_from,date_to,times_from,times_to,daily_operator_ids,days_active,monitor_ids,temp_calibrator_ids","$where AND `quote_accepted` = '1'",'','') ; + + foreach my $id (keys %{$db{$table}}) { + + next unless $id ; my $cnt = 0 ; + + my @ed_from = &common_split_sql_time($db{$table}{$id}{date_from}) ; + my @ed_to = &common_split_sql_time($db{$table}{$id}{date_to}) ; + + &common_date_array("$ed_from[0]$ed_from[1]$ed_from[2]","$ed_to[0]$ed_to[1]$ed_to[2]") ; + + $sort_calibration_by_time_ref{"$ed_from[0]$ed_from[1]$ed_from[2]$ed_from[3]$ed_from[4]-$id"} = $id ; + + my @status_arr = split(/\;/,$db{$table}{$id}{event_system_calibration_status}) ; + + my @system_arr = split(/\;/,$db{$table}{$id}{event_system_id_multiple}) ; + + my $cnt = 0 ; + + foreach my $status_data (@status_arr) { + my ($system_id,$data) = split(/\~/,$status_data) ; + if ($system_id && !$data) { + $data = $system_id ; $system_id = "" ; + } + $system_id = $system_arr[$cnt] if !$system_id ; + $cnt++ ; + my @daily_status_arr = split(/\-/,$data) ; + my $day_cnt = 0 ; + foreach (@daily_status_arr) { + $day_cnt++ ; + $calibration_status_hash{$id}{$system_id}{$day_cnt} = $_ if $_ ; + } + } + } + + &db_min_ro('sport_types','id,name','','','') ; + &db_min_ro('organisations','id,name','','','') ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + our %default_vaules = () ; + + our @sql_col_display = ("count","event","calib_date","day","start_date","start_time","venue","region","system","sport","operator") ; + + my @editable_columns = ("request_sent","late_start","calibration_done","reason_ids","comments","frames") ; + + foreach (@editable_columns) { + if ($_ ne 'reason_ids') { + push @sql_col_display ,"$_" ; + } else { + push @sql_col_display ,"reason" ; + } + } + + $print_box_content_rows .= &common_min_forms_start("$lcpage") ; + + our $calibration_report = 1 ; + + &db_min_ro($table2,'event_quote_id,request_sent,late_start,reason_ids,comments,calibration_done,upload_names','','','') ; + + $opts{reason} = qq~~ ; + $opts{late_start} = qq~~ ; + + &db_min_ro('event_systems','*',"system_type = 'mobile'",'','') ; + + &load_list_vars("$srch_where_sql") ; + + foreach my $event_id (keys %{$db{$table2}}) { + + my @request_sent = split(/\|/,$db{$table2}{$event_id}{request_sent}) ; + my @live = split(/\|/,$db{$table2}{$event_id}{live}) ; + my @late_start = split(/\|/,$db{$table2}{$event_id}{late_start}) ; + my @reason_ids = split(/\|/,$db{$table2}{$event_id}{reason_ids}) ; + my @calibration_done = split(/\|/,$db{$table2}{$event_id}{calibration_done}) ; + my @comments = split(/\|\|/,$db{$table2}{$event_id}{comments}) ; + + my $max_cnt = 0 ; + $max_cnt = scalar @request_sent ; + $max_cnt = scalar @live if scalar @live > $max_cnt ; + $max_cnt = scalar @late_start if scalar @late_start > $max_cnt ; + $max_cnt = scalar @reason_ids if scalar @reason_ids > $max_cnt ; + $max_cnt = scalar @comments if scalar @comments > $max_cnt ; + $max_cnt = scalar @calibration_done if scalar @calibration_done > $max_cnt ; + + if ($max_cnt > 0) { + + foreach my $sys_cnt (0 .. $max_cnt-1) { + + my ($system_id1,$data1) = split(/\~/,$request_sent[$sys_cnt]) ; + my ($system_id2,$data2) = split(/\~/,$live[$sys_cnt]) ; + my ($system_id3,$data3) = split(/\~/,$late_start[$sys_cnt]) ; + my ($system_id4,$data4) = split(/\~/,$reason_ids[$sys_cnt]) ; + my ($system_id5,$data5) = split(/\~/,$comments[$sys_cnt]) ; + my ($system_id6,$data6) = split(/\~/,$calibration_done[$sys_cnt]) ; + + my @request_sent_day_splt = split(/\;/,$data1) ; + my @live_day_splt = split(/\;/,$data2) ; + my @late_start_day_splt = split(/\;/,$data3) ; + my @reason_ids_day_splt = split(/\;/,$data4) ; + my @comments_day_splt = split(/\;\;/,$data5) ; + my @calibration_done_splt = split(/\;/,$data6) ; + + my $max_nr_days = 0 ; + + $max_nr_days = scalar @request_sent_day_splt ; + $max_nr_days = scalar @live_day_splt if scalar @live_day_splt > $max_nr_days ; + $max_nr_days = scalar @late_start_day_splt if scalar @late_start_day_splt > $max_nr_days ; + $max_nr_days = scalar @reason_ids_day_splt if scalar @reason_ids_day_splt > $max_nr_days ; + $max_nr_days = scalar @comments_day_splt if scalar @comments_day_splt > $max_nr_days ; + $max_nr_days = scalar @calibration_done_splt if scalar @calibration_done_splt > $max_nr_days ; + + foreach my $day_cnt (1 .. $max_nr_days) { + $default_vaules{request_sent}{$event_id}{$system_id1}{$day_cnt} = $request_sent_day_splt[$day_cnt-1] if $system_id1 ; + $default_vaules{live}{$event_id}{$system_id2}{$day_cnt} = $live_day_splt[$day_cnt-1] if $system_id2 ; + $default_vaules{late_start}{$event_id}{$system_id3}{$day_cnt} = $late_start_day_splt[$day_cnt-1] if $system_id3 ; + $default_vaules{reason}{$event_id}{$system_id4}{$day_cnt} = $reason_ids_day_splt[$day_cnt-1] if $system_id4 ; + $default_vaules{comments}{$event_id}{$system_id5}{$day_cnt} = $comments_day_splt[$day_cnt-1] if $system_id5 ; + $default_vaules{calibration_done}{$event_id}{$system_id6}{$day_cnt} = $calibration_done_splt[$day_cnt-1] if $system_id6 ; + } + $sys_cnt++ ; + } + } + } + + $fcol = 12 ; + + my $report = 1 ; + + our $xlsxdir = "calibration_status_report" ; + + our $xlsxreportname = "Calibration_Status_Report" ; + + my $date = &common_write_date_interval($i{date_from},$i{date_to}) ; + + our $xlsx_title_heading = "Calibration Status Report $date" ; + + my $found_after_date = 0 ; + my $today_val = int("$now_year$now_mm$now_dd") ; + + my @date_from_inp = split(/ /,$i{date_from}) ; + my ($year_inp1,$month_inp1,$day_inp1) = split(/\-/,$date_from_inp[0]) ; + my $date_inp_val1 = int("$year_inp1$month_inp1$day_inp1") ; + + my @date_to_inp = split(/ /,$i{date_to}) ; + my ($year_inp2,$month_inp2,$day_inp2) = split(/\-/,$date_to_inp[0]) ; + my $date_inp_val2 = int("$year_inp2$month_inp2$day_inp2") ; + + foreach (keys %{$db{$table}}) { + my @date_from = split(/ /,$db{$table}{$_}{date_from}) ; + my ($year_1,$month_1,$day_1) = split(/\-/,$date_from[0]) ; + my $date_val1 = int("$year_1$month_1$day_1") ; + my @date_to = split(/ /,$db{$table}{$_}{date_to}) ; + my ($year_2,$month_2,$day_2) = split(/\-/,$date_to[0]) ; + my $date_val2 = int("$year_2$month_2$day_2") ; + $found_after_date = 1 if ($today_val <= $date_val1 && $today_val <= $date_inp_val1) || ($today_val <= $date_val2 && $today_val <= $date_inp_val2) ; + } + + my $width = 105 ; + + $custom_column_styles{request_sent} = qq~style="width:$width\px;min-width:$width\px;max-width:$width\px;"~ ; + $custom_column_styles{live} = qq~style="width:$width\px;min-width:$width\px;max-width:$width\px;"~ ; + $custom_column_styles{late_start} = qq~style="min-width:150px;"~ ; + # $custom_column_styles{calibration_done} = qq~style="min-width:150px;"~ ; + $custom_column_styles{reason} = qq~style="min-width:150px;"~ ; + $custom_column_styles{comments} = qq~style="min-width:150px;"~ ; + # $custom_column_styles{frames} = qq~style="min-width:150px;"~ ; + + our $found_editable = 0 ; + + &build_table_and_or_excel(1) ; + + if (!$found_editable) { + $trigger_jquery_raw .= qq~ + \$("#$useropts{table_id} ").find("th:last").remove() ; + \$("#$useropts{table_id} tr").each(function() { + \$(this).find("td:last").remove() ; + }) ; + ~ ; + } else { + + &common_min_table_select_jquery("#$useropts{table_id} td:nth-last-child(4),#$useropts{table_id} td:nth-last-child(6)") ; + + $trigger_jquery_raw_default_alt .= qq~ + + let sel_value = \$("#"+changed_id).val() ; + + if (changed_id.includes("textareaComments_")) { + let sel_value = \$("#"+changed_id).val() ; + sel_value = sel_value.replace(/;;/g, "").replace("||", ""); + \$("#"+changed_id).val(sel_value) ; + } else if (changed_id.includes("selectLate_start_")) { + let row_val = get_row_nr(changed_id,3) ; + if (sel_value == '2' && \$("#selectReason_"+row_val).val()) { + \$("#selectReason_"+row_val).val("").trigger("chosen:updated") ; + } + } else if (changed_id.includes("selectReason_")) { + + console.log("1 Hello World!!") ; + + let row_val = get_row_nr(changed_id,3) ; + if (sel_value && (\$("#selectLate_start_"+row_val).val() == '2' || \$("input[name='late_start_"+row_val+"']").val() == '2')) { + \$("#selectReason_"+row_val).val("").trigger("chosen:updated") ; + console.log("2 Hello World!!") ; + } + } + + ~ ; + + &common_min_table_update_checkbox_col("3",$useropts{table_id},"[id^='selectLate_start_'],[id^='selectReason_'],[id^='textareaComments_']","[id^='timepickerRequest_sent_'],[id^='timepickerLive_']") ; + } + + if ($found_editable) { + # $trigger_jquery .= qq~ + # \$("#$useropts{table_id} td:nth-last-child(3)").css("width","12.5%"); + # \$("#$useropts{table_id} td:nth-last-child(2)").css("width","12.5%"); + # ~ ; + } + + $fnsortorder = 'asc' ; + + &common_min_extra_crumb("$lcpage","Search Screen") ; + + $trigger_jquery_raw .= qq~ + \$("#savebutt").click(function() { + \$("#$lcpage-form").submit() ; + }) ; + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub build_table_and_or_excel { + + my ($report) = @_ ; + + my $width = 105 ; + + &report_xlsx_export_header("$xlsxreportname",$xlsxdir,'',$xlsx_title_heading) ; + + push @sql_col_display,"update" ; + + my $nr_of_cols = scalar @sql_col_display ; + + my @rev_sql_col_display = reverse @sql_col_display ; + + foreach (@rev_sql_col_display) { $lastchild++ ; $last_child{$_} = $lastchild ; } # &common_debug("last-child : $_ [$last_child{$_}]"); + + $xlsxrow-- ; + + my $cali_cnt = 0 ; + # # # # # # # # # # # # # # # # # # # # my $found_editable = 0 ; + my @all_select_ids = () ; + + $format84 -> set_align("center") ; + + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + our $max_frame_width = 0 ; + + my %temp_files = () ; + + my %default_val_id = () ; + + + foreach my $date_ref (sort {$sort_calibration_by_time_ref{$b} <=> $sort_calibration_by_time_ref{$a}} keys %sort_calibration_by_time_ref) { + + my $id = $sort_calibration_by_time_ref{$date_ref} ; + + next unless $id ; + + $db{$table2}{$id}{event_system_ids} = $db{$table}{$id}{event_system_id_multiple} ; + + my $system_count = 0 ; my $system_day_cnt = 0 ; + + my %system_has_daily_op = () ; my %default_op_ids = () ; + + foreach my $system_row (split(/\|/,$db{$table}{$id}{daily_operator_ids})) { + $system_count++ ; + next unless $system_row ; + $system_day_cnt = 0 ; + foreach my $col (split(/\;/,$system_row)) { + $system_day_cnt++ ; + next unless $col ; + $default_op_ids{$system_count}{$system_day_cnt} = $col if $col ; + $system_has_daily_op{$system_count} = 1 if $col ; + } + } + $system_count = 0 ; + + unless (&common_check_if_string_contains_an_integer($db{$table}{$id}{event_system_id_multiple})) { + $db{$table}{$id}{event_system_id_multiple} = ";none;" ; + } + + # my @system_name_ids = split(";",$db{$table}{$id}{event_system_id_multiple}) ; + + my @system_name_ids = split(/\;/,$db{$table}{$id}{event_system_id_multiple}) ; + my @club_ids = split(/\;/,$db{$table}{$id}{club_ids}) ; + my @op_ids = ($db{$table}{$id}{operator_ids} =~ /,/) ? split(/\,/,$db{$table}{$id}{operator_ids}) : ($db{$table}{$id}{operator_ids} =~ /;/) ? split(/\;/,$db{$table}{$id}{operator_ids}) : $db{$table}{$id}{operator_ids} ; + my @start_times = split(/\;/,";".$db{$table}{$id}{times_from}) ; + my @end_times = split(/\;/,$db{$table}{$id}{times_to}.";") ; + my @days_active = split(/\;/,$db{$table}{$id}{days_active}) ; + + my $cnt_rows = 0 ; + for (1 .. 50) { + $cnt_rows = $_ if $system_name_ids[$_ - 1] or $club_ids[$_ - 1] ; + } + + $system_count = 0 ; + + $colname_to_id{head_operator} = "head_operator" ; + $colname_to_id{calibrator} = "calibrator_id" ; + $colname_to_id{status} = "calibration_status" ; + + $preferred_title{head_operator} = "Head Operator" ; + $preferred_title{calibrator} = "Calibrator" ; + $preferred_title{status} = "Calibration Status" ; + + $default_val_table{head_operator} = 'users' ; + $default_val_table{calibrator} = 'users' ; + $default_val_table{status} = 'calibration_status' ; + $default_val_table{late_start} = 'late_start' ; + $default_val_table{reason} = 'reason' ; + + $db{late_start}{1}{name} = "Yes" ; + $db{late_start}{2}{name} = "No" ; + + $db{reason}{1}{name} = "Equipment Failure" ; + $db{reason}{2}{name} = "Operator Issue" ; + $db{reason}{-1}{name} = "Other" ; + + $default_val_id{reason}{"Equipment Failure"} = 1 ; + $default_val_id{reason}{"Operator Issue"} = 2 ; + $default_val_id{reason}{"Other"} = -1 ; + + $default_val_id{late_start}{"Yes"} = 1 ; + $default_val_id{late_start}{"No"} = 2 ; + + &calibration_get_status_frames($id) ; + + foreach my $event_sys_id (@system_name_ids) { + + $system_count++ ; + + next unless $event_sys_id ; + + next unless $db{event_systems}{$event_sys_id}{system_type} ; + + $system_day_cnt = 0 ; + + foreach my $cal_date (sort keys %day_of_week) { + + my $srch_date_from_comp = $i{date_from} ; $srch_date_from_comp =~ s/\-//g ; + my $srch_date_to_comp = $i{date_to} ; $srch_date_to_comp =~ s/\-//g ; + my $date_from_comp = substr($db{$table}{$id}{date_from},0,10) ; $date_from_comp =~ s/\-//g ; + my $date_to_comp = substr($db{$table}{$id}{date_to},0,10) ; $date_to_comp =~ s/\-//g ; + my $cal_date_comp = $cal_date ; # $cal_date_comp =~ s/\-//g ; + $cal_date = substr($cal_date,0,4) . '-' . substr($cal_date,4,2) . '-' . substr($cal_date,6,2) ; + my $date_from = substr($db{$table}{$id}{date_from},0,10) ; + $system_day_cnt++ ; + + next if $cal_date_comp < $date_from_comp ; + next if $cal_date_comp > $date_to_comp ; + + $cnt{$event_sys_id}{$id}++ ; + + next if $db{$table}{$id}{days_active} && !$days_active[$cnt{$event_sys_id}{$id}-1] ; + next if $cal_date_comp > $srch_date_to_comp ; + next if $cal_date_comp < $srch_date_from_comp ; + + next if $i{calibration_status} && $i{calibration_status} ne 'all' && $i{calibration_status} ne $default_vaules{status}{$id}{$event_sys_id}{$cnt{$event_sys_id}{$id}} ; + + $cali_cnt++; + + $xlsxcol = 0 ; + + $print_tbody .= qq~~ if $report ; + + my $nr_of_cols_cnt = $nr_of_cols + 1 ; + + our $default_javascript = qq~~ ; + + my $contains_select = 0 ; + + foreach (@sql_col_display) { + + $nr_of_cols_cnt-- ; + + next unless $_ ; # blank for the buttons column + + my $formatting = $format84 ; + my $val = $db{$table}{$id}{$_} ; + our $val_min = $val ; + my $align = qq~ class="dt-center"~ ; + my $nowrap = '' ; + + my $sys_day_cnt = $cnt{$event_sys_id}{$id} ; + + my $field = "" ; my $default_val = $default_vaules{$_}{$id}{$event_sys_id}{$sys_day_cnt} ; my $only_display_val = 0 ; my $background_color = "#424949" ; my $default_val_is_saved = ($default_val) ? 1 : 0 ; + + if ($_ eq 'request_sent' || $_ eq 'live' || $_ eq 'late_start' || $_ eq 'reason' || $_ eq 'comments') { + + $val_min = '' ; + + $formatting = $format91 ; + + if ($report) { + # if ($db{$table}{$id}{after_start_date} and $event_sys_id ne "-1") { + # &common_debug("=== $cal_date_comp >= $now_ccyymmdd && $event_sys_id ne -1") ; + + $field = ($colname_to_id{$_}) ? "$colname_to_id{$_}\_$id\_$event_sys_id\_$sys_day_cnt" : "$_\_$id\_$event_sys_id\_$sys_day_cnt" ; + + if (($cal_date_comp >= $now_ccyymmdd && $event_sys_id ne "-1") || (!$default_val)) { + $preferred_title{$field} = $preferred_title{$_} ; + $opts{$field} = $opts{$_} ; + # $useropts{'common'}{'css'} .= qq~.$_ { min-width:180px; } ~ ; ???? + $val_min = $db{$default_val_table{$_}}{$default_val}{name} ; + $found_editable = 1 ; + $contains_select = 1 ; + } else { + $default_val = $db{$default_val_table{$_}}{$default_val}{name} if $default_val_table{$_} ; + $default_val = "None" if $default_val eq 'none' ; + $only_display_val = 1 ; + } + } else { + $default_val = $db{$default_val_table{$_}}{$default_val}{name} if $default_val_table{$_} ; + $default_val = "None" if $default_val eq 'none' ; + $only_display_val = 1 ; + } + } + + if ($_ eq 'count') { + $val = $cali_cnt ; + } elsif ($_ eq 'event') { + $val = "$db{$table}{$id}{ref} [$id]" ; + } elsif ($_ eq 'calib_date' || $_ eq 'date') { + # $val = "$cal_date [$day_of_week{$cal_date}]" ; + $val = &common_min_date_as_string("$cal_date") ; + $nowrap = "nowrap" ; + } elsif ($_ eq 'day') { + $val = "$sys_day_cnt" ; + } elsif ($_ eq 'start_date') { + $nowrap = "nowrap" ; + $val = &common_min_date_as_string($date_from) ; + } elsif ($_ eq 'start_time') { + if ($sys_day_cnt == 1 or ($sys_day_cnt > 1 and not $start_times[$sys_day_cnt-1])) { + $val = substr($db{$table}{$id}{date_from},11,5) ; + } else { + $val = substr($start_times[$sys_day_cnt-1],0,5) ; + } + } elsif ($_ eq 'venue') { + my @oids = split(/\,/,$db{$table}{$id}{organisation_ids}) ; + foreach $_oid (@oids) { + $val .= $db{organisations}{$_oid}{name} . '
    ' ; + } + $val = substr($val,0,-4) if $val ; + } elsif ($_ eq 'region') { + $val = $db{regions}{$db{$table}{$id}{region_id}}{code} ; + } elsif ($_ eq 'system') { + $val = '' ; + $val = qq~($event_sys_id) $db{event_systems}{$event_sys_id}{name}~ ; + $val .= qq~ ($db{event_systems}{$event_sys_id}{description})~ if $db{event_systems}{$event_sys_id}{description} ; + } elsif ($_ eq 'sport') { + $val = '' ; + foreach my $sport_id (split(",",$db{$table}{$id}{sport_type_ids})) { + $db{sport_types}{$sport_id}{name} = uc $db{sport_types}{$sport_id}{name} ; + $val .= qq~$db{sport_types}{$sport_id}{name}
    ~ ; + } + $val = substr($val,0,-4) if $val ; + } elsif ($_ eq 'operator') { + $nowrap = "nowrap" ; + $val = '' ; + # $val = $db{users}{$table_op_ids[$system_count - 1]}{name} if $table_op_ids[$system_count - 1] ; + $val = ($default_op_ids{$system_count}{$cnt{$event_sys_id}{$id}}) ? $db{users}{$default_op_ids{$system_count}{$cnt{$event_sys_id}{$id}}}{name} : (!$default_op_ids{$system_count}{$system_day_cnt} && $system_has_daily_op{$system_count}) ? "None" : $db{users}{$op_ids[$system_count - 1]}{name} ; + # $formatting = $format92 if $event_cnt == 2 ; + $formatting = $format92 if $cali_cnt == 2 ; + } elsif ($_ eq 'request_sent') { + # $val .= ($only_display_val && $default_val) ? qq~~ : qq~~ ; + $default_val = "$now_hour:$now_min:$now_sec" unless $default_val ; + $val .= &common_min_table_timepicker($field,$default_val,$only_display_val,$cali_cnt,$nr_of_cols_cnt,$background_color,$default_val_is_saved,$_) ; + } elsif ($_ eq 'live') { + # $val .= ($only_display_val) ? qq~~ : qq~~ ; + $default_val = "$now_hour:$now_min:$now_sec" unless $default_val ; + $val .= &common_min_table_timepicker($field,$default_val,$only_display_val,$cali_cnt,$nr_of_cols_cnt,$background_color,$default_val_is_saved,$_) ; + } elsif ($_ eq 'late_start') { + if ($default_val eq '1') { # || + $background_color = "#AD0502" ; + $formatting = $format90 ; + } elsif ($default_val eq '2') { #done || + $background_color = "#2ECC71" ; + $formatting = $format88 ; + } + $preferred_placeholder{$field} = "Select Late Start $id $system_count $sys_day_cnt" ; + $val = &common_min_table_select($field,$default_val,$only_display_val,$cali_cnt,$nr_of_cols_cnt,$background_color,$default_val_is_saved,$_) ; + $val_min = ($only_display_val) ? $default_val : $db{late_start}{$default_val}{name} ; + # $val .= ($only_display_val) ? qq~~ : qq~~ ; + } elsif ($_ eq 'calibration_done') { + + $nowrap = 'nowrap' ; + $val = &common_min_date_as_string($default_val) ; + + if ($calibration_status_hash{$id}{$event_sys_id}{$sys_day_cnt} eq '3') { #done + + my $startdatetime = $db{$table}{$id}{date_from} ; + $startdatetime =~ s/\://g ; + $startdatetime =~ s/\-//g ; + $startdatetime =~ s/ //g ; + + my $done_set_date = $default_val ; + $done_set_date =~ s/\://g ; + $done_set_date =~ s/\-//g ; + $done_set_date =~ s/ //g ; + + if (!$done_set_date || ($done_set_date && $startdatetime && $done_set_date < $startdatetime)) { + $background_color = "#2ECC71" ; + $formatting = $format88 ; + } elsif ($done_set_date && $startdatetime && $done_set_date >= $startdatetime) { + $background_color = "#AD0502" ; + $formatting = $format90 ; + } + $default_val_is_saved = 1 ; + } else { + $default_val_is_saved = 0 ; + } + + } elsif ($_ eq 'reason') { + $preferred_placeholder{$field} = "Select Reason $id $system_count $sys_day_cnt" ; + $val = &common_min_table_select($field,$default_val,$only_display_val,$cali_cnt,$nr_of_cols_cnt,$background_color,$default_val_is_saved,$_) ; + # $val .= ($only_display_val) ? qq~~ : qq~~ ; + $val_min = ($only_display_val) ? $default_val : $db{reason}{$default_val}{name} ; + } elsif ($_ eq 'comments') { + $preferred_placeholder{$field} = "Comments $id $system_count $sys_day_cnt" ; + $val = &common_min_table_textarea($field,$default_val,$only_display_val,$cali_cnt,$nr_of_cols_cnt,$background_color,$default_val_is_saved,$_) ; + # $val .= ($only_display_val) ? qq~~ : qq~~ ; + } elsif ($_ eq 'frames') { + $nowrap = "nowrap" ; + $val .= &calibration_get_frames($id,$event_sys_id,$sys_day_cnt) ; + } elsif ($_ eq 'update') { + + if (($report && $cal_date_comp >= $now_ccyymmdd && $event_sys_id ne "-1") || $contains_select) { + $val = &common_min_table_checkbox("update_$id\_$event_sys_id\_$sys_day_cnt") ; + chop $default_javascript if $default_javascript ; + if ($default_javascript) { + push @default_javascript_by_id, qq~"$id\_$event_sys_id\_$sys_day_cnt":{$default_javascript}~ ; + push @all_update_field_ids,"#selectHead_operator\_$id\_$event_sys_id\_$sys_day_cnt,#selectCalibrator_id\_$id\_$event_sys_id\_$sys_day_cnt,#selectCalibration_status\_$id\_$event_sys_id\_$sys_day_cnt,#timepickerRequest_sent\_$id\_$event_sys_id\_$sys_day_cnt,#timepickerLive_$id\_$event_sys_id\_$sys_day_cnt,#selectLate_start_$id\_$event_sys_id\_$sys_day_cnt,#selectReasons_$id\_$event_sys_id\_$sys_day_cnt,#textareaComments_$id\_$event_sys_id\_$sys_day_cnt" ; + } + } else { + $val = '' ; + } + } + + if ($_ ne 'live' && $_ ne 'late_start' && $_ ne 'request_sent' && $_ ne 'calibration_done' && $_ ne 'reason' && $_ ne 'comments' && $_ ne 'frames' && $_ ne 'update') { + $val_min = $val unless $val_min ; + $val_min =~ s/\
    /\;/g ; + } else { + $val_min = $default_val if $default_val && $default_val_is_saved && !$val_min ; + } + $val_min =~ s/MUSTBEBLANK//g ; + # if ($_ ne 'head_operator' && $_ ne 'status' && $_ ne 'calibrator' && substr($_,0,5) ne 'shift' && $_ ne 'update') { + # $val_min = $val ; + # $val_min =~ s/\
    /\;/g ; + # } + + my $style = ($default_val_is_saved && $background_color && $_ eq 'calibration_done') ? "style='background-color:$background_color;'" : "" ; + + $print_tbody .= qq~$val~ if $report ; + + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$formatting) if $val_min && $_ ne 'update' ; + $xlsxcol++ ; + } + + $print_tbody .= qq~~ if $report ; + + $xlsxrow++ ; + } + + } + } + + $worksheet{$ws}->set_column(0,0,7.5) ; + $worksheet{$ws}->set_column(1,1,40) ; + $worksheet{$ws}->set_column(2,2,15) ; + $worksheet{$ws}->set_column(3,3,10) ; + $worksheet{$ws}->set_column(4,4,15) ; + $worksheet{$ws}->set_column(5,5,10) ; + $worksheet{$ws}->set_column(6,6,40) ; + $worksheet{$ws}->set_column(7,7,10) ; + $worksheet{$ws}->set_column(8,10,40) ; + $worksheet{$ws}->set_column(11,12,15) ; + $worksheet{$ws}->set_column(13,15,20) ; + $worksheet{$ws}->set_column(16,16,$max_frame_width/7) ; + + my $all_select_ids_string = join(",",@all_select_ids) ; + $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({allow_single_deselect:true});~ ; + + &common_min_table_timepicker_jquery("[id^='timepickerRequest_sent_'],[id^='timepickerLive_']") ; + + # $worksheet{$ws}->set_row(0,100) ; + # $worksheet{$ws}->set_column(4,4,15) ; + + &report_xlsx_export_footer('L',15,$xlsxdir) ; + + foreach (keys %temp_files) { + unlink ($_) or die "unable to delete - $_ $!"; + } + +} #------------------------------------------------------------------------------- + +sub calibration_get_frames { + + my ($id,$event_sys_id,$sys_day_cnt) = @_ ; + + $nowrap = "nowrap" ; + my $attachments = "" ; my $attach_butt = "" ; + + if ($gallery{$id}{$event_sys_id}{$sys_day_cnt}) { + + my $margin = 5 ; my $scaled_height = 100 ; my $total_width = 0 ; my $max_height = 350 ; my $max_image_height = 0 ; + + foreach my $img_name (split(/\;/,$gallery{$id}{$event_sys_id}{$sys_day_cnt})) { + + my $file_path = "$htmlpath/uploads/calibration_status_uploads/$id/$img_name"; + + my ($width, $height) = imgsize($file_path); + + if ($height && -f $file_path) { + + my $final_file = $file_path; # default: use original + # my $scaled_width = $width; + # my $scaled_height = $height; + + if ($height > $max_height) { + + $max_image_height = $max_height if $max_image_height < $height ; + + # Load and resize with fixed height = 500 + my $img = Image::Magick->new ; + $img->Read($file_path) ; + + my $scale = $max_height / $height; + $width = int($width * $scale); + $height = $max_height; + + $img->Resize(geometry => "${width}x${height}"); + + # Write to temporary file + my ($fh, $tempfile) = tempfile(SUFFIX => '.jpg'); + $img->Write(filename => $tempfile, quality => 70); + + $final_file = $tempfile; + $temp_files{$tempfile} = 1; # track temp file for cleanup + } else { + $max_image_height = $height if $max_image_height < $height ; + } + + ($width,$height) = imgsize($final_file); + + $total_width += $margin; + + &xlsxcreator_insert_image($ws,$xlsxrow,$xlsxcol,$final_file,$total_width,$margin,150/$height,150/$height) if $height > 150 ; + &xlsxcreator_insert_image($ws,$xlsxrow,$xlsxcol,$final_file,$total_width,$margin) if $height <= 150 ; + + $total_width += $width*150/$height; + } + + $total_width += $margin; + } + + $worksheet{$ws}->set_row($xlsxrow,(2*$margin+150)*(83/110)) if $max_image_height ; + + $max_frame_width = $total_width if $total_width && $max_frame_width < $total_width ; + + $attachments .= &calibration_get_uploads_list($db{$table2}{$id}{event_quote_id},$gallery{$id}{$event_sys_id}{$sys_day_cnt}) ; + } + + if ($attachments) { + + $attach_butt = qq~ +   + + + + ~ ; + + } + + my $val_return = qq~ + $attach_butt + + + + + ~ ; + + return $val_return ; + +} #------------------------------------------------------------------------------- + +sub set_tick { + + my ($color,$tooltip) = @_ ; + + $tick{green} = qq~2~ ; + $tick{orange} = qq~1~ ; + $tick{red} = qq~0~ ; + + return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub set_cross { + + my ($color,$tooltip) = @_ ; + + $tick{green} = qq~2~ ; + $tick{orange} = qq~1~ ; + $tick{red} = qq~0~ ; + + return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + our $lcpage = 'calibration-status-report' ; + + &common_page_name ; + + our $table = 'event_quotes' ; + our $table2 = 'calibration_status_report' ; + $page_title = 'Calibration Report' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + my ($sql_next_day) = &common_add_delta_days(1) ; + my ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$next_year-$next_month-$next_day") ; #unless $i{date_from} ; + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$next_year-$next_month-$next_day") ; + + $selected{calibration_status}{all} = 'SELECTED' ; + if ($i{calibration_status}) { + $selected{calibration_status}{$i{calibration_status}} = 'SELECTED' ; + $selected{calibration_status}{all} = '' ; + } + + &db_min_ro('calibration_status','id,status','','','') ; + + foreach (keys %{$db{calibration_status}}) { + $opts{calibration_status} .= qq~~ ; + } + $opts{calibration_status} .= qq~~ ; + + $preferred_title{calibration_status} = "Status" ; + + $preferred_title{calibrator_id} = "Calibrator" ; + + &db_min_ro('users',"id,name,username","(user_type = 'support' OR user_type = 'manager' OR user_type = 'casual_calibrator') AND name NOT LIKE 'Rory%'",'','') ; + + $selected{calibrator_id}{all} = 'SELECTED' ; + + if ($i{calibrator_id}) { + $selected{calibrator_id}{$i{calibrator_id}} = 'SELECTED' ; + $selected{calibrator_id}{all} = '' ; + } + + foreach (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + next if $useropts{it}{$db{users}{$_}{username}} ; + $opts{calibrator_id} .= qq~~ ; + } + $opts{calibrator_id} .= qq~~ ; + + $print_box_content_rows .= &common_min_form_select('calibration_status','') ; + $print_box_content_rows .= &common_min_form_select('calibrator_id','') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# my $page = "$lcpage\s" ; + +my $page = "event-quotes" ; + +if ($s{no}) { $page = $lcpage ; } + +&common_min_table('id',$page,'list') ; + +our $savjqy = 1 ; + +$extra_form_fields .= qq~ + + + +~; + +$print_box_content_rows .= &common_min_forms_end('','','save') ; + +$useropts{'common'}{'css'} .= qq~tbody tr td { font-size: 10px; } ~ ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub redirect_screen { + +&common_min_alert_type ; + +print < + + + + $useropts{title} + + + + + + +
    + + + + + + +
    + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +use common ; +use common_min ; +use report ; +use xlsxcreator ; +use today ; +use calibration ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/calibrator_payments.pl b/scripts/_FromProd/v1.0/calibrator_payments.pl new file mode 100644 index 0000000..32f97c6 --- /dev/null +++ b/scripts/_FromProd/v1.0/calibrator_payments.pl @@ -0,0 +1,566 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +# unless ($useropts{it}{$username}) { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; +use Time::Piece ; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $debug = 1 ; +our $testing = 1 ; + +# if ($username ne 'handre') { + # print "<< MAINTENANCE IN PROGRESS >>" ; exit ; +# } + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $srchscr = 1 ; + +if ($iaction eq 'save') { + &db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &common_min_load_params ; + &report_ifields; + &update ; + # &list_screen ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + exit if $username eq 'rory' && $testing ; + # &screen3; + &redirect_screen; +} + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &report_screen if $iaction eq '' ; + + if ($iaction eq 'report') { + &common_min_load_params ; + &report_ifields; + &list_screen ; + &screen3; + } + + &common_min_action; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub update { + + foreach (keys %i) { + local @abc = split("_",$_) ; + if (substr($_,0,19) eq 'calibration_status_') { + $seen_event_id{$abc[-3]} = 1 ; + } + } + + local @event_ids = () ; + foreach (keys %seen_event_id) { + push @event_ids , "`id` = '$_'" ; + } + local $e_q_sql = join (" OR ",@event_ids) ; + + &db_min_ro($table,'id,event_system_id_multiple,date_from,date_to,calibrator_amounts_paid,calibrator_dates_paid',"$e_q_sql",'','') ; + + my %ii = () ; my %iii = %i ; + foreach (keys %i) { + local @a = split("_",$_) ; + + my $upd_field = "paid_$a[-3]\_$a[-2]\_$a[-1]" ; + next unless $i{$upd_field} ; + + if (substr($_,0,12) eq 'date_payable') { + $ii{$a[-3]}{$a[-2]}{$a[-1]}{date_payable} = $i{$_} ; + } elsif (substr($_,0,13) eq 'amount_payble') { + $ii{$a[-3]}{$a[-2]}{$a[-1]}{amount_payble} = $i{$_} ; + } + } + + my %iii = %i ; + + my $amnts_field = 'calibrator_amounts_paid' ; + my $dates_field = 'calibrator_dates_paid' ; + + foreach my $event_id (keys %ii) { + + %i = () ; + + # &common_debug("1. +++ event_id[$event_id] date_from[$db{$table}{$event_id}{date_from}] date_to[$db{$table}{$event_id}{date_to}] event_system_calibration_ids[$db{$table}{$event_id}{event_system_calibration_ids}] event_system_calibration_status[$db{$table}{$event_id}{event_system_calibration_status}] event_system_id_multiple[$db{$table}{$event_id}{event_system_id_multiple}]") ; + + my @event_system_ids = split(";",$db{$table}{$event_id}{event_system_id_multiple}) ; + my @calibrator_amounts_paid = split(";",$db{$table}{$event_id}{calibrator_amounts_paid}) ; + my @calibrator_dates_paid = split(";",$db{$table}{$event_id}{calibrator_dates_paid}) ; + + my @ed_from = &common_split_sql_time($db{$table}{$event_id}{date_from}) ; + my @ed_to = &common_split_sql_time($db{$table}{$event_id}{date_to}) ; + + &common_date_array("$ed_from[0]$ed_from[1]$ed_from[2]","$ed_to[0]$ed_to[1]$ed_to[2]") ; + + $sys_cnt = 0; + foreach my $system_id (@event_system_ids) { + # next unless $system_id ; + my (@calibrator_amounts_paid_per_event_day) = split(/\-/,$calibrator_amounts_paid[$sys_cnt]); + my $sys_day=0; + foreach my $_date (@common_date_array) { + $sys_day++; + $i{$amnts_field} .= ($ii{$event_id}{$system_id}{$sys_day}{amount_payble}) ? "$ii{$event_id}{$system_id}{$sys_day}{amount_payble}-" : ($calibrator_amounts_paid_per_event_day[$sys_day-1]) ? "$calibrator_amounts_paid_per_event_day[$sys_day-1]-" : '-' ; + } + chop $i{$amnts_field} if $i{$amnts_field} ; + $i{$amnts_field} .= ";" ; + $sys_cnt++; + } + chop $i{$amnts_field} if $i{$amnts_field} ; + + $sys_cnt = 0; + foreach my $system_id (@event_system_ids) { + # next unless $system_id ; + my (@calibrator_dates_paid_per_event_day) = split(/\:/,$calibrator_dates_paid[$sys_cnt]); + my $sys_day=0; + foreach my $_date (@common_date_array) { + $sys_day++; + $i{$dates_field} .= ($ii{$event_id}{$system_id}{$sys_day}{date_payable}) ? "$ii{$event_id}{$system_id}{$sys_day}{date_payable}:" : ($calibrator_dates_paid_per_event_day[$sys_day-1]) ? "$calibrator_dates_paid_per_event_day[$sys_day-1]:" : ':' ; + } + chop $i{$dates_field} if $i{$dates_field} ; + $i{$dates_field} .= ";" ; + $sys_cnt++; + } + chop $i{$dates_field} if $i{$dates_field} ; + + $ignore{$amnts_field} = 1 if $i{$amnts_field} eq $db{$table}{$event_id}{calibrator_amounts_paid} ; + $ignore{$dates_field} = 1 if $i{$dates_field} eq $db{$table}{$event_id}{calibrator_dates_paid} ; + + &db_min_upd($table,"`id`='$event_id'") ; + } + + %i = %iii ; + +} #------------------------------------------------------------------------------------------ + +sub report_ifields { + + &load_search_vars ; + + if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { + $error = qq~'$i{date_from}' > '$i{date_to}'~ ; &report_screen ; + } + # push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` <= '$i{date_to} 23:59:59' AND `date_to` >= '$i{date_from} 00:00:00'))" ; + # push @report_sql, "(('$i{date_from} 23:59:59' >= `date_from` AND '$i{date_from} 00:00:00' <= `date_to`) OR ('$i{date_to} 23:59:59' >= `date_from` AND '$i{date_to} 00:00:00' <= `date_to`))" ; + # push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` >= '$i{date_from} 00:00:00' AND `date_to` <= '$i{date_to} 23:59:59'))" ; + my @srch_ed_from = &common_split_sql_time($i{date_from}) ; + my @srch_ed_to = &common_split_sql_time($i{date_to}) ; + + &common_date_array("$srch_ed_from[0]$srch_ed_from[1]$srch_ed_from[2]","$srch_ed_to[0]$srch_ed_to[1]$srch_ed_to[2]") ; + + @report_sql_or = () ; + + foreach my $_srch_date (@common_date_array) { + my $srch_ccyy_mm_dd = substr($_srch_date,0,4) . '-' . substr($_srch_date,4,2) . '-' . substr($_srch_date,6,2) ; + push @report_sql_or, "('$srch_ccyy_mm_dd 23:59:59' >= date_from AND '$srch_ccyy_mm_dd 00:00:00' <= date_to)" + } + + my $sql_or = join(' OR ',@report_sql_or) ; + push @report_sql, "($sql_or)" if $sql_or ; + + # push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` >= '$i{date_from} 00:00:00' AND `date_to` <= '$i{date_to} 23:59:59'))" ; + push @report_results, "(BETWEEN '$i{date_from}' AND '$i{date_to}')" ; + } elsif (not $i{date_from}) { + $error = qq~PLEASE ENTER A START DATE!~ ; + &report_screen; + } elsif (not $i{date_to}) { + $error = qq~PLEASE ENTER AN END DATE!~ ; + &report_screen; + } + + if ($i{calibrator_id} and $i{calibrator_id} ne 'all') { + push @report_results,"`CALIBRATOR` = '$db{users}{1}{name}'" ; + push @report_sql, " + ( + `event_system_calibration_ids` LIKE '%;$i{calibrator_id};%' OR + `event_system_calibration_ids` LIKE '%;$i{calibrator_id}' OR + `event_system_calibration_ids` LIKE '$i{calibrator_id};%' OR + `event_system_calibration_ids` LIKE '%-$i{calibrator_id};%' OR + `event_system_calibration_ids` LIKE '%;$i{calibrator_id}-%' OR + `event_system_calibration_ids` LIKE '%-$i{calibrator_id}-%' OR + `event_system_calibration_ids` LIKE '$i{calibrator_id}-%' OR + `event_system_calibration_ids` LIKE '%-$i{calibrator_id}' + ) + " ; + } elsif ($i{calibrator_id} and $i{calibrator_id} eq 'all') { + push @report_results,"`CALIBRATORS` = 'ALL'" ; + } + + if ($i{event_quote_id}) { + &db_min_ro('event_quotes','1,ref',"`id`='$i{event_quote_id}'",'','') ; + push @report_sql, "(e.id = '$i{event_quote_id}')" ; + push @report_results,"EVENT QUOTE = $db{event_quotes}{1}{ref}" ; + } + + if ($i{paid_status} eq 'paid') { + push @report_results,"CALIBRATORS ARE ALL PAID" ; + # push @report_sql, + } elsif ($i{paid_status} eq 'outstanding') { + push @report_results,"CALIBRATOR PAY OUTSTANDING" ; + # push @report_sql, + } + # if ($i{calibration_status} and $i{calibration_status} ne 'all') { + # push @report_results,"`STATUS` = '$db{calibration_status}{$i{calibration_status}}{status}'" ; + # } + + $report_results_msg = uc join(', ', @report_results) ; + + if (not $report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); + &report_screen; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + + our $srch_where_sql = join(' AND ',@report_sql) ; + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + if ($i{calibrator_id} and $i{calibrator_id} ne 'all') { + &db_min_ro('users','1,name',"`id` = '$i{calibrator_id}'",'','') ; + } + + &db_min_ro('calibration_status','id,status',"",'','') ; #`status` LIKE '%done%' + + our $calibration_status = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + $print_box_content_rows .= &common_min_forms_start("$lcpage") ; + + &calibration_load_list_vars("$srch_where_sql",1) ; + + $box_icon .= qq~
    ~ ; + + + # $fcol = 2 ; + + # $print_box_content_rows .= qq~
    ~ ; + # $print_box_content_rows .= &common_min_form_input_col("date_from",$i{date_from}) ; #date_from_i_field + # $print_box_content_rows .= &common_min_form_input_col("date_to",$i{date_to}) ; #date_to_i_field + # $print_box_content_rows .= &common_min_form_input_col("calibrator_id",$i{calibrator_id}) ; #operator_id_i_field + # # $print_box_content_rows .= &common_min_form_input_col("event_quote_id",$i{event_quote_id}) ; + # $print_box_content_rows .= &common_min_form_input_col("calibration_status",$i{calibration_status}) ; + # $print_box_content_rows .= qq~
    ~ ; + + $fcol = 12 ; + + my $report = 1 ; + + our $xlsxdir = "calibrator_payments" ; + + our $xlsxreportname = "Calibrator_Payments" ; + + my $date = &common_write_date_interval($i{date_from},$i{date_to}) ; + + our $xlsx_title_heading = "Calibrator Payments $date" ; + + our $calibration_report = 1 ; + + our $paid_fields = qq~~ ; + + &calibration_build_table_and_or_excel(1,1) ; + + if ($found_after_date) { + + $trigger_jquery_raw .= qq~ + \$("#itv-table tr th:nth-last-child(3)").css("width", "12.5%") ; + \$("#itv-table tr th:nth-last-child(2)").css("width", "12.5%") ; + ~ ; + + } else { + $trigger_jquery_raw .= qq~ + \$("#itv-table tr th:nth-last-child(3)").css("width", "7.5%") ; + \$("#itv-table tr th:nth-last-child(2)").css("width", "7.5%") ; + ~ ; + } + + chop $paid_fields if $paid_fields ; + + &common_debug("paid_fields : $paid_fields " ) ; + + $trigger_jquery_raw .= qq~ + + function selectAll() { + + console.log("selectAll") ; + + let jsObject = { + $paid_fields + }; + + for (let key in jsObject) { + let parts = key.split("_") ; + let event_id = parts[0] ; + let sys_id = parts[1] ; + let day_cnt = parts[2] ; + + console.log("key : "+key) ; + + // console.log("event_id : "+event_id+" , sys_id : "+sys_id+" , day_cnt : "+day_cnt) ; + + \$(\$("#itv-table").dataTable().fnGetNodes()).find(\$("input[name='paid_"+event_id+"_"+sys_id+"_"+day_cnt+"']")).each(function () { + if(\$(this).is(':checked')) { + \$(this).prop('checked',false); + } else { + \$(this).prop('checked',true); + } + }) ; + } + } + ~; + + $fnsortorder = 'asc' ; + + &common_min_extra_crumb("$lcpage","Search Screen") ; + + $trigger_jquery_raw .= qq~ + \$("#savebutt").click(function() { + \$("#$lcpage-form").submit() ; + }) ; + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub set_tick { + + my ($color,$tooltip) = @_ ; + + $tick{green} = qq~2~ ; + $tick{orange} = qq~1~ ; + $tick{red} = qq~0~ ; + + return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub set_cross { + + my ($color,$tooltip) = @_ ; + + $tick{green} = qq~2~ ; + $tick{orange} = qq~1~ ; + $tick{red} = qq~0~ ; + + return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + our $lcpage = 'calibrator-payments' ; + + &common_page_name ; + + our $table = 'event_quotes' ; + $page_title = 'Calibrator Payments' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + # my ($sql_next_day) = &common_add_delta_days(1) ; + # my ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + + my $days_in_month = Days_in_Month($now_year,$now_mm) ; + + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-$now_mm-01") ; #unless $i{date_from} ; + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$days_in_month") ; + + $selected{calibration_status}{all} = 'SELECTED' ; + if ($i{calibration_status}) { + $selected{calibration_status}{$i{calibration_status}} = 'SELECTED' ; + $selected{calibration_status}{all} = '' ; + } + + # # &db_min_ro('calibration_status','id,status','','','') ; + + # # $opts{calibration_status} .= qq~~ ; + # foreach (keys %{$db{calibration_status}}) { + # $opts{calibration_status} .= qq~~ ; + # } + # $opts{calibration_status} .= qq~~ ; + + # $preferred_title{calibration_status} = "Status" ; + + $preferred_title{calibrator_id} = "Calibrator" ; + + # &db_min_ro('users',"id,name","`user_type` = 'support' OR `user_type` = 'casual_calibrator'",'','') ; + &db_min_ro('users',"id,name,username","(user_type = 'casual_calibrator') AND name NOT LIKE 'Rory%'",'','') ; + + $selected{calibrator_id}{all} = 'SELECTED' ; + + if ($i{calibrator_id}) { + $selected{calibrator_id}{$i{calibrator_id}} = 'SELECTED' ; + $selected{calibrator_id}{all} = '' ; + } + + # $opts{calibrator_id} .= qq~~ ; + foreach (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + next if $useropts{it}{$db{users}{$_}{username}} ; + $opts{calibrator_id} .= qq~~ ; + } + $opts{calibrator_id} .= qq~~ ; + + $opts{paid_status} .= qq~~ ; + $opts{paid_status} .= qq~~ ; + $opts{paid_status} .= qq~~ ; + + + &common_min_select_opts('event_quote_id','event_quotes',"ref",$i{event_quote_id},'','',"") ; + + # if ($i{event_quote_id}) { + # $selected{event_quote_id}{$i{event_quote_id}} = 'SELECTED' ; + # } else { + # $selected{event_quote_id}{all} = 'SELECTED' ; + # } + + # $opts{event_quote_id} .= qq~~ ; + + # $print_box_content_rows .= &common_min_form_select('operator_id','') ; + # $print_box_content_rows .= &common_min_form_select('event_quote_id','') ; + # $print_box_content_rows .= &common_min_form_select('calibration_status','') ; + $print_box_content_rows .= &common_min_form_select('calibrator_id','') ; + + $print_box_content_rows .= &common_min_form_select('event_quote_id','') ; + $print_box_content_rows .= &common_min_form_select('paid_status','') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# my $page = "$lcpage\s" ; + +my $page = "event-quotes" ; + +if ($s{no}) { $page = $lcpage ; } + +&common_min_table('id',$page,'list') ; + +our $savjqy = 1 ; + +# &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ; + +$extra_form_fields .= qq~ + + + +~; + +$print_box_content_rows .= &common_min_forms_end('','','save') ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub redirect_screen { + +&common_min_alert_type ; + +print < + + + + $useropts{title} + + + + + + +
    + + + + + + +
    + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +use common ; +use report ; +use xlsxcreator ; +use today ; +use calibrator_payments ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/camera_systems.pl b/scripts/_FromProd/v1.0/camera_systems.pl new file mode 100644 index 0000000..37d7b0a --- /dev/null +++ b/scripts/_FromProd/v1.0/camera_systems.pl @@ -0,0 +1,204 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + +my $exists = '' ; + +$i{name} = lc $i{name} ; +$i{name} =~ s/ //gi ; + +&db_min_ro($table,'*',"name = '$i{name}'",'name','') ; + +foreach my $id (keys %{$db{$table}}) { if ($db{$table}{$id}{name} eq $i{name}) { $exists = 1 ; } } + +if ($exists) { + $alert = &common_min_alert('warning',"NAME ALREADY EXISTS!",'ok') ; + %col_name = (); + &common_min_add_screen; + &common_min_screen1; + } + +} #------------------------------------------------------------------------------------------ + +sub insert { + +&add_db_fields ; + +# $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + +unless ($i{id}) { $error = qq(NO ID) ; return ; } + +&edit_db_fields ; + +# unless ($i{block}) { $i{block} = '0' ; } +# $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +my %seen_camera = () ; +my $delete_button = "" ; + +&db_min_ro('event_quotes','id, camera_system_id','','','') ; + +foreach my $id (keys %{$db{'event_quotes'}}) { + next if $seen_camera{$db{'event_quotes'}{$id}{camera_system_id}} ; + $seen_camera{$db{'event_quotes'}{$id}{camera_system_id}} = 1 ; +} + +&db_min_ro('quotes','id, camera_system_id','','','') ; + +foreach my $id (keys %{$db{'quotes'}}) { + next if $seen_camera{$db{'quotes'}{$id}{camera_system_id}} ; + $seen_camera{$db{'quotes'}{$id}{camera_system_id}} = 1 ; +} + +&db_min_ro($table,'*','','name','') ; + +foreach my $id (keys %{$db{$table}}) { + my $disp_blocked = qq(); if ($db{$table}{$id}{block}) { $disp_blocked = qq(); } + + # $opts{$lcpage} .= qq~~ ; + + my $edit_butt = '' ; my $del_butt = '' ; + + if ($useropts{super}{$username}) { + $edit_butt = qq~ ~ ; + } + if ($useropts{boss}{$username} or $useropts{super}{$username}) { + $del_butt = qq~ ~ if not $seen_camera{$id} ; + $del_butt = qq~ ~ if $seen_camera{$id} ; + } + + $print_tbody .= qq~ + $id + $db{$table}{$id}{name} + $db{$table}{$id}{description} + + $edit_butt + $del_butt + + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + +&hidden_db_fields; + +$ignore{id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + +&hidden_db_fields; + +$hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + +$ignore{iaction} = 1 ; + +# $readonly{name} = 'READONLY' ; +$required{name} = 1 ; +$required{description} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + +# called from common_add_screen + +&select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + +# our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +# $selected{based_in}{$db{$table}{$i{id}}{based_in}} = "SELECTED" ; + +# $extra_form_fields .= &common_min_form_input('new_password','','password') ; + +&select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + +# $required{based_in} = 1 ; +# $select{based_in} = 1 ; +# $opts{based_in} = qq() ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + +$print_thead = qq(IDNAMEDESCRIPTION ) ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'facetime-video' ; +our $lcpage = 'camera-system' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; +our $table = 'camera_systems' ; + +&common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/cameras.pl b/scripts/_FromProd/v1.0/cameras.pl new file mode 100644 index 0000000..520460b --- /dev/null +++ b/scripts/_FromProd/v1.0/cameras.pl @@ -0,0 +1,1117 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; +our $double_box_layout = 1 ; # box on the right layout included + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +# our $allow_add_override = 0 ; if ($user_type eq 'ops_users') { $allow_add_override = 1 ; } + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our $srchscr = 0 ; +our $fnsortcol = 0 ; +our $redirtype = 'list' ; # $redirtype = 'search' ; + +&db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + if ($iaction eq 'edit') { &load_table_vars("`camera_nr` LIKE 'VPU%' OR `camera_nr` LIKE 'S1%' OR `camera_nr` LIKE 'Prime%' OR `camera_nr` LIKE 'Coach%'"); } + + &common_min_action; + # if ( $iaction ~~ ['stock','active','purchased','demo','all','main','other','vpu','rental'] ) { + # &list_screen ; + # &common_min_screen3; + # } + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + +# called from common_min_action + +my $exists = '' ; + +&db_min_ro($table,'*',"camera_nr='$i{camera_nr}'",'','') ; + +foreach my $id (keys %{$db{$table}}) { + if ($db{$table}{$id}{camera_nr} eq $i{camera_nr}) { + $exists = 1 ; + } + } + +if ($exists) { + $alert = &common_min_alert('warning',"CAMERA_NR ALREADY EXISTS!",'ok') ; + %col_name = (); + &common_min_add_screen; + &common_min_screen1; + } + +} #------------------------------------------------------------------------------------------ + +sub insert { + +&add_db_fields ; + +$i{last_edited_by} = $userid ; +$i{user_id} = $userid ; + +$i{id} = &db_min_get_max($table,'id') ; + +&val_check ; + +$i{date_time} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; +$i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&common_upload_files("cameras/$i{id}") ; +&process_upload_ifields; +&process_sport_type_ids; + +&set_fields ; + +if ($i{linked_vpu_id}) { + local $store_serial_nr = $i{serial_nr} ; + local $store_linked_vpu_id = $i{linked_vpu_id} ; +} + +&db_min_insert($table) ; + +if ($store_linked_vpu_id) { + %i = () ; + $i{quote_linked_vpu} = $store_serial_nr ; + &db_min_upd($table,"id='$store_linked_vpu_id'") ; +} + +} #------------------------------------------------------------------------------------------ + +sub update { + +unless ($i{id}) { $error = qq(NO ID) ; return ; } + +&edit_db_fields ; + +if ($userid) { $i{last_edited_by} = $userid ; } + +&val_check ; + +$i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&common_upload_files("cameras/$i{id}") ; +&process_upload_ifields; +&process_sport_type_ids; + +&set_fields ; + +&db_min_upd($table,"id='$i{id}'") ; + +my $store_linked_vpu_id = $i{linked_vpu_id} ; +my $store_serial_nr = $i{serial_nr} ; +my $store_id = $i{id} ; + +if ($i{event_linked_vpu} and $i{event_system_id}) { # update the linked VPU too + my $store_event_system_id = $i{event_system_id} ; + my $store_event_linked_vpu = $i{event_linked_vpu} ; + %i = () ; + $i{event_system_id} = $store_event_system_id ; + &db_min_upd($table,"serial_nr='$store_event_linked_vpu'") ; +} + +if ($store_linked_vpu_id) { + %i = () ; + $i{quote_linked_vpu} = $store_serial_nr ; + &db_min_upd($table,"id='$store_linked_vpu_id'") ; # updating the VPU camera +} else { + %i = () ; + $i{quote_linked_vpu} = '' ; + &db_min_upd($table,"quote_linked_vpu='$store_serial_nr'") ; # updating the VPU camera + %i = () ; + $i{event_linked_vpu} = '' ; + &db_min_upd($table,"event_linked_vpu='$store_serial_nr'") ; # updating the VPU camera +} + +$i{id} = $store_id ; + +# exit if $username eq 'rory' ; + +} #------------------------------------------------------------------------------------------ + +sub process_sport_type_ids { + +local @sporttypeids = split(/\,/,$i{sporttypeids}) ; + +my $sporttypeids = join(",",@sporttypeids) ; + +$sporttypeids =~ s/\s//g; # remove white space + +$ignore{sporttypeids} = 1 ; +$i{sport_type_ids} = $sporttypeids ; + +} #------------------------------------------------------------------------------------------ + +sub set_fields { + +$ignore{serial_nr} = '' ; +$ignore{serial_nr_2} = '' ; +$ignore{serial_nr_3} = '' ; +$ignore{serial_nr_desc} = '' ; +$ignore{serial_nr_2_desc} = '' ; +$ignore{serial_nr_3_desc} = '' ; + +$i{usd_amount} = '0.00' unless $i{usd_amount} ; +$i{cur_amount} = '0.00' unless $i{cur_amount} ; +$i{linked_vpu_id} = '0' unless $i{linked_vpu_id} ; +$i{sport_type_ids} = 'NULL' unless $i{sport_type_ids} ; +$i{system_name} = 'NULL' unless $i{system_name} ; +$i{replaced_vpu_ids} = 'NULL' unless $i{replaced_vpu_ids} ; + +} #------------------------------------------------------------------------------------------ + +sub duplicate { + +unless ($i{id}) { $error = qq~NO ID~ ; return ; } + +local $copy_id = $i{id} ; + +&db_min_copy($table,$copy_id) ; + +&common_min_copy_files("$htmlpath/uploads/cameras/$copy_id","$htmlpath/uploads/cameras/$i{id}") ; + +} #------------------------------------------------------------------------------------------ + +sub val_check { + +# unless ($i{quote_id}) { $i{quote_id} = '0' ; } + +# unless ($i{replacement_date}) { $ignore{replacement_date} = 1 ; } +unless ($i{replacement_date}) { $i{replacement_date} = NULL ; } +unless ($i{date_received}) { $i{date_received} = NULL ; } +unless ($i{event_linked_vpu}) { $i{event_linked_vpu} = NULL ; } +unless ($i{event_system_id}) { $i{event_system_id} = 0 ; } + +if ($i{camera_system_id}) { + my @valarr = split(/\:/,$i{camera_system_id}) ; + $i{camera_system_id} = $valarr[0] ; # set the value to only be the id + $camera_nr_prefix = $valarr[1] ; # set the value to only be the id +} + +# &db_min_ro($table,'id,camera_nr',"`camera_system_id`='$i{camera_system_id}'",'','') ; + +# &set_max_cam_nr ; +# # $camera_nr_suffix++ ; + +} #------------------------------------------------------------------------------------------ + +# sub set_max_cam_nr { + +# foreach my $id (keys %{$db{$table}}) { + # # $camera_nr_suffix++ ; + # my ($cam_type,$cam_cnt) = split(/\-/,$db{$table}{$id}{camera_nr}); + + # $max_cam_cnt{$cam_type} = $cam_cnt unless $max_cam_cnt{$cam_type} > $cam_cnt; +# } + +# } #------------------------------------------------------------------------------------------ + +sub report_ifields { + +&load_search_vars ; + +if ($i{camera_id}) { + push @report_sql, "(`id`='$i{camera_id}')" ; + push @report_results, "camera = $camera_name{$i{camera_id}}" ; + $xlsreportname .= '-' . $i{camera_id} ; + # our $acc_id_sql_where = "`camera_id`='$i{camera_id}'" + } + +# if ($i{camera_system_id}) { +if ($i{camera_system_id} and $i{camera_system_id} ne 'main' and $i{camera_system_id} ne 'other' and $i{camera_system_id} ne 'all') { + push @report_sql, "(`camera_system_id`='$i{camera_system_id}')" ; + push @report_results, "camera_system = $camera_system{$i{camera_system_id}}" ; + $xlsreportname .= '-' . $i{camera_id} ; + # our $acc_id_sql_where = "`camera_id`='$i{camera_id}'" +} elsif ($i{camera_system_id} eq 'main' or $i{camera_system_id} eq 'other' or $i{camera_system_id} eq 'all') { + push @report_results, "camera_system = $i{camera_system_id}" ; +} + +if ($i{stock}) { + push @report_results, "stock = $i{stock}" ; + $xlsreportname .= '-' . $i{stock} ; + } + +if ($i{client_id}) { + # push @report_sql, "(`client_id` = '$i{client_id}')" ; + push @report_results, "Client = $client{$i{client_id}}" ; + } + +if ($i{serial_nr}) { + push @report_sql, "(`serial_nr` LIKE '%$i{serial_nr}%')" ; + push @report_results, "serial_nr LIKE `$i{serial_nr}`" ; + } + +if ($i{quote_nr}) { + push @report_sql, "(`quote_nr`='$i{quote_nr}')" ; + push @report_results, "quote_nr = `$i{quote_nr}`" ; + } + +if ($i{date_received_from} and $i{date_received_to}) { # check dates + my $date_received_from_check = $i{date_received_from} ; + $date_received_from_check =~ s/\-//g ; + my $date_received_to_check = $i{date_received_to} ; + $date_received_to_check =~ s/\-//g ; + if ($date_received_from_check > $date_received_to_check) { $error = qq(CAMERAS FROM ($i{date_received_from}) > CAMERAS TO ($i{date_received_to})); &report_screen; } + } + +if ($i{date_received_from}) { + push @report_sql, "(`date_received` >= '$i{date_received_from}')" ; + push @report_results, "date_received >= $i{date_received_from}" ; + } + +if ($i{date_received_to}) { + push @report_sql, "(`date_received` <= '$i{date_received_to}')" ; + push @report_results, "date_received <= $i{date_received_to}" ; + } + +$report_results_msg = uc join(', ', @report_results) ; + +unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); &report_screen; } else { $isaved = qq(SELECT WHERE $report_results_msg) ; } + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + &db_min_ro('cameras','id,camera_nr',"`id`='$i{camera_id}'",'','') ; + foreach my $id (keys %{$db{cameras}}) { $camera_name{$id} = $db{cameras}{$id}{camera_nr} ; } + + &db_min_ro('camera_systems','id,name',"`id`='$i{camera_system_id}'",'','') ; + foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + + if ($i{client_id}) { + my $customers_sql_where = "`id`='$i{client_id}'" ; + &db_min_ro('customers','*',$customers_sql_where,'','') ; + foreach my $id (keys %{$db{customers}}) { $client{$id} = $db{customers}{$id}{name} ; } + } + +} #------------------------------------------------------------------------------------------ + +sub process_upload_ifields { + +foreach (keys %uploads_file) { $i{$_} = $uploads_file{$_} ; $ignore{$_} = '' ; } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +our $open_new_tab = qq~target="_blank"~ ; + +my $srch_where_sql = join(' AND ', @report_sql) ; + +my $add_sql_where = '' ; + +our @sql_col_display = ("camera_nr","in_stock","camera_system_id","serial_nr","part_number","system_name","date_received","client_id","ref_nr","date_delivered","date_active","quote_ref","replacement_date") ; + +push @sql_col_display, "" ; + +&report_xls_export_header("Cameras$xlsreportname",'cameras') ; + +&load_list_vars("$srch_where_sql$add_sql_where") ; + +foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) { + + next if (&common_camera_system_filter($table,$id)) ; + + if ($i{client_id}) { next unless $client{$i{client_id}} eq $quote_customer{$id} ; } + # if ($i{stock}) { next unless $i{stock} eq lc $quote_type{$id} ; } + + # if ($i{stock}) { &common_debug("next unless $i{stock} eq $lc_stock"); } + + $camera_system_count{$camera_system{$db{$table}{$id}{camera_system_id}}}++; + + $print_tbody .= qq~~ ; + + $xlscol=0; + + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$table}{$id}{$_} ; + my $align = '' ; + + my $center = qq~ class="dt-center"~ ; + + if ($_ eq 'date_received') { $align = $center ; } + # if ($_ eq 'date_delivered') { $val = $quote_delivery_date{$id} ; $align = $center ; } + if ($_ eq 'date_delivered') { $val = $db{$table}{$id}{quote_delivery_date} ; $align = $center ; } + if ($_ eq 'date_active') { $val = $db{$table}{$id}{quote_active_date} ; $align = $center ; } + if ($_ eq 'camera_system_id') { $val = $camera_system{$val} ; } + if ($_ eq 'client_id') { $val = $quote_customer{$id} ; } + # if ($_ eq 'quote_type') { $val = $quote_type{$id} ; } + if ($_ eq 'ref_nr') { $val = $db{$table}{$id}{quote_nr} ; $align = $center ; } + if ($_ eq 'quote_ref') { $val = $db{$table}{$id}{quote_ref} ? $db{$table}{$id}{quote_ref} : $quote_ref{$id} ; } + # if ($_ eq 'purchase/rental') { $val = $quote_type{$id} ; $align = $center ; } + if ($_ eq 'demo') { $val = $db{$table}{$id}{demo_recipient} ; } + + if ($_ eq 'extended_warranty') { + $val = $db{$table}{$id}{quote_ew_date_from} if $db{$table}{$id}{quote_ew_date_from} ; + $val .= "/$db{$table}{$id}{quote_ew_date_to}" if $db{$table}{$id}{quote_ew_date_to} ; + $align = $center ; + } + + if ($_ eq 'in_stock') { if ($db{$table}{$id}{quote_nr} or $db{$table}{$id}{demo_recipient} or $db{$table}{$id}{replacement_date} or $db{$table}{$id}{event_system_id}) { $val = 0 ; } else { $val = 1 ; } } + + &report_xls_export_process_cell('','',$val) ; # ------------------------------------------------------------------------- HTML AFTER + $xlscol++; + + # if ($_ eq 'in_stock') { if ($db{$table}{$id}{quote_nr}) { $val = &set_tick('red', '') ; } else { $val = &set_tick('green', '') ; } $align = $center ; } + if ($_ eq 'in_stock') { if ($val==1) { $val = &set_tick('green', '') ; } else { $val = &set_tick('red', '') ; } $align = $center ; } + # if ($_ eq 'quote_nr') { $val = qq~$val~ ; } + + if ($_ eq 'replacement_date') { + $val = qq~$val~ ; + } + + $val = &common_camera_links($table,$id,$val) if ($_ eq 'camera_nr' or $_ eq 'ref_nr') and $pixellot_limit{$username}!=1 and $events_limit{$username}!=1 ; + + if ($_ eq 'camera_nr' && $camera_ticket{$id} && $pixellot_limit{$username}!=1 && $events_limit{$username}!=1) { + $val .= $camera_ticket{$id} ; + } + + $print_tbody .= qq~$val~ ; + } + + my $delete_butt = '' ; my $copy_butt = '' ; my $edit_butt = '' ; + + if (($useropts{boss}{$username} or $useropts{super}{$username}) and $pixellot_limit{$username}!=1 and $events_limit{$username}!=1) { + $edit_butt = qq~~ ; + $copy_butt = qq~~; + $delete_butt = qq~~ ; + } + + # if ($camera_exists_on_quote{$id}) { $delete_butt = '' ; } + if ($db{$table}{$id}{quote_nr}) { $delete_butt = '' ; } + + $print_tbody .= qq( $edit_butt $copy_butt $delete_butt) ; + $xlsrow++ ; + } + +&report_xls_export_footer('L',15,'cameras') ; + +our $fnsortcol = 0 ; our $fnsortorder = 'asc' ; + +$print_more_boxes .= qq(
    ) ; + +&common_min_extra_crumb("search-$lcpage\s","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub set_tick { + +my ($color,$tooltip) = @_ ; + +$tick{green} = qq~2~ ; +$tick{orange} = qq~1~ ; +$tick{red} = qq~0~ ; + +return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub load_list_vars { + + my ($where) = @_ ; + + &db_min_ro('camera_systems','id,name','','','') ; + foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + + &db_min_ro('customers','id,name','','','') ; + foreach my $id (keys %{$db{customers}}) { $customer{$id} = $db{customers}{$id}{name} ; } + + my $surl = qq~javascript:dlgMdl('$useropts{scripts}/dialog/read_ticket.pl~; + &db_min_ro('tickets','*',"camera_ids IS NOT NULL",'','') ; + foreach my $id (keys %{$db{tickets}}) { + my $cam_ids = $db{tickets}{$id}{camera_ids} ; + my $uid = $db{tickets}{$id}{unique_id} ; + my $sent_from = $db{tickets}{$id}{sent_from} ; + my $date_time = $db{tickets}{$id}{date_time} ; + my $s_uid = $db{tickets}{$id}{suid} ; + my $subject = $db{tickets}{$id}{subject} ; + + my @camera_ids = split(/\,/,$cam_ids) ; + + foreach my $cam_id (@camera_ids) { + $camera_ticket{$cam_id} .= '~ + } + } + + # &common_load_quote_vars('>0'); + + &common_load_quote_vars("cameras.quote_nr>0 AND cameras.quote_nr=quotes.quote_nr"); + + &load_table_vars($where); + + # &db_min_ro($table,'*',$where,'','') ; + +} #------------------------------------------------------------------------------------------ + +sub load_table_vars { + +my ($where) = @_ ; + +&db_min_ro($table,'*',$where,'','') ; + +# foreach my $id (keys %{$db{$table}}) { + # $cam_nr{$id} = $db{$table}{$id}{camera_nr} ; + # $serial_nr{$id} = $db{$table}{$id}{serial_nr} ; +# } + +} #------------------------------------------------------------------------------------------ + +sub thead { + + my $cam_qtys = '' ; + + foreach (keys %camera_system_count) { + $cam_qtys .= qq~$_ : $camera_system_count{$_}
    ~ ; + } + + $replace_blank_table_top_right = qq~ ~ if $cam_qtys ; + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub hidden_db_fields { + +$ignore{iaction} = 1 ; +# $ignore{logo} = 1 ; +$ignore{serial_nr} = 1 ; +$ignore{serial_nr_2} = 1 ; +$ignore{serial_nr_3} = 1 ; +$ignore{serial_nr_desc} = 1 ; +$ignore{serial_nr_2_desc} = 1 ; +$ignore{serial_nr_3_desc} = 1 ; + +$ignore{quote_nr} = 1 ; +$ignore{quote_customer} = 1 ; +# $ignore{quote_ref} = 1 ; +$ignore{quote_main_ref} = 1 ; +$ignore{quote_delivery_date} = 1 ; +$ignore{quote_active_date} = 1 ; +$ignore{quote_type} = 1 ; +$ignore{quote_date_from} = 1 ; +$ignore{quote_date_to} = 1 ; +$ignore{quote_linked_vpu_sn} = 1 ; +$ignore{quote_linked_vpu_cn} = 1 ; + +$hidden{quote_linked_vpu} = 2 ; +# $ignore{active} = 1 ; +$hidden{replaced_vpu_ids} = 2 ; + + +# $checkbox{active} = 1 ; +$hidden{last_updated} = 2 ; + +$hidden{last_edited_by} = 2 ; +$hidden{date_time} = 2 ; +$hidden{user_id} = 2 ; + +$required{currency} = 1 ; +$readonly{currency} = 'READONLY' ; + +$readonly{cur_amount} = 'READONLY' ; + +# $required{serial_nr} = 1 ; # alphanumeric +$textarea{notes} = 1 ; + +$datepicker{replacement_date} = 1 ; +$datepicker{date_received} = 1 ; +# $datepicker{date_delivered} = 1 ; +# $datepicker{date_active} = 1 ; + +$info_glyph_tooltip{demo_recipient} = qq~~ ; + +for (1 .. 3) { + $ignore{"camera_$_"} = 1 ; + $ignore{"iattachcamera_$_"} = 1 ; + } + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + +&sort_fields; + +&hidden_db_fields ; + +$hidden{id} = 2 ; +$required{camera_nr} = 1 ; +# $hidden{camera_nr} = 2 ; + +&common_exchange_rates; + +$db{$table}{''}{currency} = 'ZAR' ; +$db{$table}{''}{roe} = $roe{ZAR} ; + +if ($iaction eq 'add') { &build_boxes_add ; } # can't be in add_screen, only works if here + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + +&sort_fields; + +&hidden_db_fields ; + +$readonly{camera_nr} = 'READONLY' ; +$hidden{camera_system_id} = 2 ; + +$ignore{date_time} = 1 ; +$ignore{user_id} = 1 ; + +unless ($db{$table}{$i{id}}{currency}) { + &common_exchange_rates; + $db{$table}{$i{id}}{currency} = 'ZAR' ; + $db{$table}{$i{id}}{roe} = $roe{ZAR} ; +} + +$hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + +%sort_field = () ; + +$sort_field{1} = 'camera_system_id' ; $fcol{camera_system_id} = 8 ; +$sort_field{2} = 'camera_nr' ; $fcol{camera_nr} = 8 ; +$sort_field{3} = 'date_received' ; $fcol{date_received} = 4 ; +$sort_field{4} = 'usd_amount' ; $dont_end_row{usd_amount} = 1 ; $fcol{usd_amount} = 2 ; $preferred_title{usd_amount} = 'Amount' ; +$sort_field{5} = 'currency' ; $add_col{currency} = 1 ; $fcol{currency} = 2 ; +$sort_field{6} = 'roe' ; $add_col{roe} = 1 ; $fcol{roe} = 2 ; +$sort_field{7} = 'cur_amount' ; $add_col{cur_amount} = 1 ; $fcol{cur_amount} = 2 ; +$sort_field{8} = 'demo_recipient' ; $add_finish_div{demo_recipient} = 1 ; $fcol{demo_recipient} = 8 ; +$sort_field{9} = 'linked_vpu_id' ; $fcol{linked_vpu_id} = 4 ; $dont_end_row{linked_vpu_id} = 1 ; $select{linked_vpu_id} = 1 ; $preferred_title{linked_vpu_id} = "Linked VPU" ; +$sort_field{10} = 'sport_type_ids' ; $select{sport_type_ids} = 1 ; $preferred_title{sport_type_ids} = "Sport Types" ; $dlg{sport_type_ids} = qq~
    ~ ; +$sort_field{11} = 'quote_ref' ; +$sort_field{12} = 'notes' ; + +} #------------------------------------------------------------------------------- + +sub select_opts { + +my ($id) = @_ ; + +$multiple{sport_type_ids} = 1; + +my @sport_type_ids = split(/\,/,$db{$table}{$id}{sport_type_ids}); + +foreach (@sport_type_ids) { + $selected_multi{$_} = 'SELECTED' ; + &common_debug("SELECTED sport_type_ids [$_] : [selected=$selected_multi{$_}]") ; +} + +&common_min_select_opts('sport_type_ids','sport_types','name',$db{$table}{$id}{sport_type_ids},'') ; + +$extra_form_fields .= qq~~; + +$trigger_jquery_raw .= qq~ +\$("#savebutt").click(function() { + let st_val = \$("#selectSport_type_ids").chosen().val() ; + \$('#sport-type-ids').val(st_val); + \$('#cameras-form').submit(); +});~; + +if ($iaction eq 'add') { + &db_min_ro('camera_systems','*',$where,'','') ; + $select{camera_system_id} = 1 ; + $required{camera_system_id} = 1 ; + local $sel_camera_system_id = 0 ; + local %camera_system_code = () ; + foreach my $id (keys %{$db{camera_systems}}) { + my $saved_val = $db{$table}{$i{id}}{camera_system_id} ; + if ($saved_val) { my @valarr = split(/\:/,$saved_val) ; $saved_val = $valarr[0] ; } + if ($saved_val eq $id) { $selected = 'SELECTED' ; $sel_camera_system_id = $id } else { $selected = '' ; } + $opts{camera_system_id} .= qq~~ ; + } +} + +local $sel = 'SELECTED' ; +$opts{linked_vpu_id} = qq~~ ; +$sel = '' ; + +if ($db{$table}{$id}{camera_system_id} == 1 or $db{$table}{$id}{camera_system_id} == 2 or $db{$table}{$id}{camera_system_id} == 14) { + my $dbtable = "itv_admin_db.$table" ; + &db_min_ro($dbtable,'id,camera_nr,serial_nr,linked_vpu_id,quote_linked_vpu,camera_system_id',"(camera_nr LIKE 'vpu%' OR camera_nr LIKE 'S1%' OR camera_nr LIKE 'S2%') AND (quote_linked_vpu IS NULL OR quote_linked_vpu = '' OR quote_linked_vpu = '$db{cameras}{$id}{serial_nr}') AND (event_linked_vpu IS NULL OR event_linked_vpu = '')",'','') ; + + local %is_linked = () ; + foreach (sort keys %{$db{$dbtable}}) { + next if $_ == $i{id} ; + $is_linked{$db{$dbtable}{$_}{linked_vpu_id}} = $db{$dbtable}{$_}{serial_nr} if $db{$dbtable}{$_}{linked_vpu_id} ; + } + + $opts{linked_vpu_id} = qq~~ ; + foreach (sort keys %{$db{$dbtable}}) { + local ($cam_part_1,$cam_part_2) = split(/\-/,$db{$dbtable}{$_}{camera_nr}) ; + + next if substr($db{$dbtable}{$_}{camera_nr},0,3) ne 'VPU' ; + next if ($is_linked{$_} and $db{$dbtable}{$_}{quote_linked_vpu} ne $db{cameras}{$id}{serial_nr}) ; + next if substr($db{$dbtable}{$_}{camera_nr},3,2) ne 'S1' and substr($db{$dbtable}{$_}{camera_nr},3,2) ne 'S2' ; + next if $db{camera_systems}{$db{$table}{$i{id}}{camera_system_id}}{code} and $db{camera_systems}{$db{$table}{$i{id}}{camera_system_id}}{code} ne substr($db{$dbtable}{$_}{camera_nr},3,2) ; + + $sel = 'SELECTED' if $db{$dbtable}{$i{id}}{linked_vpu_id} == $_ or $db{$dbtable}{$_}{quote_linked_vpu} eq $db{cameras}{$id}{serial_nr} ; + + $opts{linked_vpu_id} .= qq~~ ; + $sel = '' ; + } +} + +$trigger_jquery_raw .= qq~ +\$("#selectCamera_system_id").change(function() { + var cam_nr = \$("#inputCamera_nr") ; + var sel_cam_id = \$("#selectCamera_system_id").val() ; + var url = "$useropts{scripts}/get/get_db_latest_cam_nr.pl?camera_system_id=" + \$("#selectCamera_system_id").val() ; + \$.get(url, function(json) { + \$.each(json, function(key, data) { + cam_nr.val(data.camera_nr); + }); + }, + 'json'); + + // console.log("sel_cam_id :"+sel_cam_id) ; + + var vpu_id = \$("#selectLinked_vpu_id") ; + vpu_id.empty(); + vpu_id.trigger("chosen:updated"); + + var linked_vpu_id = '$db{cameras}{$id}{linked_vpu_id}' ; + // console.log("1 . vpu_id : "+vpu_id.val()) ; + if (sel_cam_id == '1:S1' || sel_cam_id == '2:S2' || sel_cam_id == '14:') { + vpu_id.prepend("") ; + // var active = \$("#checkboxActive") ; + var url2 = "$useropts{scripts}/get/get_db_linked_vpu.pl?camera_system_id=" + \$("#selectCamera_system_id").val() + "&linked_vpu_id="+linked_vpu_id ; + // console.log("url2 : "+url2+" linked_vpu_id : "+linked_vpu_id) ; + vpu_id.empty(); + \$.get(url2, function(json) { + \$.each(json, function(key, data) { + // console.log("vpu_id :"+data.id+" - "+data.camera_nr+" - "+data.serial_nr+"id data.sel : "+data.sel) ; + + if (data.sel == 0) { + vpu_id.append("") ; + } + else { + vpu_id.append("") ; + } + }); + vpu_id.trigger("chosen:updated"); + }, + 'json'); + + } + // console.log("2 . vpu_id : "+vpu_id.val()) ; + if (vpu_id.val() == null) { + vpu_id.append("") ; + vpu_id.trigger("chosen:updated"); + } +}); + + +\$("#inputUsd_amount,#inputRoe").change(function() { + var roe = \$("#inputRoe").val() ; + var curr = \$("#inputCurrency").val() ; // \$("#selectCurrency").val() ; + var uval = \$("#inputUsd_amount").val() ; + + var usdAmnt = uval * 1 ; + var currAmnt = usdAmnt * roe ; + + \$("#inputCur_amount").val(currAmnt.toFixed(2)) ; +}); +~; + +$trigger_jquery .= qq~ + \$("#camera-uploads-box").trigger('click'); + \$("#camera-replacement-box").trigger('click'); +~; + +} #------------------------------------------------------------------------------- + +sub add_screen { + +# called from common_add_screen + +&select_opts('') ; + +our $savjqy = 1 ; # incorporate jquery into the save event to accommodate the multiple chosen options + +# &build_boxes_add ; # can't do this here + +} #------------------------------------------------------------------------------------------ + +sub build_boxes_add { + +$print_box_content_rows .= &common_min_forms_start($table) ; +$print_box_content_rows .= qq~
    ~ ; +$print_box_content_rows .= &common_min_box_top('camera',"  Camera",$box_main_bg) ; +$print_box_content_rows .= &common_min_edit_form($id,$table,'',3,9,1,1) ; +$print_box_content_rows .= &common_min_box_foot ; + +&build_boxes_left(''); + +$print_box_content_rows .= qq~
    ~ ; + +&build_boxes_right(''); + +$print_box_content_rows .= qq~
    ~ ; + +$print_box_content_rows .= &common_min_forms_end('',$table,'save') ; + +} #---------------------------------------------------------------------------------------- + +sub edit_screen { + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +&select_opts($i{id}) ; + +$addcpb = 1 ; # add copy button to the edit screen + +our $savjqy = 1 ; # incorporate jquery into the save event to accommodate the multiple chosen options + +&build_boxes_edit($i{id}) ; + +&common_min_extra_crumb("search-$lcpage\s","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes_edit { + +my ($id) = @_ ; + +$print_box_content_rows .= &common_min_forms_start($table) ; +$print_box_content_rows .= qq~
    ~ ; +$print_box_content_rows .= &common_min_box_top('camera',"  Camera : $db{$table}{$id}{id}",$box_main_bg) ; +$print_box_content_rows .= &common_min_edit_form($id,$table,'',3,9,1,1) ; +$print_box_content_rows .= &common_min_box_foot ; + &build_boxes_left($id); +$print_box_content_rows .= qq~
    ~ ; + &build_boxes_right($id); +$print_box_content_rows .= qq~
    ~ ; +$print_box_content_rows .= &common_min_forms_end($id,$table,'update',$skip) ; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_left { + + my ($id) = @_ ; + + # our ($lcol,$fcol) = &common_min_columns(3,9) ; + + $print_box_content_rows .= qq~ +
    +
    +
    +
    ~ ; # fixes row highlighting issue + + # #----------------- NEW BOX LEFT --------------------------------------------------------------------- + + $add_form_fields = '' ; $fcol=3 ; + + # if ($_>$cntcamloop) { $cam_display_butt = qq~display:none;~ ; } else { $cam_display_butt = '' ; } + + $add_form_fields .= qq~ +
    +
    ~ ; + $col = 'serial_nr' ; + $required{$col} = 1 ; + &common_min_forms_required ; + $add_form_fields .= &common_min_form_input('serial_nr',$db{$table}{$id}{serial_nr},'','',1) ; + $add_form_fields .= qq~ +
    + +
    + ~ ; + $add_form_fields .= &common_min_form_input_col('part_number',$db{$table}{$id}{part_number}) ; + $fcol=3 ; $lcol=3 ; + $add_form_fields .= qq~ +
    +
    ~ ; + + $add_form_fields .= qq~

    ~ ; + + unless ($db{$table}{$id}{serial_nr_2}) { + $disp_sn_2_style = qq~style="display:none;"~ ; + $add_form_fields .= qq~~ ; + $trigger_jquery_raw .= qq~ \$("#btn_serial_nr").click(function () { + \$("#sn_2_row").toggle(); + \$("#btn_serial_nr").hide(); + \$("#btn_serial_nr_2").show(); + });~ ; + } + + $add_form_fields .= qq~ +
    ~ ; + + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= &common_min_form_input('serial_nr_2',$db{$table}{$id}{serial_nr_2},'','',1) ; $fcol=5 ; + $add_form_fields .= &common_min_form_input_col('serial_nr_2_desc',$db{$table}{$id}{serial_nr_2_desc}) ; $fcol=3 ; + $add_form_fields .= qq~

    ~ ; + + unless ($db{$table}{$id}{serial_nr_3}) { + $disp_sn_3_style = qq~style="display:none;"~ ; + $add_form_fields .= qq~~ ; + $trigger_jquery_raw .= qq~ \$("#btn_serial_nr_2").click(function () { + \$("#sn_3_row").toggle(); + \$("#btn_serial_nr_2").hide(); + \$("#btn_serial_nr_3").show(); + });~ ; + } + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= &common_min_form_input('serial_nr_3',$db{$table}{$id}{serial_nr_3},'','',1) ; $fcol=5 ; + $add_form_fields .= &common_min_form_input_col('serial_nr_3_desc',$db{$table}{$id}{serial_nr_3_desc}) ; $fcol=3 ; + $add_form_fields .= qq~

    ~ ; + + unless ($db{$table}{$id}{serial_nr_4}) { + $disp_sn_4_style = qq~style="display:none;"~ ; + $add_form_fields .= qq~~ ; + $trigger_jquery_raw .= qq~ \$("#btn_serial_nr_3").click(function () { + \$("#sn_4_row").toggle(); + \$("#btn_serial_nr_3").hide(); + \$("#btn_serial_nr_4").show(); + });~ ; + } + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= &common_min_form_input('serial_nr_4',$db{$table}{$id}{serial_nr_4},'','',1) ; $fcol=5 ; + $add_form_fields .= &common_min_form_input_col('serial_nr_4_desc',$db{$table}{$id}{serial_nr_4_desc}) ; $fcol=3 ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= qq~ +
     
    +
    +
    ~ ; + $add_form_fields .= &common_min_form_input('system_name',$db{$table}{$id}{system_name},'','','') ; + $add_form_fields .= qq~ +
    +
    ~ ; + + $print_box_content_rows .= &common_min_box_top('film','Serial Nr.',$box_right_bg); + $print_box_content_rows .= $add_form_fields ; + $print_box_content_rows .= &common_min_box_foot; + + my $cam_nr_prefix = substr($db{$table}{$id}{camera_nr},0,2) ; + + if (($cam_nr_prefix eq 'S1' || $cam_nr_prefix eq 'S2' || $cam_nr_prefix eq 'VP') and $db{$table}{$id}{quote_nr} == 0) { + + $add_form_fields = '' ; + + $print_box_content_rows .= qq~
    ~ ; # fixes row highlighting issue + + %done_col_val = () ; + + &common_min_select_opts('event_linked_vpu','itv_admin_db.cameras','camera_nr',$db{$table}{$id}{event_linked_vpu},'','',"camera_nr LIKE 'VPU%' AND (quote_linked_vpu = '' OR quote_linked_vpu IS NULL)",'serial_nr') unless $cam_nr_prefix eq 'VP' ; + + $print_box_content_rows .= &common_min_box_top('star','Events',$box_right_bg); $preferred_title{event_linked_vpu} = 'Event System' ; + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= &common_min_form_select('event_linked_vpu',$db{$table}{$id}{event_linked_vpu},1) ; $fcol=5 ; + &common_min_select_opts('event_system_id','itv_admin_db.event_systems','description',$db{$table}{$id}{event_system_id},'') ; + $allow_deselect{event_system_id} = 1 ; + $print_box_content_rows .= &common_min_form_select_col('event_system_id',$db{$table}{$id}{event_system_id}) ; + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= &common_min_box_foot; + + } + + # #----------------- END BOX LEFT --------------------------------------------------------------------- + + $print_box_content_rows .= qq~
    ~ ; # fixes row highlighting issue + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_right { + +my ($id) = @_ ; + +my $box_icon = '' ; + +#----------------------------------------------------------------- New box -------------------------------------- + +if ($iaction eq 'edit') { + + &db_min_ro('customers','id,name','','','') ; + foreach my $cust_id (keys %{$db{customers}}) { $customer{$cust_id} = $db{customers}{$cust_id}{name} ; } + + my $q_nr = $db{$table}{$id}{quote_nr} ; + my $c_nr = $db{$table}{$id}{camera_nr} ; + + # &common_load_quote_vars("='$id'"); + &common_load_quote_vars("cameras.quote_nr='$q_nr' AND quotes.quote_nr='$q_nr'"); + + if ($q_nr) { + + # my $ref = $db{$table}{$id}{quote_ref} ? $db{$table}{$id}{quote_ref} : $quote_ref{$id} ; + + $print_box_content_rows .= &common_min_box_top('qrcode','Details',$box_right_bg,$box_icon,'') ; + $lcol=3; + $fcol=4; + my $field = 'quote_nr' ; $preferred_title{quote_nr} = 'Ref Nr' ; $readonly{$field} = 'READONLY' ; $print_box_content_rows .= &common_min_form_input($field,$q_nr) ; $ignore{$field} = 1 ; + my $field = 'quote_customer' ; $preferred_title{quote_customer} = 'Customer' ; $readonly{$field} = 'READONLY' ; $print_box_content_rows .= &common_min_form_input($field,$quote_customer{$id}) ; $ignore{$field} = 1 ; + my $field = 'quote_main_ref' ; $preferred_title{quote_main_ref} = 'Ref' ; $readonly{$field} = 'READONLY' ; $print_box_content_rows .= &common_min_form_input($field,$quote_ref{$id}) ; $ignore{$field} = 1 ; + my $field = 'quote_delivery_date' ; $preferred_title{quote_delivery_date} = 'Delivery Date' ; $readonly{$field} = 'READONLY' ; $print_box_content_rows .= &common_min_form_input($field,$db{$table}{$id}{quote_delivery_date}) ; $ignore{$field} = 1 ; + my $field = 'quote_active_date' ; $preferred_title{quote_active_date} = 'Active Date' ; $readonly{$field} = 'READONLY' ; $print_box_content_rows .= &common_min_form_input($field,$db{$table}{$id}{quote_active_date}) ; $ignore{$field} = 1 ; + my $field = 'quote_type' ; $preferred_title{quote_type} = 'Type' ; $readonly{$field} = 'READONLY' ; $print_box_content_rows .= &common_min_form_input($field,$quote_type{$id}) ; $ignore{$field} = 1 ; + my $field = 'quote_date_from' ; $preferred_title{quote_date_from} = 'EW From' ; $readonly{$field} = 'READONLY' ; $print_box_content_rows .= &common_min_form_input($field,$db{$table}{$id}{quote_ew_date_from}) ; $ignore{$field} = 1 ; + my $field = 'quote_date_to' ; $preferred_title{quote_date_to} = 'EW To' ; $readonly{$field} = 'READONLY' ; $print_box_content_rows .= &common_min_form_input($field,$db{$table}{$id}{quote_ew_date_to}) ; $ignore{$field} = 1 ; + my $field = 'quote_linked_vpu_sn' ; $preferred_title{quote_linked_vpu_sn} = 'Linked VPU SerialNr' ; $readonly{$field} = 'READONLY' ; $print_box_content_rows .= &common_min_form_input($field,$linked_sn{$db{$table}{$id}{serial_nr}}) ; $ignore{$field} = 1 ; # &common_debug("SN - $val [$db{$table}{$id}{camera_nr},$quote_nr{$id},$id]"); + my $field = 'quote_linked_vpu_cn' ; $preferred_title{quote_linked_vpu_cn} = 'Linked VPU CameraNr' ; $readonly{$field} = 'READONLY' ; $print_box_content_rows .= &common_min_form_input($field,$linked_cn{$db{$table}{$id}{serial_nr}}) ; $ignore{$field} = 1 ; # &common_debug("CN - $val [$db{$table}{$id}{camera_nr},$quote_nr{$id},$id]"); + $print_box_content_rows .= &common_min_box_foot ; + } +} + +$print_box_content_rows .= &common_min_box_top('picture','Uploads',$box_right_bg,$box_icon,'camera-uploads-box') ; + $print_box_content_rows .= qq~
     
    ~; + + for (1 .. 3) { + my $uploads = &common_get_field_uploads($id,"camera_$_",'id') ; + + if ($uploads) { + $print_box_content_rows .= qq~
    $uploads
    ~; + } else { + $print_box_content_rows .= qq~
    + + +

    Upload file from PC.

    +
    ~; + } + } + + $print_box_content_rows .= qq~
    ~; +$print_box_content_rows .= &common_min_box_foot ; + +#----------------------------------------------------------------- New box -------------------------------------- + +$print_box_content_rows .= &common_min_box_top('wrench','Replacement',$box_right_bg,$box_icon,'camera-replacement-box') ; + # $print_box_content_rows .= qq~
     
    ~; + $fcol=4; + $print_box_content_rows .= &common_min_form_datepicker('replacement_date',$db{$table}{$id}{replacement_date}) ; + $print_box_content_rows .= &common_min_form_input('replacement_camera_nr',$db{$table}{$id}{replacement_camera_nr}) ; + # $print_box_content_rows .= qq~
    ~; +$print_box_content_rows .= &common_min_box_foot ; + +} #---------------------------------------------------------------------------------------- + +sub get_uploads { + +my ($id,$type) = @_ ; + +unless ($id and $type) { return() ; } + +my $gallery = '' ; my %gallery = () ; + +my $field = $type ; +if ($db{$table}{$id}{$field}){ + $tooltip = qq(data-toggle="tooltip" data-placement="top" title="$type" data-original-title="$type") ; + $gallery{$type} .= qq(
  • + $type +
  • ) ; + } + +if ($gallery{$type}) { $gallery = '' ; } + +return ($gallery) ; + +} #------------------------------------------------------------------------------------------ + +sub page_opts { + +our $glyphicon = 'list' ; +our $lcpage = 'camera' ; + +&common_page_name ; + +our $table = 'cameras' ; +$page_title = 'Camera' ; + +$alert = qq~
    ~ ; + +&common_min_add_extras unless $pixellot_limit{$username} or $events_limit{$username} ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + +our $lcol = 3 ; +our $fcol = 5 ; + +# my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-365); # 6 weeks back + +# $set_month = sprintf("%02s", $set_month) ; +# $set_day = sprintf("%02s", $set_day) ; + +$print_box_content_rows .= &common_min_forms_start('report') ; + +&common_camera_opts ; + +&common_min_select_opts('camera_system_id','camera_systems','code',$i{camera_system_id},'') ; +&common_min_select_opts('client_id','customers','name',$i{client_id},'') ; +$print_box_content_rows .= &common_min_form_select('client_id',$i{client_id}) ; +$print_box_content_rows .= &common_min_form_input('serial_nr','') ; +$print_box_content_rows .= &common_min_form_select('camera_system_id',$i{camera_system_id}) ; +$print_box_content_rows .= &common_min_form_datepicker('date_received_from','') ; +$print_box_content_rows .= &common_min_form_datepicker('date_received_to','') ; +$print_box_content_rows .= &common_min_form_select('stock','') ; + +&common_min_select_opts('quote_nr','cameras','quote_nr','','','','quote_nr>0','','','DISTINCT(quote_nr)') ; + +$print_box_content_rows .= &common_min_forms_end('','','report') ; + +&common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +use common ; +use report ; +use xlsxcreator ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/cameras_report.pl b/scripts/_FromProd/v1.0/cameras_report.pl new file mode 100644 index 0000000..863c5be --- /dev/null +++ b/scripts/_FromProd/v1.0/cameras_report.pl @@ -0,0 +1,300 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our $srchscr = 1 ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + if ($iaction eq ''){ &report_screen ; } + &common_min_action; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub report_ifields { + +&load_search_vars ; + +# if ($i{camera_id}) { + # push @report_sql, "(`id`='$i{camera_id}')" ; + # push @report_results, "camera = $camera_name{$i{camera_id}}" ; + # $xlsreportname .= '-' . $i{camera_id} ; + # # our $acc_id_sql_where = "`camera_id`='$i{camera_id}'" + # } + +# if ($i{camera_system_id}) { + # push @report_sql, "(`camera_system_id`='$i{camera_system_id}')" ; + # push @report_results, "camera_system = $camera_system{$i{camera_system_id}}" ; + # $xlsreportname .= '-' . $i{camera_system_id} ; + # } + +if ($i{camera_system_id} and $i{camera_system_id} ne 'main' and $i{camera_system_id} ne 'other' and $i{camera_system_id} ne 'all') { + push @report_sql, "(`camera_system_id`='$i{camera_system_id}')" ; + push @report_results, "camera_system = $camera_system{$i{camera_system_id}}" ; + $xlsreportname .= '-' . $i{camera_id} ; + # our $acc_id_sql_where = "`camera_id`='$i{camera_id}'" +} elsif ($i{camera_system_id} eq 'main' or $i{camera_system_id} eq 'other' or $i{camera_system_id} eq 'all') { + push @report_results, "camera_system = $i{camera_system_id}" ; +} + +if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { $error = qq(CAMERAS FROM ($i{date_from}) > CAMERAS TO ($i{date_to})); &report_screen; } + } + +if ($i{date_from}) { + # push @report_sql, "(`date_active` >= '$i{date_from}')" ; + # push @report_results, "date_active >= $i{date_from}" ; + push @report_sql, "(`date_time` >= '$i{date_from}')" ; + push @report_results, "date_time >= $i{date_from}" ; + } + +if ($i{date_to}) { + # push @report_sql, "(`date_active` <= '$i{date_to}')" ; + # push @report_results, "date_active <= $i{date_to}" ; + push @report_sql, "(`date_time` <= '$i{date_to}')" ; + push @report_results, "date_time <= $i{date_to}" ; + } + +if ($i{client_id}) { + # push @report_sql, "(`client_id` = '$i{client_id}')" ; + push @report_results, "Client = $client{$i{client_id}}" ; + } + +$report_results_msg = uc join(', ', @report_results) ; + +unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); &report_screen; } else { $isaved = qq(SELECT WHERE $report_results_msg) ; } + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + # my $cameras_sql_where = "`id`='$i{camera_id}'" ; + # &db_min_ro('cameras','id,camera_nr',$cameras_sql_where,'','') ; + # foreach my $id (keys %{$db{cameras}}) { $camera_name{$id} = $db{cameras}{$id}{camera_nr} ; } + + my $camera_systems_sql_where = "`id`='$i{camera_system_id}'" ; + &db_min_ro('camera_systems','id,name',$camera_systems_sql_where,'','') ; + foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + + if ($i{client_id}) { + my $customers_sql_where = "`id`='$i{client_id}'" ; + &db_min_ro('customers','*',$customers_sql_where,'','') ; + foreach my $id (keys %{$db{customers}}) { $client{$id} = $db{customers}{$id}{name} ; } + } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +my $srch_where_sql = join(' AND ', @report_sql) ; + +my $add_sql_where = '' ; + +# our @sql_col_display = ("id","camera_nr","camera_serial_nr","vpu_serial_nr","client_id","ref_nr","ref","date_delivered","date_active") ; +our @sql_col_display = ("camera_nr","camera_system_id","camera_serial_nr","vpu_serial_nr","client_id","ref_nr","ref","date_delivered","date_active") ; + +&report_xls_export_header("Camera_Active_Report$xlsreportname",'camerareport') ; + +&load_list_vars("$srch_where_sql$add_sql_where") ; + +foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) { + if ($linked_sn{$db{$table}{$id}{serial_nr}}) { $vpu_is_linked{$linked_sn{$db{$table}{$id}{serial_nr}}} = 1 ; } +} + +foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) { + + # unless ($quote_active_date{$id}) { next ; } + unless ($db{$table}{$id}{quote_active_date}) { next ; } + + next if (&common_camera_system_filter($table,$id)) ; + + if ($i{client_id}) { + next unless $client{$i{client_id}} eq $quote_customer{$id} ; + } + + next if $vpu_is_linked{$db{$table}{$id}{serial_nr}} ; + + $print_tbody .= qq~~ ; + + $xlscol=0; + + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$table}{$id}{$_} ; + my $align = '' ; + + my $center = qq~ class="dt-center"~ ; + + # if ($_ eq 'date_received') { $align = $center ; } + if ($_ eq 'date_delivered') { $val = $db{$table}{$id}{quote_delivery_date} ; $align = $center ; } + if ($_ eq 'date_active') { $val = $db{$table}{$id}{quote_active_date} ; $align = $center ; } + if ($_ eq 'client_id') { $val = $quote_customer{$id} ; } + if ($_ eq 'ref_nr') { $val = $db{$table}{$id}{quote_nr} ; $align = $center ; } + # if ($_ eq 'ref') { $val = $db{$table}{$id}{quote_ref} ? "$db{$table}{$id}{quote_ref}" : $quote_ref{$id} ; } + if ($_ eq 'ref') { $val = $db{$table}{$id}{quote_ref} ? $db{$table}{$id}{quote_ref} : $quote_ref{$id} ; } + if ($_ eq 'camera_serial_nr') { $val = $db{$table}{$id}{serial_nr} ; } + if ($_ eq 'camera_system_id') { $val = $camera_system{$val} ; } + # if ($_ eq 'vpu_serial_nr') { $val = &common_check_for_linked_vpu($db{$table}{$id}{camera_nr},$db{$table}{$id}{quote_nr},$id,'SN') ; } + if ($_ eq 'vpu_serial_nr') { $val = $linked_sn{$db{$table}{$id}{serial_nr}} ; } # $val .= ' [' . $linked_cn{$db{$table}{$id}{serial_nr}} . ']' if $linked_cn{$db{$table}{$id}{serial_nr}} ; + + &report_xls_export_process_cell('','',$val) ; # ------------------------------------------------------------------------- HTML AFTER + $xlscol++; + + # $val = &common_camera_links($table,$id,$val) if $_ eq 'camera_nr' or $_ eq 'ref_nr' ; + $val = &common_camera_links($table,$id,$val) if ($_ eq 'camera_nr' or $_ eq 'ref_nr') and $pixellot_limit{$username}!=1 and $events_limit{$username}!=1 ; + + $print_tbody .= qq~$val~ ; + } + + $print_tbody .= qq~~ ; + $xlsrow++ ; + } + +&report_xls_export_footer('L',15,'camerareport') ; + +$fnsortcol = 8 ; +$fnsortorder = 'asc' ; + +$print_more_boxes .= qq~


    ~ ; + +&common_min_extra_crumb("$lcpage\s-report","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub set_tick { + +my ($color,$tooltip) = @_ ; + +$tick{green} = qq~2~ ; +$tick{orange} = qq~1~ ; +$tick{red} = qq~0~ ; + +return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub load_list_vars { + +my ($where) = @_ ; + +&db_min_ro('camera_systems','id,name','','','') ; +foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + +&db_min_ro('customers','id,name','','','') ; +foreach my $id (keys %{$db{customers}}) { $customer{$id} = $db{customers}{$id}{name} ; } + +# &common_load_quote_vars('>0'); +&common_load_quote_vars("cameras.quote_nr>0 AND cameras.quote_nr=quotes.quote_nr"); + +&db_min_ro($table,'*',$where,'','') ; + +# foreach my $id (keys %{$db{$table}}) { + # $cam_nr{$id} = $db{$table}{$id}{camera_nr} ; + # $serial_nr{$id} = $db{$table}{$id}{serial_nr} ; +# } + +} #------------------------------------------------------------------------------------------ + +sub thead { + +&common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'list' ; +our $lcpage = 'camera' ; + +&common_page_name ; + +our $table = 'cameras' ; +$page_title = 'Camera' ; + +# &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + +our $lcol = 3 ; +our $fcol = 5 ; + +$print_box_content_rows .= &common_min_forms_start('report') ; + +# &common_min_select_opts('camera_id','cameras','camera_nr',$i{camera_id},'') ; + +&common_camera_opts ; +&common_min_select_opts('camera_system_id','camera_systems','code',$i{camera_system_id},'') ; +&common_min_select_opts('client_id','customers','name',$i{client_id},'') ; + +my @datefrom = &common_add_delta_ymd(-2,0,0) ; + +# $print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-01-01") ; +$print_box_content_rows .= &common_min_form_datepicker('date_from',"$datefrom[0]-01-01") ; +$print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$now_dd") ; +#$print_box_content_rows .= &common_min_form_select('camera_id',$i{camera_id}) ; +$print_box_content_rows .= &common_min_form_select('camera_system_id',$i{camera_system_id}) ; +$print_box_content_rows .= &common_min_form_select('client_id',$i{client_id}) ; + +# my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-365); # 6 weeks back +# $set_month = sprintf("%02s", $set_month) ; +# $set_day = sprintf("%02s", $set_day) ; +# my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ; +#$print_box_content_rows .= &common_min_form_datepicker('date_received_from',$set_ccyy_dd_mm) ; +#$print_box_content_rows .= &common_min_form_datepicker('date_received_to',$now_ccyy_mm_dd) ; + +$print_box_content_rows .= &common_min_forms_end('','','report') ; + +&common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +use common ; +use report ; +use xlsxcreator ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/casuals.pl b/scripts/_FromProd/v1.0/casuals.pl new file mode 100644 index 0000000..d74af2c --- /dev/null +++ b/scripts/_FromProd/v1.0/casuals.pl @@ -0,0 +1,209 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Crypt::PasswdMD5; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + +my $exists = '' ; + +$i{username} = lc $i{username} ; +$i{username} =~ s/ //gi ; + +&db_min_ro($table,'*',"username = '$i{username}'",'username','') ; + +foreach my $id (keys %{$db{$table}}) { if ($db{$table}{$id}{username} eq $i{username}) { $exists = 1 ; } } + +if ($exists) { + $alert = &common_min_alert('warning',"USERNAME ALREADY EXISTS!",'ok') ; + %col_name = (); + &common_min_add_screen; + &common_min_screen1; + } + +} #------------------------------------------------------------------------------------------ + +sub insert { + +&add_db_fields ; + +my $crypted_password = apache_md5_crypt($i{password},$useropts{salt}) ; +$i{password} = $crypted_password ; +$i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; +$i{email} = lc $i{email} ; + +&db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + +unless ($i{id}) { $error = qq(NO ID) ; return ; } + +&edit_db_fields ; + +unless ($i{block}) { $i{block} = '0' ; } + +if ($i{new_password}) { + my $crypted_password = apache_md5_crypt($i{new_password},$useropts{salt}) ; + $i{password} = $crypted_password ; + $ignore{password} = 0 ; + $hidden{password} = 2 ; + } + +$i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +&db_min_ro($table,'*',"user_type like 'casual%'",'username','') ; + +foreach my $id (keys %{$db{$table}}) { + my $disp_blocked = qq(); + if ($db{$table}{$id}{block}) { $disp_blocked = qq(); } + + if ($useropts{it}{$db{$table}{$id}{username}} and $username ne 'rory') { next ; } + + $opts{$lcpage} .= qq() ; + $print_tbody .= qq( + $id + $db{$table}{$id}{username} + $db{$table}{$id}{name} + $db{$table}{$id}{email} + $disp_blocked + $db{$table}{$id}{based_in} + $db{$table}{$id}{lastupdate} + $db{$table}{$id}{lastvisitdate} + +   +   + + ) ; + } + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + +$ignore{lastvisitdate} = 1 ; +$ignore{iaction} = 1 ; +$ignore{block} = 1 ; +$ignore{id} = 1 ; +$hidden{lastupdate} = 2 ; +$required{username} = 1 ; +$required{name} = 1 ; +$required{password} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + +$ignore{lastvisitdate} = 1 ; +$ignore{password} = 1 ; +$ignore{iaction} = 1 ; +$hidden{id} = 1 ; # 1 = bypass for db update +$hidden{lastupdate} = 2 ; # 2 = update db +$readonly{username} = 'READONLY' ; +$checkbox{block} = 1 ; +$required{username} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + +# called from common_add_screen + +&select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +$selected{based_in}{$db{$table}{$i{id}}{based_in}} = "SELECTED" ; +$selected{user_type}{$db{$table}{$i{id}}{user_type}} = "SELECTED" ; + +$extra_form_fields .= &common_min_form_input('new_password','','password') ; + +&select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + +$required{based_in} = 1 ; +$select{based_in} = 1 ; +$opts{based_in} = qq~~ ; + +$required{user_type} = 1 ; +$select{user_type} = 1 ; +$opts{user_type} = qq~ + + + + + + + + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + +$print_thead = qq(IDUSERNAMENAMEEMAILACTIVEBASELASTUPDATELASTVISITDATE ) ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'user' ; +our $lcpage = 'casual' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; +our $table = 'users' ; + +&common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/cities.pl b/scripts/_FromProd/v1.0/cities.pl new file mode 100644 index 0000000..024024b --- /dev/null +++ b/scripts/_FromProd/v1.0/cities.pl @@ -0,0 +1,375 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $debug = 1 ; +# our $testing = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +&db_open_ro ; + $db_ignore_open_close = 1 ; + &common_min_action; + $db_ignore_open_close = 0 ; +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + + my $exists = '' ; + + $i{name} = &common_fix_str($i{name}) ; + + ## REMOVE LATER --------------------------------- + + $i{city} = $i{name} ; + + ## REMOVE LATER --------------------------------- + + &db_min_ro($table,'*',"name='$i{name}'",'name','') ; + + foreach my $id (keys %{$db{$table}}) { if ($db{$table}{$id}{name} eq $i{name}) { $exists = 1 ; } } + + if ($exists) { + $alert = &common_min_alert('warning',"CITY NAME ALREADY EXISTS!",'ok') ; + %col_name = (); + &common_min_add_screen; + &common_min_screen1; + } + +} #------------------------------------------------------------------------------------------ + +sub insert { + + &add_db_fields ; + + &set_default_vals ; + + $i{id} = &db_min_get_max($table,'id') ; + + $ignore{country_id} = 1 ; + + &db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + unless ($i{id}) { $error = qq(NO ID) ; return ; } + + &edit_db_fields ; + + &set_default_vals ; + + $ignore{country_id} = 1 ; + + &db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub set_default_vals { + + &db_min_ro('regions','id,name',"id = $i{region_id}",'','') ; + $i{province} = $db{regions}{$i{region_id}}{name}; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + &db_min_ro('regions','id,name,country_id',"",'','') ; + + &db_min_ro('countries','id,name',"",'','') ; + + &db_min_ro('event_quotes','id,city_id',"city_id <> 0",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + $type_id_used{$_} = 1 ; + my @city_ids = split(/\,/,$db{event_quotes}{$_id}{city_id}); + foreach my $_cid (@city_ids) { + $type_id_used{$_cid} = 1 ; + } + } + + &db_min_ro($table,'*','','','') ; + + foreach my $id (keys %{$db{$table}}) { + + my $edit_butt = qq~ ~ ; + my $del_butt = qq~ ~ ; + + if ($glod_user_level >= 3) { + $edit_butt = qq~ ~ ; + } + + if ($glod_user_level >= 3) { + $del_butt = qq~ ~ ; + } + + if ($type_id_used{$id}) { + $edit_butt = qq~ ~ ; + $del_butt = qq~ ~ ; + } + + $print_tbody .= qq~ + $id + $db{$table}{$id}{name} + $db{$table}{$id}{city_short} + $db{$table}{$id}{lat} + $db{$table}{$id}{lng} + $db{regions}{$db{$table}{$id}{region_id}}{name} + $db{countries}{$db{regions}{$db{$table}{$id}{region_id}}{country_id}}{name} + + $edit_butt + $del_butt + + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + &sort_fields; + + &hidden_db_fields; + + # $ignore{id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &sort_fields; + + &hidden_db_fields; + + $hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + + $ignore{iaction} = 1 ; + $required{name} = 1 ; + # $required{province} = 1 ; + $required{region_id} = 1 ; + + # $ignore{country_id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + %sort_field = () ; + + # $ignore{country_id} = '' ; + + + $sort_field{3} = 'name' ; $preferred_title{city_short} = "City Name" ; + $sort_field{4} = 'city_short' ; $preferred_title{city_short} = "City Acronym" ; + # $sort_field{3} = 'province' ; $preferred_title{province} = 'Region' ; + $sort_field{5} = 'lat' ; $preferred_title{lat} = 'Latitude' ; + $sort_field{6} = 'lng' ; $preferred_title{lng} = 'Longitude' ; + $sort_field{7} = 'region_id' ; + $sort_field{8} = 'country_id' ; + +} #------------------------------------------------------------------------------- + +sub add_screen { + + # called from common_add_screen + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + + # $required{based_in} = 1 ; + # $select{based_in} = 1 ; + # $opts{based_in} = qq~~ ; + + # my $sql_or = '' ; + + # if ($is_schools_manager || $is_operator) { + # @report_sql_or = () ; + # foreach $_reg_id (keys %{$glob_regids{$userid}}) { + # push @report_sql_or, "id = '$_reg_id'" + # } + # $sql_or = join(' OR ',@report_sql_or) ; + # } + + my $sql_or = ($is_schools_manager || $is_operator) ? join(' OR ', map { "id = '$_'" } keys %{$glob_regids{$userid}}) : '' ; + + $allow_deselect{country_id} = 1 ; + + # &common_min_select_opts('province','regions','name',$db{$table}{$i{id}}{province},'','',$sql_or,'name'); + + &common_min_select_opts('region_id','regions','name',$db{$table}{$i{id}}{region_id},'','code',$sql_or,''); + + &common_min_select_opts('country_id','countries','name',$db{regions}{$db{$table}{$i{id}}{region_id}}{country_id},'','','',''); + + $trigger_jquery_raw .= qq~ + + let map_region_to_country = {} ; + + const \$countrySelect = \$("#selectCountry_id") ; + const \$regionSelect = \$("#selectRegion_id") ; + + const updateChosen = \$el => \$el.trigger("chosen:updated"); + + const fetchJSON = async url => { + try { + const res = await fetch(url); + if (!res.ok) throw new Error(`Request failed: \${res.status}`); + return await res.json(); + } catch (err) { + console.error("Fetch error:", err); + return []; + } + }; + + const populateSelect = (\$field, json_list, getLabel, defaultSelected = () => "") => { + + let isSelected ; + + // Determine how to handle selected logic + if (typeof defaultSelected === "function") { + isSelected = defaultSelected ; + } else if (Array.isArray(defaultSelected)) { + isSelected = data => defaultSelected.includes(data.id) ? "selected" : "" ; + } else { + isSelected = data => data.id == defaultSelected ? "selected" : "" ; + } + + // Auto-select the only item if none explicitly selected + const autoSelectOnly = json_list.length === 1 && typeof defaultSelected === "string" && defaultSelected === "" ; + + json_list.forEach(data => { + const selected = autoSelectOnly || isSelected(data) ? "selected" : "" ; + \$field.append(``) ; + }); + + updateChosen(\$field) ; + return json_list.length ; + }; + + const getInputValue = name => \$(`input[name='\${name}']`).val(); + + const clearSelect = (\$el) => { + \$el.empty(); + \$el.append(``).trigger("chosen:updated"); + }; + + // _______________________________________________ + + \$countrySelect.change( async function() { + \$("input[name='custom_selected_country']").val("1") ; + await update_region_drop_down_from_country(\$countrySelect.val()) ; + }) ; + + async function update_region_drop_down_from_country (countryId) { + + clearSelect(\$regionSelect) ; + + const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}` ; + const regions = await fetchJSON(regionUrl); + + for (const data of regions) { + map_region_to_country[data.id] = countryId ; + } + + const regionCount = populateSelect(\$regionSelect, regions, r => r.code ? `\${r.name} [\${r.code}]` : r.name , "") ; + + if (regionCount === 0 && \$countrySelect.val()) { + \$regionSelect.append(``).trigger("chosen:updated") ; + } + + } + + // _______________________________________________ + + \$regionSelect.change( async function() { + \$("input[name='custom_selected_region']").val("1") ; + \$("input[name='custom_selected_country']").val("1") ; + const regionId = \$regionSelect.val() ; + await update_country_from_region(regionId,1) ; + }); + + async function update_country_from_region (regionId,update_country=0) { + if (map_region_to_country[regionId] || regionId == '13') { + \$countrySelect.val(map_region_to_country[regionId]).trigger("chosen:updated") ; + } else if (!\$("input[name='custom_selected_country']").val() || update_country) { + const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=®ion_id=\${regionId}`; + const regionMeta = await fetchJSON(lookupUrl); + const { country_id } = regionMeta[0] ?? {} ; + if (country_id) { + map_region_to_country[regionId] = country_id; + \$countrySelect.val(country_id).trigger("chosen:updated"); + } + } + } + + // _______________________________________________ + + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + $print_thead = qq~IDCITY NAMECITY ACRONYMLATLNGREGIONCOUNTRY ~ ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'map-marker' ; + our $lcpage = 'cities' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'cities' ; + + $s{no} = 1 ; + + &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/coding_providers.pl b/scripts/_FromProd/v1.0/coding_providers.pl new file mode 100644 index 0000000..fad11f3 --- /dev/null +++ b/scripts/_FromProd/v1.0/coding_providers.pl @@ -0,0 +1,124 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Crypt::PasswdMD5; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +# unless ($username eq 'rory') { print ">>>> DEVELOPMENT IN PROGRESS <<<<" ; exit ; } + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + + &users_validate; + +} #------------------------------------------------------------------------------------------ + +sub insert { + + &users_insert ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + &users_update ; + +} #------------------------------------------------------------------------------------------ + +sub process_multi_select { + + &users_process_multi_select ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + &users_list_screen ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + &users_sort_fields ; + +} #------------------------------------------------------------------------------- + +sub add_db_fields { + + &users_add_db_fields ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &users_edit_db_fields ; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + + # called from common_add_screen + &users_add_screen ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + &users_edit_screen ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &users_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'user' ; + our $lcpage = 'coding-provider' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'users' ; + our $user_type = 'coding_provider' ; + + &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; +use users ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/costings_detailed_report.pl b/scripts/_FromProd/v1.0/costings_detailed_report.pl new file mode 100644 index 0000000..267656e --- /dev/null +++ b/scripts/_FromProd/v1.0/costings_detailed_report.pl @@ -0,0 +1,456 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; +# unless ($username eq 'handre') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $debug = 1 ; + +our $cnt_match_credits = 4 ; # used in common_load_quote_vars + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our $srchscr = 1 ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + if ($iaction eq ''){ &report_screen ; } + &common_min_action; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub report_ifields { + + &load_search_vars ; + + if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { $error = qq(CAMERAS FROM ($i{date_from}) > CAMERAS TO ($i{date_to})); &report_screen; } + } + + if ($i{date_from}) { + push @report_sql, "(`quote_date` >= '$i{date_from}')" ; + push @report_results, "quote_date >= $i{date_from}" ; + } + + if ($i{date_to}) { + push @report_sql, "(`quote_date` <= '$i{date_to}')" ; + push @report_results, "quote_date <= $i{date_to}" ; + } + + if ($i{client_id}) { + push @report_sql, "(`quote_to`='$i{client_id}')" ; + push @report_results, "Client = $client{$i{client_id}}" ; + } + + if ($i{options} eq 'accepted') { + # push @report_sql, "(`quote_to`='$i{client_id}')" ; + # push @report_results, "Client = $client{$i{client_id}}" ; + + push @report_sql, "(`quote_accepted`=1)" ; + push @report_results, "Quote Accepted = 'Yes'" ; + } + + if ($i{options} eq 'cancelled') { + + push @report_sql, "(`quote_cancelled`=1)" ; + push @report_results, "Quote Cancelled = 'Yes'" ; + } + + if ($i{options} eq 'pending') { + + push @report_sql, "(`quote_pending`=1)" ; + push @report_results, "Quote Pending = 'Yes'" ; + } + + + push @report_sql, "(`invoice_nr`>0)" ; + push @report_results, "Invoice Nr exists" ; + + $report_results_msg = uc join(', ', @report_results) ; + + unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); &report_screen; } else { $isaved = qq(SELECT WHERE $report_results_msg) ; } + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + if ($i{client_id}) { + my $customers_sql_where = "`id`='$i{client_id}'" ; + &db_min_ro('customers','*',$customers_sql_where,'','') ; + foreach my $id (keys %{$db{customers}}) { $client{$id} = $db{customers}{$id}{name} ; } + } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + my $srch_where_sql = join(' AND ', @report_sql) ; + my $add_sql_where = '' ; + &load_list_vars("$srch_where_sql$add_sql_where") ; + "e_list ; + +} #------------------------------------------------------------------------------------------ + +sub quote_list { + + our @sql_col_display = ("nr","customer","event","location","city","quote_total","car_hire","flights","accommodation","meal_allowance","travel_expenses","other","operator_total","total_expenses","profit/Loss","invoice_nr","sports_type","date_from","date_to") ; + # our @col_display_excel = ("event", "date", "day", "sport_type", "production_type", "ligr_integration", "location","city_&_province", "onsite_team") ; + @col_display_excel = @sql_col_display ; + + &report_xlsx_export_header_events("Cosings_Detailed",'events') ; + + $worksheet{$ws} -> set_row(0, 40) ; + $worksheet{$ws} -> set_row(1, 25) ; + $worksheet{$ws} -> set_row(2, 25) ; + $worksheet{$ws} -> set_row(3, 5) ; + + $worksheet{$ws} -> set_column(0,0,10); + $worksheet{$ws} -> set_column(1,1,30); + $worksheet{$ws} -> set_column(2,3,40); + $worksheet{$ws} -> set_column(4,14,15); + $worksheet{$ws} -> set_column(15,15,10); + + my @month_fullname = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") ; + # if ($i{export_to_excel}) { &report_xls_export_header("Event Quotes",'event_quotes') ; } + my @day_of_week_text = ("", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") ; + foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) { + + unless ($id) { next ; } + + my $quote_expiry = $db{$tables}{$id}{quote_expiry} ; $quote_expiry =~ s/\-//iog ; + + # if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all') { next ; } + if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $db{$tables}{$id}{quote_accepted}!=1 and + $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all' and + $i{options} ne 'accepted' and $i{options} ne 'closed' and $i{options} ne 'all') + { next ; } + + $print_tbody .= qq~~ ; + + $xlsxcol=0; + + my $quote_nr = $db{$tables}{$id}{quote_nr} ; + our $nowrap = '' ; + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + $nowrap = '' ; + my $val = &get_val($id, $_) ; + my $align = qq~ class="dt-center"~ ; + $print_tbody .= qq~$val~ ; +## EXCEL---------------------------- + if ($_ eq 'nr'){ $val = $id ; } + if ($_ eq 'sports_type'){ $val =~ s/\
    /\;/g ; } + + if ($_ eq 'nr' or $_ eq 'customer' or $_ eq 'event' or $_ eq 'location' or $_ eq 'city' or $_ eq 'invoice_nr') { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format_event_data) + } else { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format_management_report_data) + } + + # &report_write_events($val, 0) ; + $xlsxcol++; + } + $print_tbody .= qq~~ ; + $xlsxrow++; + } +# EXCEL--------------------------------------------- + # if ($i{export_to_excel}) { + &report_xlsx_export_footer('L',15,'events') ; + # } + + # $fnsortcol = 8 ; # order by ol devices col + + $print_more_boxes .= qq~


    ~ ; + + &common_min_extra_crumb("search-$lcpage\s","Search Screen") ; + +} #------------------------------------------------------------------------------- + +sub get_val { + # our @sql_col_display = ("nr","customer","event","location","city","quote_total","car_hire","flights","accommodation","meal_allowance", "travel_expenses", "other", "operator_total", "total_expenses", "profit/Loss", "invoice_nr") ; + + my ($id, $col) = @_ ; + my $val = $db{$tables}{$id}{$_} ; + # print "$col, $val \n" ; + if ($col eq 'event') { + $val = $db{$tables}{$id}{ref} ; + # $nowrap = 'nowrap' ; + } elsif ($col eq 'location') { + $val = ($db{$tables}{$id}{region_id}) ? "$db{regions}{$db{$tables}{$id}{region_id}}{name} [$db{regions}{$db{$tables}{$id}{region_id}}{code}]" : "" ; + } elsif ($col eq 'city') { + $val = ($db{$tables}{$id}{city_id}) ? $db{cities}{$db{$tables}{$id}{city_id}}{city} : $db{$tables}{$id}{city} ; + } elsif ($col eq 'sports_type') { + $val = join("
    ", map { $db{sport_types}{$_}{name} } split(",", $db{$tables}{$id}{sport_type_ids})); + } elsif ($col eq 'customer') { + $val = $customer{$db{$tables}{$id}{quote_to}} ; + $nowrap = 'nowrap' ; + } elsif ($col eq 'location') { + # $val = "Unknown" unless $val ; + } elsif ($col eq 'city'){ + $val = $db{$tables}{$id}{city} ; + } elsif ($col eq 'ligr'){ + $val = $db{$tables}{$id}{ligr} ; + } elsif ($col eq 'quote_total'){ + $val = $db{$tables}{$id}{grand_total} ; + # $val = 100000000 ; + $val = 0 if not $val ; + # my $ttl = &common_commify($val) ; + $val = sprintf("%.2f", $val) ; + } elsif ($col eq 'total_expenses'){ + $val = $db{$tables}{$id}{total_grand_amount_workings_event} ; + # $val = 100000000 ; + $val = 0 if not $val ; + # my $ttl = &common_commify($val) ; + $val = sprintf("%.2f", $val) ; + } elsif ($col eq 'profit/Loss'){ + $val = $db{$tables}{$id}{grand_total} - $db{$tables}{$id}{total_grand_amount_workings_event} ; + # $val = 100000000 ; + $val = 0 if not $val ; + # my $ttl = &common_commify($val) ; + $val = sprintf("%.2f", $val) ; + } elsif ($col eq 'car_hire') { + $val = $total_car_hire{$id} ; + $val = 0 if not $val ; + # $val = &common_commify($val) ; + $val = sprintf("%.2f", $val) ; + } elsif ($col eq 'flights') { + $val = $total_flights{$id} ; + $val = 0 if not $val ; + # $val = &common_commify($val) ; + $val = sprintf("%.2f", $val) ; + } elsif ($col eq 'accommodation') { + $val = $total_accomodation{$id} ; + $val = 0 if not $val ; + # $val = &common_commify($val) ; + $val = sprintf("%.2f", $val) ; + } elsif ($col eq 'meal_allowance') { + $val = $total_meal_allowance{$id} ; + $val = 0 if not $val ; + # $val = &common_commify($val) ; + $val = sprintf("%.2f", $val) ; + } elsif ($col eq 'travel_expenses') { + $val = $total_travel_expenses{$id} ; + $val = 0 if not $val ; + # $val = &common_commify($val) ; + $val = sprintf("%.2f", $val) ; + } elsif ($col eq 'other') { + $val = $total_other{$id} ; + $val = 0 if not $val ; + # $val = &common_commify($val) ; + $val = sprintf("%.2f", $val) ; + } elsif ($col eq 'operator_total') { + $val = $total_operator{$id} ; + $val = 0 if not $val ; + # $val = &common_commify($val) ; + $val = sprintf("%.2f", $val) ; + } elsif ($col eq 'total') { + $val = &common_commify($db{$tables}{$id}{grand_total}) ; + } elsif ($col eq 'date_to' or $col eq 'date_from') { + $nowrap = 'nowrap' ; + $val = substr($val, 0, 10) ; + } elsif ($col eq 'nr') { + my $class = 'info' ; + if ($db{$tables}{$id}{quote_cancelled}) { + $class = 'danger' ; + } elsif ($db{$tables}{$id}{quote_accepted}) { + $class = 'success' ; + } elsif ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd") { + $class = 'danger' ; + } elsif ($db{$tables}{$id}{quote_pending}) { + $class = 'warning' ; + } + $val = qq~$id~ ; + } + return ($val) ; +} + +sub load_list_vars { + + my ($where) = @_ ; + our %event_types = () ; + &db_min_ro('event_types','id,name','','','') ; + foreach my $id (keys %{$db{event_types}}) { $event_types{$id} = $db{event_types}{$id}{name} ; } + &db_min_ro('customers','id,name','','','') ; + foreach my $id (keys %{$db{customers}}) { $customer{$id} = $db{customers}{$id}{name} ; } + + our %total_accomodation = () ; + our %total_car_hire = () ; + our %total_flights = () ; + our %total_meal_allowance = () ; + our %total_travel_expenses = () ; + our %total_other = () ; + our %total_operator = () ; + + db_min_ro('event_quotes_min','id, description_workings_event, amount_workings_event','','','') ; + + foreach my $iid (keys %{$db{event_quotes_min}}) { + + @amnt_work = split(";", $db{event_quotes_min}{$iid}{amount_workings_event}); + @des_work = split(";", $db{event_quotes_min}{$iid}{description_workings_event}); + + for (1 .. 50) { + if ($des_work[$_ - 1] == 1){ + $total_flights{$iid} += $amnt_work[$_ - 1] ; + } elsif ($des_work[$_ - 1] == 2){ + $total_accomodation{$iid} += $amnt_work[$_ - 1] ; + } elsif ($des_work[$_ - 1] == 3){ + $total_car_hire{$iid} += $amnt_work[$_ - 1] ; + } elsif ($des_work[$_ - 1] == 4){ + $total_meal_allowance{$iid} += $amnt_work[$_ - 1] ; + } elsif ($des_work[$_ - 1] == 6){ + $total_other{$iid} += $amnt_work[$_ - 1] ; + } elsif ($des_work[$_ - 1] == 13){ + $total_travel_expenses{$iid} += $amnt_work[$_ - 1] ; + } elsif ($des_work[$_ - 1] == 14){ + $total_operator{$iid} += $amnt_work[$_ - 1] ; + } + } + } + + my $sql_select = "id,ref,quote_to,city,ligr,grand_total,total_grand_amount_workings_event,quote_cancelled,quote_accepted,quote_pending,location,invoice_nr,quote_expiry,quote_nr,sport_type_ids,date_from,date_to,city,city_id,region_id" ; + # for (1 .. 15){ $sql_select .= ",description_$_\_workings_event" ; $sql_select .= ",amount_$_\_workings_event" ; } + + &db_min_ro($tables,$sql_select,$where,'','') ; + + # foreach my $iid (keys %{$db{$tables}}) { + # for (1 .. 15) { + # if ($db{$tables}{$iid}{"description_$_\_workings_event"} == 1){ + # $total_flights{$iid} += $db{$tables}{$iid}{"amount_$_\_workings_event"} ; + # } elsif ($db{$tables}{$iid}{"description_$_\_workings_event"} == 2){ + # $total_accomodation{$iid} += $db{$tables}{$iid}{"amount_$_\_workings_event"} ; + # } elsif ($db{$tables}{$iid}{"description_$_\_workings_event"} == 3){ + # $total_car_hire{$iid} += $db{$tables}{$iid}{"amount_$_\_workings_event"} ; + # } elsif ($db{$tables}{$iid}{"description_$_\_workings_event"} == 4){ + # $total_meal_allowance{$iid} += $db{$tables}{$iid}{"amount_$_\_workings_event"} ; + # } elsif ($db{$tables}{$iid}{"description_$_\_workings_event"} == 6){ + # $total_other{$iid} += $db{$tables}{$iid}{"amount_$_\_workings_event"}; + # } elsif ($db{$tables}{$iid}{"description_$_\_workings_event"} == 13){ + # $total_travel_expenses{$iid} += $db{$tables}{$iid}{"amount_$_\_workings_event"} ; + # } elsif ($db{$tables}{$iid}{"description_$_\_workings_event"} eq '14'){ + # $total_operator{$iid} += $db{$tables}{$iid}{"amount_$_\_workings_event"} ; + # } + # } + # } + + &db_min_ro('sport_types','id,name','','','') ; + &db_min_ro('cities','id,city,province','','','') ; + &db_min_ro('regions','id,code,name','','','') ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + our $lcpage = 'event-quote' ; + + &common_page_name ; + + our $tables = 'event_quotes' ; + $page_title = 'Costings Detailed' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + &common_min_select_opts('client_id','customers','name','','') ; + + my @datefrom = &common_add_delta_ymd(-2,0,0) ; + + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$datefrom[0]-01-01") ; + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$now_dd") ; + + $opts{options} = qq~ + + + + + + ~ ; + $print_box_content_rows .= &common_min_form_select('options','','',1,'') ; + + $print_box_content_rows .= &common_min_form_select('client_id','') ; + # $print_box_content_rows .= &common_min_form_select('options','') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub common_camera_links_events { + + my ($table,$id,$val) = @_ ; + + if ($_ eq 'camera_nr') { + my $class = 'info' ; $class = 'warning' if $db{$table}{$id}{quote_nr} ; + my $style = '' ; $style = "style='background-color:purple;'" if $db{$table}{$id}{demo_recipient} ; + $val = qq~$val~ ; + } + + if ($_ eq 'quote_nr' or $_ eq 'ref_nr' or $_ eq 'ref') { + my $class = 'info' ; + $class = 'warning' if $val ; + my $style = '' ; + $style = "style='background-color:purple;'" if $db{$table}{$id}{demo_recipient} ; + $class = 'success' if $db{$table}{$id}{quote_accepted} or $quote_accepted{$id} ; + $class = 'danger' if $db{$table}{$id}{quote_cancelled} or $quote_cancelled{$id} ; + my $quote_id = $quote_id{$val} ? $quote_id{$val} : $id ; + $val = $val ? qq~$val~ : '' ; + } + + return ($val) ; + +} #------------------------------------------------------------------------------------------ + +use common ; +use report ; +use xlsxcreator ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/costings_summary_report.pl b/scripts/_FromProd/v1.0/costings_summary_report.pl new file mode 100644 index 0000000..7e74d5f --- /dev/null +++ b/scripts/_FromProd/v1.0/costings_summary_report.pl @@ -0,0 +1,342 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; +# unless ($username eq 'handre') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $debug = 1 ; + +our $cnt_match_credits = 4 ; # used in common_load_quote_vars + +our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our $srchscr = 1 ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + if ($iaction eq ''){ &report_screen ; } + &common_min_action; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub report_ifields { + + &load_search_vars ; + + if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { $error = qq(CAMERAS FROM ($i{date_from}) > CAMERAS TO ($i{date_to})); &report_screen; } + } + + if ($i{date_from}) { + push @report_sql, "(`quote_date` >= '$i{date_from}')" ; + push @report_results, "quote_date >= $i{date_from}" ; + } + + if ($i{date_to}) { + push @report_sql, "(`quote_date` <= '$i{date_to}')" ; + push @report_results, "quote_date <= $i{date_to}" ; + } + + if ($i{client_id}) { + push @report_sql, "(`quote_to`='$i{client_id}')" ; + push @report_results, "Client = $client{$i{client_id}}" ; + } + + if ($i{options} eq 'accepted') { + # push @report_sql, "(`quote_to`='$i{client_id}')" ; + # push @report_results, "Client = $client{$i{client_id}}" ; + + push @report_sql, "(`quote_accepted`=1)" ; + push @report_results, "Quote Accepted = 'Yes'" ; + } + + if ($i{options} eq 'cancelled') { + + push @report_sql, "(`quote_cancelled`=1)" ; + push @report_results, "Quote Cancelled = 'Yes'" ; + } + + if ($i{options} eq 'pending') { + + push @report_sql, "(`quote_pending`=1)" ; + push @report_results, "Quote Pending = 'Yes'" ; + } + + + push @report_sql, "(`invoice_nr`>0 OR `invoice_nr` <> '')" ; + push @report_results, "Invoice Nr exists" ; + + $report_results_msg = uc join(', ', @report_results) ; + + unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); &report_screen; } else { $isaved = qq(SELECT WHERE $report_results_msg) ; } + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + if ($i{client_id}) { + my $customers_sql_where = "`id`='$i{client_id}'" ; + &db_min_ro('customers','*',$customers_sql_where,'','') ; + foreach my $id (keys %{$db{customers}}) { $client{$id} = $db{customers}{$id}{name} ; } + } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + my $srch_where_sql = join(' AND ', @report_sql) ; + my $add_sql_where = '' ; + &load_list_vars("$srch_where_sql$add_sql_where") ; + "e_list ; + +} #------------------------------------------------------------------------------------------ + +sub quote_list { + + our @sql_col_display = ("nr","customer","event","sports_type","date_from","date_to","quote_total","total_expenses") ; + # our @col_display_excel = ("event", "date", "day", "sport_type", "production_type", "ligr_integration", "location","city_&_province", "onsite_team") ; + @col_display_excel = @sql_col_display ; + + &report_xlsx_export_header_events("Cosings_Summary",'events') ; + + $worksheet{$ws} -> set_row(0, 40) ; + $worksheet{$ws} -> set_row(1, 25) ; + $worksheet{$ws} -> set_row(2, 25) ; + $worksheet{$ws} -> set_row(3, 5) ; + + $worksheet{$ws} -> set_column(0,0,10) ; + $worksheet{$ws} -> set_column(1,1,30) ; + $worksheet{$ws} -> set_column(2,3,40) ; + $worksheet{$ws} -> set_column(4,5,15) ; + + my @month_fullname = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") ; + # if ($i{export_to_excel}) { &report_xls_export_header("Event Quotes",'event_quotes') ; } + my @day_of_week_text = ("", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") ; + foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) { + + unless ($id) { next ; } + + my $quote_expiry = $db{$tables}{$id}{quote_expiry} ; $quote_expiry =~ s/\-//iog ; + + # if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all') { next ; } + if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $db{$tables}{$id}{quote_accepted}!=1 and + $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all' and + $i{options} ne 'accepted' and $i{options} ne 'closed' and $i{options} ne 'all') + { next ; } + + $print_tbody .= qq~~ ; + + $xlsxcol=0; + + my $quote_nr = $db{$tables}{$id}{quote_nr} ; + + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + my $val = &get_val($id, $_) ; + my $align = qq~ class="dt-center"~ ; + my $nowrap = '' ; + $print_tbody .= qq~$val~ ; +## EXCEL---------------------------- + if ($_ eq 'nr'){ + $val = $id ; + } + if ($_ eq 'sports_type'){ $val =~ s/\
    /\;/g ; } + + if ($_ eq 'nr' or $_ eq 'customer' or $_ eq 'event' or $_ eq 'location' or $_ eq 'city' or $_ eq 'invoice_nr') { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format_event_data) + } else { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format_management_report_data) + } + + # &report_write_events($val, 0) ; + $xlsxcol++; + } + $print_tbody .= qq~~ ; + $xlsxrow++; + } +# EXCEL--------------------------------------------- + # if ($i{export_to_excel}) { + &report_xlsx_export_footer('L',15,'events') ; + # } + + # $fnsortcol = 8 ; # order by ol devices col + + $print_more_boxes .= qq~


    ~ ; + + &common_min_extra_crumb("search-$lcpage\s","Search Screen") ; + +} #------------------------------------------------------------------------------- + +sub get_val { + # our @sql_col_display = ("nr","customer","event","location","city","quote_total","car_hire","flights","accommodation","meal_allowance", "travel_expenses", "other", "operator_total", "total_expenses", "profit/Loss", "invoice_nr") ; + + my ($id, $col) = @_ ; + my $val = $db{$tables}{$id}{$_} ; + # print "$col, $val \n" ; + if ($col eq 'event') { + $val = $db{$tables}{$id}{ref} ; + $nowrap = 'nowrap' ; + } elsif ($col eq 'sports_type') { + $val = join("
    ", map { $db{sport_types}{$_}{name} } split(",", $db{$tables}{$id}{sport_type_ids})); + } elsif ($col eq 'customer') { + $val = $customer{$db{$tables}{$id}{quote_to}} ; + $nowrap = 'nowrap' ; + } elsif ($col eq 'quote_total'){ + $val = $db{$tables}{$id}{grand_total} ; + $val = 0 if not $val ; + $val = sprintf("%.2f", $val) ; + $val = &common_commify($val) ; + } elsif ($col eq 'total_expenses'){ + $val = $db{$tables}{$id}{total_grand_amount_workings_event} ; + $val = 0 if not $val ; + $val = sprintf("%.2f", $val) ; + $val = &common_commify($val) ; + } elsif ($col eq 'date_to' or $col eq 'date_from') { + $val = substr($val, 0, 10) ; + } elsif ($col eq 'nr') { + my $class = 'info' ; + if ($db{$tables}{$id}{quote_cancelled}) { + $class = 'danger' ; + } elsif ($db{$tables}{$id}{quote_accepted}) { + $class = 'success' ; + } elsif ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd") { + $class = 'danger' ; + } elsif ($db{$tables}{$id}{quote_pending}) { + $class = 'warning' ; + } + $val = qq~$id~ ; + } + return ($val) ; +} + +sub load_list_vars { + + my ($where) = @_ ; + our %event_types = () ; + &db_min_ro('event_types','id,name','','','') ; + foreach my $id (keys %{$db{event_types}}) { $event_types{$id} = $db{event_types}{$id}{name} ; } + &db_min_ro('customers','id,name','','','') ; + foreach my $id (keys %{$db{customers}}) { $customer{$id} = $db{customers}{$id}{name} ; } + &db_min_ro('sport_types','*','','','') ; + &db_min_ro($tables,'*',$where,'','') ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + our $lcpage = 'event-quote' ; + + &common_page_name ; + + our $tables = 'event_quotes' ; + $page_title = 'Costings Summary' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + &common_min_select_opts('client_id','customers','name','','') ; + + my @datefrom = &common_add_delta_ymd(-2,0,0) ; + + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$datefrom[0]-01-01") ; + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$now_dd") ; + + $opts{options} = qq~ + + + + + + ~ ; + $print_box_content_rows .= &common_min_form_select('options','','',1,'') ; + + $print_box_content_rows .= &common_min_form_select('client_id','') ; + # $print_box_content_rows .= &common_min_form_select('options','') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub common_camera_links_events { + + my ($table,$id,$val) = @_ ; + + if ($_ eq 'camera_nr') { + my $class = 'info' ; $class = 'warning' if $db{$table}{$id}{quote_nr} ; + my $style = '' ; $style = "style='background-color:purple;'" if $db{$table}{$id}{demo_recipient} ; + $val = qq~$val~ ; + } + + if ($_ eq 'quote_nr' or $_ eq 'ref_nr' or $_ eq 'ref') { + my $class = 'info' ; + $class = 'warning' if $val ; + my $style = '' ; + $style = "style='background-color:purple;'" if $db{$table}{$id}{demo_recipient} ; + $class = 'success' if $db{$table}{$id}{quote_accepted} or $quote_accepted{$id} ; + $class = 'danger' if $db{$table}{$id}{quote_cancelled} or $quote_cancelled{$id} ; + my $quote_id = $quote_id{$val} ? $quote_id{$val} : $id ; + $val = $val ? qq~$val~ : '' ; + } + + return ($val) ; + +} #------------------------------------------------------------------------------------------ + +use common ; +use report ; +use xlsxcreator ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/credits_bought.pl b/scripts/_FromProd/v1.0/credits_bought.pl new file mode 100644 index 0000000..42ac275 --- /dev/null +++ b/scripts/_FromProd/v1.0/credits_bought.pl @@ -0,0 +1,381 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $debug = 1 ; +# our $testing = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +if ($username ne 'handre') { + print "Development in Progress!!!" ; + exit ; +} + + +&db_open_ro ; + $db_ignore_open_close = 1 ; + &common_min_action; + $db_ignore_open_close = 0 ; +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + + my $exists = '' ; + + $i{name} = &common_fix_str($i{name}) ; + + ## REMOVE LATER --------------------------------- + + $i{city} = $i{name} ; + + ## REMOVE LATER --------------------------------- + + &db_min_ro($table,'*',"name='$i{name}'",'name','') ; + + foreach my $id (keys %{$db{$table}}) { if ($db{$table}{$id}{name} eq $i{name}) { $exists = 1 ; } } + + if ($exists) { + $alert = &common_min_alert('warning',"CITY NAME ALREADY EXISTS!",'ok') ; + %col_name = (); + &common_min_add_screen; + &common_min_screen1; + } + +} #------------------------------------------------------------------------------------------ + +sub insert { + + &add_db_fields ; + + &set_default_vals ; + + $i{id} = &db_min_get_max($table,'id') ; + + $ignore{country_id} = 1 ; + + &db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + unless ($i{id}) { $error = qq(NO ID) ; return ; } + + &edit_db_fields ; + + &set_default_vals ; + + $ignore{country_id} = 1 ; + + &db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub set_default_vals { + + &db_min_ro('regions','id,name',"id = $i{region_id}",'','') ; + $i{province} = $db{regions}{$i{region_id}}{name}; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + &db_min_ro('regions','id,name,country_id',"",'','') ; + + &db_min_ro('countries','id,name',"",'','') ; + + &db_min_ro('event_quotes','id,city_id',"city_id <> 0",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + $type_id_used{$_} = 1 ; + my @city_ids = split(/\,/,$db{event_quotes}{$_id}{city_id}); + foreach my $_cid (@city_ids) { + $type_id_used{$_cid} = 1 ; + } + } + + &db_min_ro($table,'*','','','') ; + + foreach my $id (keys %{$db{$table}}) { + + my $edit_butt = qq~ ~ ; + my $del_butt = qq~ ~ ; + + if ($glod_user_level >= 3) { + $edit_butt = qq~ ~ ; + } + + if ($glod_user_level >= 3) { + $del_butt = qq~ ~ ; + } + + if ($type_id_used{$id}) { + $edit_butt = qq~ ~ ; + $del_butt = qq~ ~ ; + } + + $print_tbody .= qq~ + $id + $db{$table}{$id}{name} + $db{$table}{$id}{city_short} + $db{$table}{$id}{lat} + $db{$table}{$id}{lng} + $db{regions}{$db{$table}{$id}{region_id}}{name} + $db{countries}{$db{regions}{$db{$table}{$id}{region_id}}{country_id}}{name} + + $edit_butt + $del_butt + + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + &sort_fields; + + &hidden_db_fields; + + # $ignore{id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &sort_fields; + + &hidden_db_fields; + + $hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + + $ignore{iaction} = 1 ; + $required{name} = 1 ; + # $required{province} = 1 ; + $required{region_id} = 1 ; + + # $ignore{country_id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + %sort_field = () ; + + # $ignore{country_id} = '' ; + + + $sort_field{3} = 'name' ; $preferred_title{city_short} = "City Name" ; + $sort_field{4} = 'city_short' ; $preferred_title{city_short} = "City Acronym" ; + # $sort_field{3} = 'province' ; $preferred_title{province} = 'Region' ; + $sort_field{5} = 'lat' ; $preferred_title{lat} = 'Latitude' ; + $sort_field{6} = 'lng' ; $preferred_title{lng} = 'Longitude' ; + $sort_field{7} = 'region_id' ; + $sort_field{8} = 'country_id' ; + +} #------------------------------------------------------------------------------- + +sub add_screen { + + # called from common_add_screen + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + + # $required{based_in} = 1 ; + # $select{based_in} = 1 ; + # $opts{based_in} = qq~~ ; + + # my $sql_or = '' ; + + # if ($is_schools_manager || $is_operator) { + # @report_sql_or = () ; + # foreach $_reg_id (keys %{$glob_regids{$userid}}) { + # push @report_sql_or, "id = '$_reg_id'" + # } + # $sql_or = join(' OR ',@report_sql_or) ; + # } + + my $sql_or = ($is_schools_manager || $is_operator) ? join(' OR ', map { "id = '$_'" } keys %{$glob_regids{$userid}}) : '' ; + + $allow_deselect{country_id} = 1 ; + + # &common_min_select_opts('province','regions','name',$db{$table}{$i{id}}{province},'','',$sql_or,'name'); + + &common_min_select_opts('region_id','regions','name',$db{$table}{$i{id}}{region_id},'','code',$sql_or,''); + + &common_min_select_opts('country_id','countries','name',$db{regions}{$db{$table}{$i{id}}{region_id}}{country_id},'','','',''); + + $trigger_jquery_raw .= qq~ + + let map_region_to_country = {} ; + + const \$countrySelect = \$("#selectCountry_id") ; + const \$regionSelect = \$("#selectRegion_id") ; + + const updateChosen = \$el => \$el.trigger("chosen:updated"); + + const fetchJSON = async url => { + try { + const res = await fetch(url); + if (!res.ok) throw new Error(`Request failed: \${res.status}`); + return await res.json(); + } catch (err) { + console.error("Fetch error:", err); + return []; + } + }; + + const populateSelect = (\$field, json_list, getLabel, defaultSelected = () => "") => { + + let isSelected ; + + // Determine how to handle selected logic + if (typeof defaultSelected === "function") { + isSelected = defaultSelected ; + } else if (Array.isArray(defaultSelected)) { + isSelected = data => defaultSelected.includes(data.id) ? "selected" : "" ; + } else { + isSelected = data => data.id == defaultSelected ? "selected" : "" ; + } + + // Auto-select the only item if none explicitly selected + const autoSelectOnly = json_list.length === 1 && typeof defaultSelected === "string" && defaultSelected === "" ; + + json_list.forEach(data => { + const selected = autoSelectOnly || isSelected(data) ? "selected" : "" ; + \$field.append(``) ; + }); + + updateChosen(\$field) ; + return json_list.length ; + }; + + const getInputValue = name => \$(`input[name='\${name}']`).val(); + + const clearSelect = (\$el) => { + \$el.empty(); + \$el.append(``).trigger("chosen:updated"); + }; + + // _______________________________________________ + + \$countrySelect.change( async function() { + \$("input[name='custom_selected_country']").val("1") ; + await update_region_drop_down_from_country(\$countrySelect.val()) ; + }) ; + + async function update_region_drop_down_from_country (countryId) { + + clearSelect(\$regionSelect) ; + + const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}` ; + const regions = await fetchJSON(regionUrl); + + for (const data of regions) { + map_region_to_country[data.id] = countryId ; + } + + const regionCount = populateSelect(\$regionSelect, regions, r => r.code ? `\${r.name} [\${r.code}]` : r.name , "") ; + + if (regionCount === 0 && \$countrySelect.val()) { + \$regionSelect.append(``).trigger("chosen:updated") ; + } + + } + + // _______________________________________________ + + \$regionSelect.change( async function() { + \$("input[name='custom_selected_region']").val("1") ; + \$("input[name='custom_selected_country']").val("1") ; + const regionId = \$regionSelect.val() ; + await update_country_from_region(regionId,1) ; + }); + + async function update_country_from_region (regionId,update_country=0) { + if (map_region_to_country[regionId] || regionId == '13') { + \$countrySelect.val(map_region_to_country[regionId]).trigger("chosen:updated") ; + } else if (!\$("input[name='custom_selected_country']").val() || update_country) { + const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=®ion_id=\${regionId}`; + const regionMeta = await fetchJSON(lookupUrl); + const { country_id } = regionMeta[0] ?? {} ; + if (country_id) { + map_region_to_country[regionId] = country_id; + \$countrySelect.val(country_id).trigger("chosen:updated"); + } + } + } + + // _______________________________________________ + + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + $print_thead = qq~IDCITY NAMECITY ACRONYMLATLNGREGIONCOUNTRY ~ ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'map-marker' ; + our $lcpage = 'cities' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'cities' ; + + $s{no} = 1 ; + + &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/cron/auto_get_next_day_events.pl b/scripts/_FromProd/v1.0/cron/auto_get_next_day_events.pl new file mode 100644 index 0000000..6004c7d --- /dev/null +++ b/scripts/_FromProd/v1.0/cron/auto_get_next_day_events.pl @@ -0,0 +1,171 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI::Carp qw(fatalsToBrowser); +use Mail::POP3Client; +use MIME::Parser; +use Fcntl qw(:flock) ; +use DBI ; +use MIME::Lite; +use Mail::Sendmail; +use Date::Calc qw(:all); +use Excel::Writer::XLSX ; +use Time::Piece ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +require cfg_paths ; + +&config_set_vars ; +&config_set_paths ; + +# perl /usr/lib/cgi-bin/scripts/cron/auto_get_next_day_events.pl 1 + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $debug = $ARGV[0] ; our $username = 'rory' if $debug == 1 ; print "Content-type: text/html\n\n" if $debug == 1 ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&today; + +# &common_send_smtp_mail('','rory@kre8it.co.za','','',"Calibration : $now_dd_mm_ccyy","Start calibration cron...",'',1,'','','','',0,0) ; + +&db_open_ro; + $db_ignore_open_close=1; + &load_vars ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; +&create_excel_file ; +&send_email ; + +exit; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +sub load_vars { + + our ($sql_next_day) = &common_add_delta_days(1) ; + + our ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + + our $table = 'event_quotes' ; + + &db_min_ro($table,"1,count(*) AS 'next_day_cnt'","('$sql_next_day 23:59:59' >= `date_from` AND '$sql_next_day 00:00:00' <= `date_to`) AND `quote_accepted` = '1'",'','') ; + unless ($db{event_quotes}{1}{next_day_cnt}) { + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + exit ; + } + + $i{date_from} = $sql_next_day ; # hack for calibration_build_table_and_or_excel to simulate search + $i{date_to} = $sql_next_day ; # hack for calibration_build_table_and_or_excel to simulate search + + &calibration_load_list_vars("('$sql_next_day 23:59:59' >= `date_from` AND '$sql_next_day 00:00:00' <= `date_to`)") ; + +} #------------------------------------------------------------------------------- + +sub create_excel_file { + + # return if $file_exists ; + + our $day_of_week = Day_of_Week($next_year,$next_month,$next_day) ; + + my @day_of_week_name = ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday") ; + + $day_of_week = $day_of_week_name[$day_of_week] ; + + my $date = &common_write_date_interval("$next_year-$next_month-$next_day","$next_year-$next_month-$next_day") ; + + our $xlsx_title_heading = "Events $date" ; + + our $xlsxdir = "next_day_events" ; + + our $xlsxreportname = "Next_Day_Events" ; + + our $calibration_report = 1 ; #our $calibration_report_cron = 1 ; + + &calibration_build_table_and_or_excel(0) ; + +} #------------------------------------------------------------------------------- + +sub send_email { + + &common_debug("send_email START") ; + + # my @email_adds = ('cristy@aisport.africa','marizen@aisport.africa','dom@aisport.africa','erin@aisport.africa','techsupport@aisport.africa','dan@aisport.africa','kyle@aisport.africa','admin@kre8it.co.za') ; + + # # my $to = 'rory@kre8it.co.za' ; # only 1 email address in $to + # my $to = 'cristy@aisport.africa' ; # only 1 email address in $to + # # my $cc = 'marizen@aisport.africa;dom@aisport.africa;erin@aisport.africa;techsupport@aisport.africa;dan@aisport.africa;kyle@aisport.africa;admin@kre8it.co.za' ; + # my $cc = 'marizen@aisport.africa' ; + # # my $bcc = 'viv@aisport.africa' ; + # # my $bcc = 'rory@kre8it.co.za' ; + # # my $bcc = 'k@re8it.com' ; + # my $bcc = 'dom@aisport.africa' ; + + # &common_debug("send_email $to") ; + + # if ($email{$userid}) { $bcc .= ';' . $email{$userid} ; } + + # if ($username eq 'rory') { $to = 'rory@kre8it.co.za' ; $cc = 'k@re8it.com;rory@mathew.za.net' ; $bcc = 'admin@kre8it.co.za' ; } + # # if ($debug) { $to = 'rory@kre8it.co.za' ; $cc = 'k@re8it.com;rory@mathew.za.net' ; $bcc = 'admin@kre8it.co.za' ; } + # # if ($username eq 'handre') { $to = 'handre@kre8it.co.za' ; } + + if (not -f $xlsxfile) { + $attachpath = '' ; $attachfile = '' ; + } else { + $attachpath = $xlsxdir ; $attachfile = $xlsxname ; + } + + &common_debug("send_email $xlsxpath/$xlsxname") ; + + # my $attach_flyer = 0 ; my $message = qq~Hello World~ ; my $isubject = qq~Hello World~ ; + + my $date_to_text = Date_to_Text($next_year,$next_month,$next_day) ; + + &common_debug("send_email : $date_to_text") ; + + $cntsend=0; + + my $to = ($debug) ? $email_it_1 : $email_events{1} ; + + delete $email_events{1}; # remove as to not Cc as well as To + + my @keys = sort {$a <=> $b} keys %email_events; + my $last_key = $keys[-1]; + + my $bcc = ($debug) ? '' : $email_events{$last_key} ; + + delete $email_events{$last_key}; + + my $cc = ($debug) ? '' : join(", ", values %email_events); + + # print "'','$to','$cc','$bcc','Calibration : $date_to_text','Please see attached calibration...','','html','',$xlsxpath,$xlsxname,'vnd.openxmlformats-officedocument.spreadsheetml.sheet',0,0" + + &common_send_smtp_mail('',"$to","$cc","$bcc","Calibration : $date_to_text","Please see attached calibration...",'','html','',$xlsxpath,$xlsxname,'vnd.openxmlformats-officedocument.spreadsheetml.sheet',0,0) ; + + # # foreach my $_eadd (@email_adds) { + # foreach my $_eaddcnt (keys %email_events) { + # my $_eadd = $email_events{$_eaddcnt} ; + # $cntsend++ ; + # $to = ($debug) ? $email_it_1 : $_eadd ; + # $cc = '' ; + # $bcc = ($email{$userid} && $cntsend == 1) ? "$email{$userid}" : '' ; $bcc = 'rory@mathew.za.net' if $debug ; + # &common_send_smtp_mail('',"$to","$cc","$bcc","Calibration : $date_to_text","Please see attached calibration...",'','html','',$xlsxpath,$xlsxname,'vnd.openxmlformats-officedocument.spreadsheetml.sheet',0,0) ; + # last if $debug ; + # } + + # &common_send_smtp_mail('',$to,'',$bcc,$isubject,$message,'',1,'','','','',0,0) ; + +} #------------------------------------------------------------------------------- + +use db ; +use common ; +use today ; +use xlsxcreator ; +use report ; +use calibration ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/cron/auto_get_next_day_events_test.pl b/scripts/_FromProd/v1.0/cron/auto_get_next_day_events_test.pl new file mode 100644 index 0000000..1aeac89 --- /dev/null +++ b/scripts/_FromProd/v1.0/cron/auto_get_next_day_events_test.pl @@ -0,0 +1,155 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI::Carp qw(fatalsToBrowser); +use Mail::POP3Client; +use MIME::Parser; +use Fcntl qw(:flock) ; +use DBI ; +use MIME::Lite; +use Mail::Sendmail; +use Date::Calc qw(:all); +use Excel::Writer::XLSX ; +use Time::Piece ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +require cfg_paths ; + +&config_set_vars ; +&config_set_paths ; + +# https://itvadmin.co.za/cgi-bin/scripts/cron/auto_get_next_day_events.pl?1 + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +# my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0] ; our $username = 'rory' if $debug == 1 ; print "Content-type: text/html\n\n" if $debug == 1 ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&today; + +# &common_send_smtp_mail('','rory@kre8it.co.za','','',"Calibration : $now_dd_mm_ccyy","Start calibration cron...",'',1,'','','','',0,0) ; + +&db_open_ro; + $db_ignore_open_close=1; + &load_vars ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; +&create_excel_file ; +&send_email ; + +exit; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +sub load_vars { + + our ($sql_next_day) = &common_add_delta_days(1) ; + + our ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + + our $table = 'event_quotes' ; + + &db_min_ro($table,"1,count(*) AS 'next_day_cnt'","('$sql_next_day 23:59:59' >= `date_from` AND '$sql_next_day 00:00:00' <= `date_to`) AND `quote_accepted` = '1'",'','') ; + unless ($db{event_quotes}{1}{next_day_cnt}) { + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + exit ; + } + + $i{date_from} = $sql_next_day ; # hack for calibration_build_table_and_or_excel to simulate search + $i{date_to} = $sql_next_day ; # hack for calibration_build_table_and_or_excel to simulate search + + &calibration_load_list_vars("('$sql_next_day 23:59:59' >= `date_from` AND '$sql_next_day 00:00:00' <= `date_to`)") ; + +} #------------------------------------------------------------------------------- + +sub create_excel_file { + + # return if $file_exists ; + + our $day_of_week = Day_of_Week($next_year,$next_month,$next_day) ; + + my @day_of_week_name = ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday") ; + + $day_of_week = $day_of_week_name[$day_of_week] ; + + my $date = &common_write_date_interval("$next_year-$next_month-$next_day","$next_year-$next_month-$next_day") ; + + our $xlsx_title_heading = "Events $date" ; + + our $xlsxdir = "next_day_events" ; + + our $xlsxreportname = "Next_Day_Events" ; + + our $calibration_report = 1 ; #our $calibration_report_cron = 1 ; + + &calibration_build_table_and_or_excel(0) ; + +} #------------------------------------------------------------------------------- + +sub send_email { + + &common_debug("send_email START") ; + + # my @email_adds = ('cristy@itvafrica.net','marizen@itvafrica.net','dom@itvafrica.net','erin@itvafrica.net','techsupport@itvafrica.net','dan@itvafrica.net','kyle@itvafrica.net','admin@kre8it.co.za') ; + my @email_adds = ('rory@kre8it.co.za') ; + + # # my $to = 'rory@kre8it.co.za' ; # only 1 email address in $to + # my $to = 'cristy@itvafrica.net' ; # only 1 email address in $to + # # my $cc = 'marizen@itvafrica.net;dom@itvafrica.net;erin@itvafrica.net;techsupport@itvafrica.net;dan@itvafrica.net;kyle@itvafrica.net;admin@kre8it.co.za' ; + # my $cc = 'marizen@itvafrica.net' ; + # # my $bcc = 'viv@itvafrica.net' ; + # # my $bcc = 'rory@kre8it.co.za' ; + # # my $bcc = 'k@re8it.com' ; + # my $bcc = 'dom@itvafrica.net' ; + + # &common_debug("send_email $to") ; + + # if ($email{$userid}) { $bcc .= ';' . $email{$userid} ; } + + # if ($username eq 'rory') { $to = 'rory@kre8it.co.za' ; $cc = 'k@re8it.com;rory@mathew.za.net' ; $bcc = 'admin@kre8it.co.za' ; } + # # if ($debug) { $to = 'rory@kre8it.co.za' ; $cc = 'k@re8it.com;rory@mathew.za.net' ; $bcc = 'admin@kre8it.co.za' ; } + # # if ($username eq 'handre') { $to = 'handre@kre8it.co.za' ; } + + if (not -f $xlsxfile) { + $attachpath = '' ; $attachfile = '' ; + } else { + $attachpath = $xlsxdir ; $attachfile = $xlsxname ; + } + + &common_debug("send_email $xlsxpath/$xlsxname") ; + + # my $attach_flyer = 0 ; my $message = qq~Hello World~ ; my $isubject = qq~Hello World~ ; + + my $date_to_text = Date_to_Text($next_year,$next_month,$next_day) ; + + &common_debug("send_email : $date_to_text") ; + + $cntsend=0; + + foreach my $_eadd (@email_adds) { + $cntsend++ ; + # $to = ($debug) ? 'rory@kre8it.co.za' : $_eadd ; + $to = $_eadd ; + $cc = '' ; + $bcc = ($email{$userid} && $cntsend == 1) ? "$email{$userid}" : '' ; $bcc = '' if $debug ; + &common_send_smtp_mail('',"$to","$cc","$bcc","Calibration : $date_to_text","Please see attached calibration...",'','html','',$xlsxpath,$xlsxname,'',0,0) ; + last if $debug ; + } + + # &common_send_smtp_mail('',$to,'',$bcc,$isubject,$message,'',1,'','','','',0,0) ; + +} #------------------------------------------------------------------------------- + +use db ; +use common ; +use today ; +use xlsxcreator ; +use report ; +use calibration_test ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/cron/auto_get_next_day_events_with_fixed_system_test.pl b/scripts/_FromProd/v1.0/cron/auto_get_next_day_events_with_fixed_system_test.pl new file mode 100644 index 0000000..f12740c --- /dev/null +++ b/scripts/_FromProd/v1.0/cron/auto_get_next_day_events_with_fixed_system_test.pl @@ -0,0 +1,148 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI::Carp qw(fatalsToBrowser); +use Mail::POP3Client; +use MIME::Parser; +use Fcntl qw(:flock) ; +use DBI ; +use MIME::Lite; +use Mail::Sendmail; +use Date::Calc qw(:all); +use Excel::Writer::XLSX ; +use Time::Piece ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +require cfg_paths ; + +&config_set_vars ; +&config_set_paths ; + +# https://itvadmin.co.za/cgi-bin/scripts/cron/auto_get_next_day_events.pl?1 + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +# my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0] ; our $username = 'rory' if $debug == 1 ; print "Content-type: text/html\n\n" if $debug == 1 ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&today; + +# &common_send_smtp_mail('','rory@kre8it.co.za','','',"Calibration : $now_dd_mm_ccyy","Start calibration cron...",'',1,'','','','',0,0) ; + +&db_open_ro; + $db_ignore_open_close=1; + &load_calibration_vars ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; +&create_calibration_excel_file ; +&send_email('calibration') ; +&create_fixedsystem_excel_file ; +&send_email('fixed') ; + +exit; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +sub load_calibration_vars { + + our ($sql_next_day) = &common_add_delta_days(1) ; + + our ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + + our $table = 'event_quotes' ; + + &db_min_ro($table,"1,count(*) AS 'next_day_cnt'","('$sql_next_day 23:59:59' >= `date_from` AND '$sql_next_day 00:00:00' <= `date_to`) AND `quote_accepted` = '1'",'','') ; + unless ($db{event_quotes}{1}{next_day_cnt}) { + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + exit ; + } + + $i{date_from} = $sql_next_day ; # hack for calibration_build_table_and_or_excel to simulate search + $i{date_to} = $sql_next_day ; # hack for calibration_build_table_and_or_excel to simulate search + + &calibration_load_list_vars("('$sql_next_day 23:59:59' >= `date_from` AND '$sql_next_day 00:00:00' <= `date_to`)") ; + +} #------------------------------------------------------------------------------- + +sub create_calibration_excel_file { + + # return if $file_exists ; + + our $day_of_week = Day_of_Week($next_year,$next_month,$next_day) ; + our @day_of_week_name = ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday") ; + $day_of_week = $day_of_week_name[$day_of_week] ; + our $date = &common_write_date_interval("$next_year-$next_month-$next_day","$next_year-$next_month-$next_day") ; + our $xlsx_title_heading = "Calibration Events $date" ; + our $xlsxdir = "next_day_events" ; + our $xlsxreportname = "Next_Day_Events_Calibration" ; + our $calibration_report = 1 ; #our $calibration_report_cron = 1 ; + + &calibration_build_table_and_or_excel(0) ; + +} #------------------------------------------------------------------------------- + +sub create_fixedsystem_excel_file { + + our $xlsx_title_heading = "Fixed Systems Test Events $date" ; + our $xlsxreportname = "Next_Day_Events_Fixed_Systems_Test" ; + + &db_min_ro('event_systems','*',"`system_type` = 'fixed'",'','') ; + + &fixedsystem_build_table_and_or_excel(0) ; + +} #------------------------------------------------------------------------------- + +sub send_email { + + my ($fxc) = @_ ; + + &common_debug("send_email START") ; + + # my @email_adds = ('cristy@itvafrica.net','marizen@itvafrica.net','dom@itvafrica.net','erin@itvafrica.net','techsupport@itvafrica.net','dan@itvafrica.net','kyle@itvafrica.net','admin@kre8it.co.za') ; + my @email_adds = ('admin@kre8it.co.za') ; + + if (not -f $xlsxfile) { + $attachpath = '' ; $attachfile = '' ; + } else { + $attachpath = $xlsxdir ; $attachfile = $xlsxname ; + } + + &common_debug("send_email $xlsxpath/$xlsxname") ; + + my $date_to_text = Date_to_Text($next_year,$next_month,$next_day) ; + + &common_debug("send_email : $date_to_text") ; + + $cntsend=0; + + foreach my $_eadd (@email_adds) { + $cntsend++ ; + $to = ($debug) ? 'rory@kre8it.co.za' : $_eadd ; + $cc = '' ; + $bcc = ($email{$userid} && $cntsend == 1) ? "$email{$userid}" : '' ; $bcc = '' if $debug ; + if ($fxc eq 'calibration') { + &common_send_smtp_mail('',"$to","$cc","$bcc","Calibration : $date_to_text","Please see attached calibration...",'','html','',$xlsxpath,$xlsxname,'',0,0) ; + } elsif ($fxc eq 'fixed') { + &common_send_smtp_mail('',"$to","$cc","$bcc","Fixed System Tests : $date_to_text","Please see attached Fixed System Tests...",'','html','',$xlsxpath,$xlsxname,'',0,0) ; + } + last if $debug ; + } + + # &common_send_smtp_mail('',$to,'',$bcc,$isubject,$message,'',1,'','','','',0,0) ; + +} #------------------------------------------------------------------------------- + +use db ; +use common ; +use today ; +use xlsxcreator ; +use report ; +use calibration ; +use fixedsystems ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/cron/auto_getmail.pl b/scripts/_FromProd/v1.0/cron/auto_getmail.pl new file mode 100644 index 0000000..1a23e85 --- /dev/null +++ b/scripts/_FromProd/v1.0/cron/auto_getmail.pl @@ -0,0 +1,42 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use Mail::POP3Client; +use MIME::Parser; +use Fcntl qw(:flock) ; +use DBI ; +use MIME::Lite; +use Mail::Sendmail; + +require cfg_paths ; + +&config_set_vars ; +&config_set_paths ; + +# https://itvadmin.co.za/cgi-bin/scripts/cron/auto_getmail.pl?debug=1 + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $debug = $ARGV[0] ; our $username = 'rory' if $debug == 1 ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exit; # tickets not being used on the system + +&getmail_fetch; + +exit; + +#------------------------------------------------------------------------------------------ + +use db ; +use common ; +use today ; +use getmail ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/cron/email_sql_backup.pl b/scripts/_FromProd/v1.0/cron/email_sql_backup.pl new file mode 100644 index 0000000..a87e322 --- /dev/null +++ b/scripts/_FromProd/v1.0/cron/email_sql_backup.pl @@ -0,0 +1,138 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use MIME::Lite; +use Mail::Sendmail; +use Date::Calc qw(:all); + +#------------------------------------------------------------------------------- + +our $debug = $ARGV[0] ; +our $username = $ARGV[1] ; + +# perl /usr/lib/cgi-bin/scripts/cron/email_sql_backup.pl 1 rory + +#------------------------------------------------------------------------------------------ + +&config_set_paths; +&config_set_vars ; + +&today; +&read_bz2_backups($mysqlbakpath,'bz2'); +&sort_files; + +exit ; + +#------------------------------------------------------------------------------- + +sub read_bz2_backups { + + my ($path,$ext) = @_; + + opendir BP_DIR,"$path" or die "Cannot open $path: $!\n"; + my @backups = grep { /\.$ext$/ } readdir BP_DIR; + closedir BP_DIR; + + for (@backups) { + my ($db_bk_name,$db_bk_date,$db_bk_time,$db_bk_ext) = split(/\./); + + $db_bk_date =~ s/\-//g; + + push @bkfiles, "$db_bk_date$db_bk_time|$_" ; + } + +} #------------------------------------------------------------------------------- + +sub sort_files { + + my @sorted_bkfiles = sort {$b <=> $a} @bkfiles ; + + my ($sortprefix,$file) = split(/\|/, shift @sorted_bkfiles); + + if ($file) { + &send_email($file); + } + +} #------------------------------------------------------------------------------- + +sub send_email { + + my ($attachname) = @_ ; + + my $to = ($debug) ? $email_it_1 : $email_accounts ; + my $bcc = ($debug) ? '' : $email_it_1 ; + + &common_send_smtp_mail('',$to,'',$bcc,"$useropts{acronym} MySQL Backup : $attachname",'Please see DB backup attached...'," $attachname ",'html'," MySQL latest Backup ",$mysqlbakpath,$attachname,'','','') ; + + # $msg = MIME::Lite -> new( + # From => "$useropts{acronym} ", + # To => $to, + # Subject => "$useropts{acronym} MySQL Backup : $attachname", + # Type => 'multipart/mixed' + # ); + + # # my $boundary = "====" . time() . "===="; + + # my $email_body = < + # + # + # + # + + # + + # + # + + #
    + + # ITV + #

    + + # + # + # + # + # + #
     MySQL latest Backup 
     $attachname 
    + + #

    + #
    + # + # +# END_OF_BODY + + # $msg -> attach( + # Type => 'text/html', + # Data => $email_body + # ); + + # $msg -> attach ( + # Type => 'AUTO', + # Path => "$mysqlbakpath/$attachname", + # Filename => "$attachname", + # Disposition => 'attachment' + # ) or die "Error adding $path : $attach $!\n"; + + # $msg -> send ('smtp','localhost', Debug=>0 ); + +} #------------------------------------------------------------------------------- + +use common ; +use today ; +use uploader ; +use cfg_paths ; + +1; + diff --git a/scripts/_FromProd/v1.0/cron/feed.dat b/scripts/_FromProd/v1.0/cron/feed.dat new file mode 100644 index 0000000..710386c --- /dev/null +++ b/scripts/_FromProd/v1.0/cron/feed.dat @@ -0,0 +1,3 @@ +USD|ZAR|14.34|14.34|19.50| +USD|EUR|0.84|0.84|0.839715| +USD|GBP|0.72|0.72|0.721695| diff --git a/scripts/_FromProd/v1.0/cron/get_exchange_rates.pl b/scripts/_FromProd/v1.0/cron/get_exchange_rates.pl new file mode 100644 index 0000000..3764d91 --- /dev/null +++ b/scripts/_FromProd/v1.0/cron/get_exchange_rates.pl @@ -0,0 +1,135 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use Fcntl qw(:flock); +use CGI::Carp qw(fatalsToBrowser); +use JSON; +use LWP::Simple qw($ua get); + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0] ; + +# https://itvadmin.co.za/cgi-bin/scripts/cron/get_exchange_rates.pl?1 + +if ($debug) { our $username = 'rory' ; print "Content-type: text/html\n\n"; } + +exit; + +#------------------------------------------------------------------------------------------ + +&fetch_exchange_rates ; +&save_info ; +exit ; + +#------------------------------------------------------------------------------- + +sub fetch_exchange_rates { + +&fetch_exchange_rates_using_json_send_post_api_1('USD','ZAR') ; +&fetch_exchange_rates_using_json_send_post_api_1('USD','GBP') ; +&fetch_exchange_rates_using_json_send_post_api_1('USD','EUR') ; + +&fetch_exchange_rates_using_json_send_post_api_2('USD','ZAR') ; +&fetch_exchange_rates_using_json_send_post_api_2('USD','GBP') ; +&fetch_exchange_rates_using_json_send_post_api_2('USD','EUR') ; + +} #------------------------------------------------------------------------------------------ + +sub fetch_exchange_rates_using_json_send_post_api_1 { + +my ($from_curr,$to_curr) = @_ ; + +my $url = "http://currency-api.appspot.com/api/$from_curr/$to_curr.json" ; + +my $json = get $url ; +print "Couldn't get $url ! $!" unless defined $json ; + +&common_debug($json); +# exit; + +my $perl_scalar = decode_json $json ; + +# my $rate = $perl_scalar->{'rate'} ; +my $rate = $perl_scalar->{'amount'} ; # rounded to 2 decimal places + +$exchng_rate{$from_curr}{$to_curr} = $rate ; + +} #------------------------------------------------------------------------------- + +sub fetch_exchange_rates_using_json_send_post_api_2 { + +my ($from_curr,$to_curr) = @_ ; + +my $cft = $from_curr . '_' . $to_curr ; + +my $url = "http://free.currencyconverterapi.com/api/v5/convert?q=$cft&compact=y&apiKey=1ada7dd66cf88a0211cd" ; # rory@kre8it.co.za API key +# my $url = "http://free.currencyconverterapi.com/api/v5/convert?q=$cft&compact=y&apiKey=1a0ae2c44dc4a60c7539" ; # vivian@filmfreight.co.za API key + +my $json = get $url ; +die "Couldn't get $url ! $!" unless defined $json ; + +my $decoded_json = decode_json $json ; + +if ($debug) { print "json=$json \n" ; } + +my $ccapirate = $decoded_json->{$cft}->{'val'} ; # rounded to 2 decimal places + +$exchng_rate_ccapi{$from_curr}{$to_curr} = $ccapirate ; + +} #------------------------------------------------------------------------------- + +sub save_info { + +unless (%exchng_rate) { return ; } + +$exchgfile = "/usr/lib/cgi-bin/scripts/cron/feed.dat"; + +open (IFILE, "+>>$exchgfile") or die "can't open $exchgfile : $!" ; +flock (IFILE, LOCK_EX) or die "can't lock $exchgfile : $!" ; +seek (IFILE, 0, 0) or die "can't rewind $exchgfile : $!" ; +@exchng = ; +seek (IFILE, 0, 0) or die "can't rewind $exchgfile : $!" ; +truncate (IFILE, 0) or die "can't truncate $exchgfile : $!" ; + +foreach $line (@exchng) { + chomp $line; + @linex = split(/\|/,$line); + + my $from = $linex[0] ; + my $to = $linex[1] ; + my $rate = $linex[2] ; + my $prate = $linex[3] ; + my $ccapirate = $linex[4] ; + + if ($exchng_rate{$from}{$to}) { + $prate = $rate ; + $rate = $exchng_rate{$from}{$to} ; + } + + if ($exchng_rate_ccapi{$from}{$to}) { + $ccapirate = $exchng_rate_ccapi{$from}{$to} ; + } + + $done{$from}{$to} = 1 ; + + print IFILE "$from|$to|$rate|$prate|$ccapirate|\n"; + } + +foreach my $from (keys %exchng_rate) { + foreach my $to (keys %{$exchng_rate{$from}}) { + if ($done{$from}{$to}) { next ; } + print IFILE "$from|$to|$exchng_rate{$from}{$to}||$exchng_rate_ccapi{$from}{$to}|\n"; + } + } + +close (IFILE) ; + +} #---------------------------------------------------------------------------------------- + +use common ; + +1; + diff --git a/scripts/_FromProd/v1.0/cron/load_leave_settings.pl b/scripts/_FromProd/v1.0/cron/load_leave_settings.pl new file mode 100644 index 0000000..a31a5e1 --- /dev/null +++ b/scripts/_FromProd/v1.0/cron/load_leave_settings.pl @@ -0,0 +1,221 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); +use Date::Calc qw(:all); +use DBI; + +# require cfg ; + +print header; # CGI.pm method + +# run with https://www.ffwaybill.co.za/cgi-bin/scripts/admin/load_leave_settings.pl + +exit; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +# unless ($username eq 'rory') { print ">>>>>> RORY DOING MAINTENANCE <<<<<<"; exit; } + + # @ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +# our $debug = $ARGV[0] ; + +our $debug = 1 ; +our $username = 'rory' ; + +my $last_year = $now_year - 1 ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&common_min_debug(">>> START <<< load_leave_settings.pl"); + +&read_leave_settings; +&read_leave_calendar; +&process; + +&common_min_debug(">>> END <<< load_leave_settings.pl"); + +exit; + +#------------------------------------------------------------------------------------------ + +sub read_leave_settings { + +# &db_min_ro(leave_settings,'*',"`leave_year`='$i{leave_year}' AND `category`='$i{category}' AND `user_id`='$i{user_id}'",'','') ; +&db_min_ro('leave_settings','*',"`leave_year`='$now_year' OR `leave_year`='$last_year'",'','') ; + +foreach my $id (keys %{$db{leave_settings}}) { + # if (($db{leave_settings}{$id}{leave_year} eq $i{leave_year}) and ($db{leave_settings}{$id}{category} eq $i{category}) and ($db{leave_settings}{$id}{user_id} eq $i{user_id})) { + $days_entitled{$db{leave_settings}{$id}{category}}{$db{leave_settings}{$id}{leave_year}}{$db{leave_settings}{$id}{user_id}} = $db{leave_settings}{$id}{days_entitled} ; + $days_carried_over{$db{leave_settings}{$id}{category}}{$db{leave_settings}{$id}{leave_year}}{$db{leave_settings}{$id}{user_id}} = $db{leave_settings}{$id}{days_carried_over} ; + } + + +} #------------------------------------------------------------------------------------------ + +sub read_leave_calendar { + +my $last_year = $now_year - 1 ; + +&db_min_ro('events','*',"(((`startdate` LIKE '$now_year%') OR (`enddate` LIKE '$now_year%')) OR ((`startdate` LIKE '$last_year%') OR (`enddate` LIKE '$last_year%'))) AND `category`='leave'",'`id` DESC','') ; + +foreach my $id (keys %{$db{events}}) { + # if (($db{leave_settings}{$id}{leave_year} eq $i{leave_year}) and ($db{leave_settings}{$id}{category} eq $i{category}) and ($db{leave_settings}{$id}{user_id} eq $i{user_id})) { + # $days_taken{$db{leave_settings}{$id}{leave_year}}{$db{leave_settings}{$id}{category}} = $db{leave_settings}{$id}{days_entitled} ; + # $days_carried_over{$db{leave_settings}{$id}{leave_year}}{$db{leave_settings}{$id}{category}} = $db{leave_settings}{$id}{days_carried_over} ; + + my ($sdate,$stime) = split(/ /,$db{events}{$id}{startdate}) ; + my $s_ccyymmdd = &common_min_convert_sql_date_time($sdate); + my ($edate,$etime) = split(/ /,$db{events}{$id}{enddate}) ; + my $e_ccyymmdd = &common_min_convert_sql_date_time($edate); + + &dates_array($s_ccyymmdd,$e_ccyymmdd) ; + + my $val = $db{events}{$id}{days} ; + + # $days_taken{$db{events}{$id}{type}}+=$val; + # $cats{$db{events}{$id}{type}} = 1 ; + + my $scalar = scalar @dates_array ; my $taken_per_day = 1 ; + + if ($scalar>0) { + $taken_per_day = $val / $scalar ; + } + else + { + # $taken_per_day = $days_taken{$db{events}{$id}{type}} ; + $taken_per_day = $db{events}{$id}{days} ; + my $sccyymmdd = &common_min_convert_sql_date_time($db{events}{$id}{startdate}); + push @dates_array, $sccyymmdd ; # create array when start and end date same + } + + foreach my $date (@dates_array) { + my $ccyy = substr($date,0,4) ; + my $mm = substr($date,4,2) ; $mm = sprintf("%0.0f",$mm) ; + my $dd = substr($date,6,2) ; $dd = sprintf("%0.0f",$dd) ; + + $days_taken_by_year{$db{events}{$id}{type}}{$ccyy}{$db{events}{$id}{user_id}}+=$taken_per_day; + + # if (($day_of_week{$date} > 0) and (($day_of_week{$date} < 6))) { # mon - fri + # $days_txt{$mm}{$db{events}{$id}{type}} .= "$dd/" ; + # } + + # &common_min_debug(">>> $db{events}{$id}{type} [$mm] [$days_taken_by_month{$mm}{$ccyy}{$db{events}{$id}{type}}] [$taken_per_day]"); + } + } + + +} #------------------------------------------------------------------------------------------ + +sub process { + +&db_min_ro('users','*','','','') ; +foreach my $id (keys %{$db{users}}) { $user{$id} = $db{users}{$id}{name} ; } + +foreach my $year (keys %{$days_entitled{annual}}) { + foreach my $user_id (keys %{$days_entitled{annual}{$year}}) { + if ($done{$user_id}{$year}) { next ; } + # &common_min_debug(">>> 1. $year [$user{$user_id}] [days_entitled=$days_entitled{annual}{$year}{$user_id}] [days_carried_over=$days_carried_over{annual}{$year}{$user_id}] [days_taken in $year = $days_taken_by_year{annual}{$year}{$user_id}]"); + $done{$user_id}{$year} = 1 ; + $leave_settings_for_current_year{$user_id}{$year} = 1 ; + &insert_leave_settings($user_id,$year) ; + } + } + +foreach my $year (keys %{$days_taken_by_year{annual}}) { + foreach my $user_id (keys %{$days_taken_by_year{annual}{$year}}) { + if ($done{$user_id}{$year}) { next ; } + # &common_min_debug(">>> 2. $year [$user{$user_id}] [days_entitled=$days_entitled{annual}{$year}{$user_id}] [days_carried_over=$days_carried_over{annual}{$year}{$user_id}] [days_taken in $year = $days_taken_by_year{annual}{$year}{$user_id}]"); + $done{$user_id}{$year} = 1 ; + &insert_leave_settings($user_id,$year) ; + } + } + +foreach my $id (keys %{$db{users}}) { + unless ($done{$id}{$now_year}) { + &insert_leave_settings($id,$now_year) ; + } + } + +} #------------------------------------------------------------------------------------------ + +sub insert_leave_settings { + +my ($user_id,$year) = @_ ; + +unless ($year eq $now_year) { return ; } # &common_min_debug("insert_leave_settings ERROR : $year ne $now_year"); +if ($leave_settings_for_current_year{$user_id}{$now_year}) { &common_min_debug("insert_leave_settings ERROR : $year settings already EXIST [$user{$user_id}]"); return ; } +if (lc substr($user{$user_id},0,4) eq 'rory') { return ; } +if (lc substr($user{$user_id},0,4) eq 'test') { return ; } + +# $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +my $balance = $days_entitled{annual}{$last_year}{$user_id} + $days_carried_over{annual}{$last_year}{$user_id} - $days_taken_by_year{annual}{$last_year}{$user_id} ; + +$i{user_id} = $user_id ; +$i{days_entitled} = 15 ; +$i{category} = 'annual' ; +$i{leave_year} = $now_year ; +$i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; +$i{days_carried_over} = $balance ; +$i{leave_start_date} = "$year-01-01" ; + +# &common_min_debug("insert_leave_settings INSERT >>> [$user{$user_id},$year] days_carried_over=$i{days_carried_over} [$balance = $days_entitled{annual}{$last_year}{$user_id} + $days_carried_over{annual}{$last_year}{$user_id} - $days_taken_by_year{annual}{$last_year}{$user_id}] ;"); + +&db_min_insert('leave_settings') ; + +} #------------------------------------------------------------------------------------------ + +sub dates_array { + +my ($start_date,$end_date) = @_ ; + +my $array_date = $start_date ; + +@dates_array=() ; + +while ($array_date < $end_date) { + + push @dates_array, $array_date ; + + my $stay_date_dd = substr($array_date,6,2) ; + my $stay_date_mm = substr($array_date,4,2) ; + my $stay_date_ccyy = substr($array_date,0,4) ; + + $day_of_week{$array_date} = Day_of_Week($stay_date_ccyy,$stay_date_mm,$stay_date_dd) ; # 1 is Monday + + my ($ccyy,$month,$day) = Add_Delta_Days($stay_date_ccyy,$stay_date_mm,$stay_date_dd,1) ; + $month = sprintf("%02s", $month) ; + $day = sprintf("%02s", $day) ; + + $array_date = "$ccyy$month$day" ; + } + +} #------------------------------------------------------------------------------- + +# sub validate { + +# &db_min_ro(leave_settings,'*',"`leave_year`='$i{leave_year}' AND `category`='$i{category}' AND `user_id`='$i{user_id}'",'','') ; + +# foreach my $id (keys %{$db{leave_settings}}) { + # if (($db{leave_settings}{$id}{leave_year} eq $i{leave_year}) and ($db{leave_settings}{$id}{category} eq $i{category}) and ($db{leave_settings}{$id}{user_id} eq $i{user_id})) { + # $exists = 1 ; + # } + # } + + +# } #------------------------------------------------------------------------------------------ + +use db ; +use db_min ; +use common ; +use common_min ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/cron/mysql_backup.pl b/scripts/_FromProd/v1.0/cron/mysql_backup.pl new file mode 100644 index 0000000..1a845f6 --- /dev/null +++ b/scripts/_FromProd/v1.0/cron/mysql_backup.pl @@ -0,0 +1,110 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI::Carp qw(fatalsToBrowser); +use strict; +use DBI; +use Date::Calc qw(:all); +use Date::Manip; + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +my $debug = $ARGV[0] ; + +# test link : https://www.itvadmin.co.za/cgi-bin/scripts/cron/mysql_backup.pl?1 + +#------------------------------------------------------------------------------- + +my ($now_sec,$now_min,$now_hour,$now_dd,$now_mm,$now_year,$now_wday,$now_yday,$isdst)=localtime(); + +$now_sec = sprintf("%02d", $now_sec) ; +$now_min = sprintf("%02d", $now_min) ; +$now_hour = sprintf("%02d", $now_hour) ; + +$now_year += 1900; + + $now_dd = sprintf("%02s", $now_dd) ; + $now_mm = sprintf("%02s", $now_mm + 1) ; +my $now_yy = sprintf("%02s", $now_year - 2000) ; + +exit if $now_hour > 21 || $now_hour < 8 ; + +# my ($bkyear,$bkmonth,$bkday) = Add_Delta_Days($now_year,$now_mm,$now_dd,-7) ; + +# $bkmonth = sprintf("%02s", $bkmonth) ; +# $bkday = sprintf("%02s", $bkday) ; + +my $err = '' ; + +my $date1 = &ParseDate("$now_mm/$now_dd/$now_yy"); + +my $date2 = &DateCalc($date1,"- 7 days",\$err); + +my $bkyear = substr($date2,0,4); +my $bkmonth = substr($date2,4,2); +my $bkday = substr($date2,6,2); + +#------------------------------------------------------------------------------- + +my $db = "itv_admin_db"; +my $dbhost = "localhost"; +my $dbuser = "itv_admin_user"; +my $dbpass = "!Ja16Q7P0X3SVTWr"; +my $date = "`date +%Y-%m-%d`"; +my $path = "/home/mysqlbak"; +my $ext = "bz2"; + +if ($debug) { print "Content-type: text/html\n\n"; } + +flush_old($path,$ext); +my($dbh,$sth,$query); + +my $dsn = "DBI:mysql:$db;host=$dbhost"; +$dbh = DBI->connect($dsn,$dbuser,$dbpass,{PrintError => 0, RaiseError => 1}) or die "Unable to connect, $DBI::errstr"; +$query = qq^SHOW DATABASES^; +$sth = $dbh->prepare($query); +$sth->execute(); + +while(my $ref = $sth->fetchrow_array()) { + unless ($ref eq 'itv_admin_db') { next ; } + if ($debug) { print "ref=$ref \n"; } + my @bp = `mysqldump --user=$dbuser --password=$dbpass --add-drop-table $ref | bzip2 -1 > $path/$ref.$date.$now_hour$now_min.$ext`; +} + +$sth->finish(); +$dbh->disconnect(); + +my $dow = Day_of_Week($now_year,$now_mm,$now_dd); +our $ftp_file_name = "itv_admin_db.$dow.bz2" ; +&uploader_filmfreight("$path/itv_admin_db.$now_year-$now_mm-$now_dd.$now_hour$now_min.$ext","/mysqlbak",$ftp_file_name,'n') ; + +# - - - - - - - - - - - - - - - - - +if ($debug) { print "Done."; } +# - - - - - - - - - - - - - - - - - + +sub flush_old { + my ($path,$ext) = @_; + opendir BP_DIR,"$path" or die "Cannot open $path: $!\n"; + my @old_backups = grep { /\.$ext$/ } readdir BP_DIR; + closedir BP_DIR; + + for (@old_backups) { + my ($db_bk_name,$db_bk_date,$db_bk_time,$db_bk_ext) = split(/\./); + $db_bk_date =~ s/\-//g; + my $bk_7_days_back_date = "$bkyear$bkmonth$bkday"; + # print "
    1. $_ -> $db_bk_date = $bkyear$bkmonth$bkday" ; + if ($db_bk_date > $bk_7_days_back_date) { next; } + # print "
    2. $_ -> $db_bk_date = $bkyear$bkmonth$bkday" ; + my @args = ("rm","-f","$path/$_"); + system(@args); + } +} + +# - - - - - - - - - - - - - - - - - + +use common ; +use uploader ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/cron/remove_expired_sessions_mysql.pl b/scripts/_FromProd/v1.0/cron/remove_expired_sessions_mysql.pl new file mode 100644 index 0000000..5748810 --- /dev/null +++ b/scripts/_FromProd/v1.0/cron/remove_expired_sessions_mysql.pl @@ -0,0 +1,102 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI::Carp qw(fatalsToBrowser); +use Date::Calc qw(:all); +use DBI; + + # /usr/lib/cgi-bin/scripts/cron/remove_expired_sessions_mysql.pl 1 + +#------------------------------------------------------------------------------- + +our $debug = $ARGV[0] ; +our $username = 'rory' ; + +#------------------------------------------------------------------------------------------ + +&today ; +&set_delete_date ; + +&db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &delete_sessions ; + &set_expired_event_quotes_status ; + $db_ignore_open_close = 0 ; +&db_close_conn ; + +print "Done." if $debug ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub delete_sessions { + + my $sql = qq(SELECT * FROM `sessions`) ; + + &common_debug($sql) ; + + my $sth = $dbh->prepare($sql) ; + + $sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; + $id_array_ref = $sth->fetchall_arrayref(); + $sth->finish(); + + + foreach my $row (@$id_array_ref) { + my $id = @$row[0] ; + my $a_session = @$row[1] ; + my @a_session = split(/\,/,$a_session) ; + foreach (@a_session) { + my ($param,$val) = split(/=>/) ; + if ($param =~ /timestamp/) { + my $date_ccyy_mm_dd = substr($val,2,10); + my ($sccyy,$smm,$sdd) = split(/\-/,$date_ccyy_mm_dd); + my $sdate = $sccyy . $smm . $sdd ; + if ($sdate < $delete_date) { + # print "
    ($sdate < $delete_date)" ; + # &common_debug("$param,$val [$sdate < $delete_date] [$id]") ; + &delete_session($id) ; + } + } + } + } + +} #------------------------------------------------------------------------------- + +sub set_expired_event_quotes_status { + + %i = () ; + $i{quote_completed} = 1 ; + &db_min_upd('event_quotes',"date_to < '$now_year-$now_mm-$now_dd 00:00:00' AND quote_to <> '5' AND quote_completed = '0' AND quote_accepted = '1'") ; # Everyone except SuperSport Schools + + %i = () ; + $i{quote_rejected} = 1 ; + &db_min_upd('event_quotes',"date_to < '$now_year-$now_mm-$now_dd 00:00:00' AND quote_to <> '5' AND quote_completed = '0' AND quote_accepted = '0' AND quote_pending = '1'") ; # Everyone except SuperSport Schools + +} #------------------------------------------------------------------------------- + +sub set_delete_date { + + my ($ayear,$amonth,$aday) = Add_Delta_Days($now_year,$now_mm,$now_dd,-2) ; + + $amonth = sprintf("%02s", $amonth) ; + $aday = sprintf("%02s", $aday) ; + + $delete_date = $ayear . $amonth . $aday ; + +} #------------------------------------------------------------------------------- + +sub delete_session { + + my ($id) = @_ ; + + &db_min_delete('sessions',"id='$id'") ; + +} #------------------------------------------------------------------------------------------ + +use db ; +use today ; +use common ; +use common_min ; diff --git a/scripts/_FromProd/v1.0/cron/sss_aisa_upload_check.pl b/scripts/_FromProd/v1.0/cron/sss_aisa_upload_check.pl new file mode 100644 index 0000000..d9b0ea8 --- /dev/null +++ b/scripts/_FromProd/v1.0/cron/sss_aisa_upload_check.pl @@ -0,0 +1,93 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI::Carp qw(fatalsToBrowser); +use Date::Calc qw(:all); +use DBI; +use File::Copy; + +# perl /usr/lib/cgi-bin/scripts/cron/sss_aisa_upload_check.pl 1 + +#------------------------------------------------------------------------------- + +our $debug = $ARGV[0] ; +our $username = 'rory' if $debug ; + +#------------------------------------------------------------------------------------------ + +&today ; + +&config_set_vars ; +&config_set_paths ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &check_files ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +print "Done." if $debug ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub check_files { + + our $table_sss = "event_quotes sss" ; + our $table_aisa = "event_quotes" ; + + &db_switch_conn('sss'); + &db_min_ro($table_sss,"id,aisa_quote_nr,upload_1,upload_2,upload_3","aisa_quote_nr <> '0' AND ((upload_1 IS NOT NULL AND upload_1 <> '') OR (upload_2 IS NOT NULL AND upload_2 <> '') OR (upload_3 IS NOT NULL AND upload_3 <> ''))",'','') ; + &db_switch_conn('aisa'); + &db_min_ro($table_aisa,"id,sss_quote_nr,upload_1,upload_2,upload_3","sss_quote_nr <> '0'",'','') ; + + # # AND ((upload_1 IS NOT NULL AND upload_1 <> '') OR (upload_2 IS NOT NULL AND upload_2 <> '') OR (upload_3 IS NOT NULL AND upload_3 <> '')) + + foreach our $event_id (sort {$b <=> $a} keys %{$db{$table_sss}}) { + + our $dir_from = $htmlpath_sss . "/uploads/uploads/$event_id" ; + our $dir_to = $htmlpath . "/uploads/uploads/$db{$table_sss}{$event_id}{aisa_quote_nr}" ; + + &check_indidual_files("upload_1",$table_sss) ; + &check_indidual_files("upload_2",$table_sss) ; + &check_indidual_files("upload_3",$table_sss) ; + } + +} #------------------------------------------------------------------------------- + +sub check_indidual_files { + + my ($table_col_name,$table) = @_ ; + + return unless $db{$table}{$event_id}{$table_col_name} ; + + # if ($db{$table}{$event_id}{$table_col_name}) { + + my $from_file = $dir_from . '/' . $db{$table}{$event_id}{$table_col_name} ; + my $to_file = $dir_to . '/' . $db{$table}{$event_id}{$table_col_name} ; + + my $from_file_exists = (-f $from_file) ? 1 : 0 ; + my $to_file_exists = (-f $to_file) ? 1 : 0 ; + my $to_dir_exists = (-d $dir_to) ? 1 : 0 ; + my $from_dir_exists = (-d $dir_from) ? 1 : 0 ; + + if ($from_file_exists && (!$to_file_exists || !$to_dir_exists)) { + # $aisa_event_checked{$db{$table_sss}{$event_id}{aisa_quote_nr}} = 1 if $db{$table_sss}{$event_id}{aisa_quote_nr} && $table_sss eq $table ; + print "\n common_min_copy_files($dir_from,$dir_to,$db{$table_sss}{$event_id}{$table_col_name})" if $debug ; + &common_min_copy_files($dir_from,$dir_to,"$db{$table_sss}{$event_id}{$table_col_name}") ; + } + + if (!$db{$table_aisa}{$db{$table_sss}{$event_id}{aisa_quote_nr}}{$table_col_name} && $table eq $table_sss) { + %i = () ; + $i{$table_col_name} = $db{$table}{$event_id}{$table_col_name} ; + &db_min_upd($table_aisa,"`id`='$db{$table_sss}{$event_id}{aisa_quote_nr}'") ; + } + +} #------------------------------------------------------------------------------- + +use db ; +use today ; +use common ; +use cfg_paths ; diff --git a/scripts/_FromProd/v1.0/customers.pl b/scripts/_FromProd/v1.0/customers.pl new file mode 100644 index 0000000..de14183 --- /dev/null +++ b/scripts/_FromProd/v1.0/customers.pl @@ -0,0 +1,979 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Excel::Writer::XLSX; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; +# our $testing = 1 ; +# our $double_box_layout = 1 ; # box on the right layout included + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +# our $allow_add_override = 0 ; if ($user_type eq 'ops_users') { $allow_add_override = 1 ; } + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab +our $srchscr = 0 ; +our $fnsortcol = 0 ; +our $redirtype = 'list' ; # $redirtype = 'search' ; + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + +# called from common_min_action + +my $exists = '' ; + +&db_min_ro($table,'*',"name='$i{name}'",'','') ; + +foreach my $id (keys %{$db{$table}}) { + if (lc $db{$table}{$id}{name} eq lc $i{name}) { + $exists = 1 ; + } +} + +if ($exists) { + $alert = &common_min_alert('warning',"'$i{name}' AS A CUSTOMER NAME ALREADY EXISTS!",'ok') ; + %col_name = (); + # &add_screen; + # &screen1; + &common_min_add_screen; + &common_min_screen1; +} + +} #------------------------------------------------------------------------------------------ + +sub insert { + +&add_db_fields ; + +$i{last_edited_by} = $userid ; +$i{user_id} = $userid ; + +$i{id} = &db_min_get_max($table,'id') ; + +$i{date_time} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; +$i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +# &common_upload_files("trackusers/$i{id}") ; +# &process_upload_ifields; + +# $ignore{country_id} = 1 ; + +&default_values ; + +&db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + +unless ($i{id}) { $error = qq(NO ID) ; return ; } + +&edit_db_fields ; + +if ($userid) { $i{last_edited_by} = $userid ; } + +unless ($i{active}) { $i{active} = '0' ; } + +$i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +# &common_upload_files("trackusers/$i{id}") ; +# &process_upload_ifields; + +# $ignore{country_id} = 1 ; + +&default_values ; + +&db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub default_values { + + $i{country_id} = '0' unless $i{country_id} ; + $i{region_id} = '0' unless $i{region_id} ; + $i{city_id} = '0' unless $i{city_id} ; + +} #------------------------------------------------------------------------------------------ + +sub report_ifields { + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &load_search_vars ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +if ($i{customer_id}) { + push @report_sql, "(`id` = '$i{customer_id}')" ; + push @report_results, "customer = $customer_name{$i{customer_id}}" ; + $xlsreportname .= '-' . $i{customer_id} ; + our $acc_id_sql_where = "`customer_id`='$i{customer_id}'" + } + +# if ($i{company_id}) { + # push @report_sql, "(`company_id` = '$i{company_id}')" ; + # push @report_results, "company = $company_name{$i{company_id}}" ; + # $xlsreportname .= '-' . $i{company_id} ; + # } + +# if ($i{asset_insurer_id}) { + # push @report_sql, "(`asset_insurer_id` = '$i{asset_insurer_id}')" ; + # push @report_results, "asset insurer = $asset_insurer_name{$i{asset_insurer_id}}" ; + # $xlsreportname .= '-' . $i{asset_insurer_id} ; + # } + +if ($i{active}) { + my $active = '' ; if ($i{active} eq 'active') { $active = '1' ; } elsif ($i{active} eq 'inactive') { $active = '0' ; } + push @report_sql, "(`active` = '$active')" ; + push @report_results, "active = $i{active}" ; +} + +$report_results_msg = uc join(', ', @report_results) ; + +unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); &report_screen; } else { $isaved = qq(SELECT WHERE $report_results_msg) ; } + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + +# &db_min_ro('customer','id,name','','','') ; +# foreach my $id (keys %{$db{customer}}) { $customer_name{$id} = $db{customer}{$id}{name} ; } + +# &db_min_ro('company','id,name','','','') ; +# foreach my $id (keys %{$db{company}}) { $company_name{$id} = $db{company}{$id}{name} ; } + +&db_min_ro('users','id,name','','','') ; +foreach my $id (keys %{$db{users}}) { $user{$id} = $db{users}{$id}{name} ; } + +our $done_load_search_vars = 1 ; + +} #------------------------------------------------------------------------------------------ + +# sub process_upload_ifields { + +# foreach (keys %uploads_file) { $i{$_} = $uploads_file{$_} ; $ignore{$_} = '' ; } + +# } #------------------------------------------------------------------------------------------ + +sub list_screen { + +my %seen_customer = () ; +my $delete_button = "" ; + +my $srch_where_sql = join(' AND ', @report_sql) ; + +my $add_sql_where = '' ; + +unless ($done_load_search_vars) { &load_search_vars ; } + +# our @sql_col_display = ("id","customer_nr","name","contact_email","vat_nr","physical_address","postal_address","date_time","last_edited_by","user_id","active","last_updated","phone","company_email") ; +our @sql_col_display = ("id","name","contact_email","vat_nr","physical_address","postal_address","active","events","analytics","phone","company_email","last_updated","last_edited_by") ; + +if ($iaction eq 'report') { push @sql_col_display, "company_id" ; } + +push @sql_col_display, "" ; + +&report_xlsx_export_header("Customers$xlsreportname",'customers') ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + &db_min_ro('event_quotes','id, quote_to','','','') ; + + foreach my $id (keys %{$db{'event_quotes'}}) { + next if $seen_customer{$db{'event_quotes'}{$id}{quote_to}} ; + $seen_customer{$db{'event_quotes'}{$id}{quote_to}} = 1 ; + } + + &db_min_ro('quotes','id, quote_to','','','') ; + + foreach my $id (keys %{$db{'quotes'}}) { + next if $seen_customer{$db{'quotes'}{$id}{quote_to}} ; + $seen_customer{$db{'quotes'}{$id}{quote_to}} = 1 ; + } + + &load_list_vars("$srch_where_sql$add_sql_where") ; + + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +$xlsxrow = 4 ; + +our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + +foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) { + + # if (($i{active} == 1) and ($customer_id_in_use_for_devices{$id} < 1)) { next ; } # Active with devices + # if (($i{active} == 2) and ($customer_id_in_use_for_devices{$id} > 0)) { next ; } # Active without devices + + $print_tbody .= qq() ; + + $xlsxcol=0; + + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$table}{$id}{$_} ; + my $align = '' ; + my $val_xlsx = '' ; + + # if ($_ eq 'last_edited_by') { } + + # if ($_ eq 'device_types') { + # $val = '' ; + # foreach $dev_nam (keys %{$cnt_dev_typ{$id}}) { + # $val .= "$dev_nam [$cnt_dev_typ{$id}{$dev_nam}], "; + # } + # $val = substr($val,0,-2) ; + # } + + # my $format = '' ; if ($_ eq 'imei') { if (length($db{$table}{$id}{imei})==5){ $format = 'imei' ; } } + + # &report_xlsx_export_process_cell('','',$val) ; # ------------------------------------------------------------------------- HTML AFTER$xlscol++; + + # my $green_tick = qq~2~ ; + # my $orange_tick = qq~1~ ; + # my $red_tick = qq~0~ ; + my $center = qq~ class="dt-center"~ ; + + if ($_ eq 'active' || $_ eq 'events' || $_ eq 'analytics') { + $val_xlsx = ($val == 1) ? "Yes" : "No" ; + if ($val == 1) { + $val = &set_tick('green', '') ; + } else { + $val = &set_tick('red', '') ; + } + $align = $center ; + } elsif ($_ eq 'last_edited_by') { + $val = $user{$db{$table}{$id}{$_}} ; + } elsif ($_ eq 'last_updated') { + $val = &common_min_date_as_string($val) ; + } + + $val_xlsx = $val unless $val_xlsx ; + + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format1) ; + $xlsxcol++ ; + + # if ($_ eq 'monitor_after_hours_snapshots') { if ($val == 1) { $val = &set_tick('green', '') ; } else { $val = &set_tick('red', '') ; } $align = $center ; } + # if ($_ eq 'facial_recognition') { if ($val == 1) { $val = &set_tick('green', '') ; } else { $val = &set_tick('red', '') ; } $align = $center ; } + # if ($_ eq 'object_recognition') { + # if ($val == 1) { + # if ($protocol_action{$id}) { + # my $tt = qq~ data-toggle="tooltip" data-placement="left" data-title="$protocol_action{$id}"~ ; + # $val = &set_tick('green', $tt) ; + # } + # else + # { + # my $tt = qq~ data-toggle="tooltip" data-placement="left" data-title="Needs protocol actions set!"~ ; + # $val = &set_tick('orange', $tt) ; + # } + # } + # else + # { + # $val = &set_tick('red', '') ; + # } + # $align = $center ; + # } + + # $protocol_action{$acc_id} + + # data-toggle="tooltip" data-placement="right" data-title="Set to 'Yes' to enable Object Recognition for this client!" + + $print_tbody .= qq($val) ; + } + + my $delete_butt = '' ; my $edit_butt = '' ; + + if ($useropts{boss}{$username} or $useropts{super}{$username}) { + $edit_butt = qq() ; + if ($useropts{super}{$username}) { + $delete_butt = qq() if not $seen_customer{$id}; + $delete_butt = qq() if $seen_customer{$id}; + } + } + + # &common_debug("$id : $customer_id_in_use_for_devices{$id}"); + + if ($customer_id_in_use_for_devices{$id}) { $delete_butt = '' ; } + + $print_tbody .= qq~ $edit_butt $delete_butt~ ; + $xlsxrow++ ; + +} + +$worksheet{$ws}->set_column("A:L",15) ; + +&report_xlsx_export_footer('L',15,'customers') ; + +$fnsortcol = 8 ; # order by ol devices col + +$print_more_boxes .= qq(
    ) ; + +&common_min_extra_crumb("search-$lcpage\s","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub set_tick { + +my ($color,$tooltip) = @_ ; + +$tick{green} = qq~2~ ; +$tick{orange} = qq~1~ ; +$tick{red} = qq~0~ ; + +return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub load_list_vars { + +my ($where) = @_ ; + +# &db_min_ro('insurer','*','','','') ; +# foreach my $id (keys %{$db{insurer}}) { $insurer{$id} = $db{insurer}{$id}{name} ; } + +# &db_min_ro('device_type','*','','','') ; +# foreach my $id (keys %{$db{device_type}}) { + # $is_mdvr{$id} = $db{device_type}{$id}{mdvr} ; + # $device_name{$id} = $db{device_type}{$id}{name} ; + # } + +# &db_min_ro('risk_profile_types','*','','','') ; +# foreach my $id (keys %{$db{risk_profile_types}}) { $risk_profile_type{$id} = $db{risk_profile_types}{$id}{name} ; } # customer hash + +# &db_min_ro('protocol_actions','*',$acc_id_sql_where,'','') ; +# foreach my $id (keys %{$db{protocol_actions}}) { + # my $acc_id = $db{protocol_actions}{$id}{customer_id} ; + # my $max = $db{protocol_actions}{$id}{max} ; + # my $show_max = '' ; if ($max) { $show_max = " > $max" ; } + + # $protocol_action{$acc_id} .= "$risk_profile_type{$db{protocol_actions}{$id}{risk_profile_type_id}}$show_max
    " ; + # } + +# &db_min_ro('device','id,customer_id,online,type_id',$acc_id_sql_where,'','') ; +# foreach my $id (keys %{$db{device}}) { + # $customer_id_in_use_for_devices{$db{device}{$id}{customer_id}}++ ; + + # if ($db{device}{$id}{online}==1) { + # $customer_online_devices{$db{device}{$id}{customer_id}}++ ; + # } + + # my $dev_nam = $device_name{$db{device}{$id}{type_id}} ; + + # $cnt_dev_typ{$db{device}{$id}{customer_id}}{$dev_nam}++ ; + # } + +&db_min_ro($table,'*',$where,'name','') ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + +&common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub add_db_fields { + +&common_customer_hidden_db_fields ; + +$hidden{id} = 2 ; +# $hidden{user_id} = 2 ; + + +# $required{customer_nr} = 2 ; + +if ($iaction eq 'add'){ &build_boxes_add ; } # can't be in add_screen, only works if here + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + +&common_customer_hidden_db_fields ; + +$ignore{date_time} = 1 ; +$ignore{user_id} = 1 ; +# $ignore{customer_nr} = 1 ; +$ignore{last_updated} = 1 ; + +# if ($user{privilege}{$username} eq 'super') { + # $ignore{facial_recognition} = '' ; # enable the switch for super users + # $checkbox{facial_recognition} = 1 ; + # $info_glyph_tooltip{facial_recognition} = qq() ; + + # $ignore{object_recognition} = '' ; # enable the switch for super users + # $checkbox{object_recognition} = 1 ; + # $info_glyph_tooltip{object_recognition} = qq() ; + # } + +$hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + +my ($id) = @_ ; + +# &common_min_select_opts('asset_insurer_id','insurer','name',$db{$table}{$id}{asset_insurer_id}) ; +# &common_min_select_opts('git_insurer_id','insurer','name',$db{$table}{$id}{git_insurer_id}) ; +# &common_min_select_opts('insure_as_id','insurer','name',$db{$table}{$id}{insure_as_id}) ; +# &common_min_select_opts('company_id','company','name',$db{$table}{$id}{company_id},1) ; + +# $db{$table}{$id}{country_id} = '242' unless $db{$table}{$id}{country_id} ; + +# $db{$table}{$id}{region_id} = 1 ; + +# &db_min_ro('regions','1,country_id',"`id`='$db{$table}{$id}{region_id}'",'','') if $db{$table}{$id}{region_id} ; + +# $db{$table}{$id}{country_id} = $db{regions}{1}{country_id} ; + +# my $regions_sql = ($db{regions}{1}{country_id}) ? "`country_id`='$db{regions}{1}{country_id}'" : "" ; +my $regions_sql = ($db{$table}{$id}{country_id}) ? "`country_id`='$db{$table}{$id}{country_id}'" : "" ; + +$regions_sql = &add_extra_region_filter($regions_sql) ; + +&common_min_select_opts('region_id','regions','name',$db{$table}{$id}{region_id},'','code',"$regions_sql") ; + +my $other_region = qq~~ ; +if ($db{$table}{$id}{country_id} && !$opts{region_id}) { + $other_region = qq~id='13'~ ; + &common_min_select_opts('region_id','regions','name',$db{$table}{$id}{region_id},'','code',"name='Other'") ; +} + + +# &common_min_select_opts('country_id','countries','name',$db{regions}{$db{$table}{$id}{region_id}}{country_id}) ; +&common_min_select_opts('country_id','countries','name',$db{$table}{$id}{country_id}) ; + +my $city_sql ; + +$city_sql .= qq~country_id='$db{$table}{$id}{country_id}'~ if $db{$table}{$id}{country_id} ; +$city_sql .= qq~ AND ~ if $db{$table}{$id}{country_id} && $db{$table}{$id}{region_id} ; +$city_sql .= qq~region_id='$db{$table}{$id}{region_id}'~ if $db{$table}{$id}{region_id} ; +$city_sql = qq~($city_sql) OR region_$other_region~ if $other_region ; +# $other_region = "region_$other_region" if $other_region ; + +&common_min_select_opts('city_id','cities','name',$db{$table}{$id}{city_id},'','',"$city_sql") ; + +$trigger_jquery_raw .= qq~ + + //gallery delete + \$('.thumbnails').on('click', '.gallery-delete', function (e) { + e.preventDefault(); + // alert(\$(this).parents('.thumbnail').attr('id')); + var imgid = \$(this).parents('.thumbnail').attr('id') ; + var thumb = \$(this).parents('.thumbnail'); + BootstrapDialog.confirm({ + title: 'Confirm Delete', + message: 'Are you sure you want to delete it?', + type: BootstrapDialog.TYPE_WARNING, + callback: function(result) { + if(result) { + var url = "$useropts{scripts}/get/get_db_delete_upload_common.pl?$i{id}&trackusers/$i{id}&customer&"+imgid ; + // alert(url); + \$.get(url); + thumb.fadeOut(); + location.reload(); + } + } + }); + + }); + + //gallery edit + \$('.thumbnails').on('click', '.gallery-edit', function (e) { + e.preventDefault(); + //get image id + alert('Delete logo and re-upload!'); + //alert(\$(this).parents('.thumbnail').attr('id')); + //dlgMdl('/scripts/dialog/uploads.pl?$i{id}&photo&'+\$(this).parents('.thumbnail').attr('id'),'Photo Uploads','','medium-dialog'); + }); + + \$("#customers-form [id^='select']").chosen({ allow_single_deselect:true }); + + const mapCityToRegion = {}; + const mapCityToCountry = {}; + const mapRegionToCountry = {}; + + const \$countrySelect = \$("#selectCountry_id") ; + const \$regionSelect = \$("#selectRegion_id") ; + const \$citySelect = \$("#selectCity_id") ; + + let countryId = \$countrySelect.val() ; + let regionId = \$regionSelect.val() ; + let cityId = \$citySelect.val() ; + + const updateChosen = \$el => \$el.trigger("chosen:updated"); + + const clearSelect = (\$el, includeBlank = true) => { + \$el.empty(); + if (includeBlank) \$el.append(``); + updateChosen(\$el) ; + }; + + const fetchJSON = async url => { + try { + const res = await fetch(url); + if (!res.ok) throw new Error(`Request failed: \${res.status}`); + return await res.json(); + } catch (err) { + console.error("Fetch error:", err); + return []; + } + }; + + // const populateSelect = (\$el, dataList, labelFn) => { + // let lastId = null ; + // for (const data of dataList) { + // \$el.append(``); + // lastId = data.id; + // } + // updateChosen(\$el) ; + // return { count: dataList.length, lastId } ; + // } ; + + const populateSelect = (\$field, json_list, getLabel, defaultSelected = () => "") => { + + let isSelected ; + + // Determine how to handle selected logic + if (typeof defaultSelected === "function") { + isSelected = defaultSelected ; + } else if (Array.isArray(defaultSelected)) { + isSelected = data => defaultSelected.includes(data.id) ? "selected" : "" ; + } else { + isSelected = data => data.id == defaultSelected ? "selected" : "" ; + } + + // Auto-select the only item if none explicitly selected + const autoSelectOnly = json_list.length === 1 && typeof defaultSelected === "string" && defaultSelected === "" ; + + let lastId = null ; + json_list.forEach(data => { + const selected = autoSelectOnly || isSelected(data) ? "selected" : "" ; + \$field.append(``) ; + lastId = data.id; + }); + + updateChosen(\$field) ; + // return json_list.length ; + return { count: json_list.length, lastId } ; + }; + + // --- Country Change --- + + \$countrySelect.on("change", async function () { + + countryId = \$(this).val() ; + regionId = \$regionSelect.val() ; + cityId = \$citySelect.val() ; + + clearSelect(\$regionSelect) ; + + const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}`; + const regionData = await fetchJSON(regionUrl); + + // const { count: regionCount, lastId: region_est } = populateSelect( + const { count: regionCount, lastId: region_est } = populateSelect( + \$regionSelect, + regionData, + // ({ name, code }) => `\${name} [\${code}]` + r => r.code ? `\${r.name} [\${r.code}]` : r.name , + "" + ) ; + + let selectedRegionId = 0 ; + + if (regionCount === 1) { + selectedRegionId = region_est ; + // \$regionSelect.val(region_est).trigger("chosen:updated") ; + } else if (regionCount === 0) { + selectedRegionId = 13 ; + \$regionSelect.append(``).trigger("chosen:updated") ; + // updateChosen(\$regionSelect) ; + } + + // if (!\$regionSelect.val()) { + // \$regionSelect.val(regionId).trigger("chosen:updated") ; + // } + + // Load cities based on region (if available) or country + clearSelect(\$citySelect); + + const script = `get_cities_from_region.pl?country_id=\${countryId}®ion_id=\${selectedRegionId}` ; + const citiesUrl = `$useropts{scripts}/get/\${script}` ; + const cityData = await fetchJSON(citiesUrl) ; + + const { count: cityCount, lastId: city_est } = populateSelect( + \$citySelect, + cityData, + d => d.city_name ?? d.name, + "" + ) ; + + // if (cityCount === 1) { + // \$citySelect.val(cityId).trigger("chosen:updated") ; + // } + + if (!countryId) { + console.log("2 countryId : "+countryId) ; + if (!\$regionSelect.val()) \$regionSelect.val(regionId).trigger("chosen:updated") ; + if (!\$citySelect.val()) \$citySelect.val(cityId).trigger("chosen:updated") ; + } + + }); + + // --- Region Change --- + + \$regionSelect.on("change", async function () { + + console.log("1 : regionId : "+regionId) ; + regionId = \$(this).val(); + console.log("2 : regionId : "+regionId) ; + countryId = \$countrySelect.val(); + cityId = \$citySelect.val() ; + + clearSelect(\$citySelect); + + if (!regionId) return; + + const url = `$useropts{scripts}/get/get_cities_from_region.pl?country_id=\${countryId}®ion_id=\${regionId}`; + const cityData = await fetchJSON(url); + const { count: cityCount, lastId: city_est } = populateSelect(\$citySelect, cityData, d => d.city_name,""); + + // if (cityCount === 1) { + // \$citySelect.val(cityId).trigger("chosen:updated"); + // } + + if (!mapRegionToCountry[regionId]) { + const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=\${countryId}®ion_id=\${regionId}`; + const regionMeta = await fetchJSON(lookupUrl); + + const { country_id } = regionMeta[0] ?? {}; + if (country_id) { + mapRegionToCountry[regionId] = country_id; + \$countrySelect.val(country_id).trigger("chosen:updated"); + } + } else { + \$countrySelect.val(mapRegionToCountry[regionId]).trigger("chosen:updated"); + } + + if (!regionId && !\$citySelect.val()) { + \$citySelect.val(cityId).trigger("chosen:updated") ; + } + + }); + + // --- City Change --- + + \$citySelect.on("change", async function () { + + cityId = \$(this).val(); + if (!cityId) return; + + regionId = mapCityToRegion[cityId]; + countryId = mapCityToCountry[cityId]; + + if (typeof regionId === 'undefined') regionId = "" ; + if (typeof countryId === 'undefined') countryId = "" ; + + if (regionId && regionId != \$regionSelect.val()) { + \$regionSelect.val(regionId).trigger("chosen:updated"); + } + if (countryId && countryId != \$countrySelect.val()) { + \$countrySelect.val(countryId).trigger("chosen:updated"); + } + + if (!regionId || !countryId) { + + const lookupUrl = `$useropts{scripts}/get/get_country_and_region_from_city.pl?city_id=\${cityId}®ion_id=\${regionId}&country_id=\${countryId}`; + const cityMeta = await fetchJSON(lookupUrl); + const { region_id, country_id } = cityMeta[0] ?? {}; + + if (region_id) { + mapCityToRegion[cityId] = region_id; + \$regionSelect.val(region_id).trigger("chosen:updated"); + } + + if (country_id) { + mapCityToCountry[cityId] = country_id; + \$countrySelect.val(country_id).trigger("chosen:updated"); + } + } + + if (!\$regionSelect.val()) { + \$regionSelect.val("13").trigger("chosen:updated"); + mapCityToCountry[cityId] = 13; + } + + }); + +~ ; + +} #------------------------------------------------------------------------------- + +sub add_screen { + +# called from common_add_screen + +# if ($user_type eq 'track_users') { + # $db{$table}{''}{customer_id} = $client_id ; # set for input box + # } + +&select_opts('') ; + +# &build_boxes_add ; # can't do this here + +} #------------------------------------------------------------------------------------------ + +sub build_boxes_add { + +&sort_fields ; + +$print_box_content_rows .= &common_min_forms_start($table) ; + +$print_box_content_rows .= qq(
    ) ; +$print_box_content_rows .= &common_min_box_top('user',"  Customer",$box_main_bg) ; +# $print_box_content_rows .= &common_add_form($table,'',3,9,1,1) ; +$print_box_content_rows .= &common_min_add_form($table,'save',3,9,1,1) ; +$print_box_content_rows .= &common_min_box_foot ; +$print_box_content_rows .= qq(
    ) ; + +&build_boxes_right; + +$print_box_content_rows .= qq(
    ) ; + +$print_box_content_rows .= &common_min_forms_end('',$table,'save') ; + +} #---------------------------------------------------------------------------------------- + +sub edit_screen { + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +# $selected{warranty_period}{$db{$table}{$id}{warranty_period}} = 'SELECTED'; + +&sort_fields ; +&select_opts($i{id}) ; + +# &build_boxes_edit($i{id}) ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + %sort_field = () ; + + $sort_field{1} = 'active' ; + $sort_field{2} = 'events' ; + $sort_field{3} = 'analytics' ; + $sort_field{4} = 'name' ; + $sort_field{5} = 'phone' ; + $sort_field{6} = 'company_email' ; + $sort_field{7} = 'contact_name' ; + $sort_field{8} = 'contact_email' ; + $sort_field{9} = 'physical_address' ; + $sort_field{10} = 'postal_address' ; + $sort_field{11} = 'country_id' ; + $sort_field{12} = 'region_id' ; + $sort_field{13} = 'city_id' ; + $sort_field{14} = 'vat_nr' ; + + $select{country_id} = 1 ; + $select{region_id} = 1 ; + $select{city_id} = 1 ; + + $trigger_jquery_raw .= qq~ + + + + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes_edit { + +my ($id) = @_ ; + +$print_box_content_rows .= &common_min_forms_start($table) ; +$print_box_content_rows .= qq(
    ) ; +$print_box_content_rows .= &common_min_box_top('user',"  Customer : $db{$table}{$id}{id}",$box_main_bg) ; +# $print_box_content_rows .= &common_edit_form($id,$table,'',3,9,1,1) ; +$print_box_content_rows .= &common_min_edit_form($i{id},$table,'update',3,9,1,1) ; +$print_box_content_rows .= &common_min_box_foot ; +$print_box_content_rows .= qq(
    ) ; + +&build_boxes_right($id); + +$print_box_content_rows .= qq(
    ) ; + +$print_box_content_rows .= &common_min_forms_end($id,$table,'update',$skip) ; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_right { + +my ($id) = @_ ; + +my $box_icon = '' ; + +$print_box_content_rows .= &common_min_box_top('picture','Logo Upload',$box_right_bg,$box_icon) ; + +$logo_uploads = &get_uploads($id,'logo') ; + +$print_box_content_rows .= qq(
     
    ); + +if ($logo_uploads) { + $print_box_content_rows .= qq(
    $logo_uploads
    ); +} else { + $print_box_content_rows .= qq(
    + + +

    Upload file from PC.

    +
    ); + } + +$print_box_content_rows .= qq(
    ); + +$print_box_content_rows .= &common_min_box_foot ; + +} #---------------------------------------------------------------------------------------- + +sub get_uploads { + +my ($id,$type) = @_ ; + +unless ($id and $type) { return() ; } + +my $gallery = '' ; my %gallery = () ; + +my $field = $type ; +if ($db{$table}{$id}{$field}){ + $tooltip = qq(data-toggle="tooltip" data-placement="top" title="$type" data-original-title="$type") ; + $gallery{$type} .= qq(
  • + $type +
  • ) ; + } + +if ($gallery{$type}) { $gallery = '' ; } + +return ($gallery) ; + +} #------------------------------------------------------------------------------------------ + +sub page_opts { + +our $glyphicon = 'list' ; +our $lcpage = 'customer' ; + +&common_page_name ; + +our $table = 'customers' ; + +$page_title = 'Customer' ; + +&common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + +our $lcol = 3 ; +our $fcol = 5 ; + +$print_box_content_rows .= &common_min_forms_start('report') ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + &common_min_select_opts('customer_id','customers','name',$i{customer_id},'') ; + # &common_min_select_opts('company_id','company','name',$i{company_id},'') ; + + # &common_min_select_opts('asset_insurer_id','insurer','name',$i{asset_insurer_id},'') ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +$print_box_content_rows .= &common_min_form_select('customer_id',$i{customer_id}) ; +# $print_box_content_rows .= &common_min_form_select('company_id',$i{company_id}) ; +# $print_box_content_rows .= &common_min_form_select('asset_insurer_id',$i{asset_insurer_id}) ; +$print_box_content_rows .= &common_min_form_input('active',$i{active}) ; + +$opts{active} = qq( + +) ; +$print_box_content_rows .= &common_min_form_select('active','','',1,'') ; + +$print_box_content_rows .= &common_min_forms_end('','','report') ; + +&common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +# sub send_email { + +# my ($email_subject,$email_msg) = @_ ; + +# unless ($email_msg) { return ; } + +# my %mail = () ; + +# my $to = 'duvan@kre8it.co.za' ; +# my $cc = 'rory@kre8it.co.za' ; + +# %mail = ( + # smtp => 'localhost', + # From => 'TruckAssist IT ', + # To => $to, + # Cc => $cc, + # Subject => $email_subject + # ); + +# $mail{body} = <prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +$manifest_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +foreach $row (@$manifest_array_ref) { + + &db_manifest_fields ; + + if (($done{$mn_waybillno}) and ($done{$mn_waybillno} ne $mn_manifestdetailid)) { + print "
    $mn_waybillno -> $done{$mn_waybillno} -> $mn_manifestdetailid" ; + } + + $done{$mn_waybillno} = $mn_manifestdetailid ; + } + +} #------------------------------------------------------------------------------------------ + +use db ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/db/admin/admin_db_clients_table_1.pl b/scripts/_FromProd/v1.0/db/admin/admin_db_clients_table_1.pl new file mode 100644 index 0000000..e618200 --- /dev/null +++ b/scripts/_FromProd/v1.0/db/admin/admin_db_clients_table_1.pl @@ -0,0 +1,62 @@ +#!/usr/bin/perl + +print "Content-type: text/html\n\n"; + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +&today ; + +#------------------------------------------------------------------------------------------ + +use DBI; +use CGI::Carp qw(fatalsToBrowser); + +&admin_db_clients_table ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub admin_db_clients_table { + +&db_open_ro ; + +my $sql = qq(SELECT * FROM ffwaypls_filmfreight.clients ORDER BY client) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +$clients_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +foreach $row (@$clients_array_ref) { + + $cl_client = @$row[0] ; + $cl_accno = @$row[1] ; + $cl_branc = @$row[2] ; + $cl_postal_address = @$row[20] ; + $cl_contact1 = @$row[21] ; + $cl_email1 = @$row[23] ; + + $line = qq(
    $cl_client, $cl_accno, $cl_branc, $cl_postal_address, $cl_contact1, $cl_email1) ; + + if ($done{$cl_client}) { print $done{$cl_client} . $line . "
    " ; } + $done{$cl_client} = $line ; + + # if ($done{$cl_accno}) { print "DUPLICATE" . $done{$cl_accno} . $line ; } + # $done{$cl_accno} = $line ; + } + + + +} #------------------------------------------------------------------------------------------ + +use db ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/db/admin/admin_db_shipper_details.pl b/scripts/_FromProd/v1.0/db/admin/admin_db_shipper_details.pl new file mode 100644 index 0000000..27c4541 --- /dev/null +++ b/scripts/_FromProd/v1.0/db/admin/admin_db_shipper_details.pl @@ -0,0 +1,89 @@ +#!/usr/bin/perl + +print "Content-type: text/html\n\n"; + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +&today ; + +#------------------------------------------------------------------------------------------ + +use DBI; +use CGI::Carp qw(fatalsToBrowser); + +&get_db_shipper_details ; + +print $json ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub get_db_shipper_details { + +&db_open_ro ; + +my $sql = qq(SELECT * FROM ffwaypls_filmfreight.shippers ORDER BY receiver) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +$senders_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +foreach $row (@$senders_array_ref) { + + &db_shipper_fields ; + + $sn_id =~ s/^\s+|\s+$//g ; # trim both ends whitespace + $sn_receiver =~ s/^\s+|\s+$//g ; + $sn_addr1 =~ s/^\s+|\s+$//g ; + $sn_addr2 =~ s/^\s+|\s+$//g ; + $sn_addr3 =~ s/^\s+|\s+$//g ; + $sn_addr4 =~ s/^\s+|\s+$//g ; + $sn_pc =~ s/^\s+|\s+$//g ; + $sn_contact =~ s/^\s+|\s+$//g ; + $sn_phoneno =~ s/^\s+|\s+$//g ; + + &update_shipper($sn_id,$sn_receiver,$sn_addr1,$sn_addr2,$sn_addr3,$sn_addr4,$sn_pc,$sn_contact,$sn_phoneno) ; + } + +} #------------------------------------------------------------------------------------------ + +sub update_shipper { + +my ($id,$receiver,$addr1,$addr2,$addr3,$addr4,$pc,$contact,$phoneno) = @_ ; + +&db_open_upd ; + +my $sql = qq(UPDATE ffwaypls_filmfreight.shippers +SET + +Receiver = "$receiver", +Addr1 = "$addr1", +Addr2 = "$addr2", +Addr3 = "$addr3", +Addr4 = "$addr4", +PC = "$pc", +Contact = "$contact", +PhoneNo = "$phoneno" + +WHERE id = "$id") ; + +print "
    $sql" ; + +$sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +&db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +use db ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/db/admin/amend_db_clients_with_id.pl b/scripts/_FromProd/v1.0/db/admin/amend_db_clients_with_id.pl new file mode 100644 index 0000000..0f0fd2a --- /dev/null +++ b/scripts/_FromProd/v1.0/db/admin/amend_db_clients_with_id.pl @@ -0,0 +1,180 @@ +#!/usr/bin/perl + +print "Content-type: text/html\n\n"; + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +&today ; + +#------------------------------------------------------------------------------------------ + +use DBI; +use CGI::Carp qw(fatalsToBrowser); + +# &update_db_clients_from_waybills ; +# &update_db_clients_from_client_accno ; +&check_db_clients_for_duplicates ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub check_db_clients_for_duplicates { + +&db_open_ro ; + +my $sql = qq(SELECT id,client,accno FROM ffwaypls_filmfreight.clients) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $clients_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +foreach $row (@$clients_array_ref) { + $cl_id = @$row[0] ; + $cl_client = @$row[1] ; + $cl_accno = @$row[2] ; + + if ($client{$cl_id}) { &load_waybill($cl_accno) ; print '
    ' . $client{$cl_id} . ' DUPLIACTED - ' . $cl_id . ' : ' . $cl_client . ' : ' . $cl_accno . ' ---------> ' . $wbs{$cl_accno} ; } + + $client{$cl_id} .= $cl_accno . ' : ' . $cl_client ; + } + +} #------------------------------------------------------------------------------------------ + +sub load_waybill { + +my ($accno) = @_ ; + +&db_open_ro ; + +my $sql = qq(SELECT * FROM ffwaypls_filmfreight.waybills WHERE accno = '$accno') ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $id_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +foreach $row (@$id_array_ref) { + &db_waybills_fields ; + + $wbs{$accno} .= $wb{'waybillno'} . ' (' . $wb{'clientid'} . ' - ' . $wb{'client'} . ') ' ; + } + +} #------------------------------------------------------------------------------------------ + +sub update_db_clients_from_client_accno { + +&db_open_ro ; + +my $sql = qq(SELECT id,client,accno FROM ffwaypls_filmfreight.clients) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $clients_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +foreach $row (@$clients_array_ref) { + $cl_id = @$row[0] ; + $cl_client = @$row[1] ; + $cl_accno = @$row[2] ; + + if (length($cl_accno) > 3) { next ; } + if ($cl_id == $cl_accno) { next ; } + + $client{$cl_id} = $cl_accno ; + } + +foreach my $id (keys %client) { + # print "
    *** $id -> $client{$id}" ; + # &update_clients($id,$client{$id}) ; + &update_clients($client{$id},$client{$id}) ; + } + +} #------------------------------------------------------------------------------------------ + +sub update_db_clients_from_waybills { + +&db_open_ro ; + +my $sql = qq(SELECT client,accno,clientid FROM ffwaypls_filmfreight.waybills WHERE clientid <> '') ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $waybill_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +foreach $row (@$waybill_array_ref) { + $wb_client = @$row[0] ; + $wb_accno = @$row[1] ; + $wb_clientid = @$row[2] ; + + # $client{$wb_clientid} = $wb_accno . ' -> ' . $wb_client ; + $client{$wb_clientid} = $wb_accno ; + $client_name{$wb_clientid} = $wb_client ; + } + +foreach my $id (keys %client) { + # print "
    *** $id -> $client{$id}" ; + # &update_clients($id,$client{$id}) ; + # &update_clients_1($id,$client_name{$id}) ; + } + +} #------------------------------------------------------------------------------------------ + +sub update_clients_1 { + +my ($id,$client) = @_ ; + +&db_open_upd ; + +$sql = qq(UPDATE clients SET ID = '$id' WHERE client = "$client") ; + +&common_debug($sql) ; + +$sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +&db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +# sub update_clients { + +# my ($id,$accno) = @_ ; + +# &db_open_upd ; + +# $sql = qq(UPDATE ffwaypls_filmfreight.clients SET ID = '$id' WHERE accno = '$accno' +# ) ; + +# &common_debug($sql) ; + +# $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +# &db_close_conn ; + +# } #------------------------------------------------------------------------------------------ + +use db ; +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/db/admin/amend_db_clients_with_missing.pl b/scripts/_FromProd/v1.0/db/admin/amend_db_clients_with_missing.pl new file mode 100644 index 0000000..22a8fe0 --- /dev/null +++ b/scripts/_FromProd/v1.0/db/admin/amend_db_clients_with_missing.pl @@ -0,0 +1,193 @@ +#!/usr/bin/perl + +print "Content-type: text/html\n\n"; + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +&today ; + +#------------------------------------------------------------------------------------------ + +use DBI; +use CGI::Carp qw(fatalsToBrowser); + +&select_db_clients_add ; +&select_db_clients ; +&select_db_clients_from_waybills ; +&check_clients ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub select_db_clients_add { + +&db_open_ro ; + +my $sql = qq(SELECT client,accno FROM CLIENT_ADD) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $clients_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +foreach $row (@$clients_array_ref) { + my $cl_client = @$row[0] ; + my $cl_accno = @$row[1] ; + + $client_add{$cl_client} = $cl_accno ; + } + +# foreach my $client (keys %client) { + # # print "
    *** $id -> $client{$id}" ; + # # &update_clients($id,$client{$id}) ; + # # &update_clients($client{$id},$client{$id}) ; + # } + +} #------------------------------------------------------------------------------------------ + +sub select_db_clients { + +&db_open_ro ; + +my $sql = qq(SELECT id,client,accno FROM clients) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $clients_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +foreach $row (@$clients_array_ref) { + my $cl_id = @$row[0] ; + my $cl_client = @$row[1] ; + my $cl_accno = @$row[2] ; + + $clientids{$cl_id} = $cl_client ; + $clients{$cl_client} = $cl_id ; + } + +} #------------------------------------------------------------------------------------------ + +sub select_db_clients_from_waybills { + +&db_open_ro ; + +my $sql = qq(SELECT client,accno,clientid FROM ffwaypls_filmfreight.waybills WHERE clientid <> '') ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $waybill_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +foreach $row (@$waybill_array_ref) { + $wb_client = @$row[0] ; + $wb_accno = @$row[1] ; + $wb_clientid = @$row[2] ; + + # $client{$wb_clientid} = $wb_accno . ' -> ' . $wb_client ; + # $client{$wb_clientid} = $wb_accno ; + $client_name{$wb_clientid} = $wb_client ; + $client_id{$wb_client} = $wb_clientid ; + $client_accno{$wb_client} = $wb_accno ; + } + +} #------------------------------------------------------------------------------------------ + +sub check_clients { + +# foreach my $client (keys %clients) { + # # print "
    *** $id -> $client{$id}" ; + # } + +foreach my $name (keys %client_add) { + # unless ($client_id{$name}) { + unless ($clients{$name}) { + if ($clientids{$client_id{$name}}) { $print_dup = qq( >>>>> EXISTS as $clientids{$client_id{$name}}) ; } else { $print_dup = qq() ; } + print "
    *** $name ------------------> $client_id{$name} $print_dup" ; + &insert_client($name,$client_id{$name},$client_accno{$name}) ; + } + } + +# foreach my $name (keys %client_add) { + # unless ($client_id{$name}) { + # print "
    *** $name" ; + # } + # } + +} #------------------------------------------------------------------------------------------ + +sub insert_client { + +my ($name,$id,$accno) = @_ ; + +unless ($id){ + $accno = &db_get_max_client_acc_no ; + $id = &db_get_max_client_id ; + } + +# &db_open_upd ; + +$sql = qq(INSERT INTO ffwaypls_filmfreight.clients (`ID`,`Client`,`AccNo`,`Branc`,`OnHold`,`Dormant`,`Fuel %`,`Fuel Min.`,`Doc Fee`,`Ins %`,`Ins Min`,`Taxable`,`Billing Cycle`,`Credit Limit`,`Owing`,`DateCreated`,`RateDate`,`TradingDate`,`CutoffDay`,`SalesRep`,`PhyicalAddr`,`PostalAddr`,`Contact1`,`Designation1`,`Email1`,`Contact2`,`Designation2`,`Email2`,`Contact3`,`Designation3`,`Email3`,`Website`,`PhoneNo`,`AhPhoneNo`,`FaxNo`,`CellNo`,`RegNo`,`VatNo`,`Director`,`BankName`,`BankAccNo`,`BankBranchCode`,`BankBranchName`) +VALUES ('$id','$name','$accno','Film Freight - Johannesburg','0','0','','0','0','0','0','-1','M','0','0.00','$now_ccyy_mm_dd','0000-00-00','0000-00-00','0','','$i{'icl_phys_address'}','$i{'icl_post_address'}','$i{'icl_contact_1'}','','$i{'icl_email_1'}','$i{'icl_contact_2'}','','$i{'icl_email_2'}','$i{'icl_contact_3'}','','$i{'icl_email_3'}','','$i{'icl_phoneno'}','','','$i{'icl_cellno'}','$i{'icl_regno'}','$i{'icl_vatno'}','','','','','') ; +) ; + +&common_debug($sql) ; + +# $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +# &db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +# sub update_clients_1 { + +# my ($id,$client) = @_ ; + +# # &db_open_upd ; + +# $sql = qq(UPDATE clients SET ID = '$id' WHERE client = "$client") ; + +# &common_debug($sql) ; + +# # $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +# # &db_close_conn ; + +# } #------------------------------------------------------------------------------------------ + +# sub update_clients { + +# my ($id,$accno) = @_ ; + +# &db_open_upd ; + +# $sql = qq(UPDATE ffwaypls_filmfreight.clients SET ID = '$id' WHERE accno = '$accno' +# ) ; + +# &common_debug($sql) ; + +# $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +# &db_close_conn ; + +# } #------------------------------------------------------------------------------------------ + +use db ; +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/db/admin/amend_db_towns_airportcode.pl b/scripts/_FromProd/v1.0/db/admin/amend_db_towns_airportcode.pl new file mode 100644 index 0000000..9a169e5 --- /dev/null +++ b/scripts/_FromProd/v1.0/db/admin/amend_db_towns_airportcode.pl @@ -0,0 +1,68 @@ +#!/usr/bin/perl + +print "Content-type: text/html\n\n"; + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +&today ; + +#------------------------------------------------------------------------------------------ + +use DBI; +use CGI::Carp qw(fatalsToBrowser); + +&load_towns ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub load_towns { + +&db_open_ro ; + +my $sql = qq(SELECT * FROM towns WHERE airportcode = '') ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +# &db_open_upd ; + +foreach $row (@$array_ref) { + &db_town_fields ; + &common_debug("$tn_town - $tn_opshubcode - $tn_airportcode") ; + # &update_towns($tn_townid,$tn_opshubcode) ; + } + +# &db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +sub update_towns { + +my ($townid,$airportcode) = @_ ; + +unless ($airportcode) { return ; } + +$sql = qq(UPDATE towns SET airportcode = '$airportcode' WHERE townid = '$townid' AND airportcode = '' +) ; + +&common_debug($sql) ; + +# $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +} #------------------------------------------------------------------------------------------ + +use db ; +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/db/admin/amend_db_waybills_add_address.pl b/scripts/_FromProd/v1.0/db/admin/amend_db_waybills_add_address.pl new file mode 100644 index 0000000..cccb309 --- /dev/null +++ b/scripts/_FromProd/v1.0/db/admin/amend_db_waybills_add_address.pl @@ -0,0 +1,133 @@ +#!/usr/bin/perl + +print "Content-type: text/html\n\n"; + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +&today ; + +#------------------------------------------------------------------------------------------ + +use DBI; +use CGI::Carp qw(fatalsToBrowser); + +&load_waybills ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub load_waybills { + +&db_open_ro ; + +my $sql = qq(SELECT * FROM ffwaypls_filmfreight.waybills) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $id_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +&db_open_upd ; + +foreach $row (@$id_array_ref) { + &db_waybills_fields ; + + # if ($wb{waybillno} > 17534) { next ; } + # if ($wb{waybillno} < 17000) { next ; } + + # if ($wb{waybillno} > 17534) { next ; } + # if ($wb{waybillno} < 17000) { next ; } + + if ($wb{waybillno} > 100) { next ; } + + $get_inline_address = 1 ; + &common_get_addresses ; + + $new_wb{receiver} = $shipper{receiver} ; + $new_wb{reccontact} = $contact{receiver} ; + $new_wb{recphone} = $phoneno{receiver} ; + $new_wb{reccellno} = $cellno{receiver} ; + $new_wb{recaddr1} = $addr1{receiver} ; + $new_wb{recaddr2} = $addr2{receiver} ; + $new_wb{recaddr3} = $addr3{receiver} ; + $new_wb{recaddr4} = $addr4{receiver} ; + $new_wb{recpc} = $pc{receiver} ; + $new_wb{recemail} = $email{receiver} ; + + $new_wb{sender} = $shipper{sender} ; + $new_wb{sencontact} = $contact{sender} ; + $new_wb{senphone} = $phoneno{sender} ; + $new_wb{sencellno} = $cellno{sender} ; + $new_wb{senaddr1} = $addr1{sender} ; + $new_wb{senaddr2} = $addr2{sender} ; + $new_wb{senaddr3} = $addr3{sender} ; + $new_wb{senaddr4} = $addr4{sender} ; + $new_wb{senpc} = $pc{sender} ; + $new_wb{senemail} = $email{sender} ; + + foreach (sort keys %new_wb) { + # $pre = substr($_,0,3) ; + # if ($pre ne $post) { print uc "
    $pre : $wb{waybillno} $wb{senderaddid} : " ; } + # $font = 'black' ; + # if ($new_wb{$_} ne $wb{$_}) { $font = 'red' ; } + # # print $_ . " = $new_wb{$_} : $wb{$_}, " ; + + unless ($wb{$_}) {$wb{$_} = $new_wb{$_} ; } + # print "$wb{$_}, " ; + # $post = $pre ; + } + + &update_waybills($wb{waybillno}) ; + + } + +&db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +sub update_waybills { + +my ($waybillno) = @_ ; + +$sql = qq(UPDATE ffwaypls_filmfreight.waybills SET +Sender = "$wb{sender}", +Receiver = "$wb{receiver}", +RecContact = "$wb{reccontact}", +RecPhone = "$wb{recphone}", +RecAddr1 = "$wb{recaddr1}", +RecAddr2 = "$wb{recaddr2}", +RecAddr3 = "$wb{recaddr3}", +reccellno = "$wb{reccell}", +sencontact = "$wb{sencontact}", +senphone = "$wb{senphone}", +sencellno = "$wb{sencell}", +recemail = "$wb{recemail}", +senemail = "$wb{senemail}", +SenAddr1 = "$wb{senaddr1}", +SenAddr2 = "$wb{senaddr2}", +SenAddr3 = "$wb{senaddr3}", +SenAddr4 = "$wb{senaddr4}", +RecAddr4 = "$wb{recaddr4}", +RecPC = "$wb{recpostalcode}", +SenPC = "$wb{senpostalcode}" +WHERE WaybillNo = "$waybillno" +) ; + +&common_debug($sql) ; + +$sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +} #------------------------------------------------------------------------------------------ + +use db ; +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/db/admin/amend_db_waybills_fix_address.pl b/scripts/_FromProd/v1.0/db/admin/amend_db_waybills_fix_address.pl new file mode 100644 index 0000000..efad28d --- /dev/null +++ b/scripts/_FromProd/v1.0/db/admin/amend_db_waybills_fix_address.pl @@ -0,0 +1,98 @@ +#!/usr/bin/perl + +print "Content-type: text/html\n\n"; + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +&today ; + +#------------------------------------------------------------------------------------------ + +use DBI; +use CGI::Carp qw(fatalsToBrowser); + +&load_waybills ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub load_waybills { + +&db_open_ro ; + +my $sql = qq(SELECT * FROM ffwaypls_filmfreight.waybills WHERE senaddr1 = recaddr1) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $id_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +# &db_open_upd ; + +foreach $row (@$id_array_ref) { + &db_waybills_fields ; + + # if ($wb{waybillno} > 17534) { next ; } + # if ($wb{waybillno} < 17000) { next ; } + + # if ($wb{waybillno} > 17534) { next ; } + if ($wb{waybillno} < 17000) { next ; } + + # if ($wb{waybillno} > 100) { next ; } + + $get_inline_address = 1 ; + &common_get_addresses ; + + $new_wb{senaddr1} = $addr1{sender} ; + $new_wb{senaddr2} = $addr2{sender} ; + $new_wb{senaddr3} = $addr3{sender} ; + + # foreach (sort keys %new_wb) { + # # $pre = substr($_,0,3) ; + # if ($new_wb{$_} ne $wb{$_}) { print uc "
    $wb{waybillno} $_ : $wb{$_} vs $new_wb{$_}" ; } + # # $font = 'black' ; + # # if ($new_wb{$_} ne $wb{$_}) { $font = 'red' ; } + # # # print $_ . " = $new_wb{$_} : $wb{$_}, " ; + + # # unless ($wb{$_}) {$wb{$_} = $new_wb{$_} ; } + # # print "$wb{$_}, " ; + # # $post = $pre ; + # } + + &update_waybills($wb{waybillno}) ; + + } + +# &db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +sub update_waybills { + +my ($waybillno) = @_ ; + +$sql = qq(UPDATE ffwaypls_filmfreight.waybills SET +SenAddr1 = "$new_wb{senaddr1}", +SenAddr2 = "$new_wb{senaddr2}", +SenAddr3 = "$new_wb{senaddr3}" +WHERE WaybillNo = "$waybillno" +) ; + +&common_debug($sql) ; + +# $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +} #------------------------------------------------------------------------------------------ + +use db ; +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/db/admin/amend_db_waybills_remove_f.pl b/scripts/_FromProd/v1.0/db/admin/amend_db_waybills_remove_f.pl new file mode 100644 index 0000000..ab20213 --- /dev/null +++ b/scripts/_FromProd/v1.0/db/admin/amend_db_waybills_remove_f.pl @@ -0,0 +1,135 @@ +#!/usr/bin/perl + +print "Content-type: text/html\n\n"; + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +&today ; + +#------------------------------------------------------------------------------------------ + +use DBI; +use CGI::Carp qw(fatalsToBrowser); + +&load_waybills ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub load_waybills { + +&db_open_ro ; + +my $sql = qq(SELECT * FROM ffwaypls_filmfreight.waybills) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $id_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +foreach $row (@$id_array_ref) { + &db_waybills_fields ; + unless (substr($wb{waybillno},0,1) eq 'F') { next; } + my $new_waybillno = substr($wb{waybillno},1) ; + &db_open_upd ; + &update_waybills($new_waybillno,$wb{waybillno}) ; + # &update_ata_carnet($new_waybillno,$wb{waybillno}) ; + # &update_journeys($new_waybillno,$wb{waybillno}) ; + &update_manifests($new_waybillno,$wb{waybillno}) ; + &update_parcels($new_waybillno,$wb{waybillno}) ; + # &update_supplier_invoice_waybills($new_waybillno,$wb{waybillno}) ; + &db_close_conn ; + } + +} #------------------------------------------------------------------------------------------ + +sub update_waybills { + +my ($new_waybillno,$waybillno) = @_ ; + +$sql = qq(UPDATE waybills SET waybillno = '$new_waybillno' WHERE waybillno = '$waybillno' +) ; + +&common_debug($sql) ; + +$sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +} #------------------------------------------------------------------------------------------ + +sub update_manifests { + +my ($new_waybillno,$waybillno) = @_ ; + +$sql = qq(UPDATE manifests SET waybillno = '$new_waybillno' WHERE waybillno = '$waybillno' +) ; + +&common_debug($sql) ; + +$sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +} #------------------------------------------------------------------------------------------ + +sub update_parcels { + +my ($new_waybillno,$waybillno) = @_ ; + +$sql = qq(UPDATE parcels SET waybillno = '$new_waybillno' WHERE waybillno = '$waybillno' +) ; + +&common_debug($sql) ; + +$sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +} #------------------------------------------------------------------------------------------ + +sub update_ata_carnet { + +my ($new_waybillno,$waybillno) = @_ ; + +$sql = qq(UPDATE ata_carnet SET hawb = '$new_waybillno' WHERE hawb = '$waybillno' +) ; + +&common_debug($sql) ; + +$sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +} #------------------------------------------------------------------------------------------ + +sub update_journeys { + +my ($new_waybillno,$waybillno) = @_ ; + +$sql = qq(UPDATE journeys SET hawb = '$new_waybillno' WHERE hawb = '$waybillno' +) ; + +&common_debug($sql) ; + +$sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +} #------------------------------------------------------------------------------------------ + +sub update_supplier_invoice_waybills { + +my ($new_waybillno,$waybillno) = @_ ; + +$sql = qq(UPDATE supplier_invoice_waybills SET waybillno = '$new_waybillno' WHERE waybillno = '$waybillno' +) ; + +&common_debug($sql) ; + +$sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +} #------------------------------------------------------------------------------------------ + +use db ; +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/db/admin/amend_db_waybills_update_invno.pl b/scripts/_FromProd/v1.0/db/admin/amend_db_waybills_update_invno.pl new file mode 100644 index 0000000..f3be81c --- /dev/null +++ b/scripts/_FromProd/v1.0/db/admin/amend_db_waybills_update_invno.pl @@ -0,0 +1,96 @@ +#!/usr/bin/perl + +print "Content-type: text/html\n\n"; + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +&today ; + +#------------------------------------------------------------------------------------------ + +use DBI; +use CGI::Carp qw(fatalsToBrowser); + +# &load_invoices ; +&load_waybills ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub load_waybills { + +&db_open_ro ; + +my $sql = qq(SELECT waybillno, invno FROM waybills WHERE InvNo = '' AND WaybillNo < 15878 ORDER BY WaybillNo DESC) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +# &db_open_upd ; + +foreach $row (@$array_ref) { + $waybillno = @$row[0] ; + $invoiceno = @$row[1] ; + # unless ($invoiceno) { next ; } + &update_waybills($waybillno,'NC') ; + } + +# &db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +sub update_waybills { + +my ($waybillno,$invoiceno) = @_ ; + +$sql = qq(UPDATE waybills SET invno = '$invoiceno' WHERE waybillno = '$waybillno' +) ; + +&common_debug($sql) ; + +# $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +} #------------------------------------------------------------------------------------------ + +# sub load_invoices { + +# &db_open_ro ; + +# my $sql = qq(SELECT * FROM invoices) ; + +# my $sth = $dbh->prepare($sql) ; + +# $sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +# my $inv_array_ref = $sth->fetchall_arrayref(); + +# $sth->finish(); + +# &db_close_conn ; + +# # &db_open_upd ; + +# foreach $row (@$inv_array_ref) { + # $waybillno = @$row[0] ; + # $invoiceno = @$row[1] ; + # unless ($invoiceno) { next ; } + # &update_waybills($waybillno,$invoiceno) ; + # } + +# # &db_close_conn ; + +# } #------------------------------------------------------------------------------------------ + +use db ; +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/db/admin/create_db_loc_table.pl b/scripts/_FromProd/v1.0/db/admin/create_db_loc_table.pl new file mode 100644 index 0000000..0aacd9a --- /dev/null +++ b/scripts/_FromProd/v1.0/db/admin/create_db_loc_table.pl @@ -0,0 +1,73 @@ +#!/usr/bin/perl + +print "Content-type: text/html\n\n"; + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +&today ; + +#------------------------------------------------------------------------------------------ + +use DBI; +use CGI::Carp qw(fatalsToBrowser); + +&create_db_loc_table ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub create_db_loc_table { + +&db_open_ro ; + +# my $sql = qq(SELECT originopshub,originhub,origin,originreg,originoutlying,originhubid,originid FROM ffwaypls_filmfreight.waybills) ; +my $sql = qq(SELECT * FROM ffwaypls_filmfreight.waybills) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +$waybill_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +foreach $row (@$waybill_array_ref) { + &db_waybills_fields ; + + if ($done{'loc'}{$wb_origin}) { next ; } + if ($done{'locid'}{$wb_originid}) { print "
    DUPLICATE - $wb_originid" ; next ; } + + $wbcnt++ ; + + # print qq(
    $wbcnt. $wb_originopshub,$wb_originhub,$wb_origin,$wb_originreg,$wb_originoutlying,$wb_originhubid,$wb_originid) ; + print qq(
    $wb_originid,$wb_origin,$wb_originopshub,$wb_originhub,$wb_originreg,$wb_originoutlying,$wb_originhubid) ; + + $done{'loc'}{$wb_origin} = 1 ; + $done{'locid'}{$wb_originid} = 1 ; + } + +foreach $row (@$waybill_array_ref) { + &db_waybills_fields ; + + if ($done{'loc'}{$wb_dest}) { next ; } + if ($done{'locid'}{$wb_destid}) { print "
    DUPLICATE - $wb_destid" ; next ; } + + $wbcnt++ ; + + # print qq(
    $wbcnt. $wb_destopshub,$wb_desthub,$wb_dest,$wb_destreg,$wb_destoutlying,$wb_desthubid,$wb_destid) ; + print qq(
    $wb_destid,$wb_dest,$wb_destopshub,$wb_desthub,$wb_destreg,$wb_destoutlying,$wb_desthubid) ; + + $done{'loc'}{$wb_dest} = 1 ; + $done{'locid'}{$wb_destid} = 1 ; + } + +} #------------------------------------------------------------------------------------------ + +use db ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/db/admin/create_db_other_service_table.pl b/scripts/_FromProd/v1.0/db/admin/create_db_other_service_table.pl new file mode 100644 index 0000000..e4572a5 --- /dev/null +++ b/scripts/_FromProd/v1.0/db/admin/create_db_other_service_table.pl @@ -0,0 +1,76 @@ +#!/usr/bin/perl + +print "Content-type: text/html\n\n"; + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +&today ; + +#------------------------------------------------------------------------------------------ + +use DBI; +use CGI::Carp qw(fatalsToBrowser); + +&create_db_other_service_table ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub create_db_other_service_table { + +&db_open_ro ; + +my $sql = qq(SELECT OthSvc1,otherservice1id,OthSvc2,otherservice2id FROM ffwaypls_filmfreight.waybills WHERE OthSvc1 <> '') ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $waybill_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +foreach $row (@$waybill_array_ref) { + $wb_othsvc1 = @$row[0] ; + $wb_otherservice1id = @$row[1] ; + $wb_othsvc2 = @$row[2] ; + $wb_otherservice2id = @$row[3] ; + + $service{$wb_otherservice1id} = $wb_othsvc1 ; + # $service{$wb_otherservice2id} = $wb_othsvc2 ; + } + +foreach my $id (keys %service) { + # print "
    *** $id -> $service{$id}" ; + &insert_other_service($id,$service{$id}) ; + } + +} #------------------------------------------------------------------------------------------ + +sub insert_other_service { + +my ($id,$name) = @_ ; + +# &db_open_upd ; + +$sql = qq(INSERT INTO ffwaypls_filmfreight.other_services (ID,OthServiceName) +VALUES ('$id','$name'); +) ; + +&common_debug($sql) ; + +# $sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +# &db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +use db ; +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/delivered_report.pl b/scripts/_FromProd/v1.0/delivered_report.pl new file mode 100644 index 0000000..bab3180 --- /dev/null +++ b/scripts/_FromProd/v1.0/delivered_report.pl @@ -0,0 +1,276 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our $srchscr = 1 ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + if ($iaction eq ''){ &report_screen ; } + &common_min_action; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub report_ifields { + +&load_search_vars ; + +# if ($i{camera_system_id}) { + # push @report_sql, "(`camera_system_id`='$i{camera_system_id}')" ; + # push @report_results, "camera_system = $camera_system{$i{camera_system_id}}" ; + # $xlsreportname .= '-' . $i{camera_system_id} ; + # } + +if ($i{camera_system_id} and $i{camera_system_id} ne 'main' and $i{camera_system_id} ne 'other' and $i{camera_system_id} ne 'all') { + push @report_sql, "(`camera_system_id`='$i{camera_system_id}')" ; + push @report_results, "camera_system = $camera_system{$i{camera_system_id}}" ; + $xlsreportname .= '-' . $i{camera_id} ; +} elsif ($i{camera_system_id} eq 'main' or $i{camera_system_id} eq 'other' or $i{camera_system_id} eq 'all') { + push @report_results, "camera_system = $i{camera_system_id}" ; +} + +if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { $error = qq(CAMERAS FROM ($i{date_from}) > CAMERAS TO ($i{date_to})); &report_screen; } + } + +if ($i{date_from}) { + push @report_sql, "(`date_time` >= '$i{date_from}')" ; + push @report_results, "date_time >= $i{date_from}" ; + } + +if ($i{date_to}) { + push @report_sql, "(`date_time` <= '$i{date_to}')" ; + push @report_results, "date_time <= $i{date_to}" ; + } + +if ($i{client_id}) { + # push @report_sql, "(`client_id` = '$i{client_id}')" ; + push @report_results, "Client = $client{$i{client_id}}" ; + } + +$report_results_msg = uc join(', ', @report_results) ; + +unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); &report_screen; } else { $isaved = qq(SELECT WHERE $report_results_msg) ; } + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + # my $cameras_sql_where = "`id`='$i{camera_id}'" ; + # &db_min_ro('cameras','id,camera_nr',$cameras_sql_where,'','') ; + # foreach my $id (keys %{$db{cameras}}) { $camera_name{$id} = $db{cameras}{$id}{camera_nr} ; } + + my $camera_systems_sql_where = "`id`='$i{camera_system_id}'" if $i{camera_system_id} ; + &db_min_ro('camera_systems','id,name',$camera_systems_sql_where,'','') ; + foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + + # my $price_list_sql_where = " AND `id`='$i{camera_system_id}'" if $i{camera_system_id} ; + # &db_min_ro('price_list','id,description',"`excl`<>'1' AND `type`='systems'$price_list_sql_where",'','') ; + # foreach my $id (keys %{$db{price_list}}) { $camera_system{$id} = $db{price_list}{$id}{name} ; } + + # my $customers_sql_where = "`id`='$i{client_id}'" if $i{client_id} ; + # &db_min_ro('customers','*',$customers_sql_where,'','') ; + # foreach my $id (keys %{$db{customers}}) { $client{$id} = $db{customers}{$id}{name} ; } + + if ($i{client_id}) { + my $customers_sql_where = "`id`='$i{client_id}'" ; + &db_min_ro('customers','*',$customers_sql_where,'','') ; + foreach my $id (keys %{$db{customers}}) { $client{$id} = $db{customers}{$id}{name} ; } + } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +my $srch_where_sql = join(' AND ', @report_sql) ; + +my $add_sql_where = '' ; + +# if ($username eq 'rory') { push @sql_col_display, "id" ; } + +# our @sql_col_display = ("camera_nr","camera_system_id","camera_serial_nr","vpu_serial_nr","date_received","client_id","ref_nr","ref") ; +our @sql_col_display = ("camera_nr","camera_system_id","camera_serial_nr","vpu_serial_nr","date_delivered","client_id","ref_nr","ref") ; + +&report_xls_export_header("Camera_Delivered_Report$xlsreportname",'deliveredreport') ; + +&load_list_vars("$srch_where_sql$add_sql_where") ; + +foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) { + if ($linked_sn{$db{$table}{$id}{serial_nr}}) { $vpu_is_linked{$linked_sn{$db{$table}{$id}{serial_nr}}} = 1 ; } +} + +foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) { + + # unless ($quote_delivery_date{$id}) { next ; } + unless ($db{$table}{$id}{quote_delivery_date}) { next ; } + + next if (&common_camera_system_filter($table,$id)) ; + + if ($i{client_id}) { + next unless $client{$i{client_id}} eq $quote_customer{$id} ; + } + + next if $vpu_is_linked{$db{$table}{$id}{serial_nr}} ; + + $print_tbody .= qq~~ ; + + $xlscol=0; + + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$table}{$id}{$_} ; + my $align = '' ; + + my $center = qq~ class="dt-center"~ ; + + if ($_ eq 'date_delivered') { $val = $db{$table}{$id}{quote_delivery_date} ; $align = $center ; } + if ($_ eq 'client_id') { $val = $quote_customer{$id} ; } + if ($_ eq 'ref_nr') { $val = $db{$table}{$id}{quote_nr} ; $align = $center ; } + # if ($_ eq 'ref') { $val = $db{$table}{$id}{quote_ref} ? "$db{$table}{$id}{quote_ref}" : $quote_ref{$id} ; } + if ($_ eq 'ref') { $val = $db{$table}{$id}{quote_ref} ? $db{$table}{$id}{quote_ref} : $quote_ref{$id} ; } + if ($_ eq 'camera_system_id') { $val = $camera_system{$val} ; } + if ($_ eq 'camera_serial_nr') { $val = $db{$table}{$id}{serial_nr} ; } + if ($_ eq 'vpu_serial_nr') { $val = $linked_sn{$db{$table}{$id}{serial_nr}} ; } # $val .= ' [' . $linked_cn{$db{$table}{$id}{serial_nr}} . ']' if $linked_cn{$db{$table}{$id}{serial_nr}} ; + + &report_xls_export_process_cell('','',$val) ; # ------------------------------------------------------------------------- HTML AFTER + $xlscol++; + + # $val = &common_camera_links($table,$id,$val) if $_ eq 'camera_nr' or $_ eq 'ref_nr' ; + $val = &common_camera_links($table,$id,$val) if ($_ eq 'camera_nr' or $_ eq 'ref_nr') and $pixellot_limit{$username}!=1 and $events_limit{$username}!=1 ; + + $print_tbody .= qq~$val~ ; + } + + $print_tbody .= qq~~ ; + $xlsrow++ ; + } + +&report_xls_export_footer('L',15,'deliveredreport') ; + +$fnsortcol = 7 ; +$fnsortorder = 'asc' ; + +$print_more_boxes .= qq~


    ~ ; + +&common_min_extra_crumb("$lcpage-report","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub set_tick { + +my ($color,$tooltip) = @_ ; + +$tick{green} = qq~2~ ; +$tick{orange} = qq~1~ ; +$tick{red} = qq~0~ ; + +return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub load_list_vars { + +my ($where) = @_ ; + +&db_min_ro('camera_systems','id,name','','','') ; +foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + +&db_min_ro('customers','id,name','','','') ; +foreach my $id (keys %{$db{customers}}) { $customer{$id} = $db{customers}{$id}{name} ; } + +# &common_load_quote_vars('>0'); +&common_load_quote_vars("cameras.quote_nr>0 AND cameras.quote_nr=quotes.quote_nr"); + +&db_min_ro($table,'*',$where,'','') ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + +&common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'list' ; +our $lcpage = 'delivered' ; + +&common_page_name ; + +our $table = 'cameras' ; +$page_title = 'Delivered' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + +our $lcol = 3 ; +our $fcol = 5 ; + +$print_box_content_rows .= &common_min_forms_start('report') ; + +&common_camera_opts ; +&common_min_select_opts('camera_system_id','camera_systems','code',$i{camera_system_id},'') ; +&common_min_select_opts('client_id','customers','name',$i{client_id},'') ; + +my @datefrom = &common_add_delta_ymd(-2,0,0) ; + +$print_box_content_rows .= &common_min_form_datepicker('date_from',"$datefrom[0]-01-01") ; +$print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$now_dd") ; +$print_box_content_rows .= &common_min_form_select('camera_system_id',$i{camera_system_id}) ; +$print_box_content_rows .= &common_min_form_select('client_id','') ; +$print_box_content_rows .= &common_min_forms_end('','','report') ; + +&common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +use common ; +use report ; +use xlsxcreator ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/demos.pl b/scripts/_FromProd/v1.0/demos.pl new file mode 100644 index 0000000..bd66ed9 --- /dev/null +++ b/scripts/_FromProd/v1.0/demos.pl @@ -0,0 +1,4402 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); + +require cfg ; + +print header; # CGI.pm method + +# unless ($username eq 'handre'or $username eq 'rory') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; +use LWP::Simple qw($ua get); +use JSON ; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +# INSERT INTO demos +# (`location_id`,`brief_description`,`id`,`additional_requirements_from_events_dept`,`events_operator_allocated`,`tenant_id`,`pre_demo_testing_requirements`,`demo_type_id`,`events_operator_required`,`calibrator_required`,`additional_requirements_from_support_dept`) VALUES +# ("1","test","1009","test","132","1","test","1","1","1","test") ; + +# INSERT INTO event_quotes + +# (`days_active`,`date_from`,`ref`,`roe`,`office_notes`,`user_id`,`slip`,`demo_id`,`address`,`event_system_id_multiple`,`organisation_ids`,`total_vat_amount_workings_event`,`total_grand_amount_workings_event`,`times_from`,`quote_to`,`operator_ids`,`total_amount_workings_event`,`country_id`,`email`,`last_update`,`contact_name`,`notes`,`club_ids`,`datetime`,`id`,`currency`,`quote_nr`,`date_to`,`tel`) VALUES ( +# "1;;;;;;;;;;;;;;;;;;;","2025-07-12 08:00:00","test","1","test","25","","1009","113 Cinsaut St, Steynsrust, Somerset West","277;278;;;;;;;;;;;;;","532","237.60","1821.60",";;;;;;;;;;;;;;;;;;","1:Rory Mathew:rory@kre8it.co.za:0621336752:113 Cinsaut St, Steynsrust, Somerset West","291;189;","1584.00","242","rory@kre8it.co.za","2025-07-07 09:46:34","Rory Mathew","test","727;727;;;;;;;;;;;;;","2025-07-07 09:46:34","10943","ZAR","1009","2025-07-12 17:00:00","0621336752") ; + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $testing = 1 ; +# our $debug = 1 ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +if ($is_operator && $glod_user_level == 2) { $glod_user_level = 3 ; } # upgrade operators level 2&3 to 3&4 + +our $nr_of_system_names_and_clubs = 15 ; our @all_select_ids = () ; our $minify_jquery = 1 ; + +&db_open_ro ; + $db_ignore_open_close = 1 ; + + &page_opts ; + + if ($iaction eq 'filter' || $iaction eq 'search' || $iaction eq 'report') { + our $srchscr = 1 ; + our $savjqy = 0 ; + } + + #------------------------------------------------------------------------------------------------------------------------------------------------------------------ + + our $table = 'demos'; + + if ($iaction eq 'add') { + &add_screen ; + &common_min_screen1 ; + } elsif ($iaction eq 'edit') { + &common_min_load_params ; + # $i{id} = 1009 ; + &edit_screen ; + &common_min_screen1 ; + } elsif ($iaction eq 'save') { + &common_min_load_params ; + &insert ; + # &log_changes ; + &edit_or_list ; + } elsif ($iaction eq 'update') { + &common_min_load_params ; + &update ; + # &log_changes ; + &edit_or_list ; + } elsif ($iaction eq 'copy') { + &common_min_load_params ; + &duplicate ; + &edit_screen ; + &common_min_screen1 ; + } elsif ($iaction eq 'delete') { + &common_min_load_params ; + &delete ; + &common_min_screen2 ; + } + + &common_min_action ; + + $db_ignore_open_close = 0 ; +&db_close_conn ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub edit_or_list { + + exit if $testing && substr($username,0,4) eq 'rory' ; + $isaved = $i{id} ; + &edit_screen ; + &common_min_screen1; + +} #------------------------------------------------------------------------------------------ + +sub insert { + + &build_system_details_table_fields($quote_accepted,$quote_rejected,$quote_cancelled) ; + &process_multi_select($quote_accepted,$quote_rejected,$quote_cancelled) ; + &add_db_fields ; + &default_values ; + + $i{id} = &db_min_get_max($table,'id') ; + + our %i2 = () ; + + &build_demos_min_fields_1 ; + + &process_daily_details_from_the_events_datails_tab ; + + &db_min_insert($table) ; + + our %ii = %i ; + %i = () ; + + $i{id} = &db_min_get_max('event_quotes','id') ; + $i{id} = 1000 if $i{id} < 1000 ; + $i{quote_nr} = $i{id} ; + + my $i_demo_id = $i{demo_id} ; + my $i_event_id = $i{id} ; + $i{datetime} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{quote_date} = "$now_ccyy_mm_dd" ; + + &build_event_quotes_fields ; + + &build_demos_min_fields_2 ; + + if ($ii{iattachslip}) { + my $attachmentdir = $htmlpath . "/uploads/slips/$i_event_id" ; + mkdir $attachmentdir if not -d $attachmentdir ; + &common_upload_files("slips/$i_event_id") ; + } + + $i{quote_created} = 1 if $glod_user_level < 3 ; + $i{quote_pending} = 1 unless $i{quote_accepted} || $i{quote_cancelled} || $i{quote_completed} || $i{quote_rejected} ; + $ignore{quote_created} = '' ; + $i{quote_created} = 0 unless $i{quote_created} ; + + $ignore{country_id} = 1 ; + + &db_min_insert('event_quotes') ; + + $ignore{quote_created} = 1 ; + + my %iii = %i ; + + %i = () ; + $i{id} = $iii{id} ; + $i{quote_nr} = $iii{id} ; + + if ($ii{custom_set}) { + &build_demos_min_fields_3 ; + } else { + foreach (keys %i2) { + $i{$_} = $i2{$_} ; + } + } + + &db_min_insert('event_quotes_min') ; + + %i = %ii ; + + my $to = $email_events{1} ; my $cc = "$email_events{2};$email_events{3};$email_events{6}" ; my $bcc = '' ; + + if ($useropts{it}{$username}) { + $to = $email_it_2 ; $cc = $email_it_1 ; $bcc = '' ; + } + + &common_send_smtp_mail('',$to,$cc,$bcc,"Demo Created","Please note Demo $i_demo_id has been created as Event Quote $i_event_id",'','html','','','','',0,0) if $to || $cc || $bcc ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + unless ($i{id}) { + $error = qq(NO ID) ; + return ; + } + + &db_min_ro($table,"*","`id`='$i{id}'",'','') ; + + &db_min_ro('event_quotes','*',"demo_id='$i{id}'","",'') ; + + our $event_quote_id = 0 ; + foreach (keys %{$db{event_quotes}}) { + $event_quote_id = $_ ; + } + + my %iiii = %i ; + our %i2 = () ; + + &build_system_details_table_fields($quote_accepted,$quote_rejected,$quote_cancelled) ; + &process_multi_select($quote_accepted,$quote_rejected,$quote_cancelled) ; + &add_db_fields ; + &default_values ; + + &build_demos_min_fields_1 ; + + &process_daily_details_from_the_events_datails_tab ; + + our $line = qq~~ ; + + $ignore{country_id} = 1 ; + + &common_shared_log_update_changes("demos","demo_changes","changes_demos") ; + + our %ii = %i ; + %i = () ; + + $i{id} = $event_quote_id ; + + &build_event_quotes_fields ; + + &build_demos_min_fields_2 ; + + if ($ii{iattachslip}) { + my $attachmentdir = $htmlpath . "/uploads/slips/$i{id}" ; + mkdir $attachmentdir if not -d $attachmentdir ; + &common_upload_files("slips/$i{id}") ; + } + + $line = qq~~ ; + + &common_shared_log_update_changes("event_quotes") ; + + %i = () ; + + if ($iiii{custom_set}) { + &build_demos_min_fields_3 ; + } else { + foreach (keys %i2) { + $i{$_} = $i2{$_} ; + } + } + + $i{id} = $event_quote_id ; + $i{quote_nr} = $event_quote_id ; + + foreach (keys %i) { + $i{$_} =~ s/;+$//; + } + + &common_shared_log_update_changes("event_quotes_min","event_quotes_changes","changes") ; + + %i = %iiii ; + +} #------------------------------------------------------------------------------------------ + +sub build_event_quotes_fields { + + $i{last_update} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{demo_id} = $ii{id} ; + $i{user_id} = $userid ; + $i{date_from} = $ii{date_from} ; + $i{date_to} = $ii{date_to} ; + $i{ref} = $ii{name} ; + $i{event_system_id_multiple} = $ii{event_system_id_multiple} ; + $i{club_ids} = $ii{club_ids} ; + $i{operator_ids} = $ii{operator_ids} ; + $i{organisation_ids} = $ii{venue_ids} ; + $i{qty} = $ii{qty} ; + $i{slip} = $ii{slip} ; + $i{notes} = $ii{notes} ; + $i{office_notes} = $ii{office_notes} ; + $i{email} = $ii{email} ; + $i{tel} = $ii{tel} ; + $i{address} = $ii{address} ; + $i{contact_name} = $ii{contact_name} ; + $i{currency} = $ii{currency} ; + $i{roe} = $ii{roe} ; + $i{region_id} = $ii{region_id} ; + $i{quote_to} = $ii{quote_to} ; + $i{quote_accepted} = $ii{quote_accepted} ; + $i{quote_pending} = $ii{quote_pending} ; + $i{quote_cancelled} = $ii{quote_cancelled} ; + $i{quote_completed} = $ii{quote_completed} ; + # $i{quote_created} = $ii{quote_created} ; + $i{quote_rejected} = $ii{quote_rejected} ; + $i{times_from} = $ii{times_from} ; + $i{times_to} = $ii{times_to} ; + $i{days_active} = $ii{days_active} ; + $i{event_length} = $ii{event_length} ; + $i{custom_set} = $ii{custom_set} ; + $i{total_amount_workings_event} = $ii{total_amount_workings_event} ; + $i{total_vat_amount_workings_event} = $ii{total_vat_amount_workings_event} ; + $i{total_grand_amount_workings_event} = $ii{total_grand_amount_workings_event} ; + $i{sport_type_ids} = $ii{sport_type_ids} ; + $i{slip} = ($ii{iattachslip}) ? "slip-$ii{iattachslip}" : "" ; + + my @quote_to_splt = split(/\:/,$i{quote_to}) ; + $i{quote_to} = $quote_to_splt[0] ; + + $ignore{date_from} = '' ; + $ignore{date_to} = '' ; + $ignore{event_system_id_multiple} = '' ; + $ignore{club_ids} = '' ; + $ignore{operator_ids} = '' ; + $ignore{slip} = '' ; + $ignore{notes} = '' ; + $ignore{office_notes} = '' ; + $ignore{email} = '' ; + $ignore{tel} = '' ; + $ignore{address} = '' ; + $ignore{contact_name} = '' ; + $ignore{currency} = '' ; + $ignore{quote_nr} = '' ; + $ignore{roe} = '' ; + $ignore{quote_to} = '' ; + $ignore{qty} = '' ; + $ignore{organisation_ids} = '' ; + $ignore{ref} = '' ; + $ignore{demo_id} = '' ; + $ignore{user_id} = '' ; + $ignore{quote_date} = '' ; + $ignore{quote_accepted} = '' ; + $ignore{quote_pending} = '' ; + $ignore{quote_cancelled} = '' ; + $ignore{quote_completed} = '' ; + # $ignore{quote_created} = '' ; + $ignore{quote_rejected} = '' ; + $ignore{times_from} = '' ; + $ignore{times_to} = '' ; + $ignore{days_active} = '' ; + $ignore{event_length} = '' ; + $ignore{custom_set} = '' ; + $ignore{total_amount_workings_event} = '' ; + $ignore{total_vat_amount_workings_event} = '' ; + $ignore{total_grand_amount_workings_event} = '' ; + $ignore{sport_type_ids} = '' ; + $ignore{region_id} = '' ; + +} #------------------------------------------------------------------------------------------ + +sub process_daily_details_from_the_events_datails_tab { + + my ($id) = @_ ; + + use Time::Piece; + + my $final_day = &common_min_calc_day_diff($i{date_to},$i{date_from}) ; + + # for (1 .. 20) { + # $final_day = $_ if $i{"day_$_"} ; + # } + + for my $event_day (1 .. 20) { + + $ignore{"time_from_$event_day"} = 1 ; + $ignore{"time_to_$event_day"} = 1 ; + $ignore{"day_$event_day"} = 1 ; + $ignore{"event_length_$event_day"} = 1 ; + $ignore{"selected_$event_day\_event_length"} = 1 ; + + $i{times_from} .= qq~$i{"time_from_$event_day"};~ if $event_day > 1 && $i{"day_$event_day"} ; + $i{times_from} .= qq~;~ if $event_day > 1 && !$i{"day_$event_day"} ; + + $i{times_to} .= qq~$i{"time_to_$event_day"};~ if $event_day < $final_day && $i{"day_$event_day"} ; + $i{times_to} .= qq~;~ if $event_day < $final_day && !$i{"day_$event_day"} ; + + $i{days_active} .= qq~$i{"day_$event_day"};~ ; + $i{event_length} .= ($i{"day_$event_day"}) ? qq~$i{"event_length_$event_day"};~ : qq~;~ ; + } + + # chop $i{times_from} if $i{times_from} ; + # chop $i{times_to} if $i{times_to} ; + # chop $i{days_active} if $i{days_active} ; + # chop $i{event_length} if $i{event_length} ; + + $i{times_from} =~ s/([^;])(;+)\z/$1/; + $i{times_to} =~ s/([^;])(;+)\z/$1/; + $i{days_active} =~ s/([^;])(;+)\z/$1/; + $i{event_length} =~ s/([^;])(;+)\z/$1/; + + # $i{times_from} =~ s/;+$//; + # $i{times_to} =~ s/;+$//; + # $i{days_active} =~ s/;+$//; + # $i{event_length} =~ s/;+$//; + + $ignore{times_from} = 1 ; + $ignore{times_to} = 1 ; + $ignore{days_active} = 1 ; + $ignore{event_length} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub default_values { + + $i{events_operator_required} = 0 unless $i{events_operator_required} ; + $i{calibrator_required} = 0 unless $i{calibrator_required} ; + $i{demo_type_id} = 0 unless $i{demo_type_id} ; + $i{calibrator_required} = 0 unless $i{calibrator_required} ; + $i{events_operator_allocated} = 0 unless $i{events_operator_allocated} ; + $i{location_id} = 0 unless $i{location_id} ; + $i{quote_accepted} = 0 unless $i{quote_accepted} ; + $i{quote_pending} = 0 unless $i{quote_pending} ; + $i{quote_cancelled} = 0 unless $i{quote_cancelled} ; + $i{quote_completed} = 0 unless $i{quote_completed} ; + $i{quote_created} = 0 unless $i{quote_created} ; + $i{quote_rejected} = 0 unless $i{quote_rejected} ; + $i{custom_set} = 0 unless $i{custom_set} ; + +} #------------------------------------------------------------------------------------------ + +sub send_email_to_manager { + + my ($event_id,$status,$msg) = @_ ; + + return if $username eq 'marizen' ; # don't send to marizen if she did the change. + + my $usernametemp = (substr($username,0,4) eq 'rory') ? 'rory' : $username ; + + my $attachpath = "$pdfpath/event_details" ; $attachfile = "Event_Details-$event_id.pdf" ; + + my $subj = 'Event [' . $event_id . ']' ; + $subj .= " $status" if $status ; + $subj .= " by $username" if $username ; + $subj .= " : $i{ref}" if $i{ref} ; + + my $event_details_pdf = get("$useropts{domain}$useropts{'scripts'}/pdf/event_details_pdf.pl?$event_id&&") ; + my $to = ($useropts{it}{$usernametemp}) ? "$usernametemp\@kre8it.co.za" : $email_events{1} ; + $got_mail_add{$to} = 1 ; + my $cc = ($is_schools_manager) ? "$useremail" : (!$got_mail_add{$useremail}) ? "$useremail" : '' ; + # my $bcc = ($useropts{it}{$usernametemp}) ? '' : 'rory@kre8it.co.za' ; + my $bcc = '' ; + &common_send_smtp_mail('',$to,$cc,$bcc,"$subj","Click here to view event details

    $msg",'','html','',$attachpath,$attachfile,'',0,0) ; + +} #------------------------------------------------------------------------------------------ + +sub build_system_details_table_fields { + + my ($quote_accepted,$quote_rejected,$quote_cancelled) = @_ ; + + # $i{operator_ids} .= qq~;\~;~ ; + my $cnt_last_row = 0 ; + for (1 .. $nr_of_system_names_and_clubs) { + + my $system_name = "system_name_$_" ; + my $club_name = "club_name_$_" ; + my $op_name = "operator_id_calibration_$_" ; + + $cnt_last_row = $_ if $i{$system_name} || $i{$club_name} ; + + $ignore{$system_name} = 1 ; + $ignore{$club_name} = 1 ; + $ignore{$op_name} = 1 ; + } + + return if ($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3 ; + + unless ($cnt_last_row) { + $i{club_ids} = qq~~ ; + $i{event_system_id_multiple} = qq~~ ; + return ; + } + + # return if $is_schools_manager ; + # return if $glod_user_level < 4 ; + # return if $glod_user_level < 3 ; + + $i{operator_ids} = '' ; my $table_row_cnt = 0 ; + + for (1 .. $nr_of_system_names_and_clubs) { + + my $system_name = "system_name_$_" ; + my $club_name = "club_name_$_" ; + my $op_name = "operator_id_calibration_$_" ; + + $i{club_ids} .= qq~$i{$club_name};~ ; + $i{event_system_id_multiple} .= qq~$i{$system_name};~ ; + $i{operator_ids} .= qq~$i{$op_name},~ if $_ <= $cnt_last_row ; + + $table_row_cnt++ if $i{$club_name} || $i{$system_name} ; + + } + + my @saved_operator_ids = split(/\,/,$db{event_quotes}{$event_quote_id}{operator_ids}) ; + + $i{operator_ids} .= join(',', @saved_operator_ids[$table_row_cnt .. $#saved_operator_ids]); + + $ignore{club_name} = 1 ; + # chop $i{club_ids} if $i{club_ids} ; chop $i{event_system_id_multiple} if $i{event_system_id_multiple} ; + # chop $i{operator_ids} if $i{operator_ids} ; + + $i{club_ids} =~ s/;+$//; + $i{event_system_id_multiple} =~ s/;+$//; + $i{operator_ids} =~ s/,+$//; + +} #------------------------------------------------------------------------------------------ + +sub build_demos_min_fields_1 { + + my ($id) = @_ ; + + for (1 .. 50) { + + $y{7}{$_} = "excl_workings_event_$_" ; + $y{8}{$_} = "description_workings_event_$_" ; + $y{9}{$_} = "operator_workings_event_$_" ; + $y{10}{$_} = "remarks_workings_event_$_" ; + $y{11}{$_} = "supplier_workings_event_$_" ; + $y{12}{$_} = "ref_nr_workings_event_$_" ; + $y{13}{$_} = "qty_workings_event_$_" ; + $y{14}{$_} = "amount_usd_workings_event_$_" ; + $y{15}{$_} = "amount_ttl_workings_event_$_" ; + $y{16}{$_} = "vat_workings_event_$_" ; + + foreach my $a (keys %y) { + foreach my $b (keys %{$y{$a}}) { + $ignore{$y{$a}{$b}} = 1 ; + $x{$a}{$b} = $i{$y{$a}{$b}} ; + } + } + } + + $ignore{sub_total_workings_event} = 1 ; + $ignore{vat_total_workings_event} = 1 ; + $ignore{grand_total_workings_event} = 1 ; + + $ignore{total_amount_workings_event} = 1 ; + $ignore{total_vat_amount_workings_event} = 1 ; + $ignore{total_grand_amount_workings_event} = 1 ; + + if ($i{custom_set}) { + $i{total_amount_workings_event} = $i{sub_total_workings_event} ; + $i{total_vat_amount_workings_event} = $i{vat_total_workings_event} ; + $i{total_grand_amount_workings_event} = $i{grand_total_workings_event} ; + return ; + } + + $i{sub_total_workings_event} = 0 ; + $i{vat_total_workings_event} = 0 ; + $i{grand_total_workings_event} = 0 ; + + for my $system_name_row_nr (1 .. 15) { + + my $field = "operator_id_calibration_$system_name_row_nr" ; + next unless $i{$field} ; + + for my $days (1 .. 20) { + my $day_field = "day_$days" ; + next unless $i{$day_field} ; + $operator_day_count{full_day}{$i{$field}}++ if $i{"event_length_$days"} eq '1' ; + $operator_day_count{half_day}{$i{$field}}++ if $i{"event_length_$days"} eq '2' ; + } + } + + my %iii = %i ; + + for (1 .. 50) { + + if ($i{"description_workings_event_$_"} eq '14' && $i{"operator_workings_event_$_"}) { + my $op = $i{"operator_workings_event_$_"} ; + my $day_len = ($i{"amount_usd_workings_event_$_"} eq '1000.00') ? "full_day" : ($i{"amount_usd_workings_event_$_"} eq '750.00') ? "half_day" : "" ; + if ($day_len && ($operator_day_count{full_day}{$op} || $operator_day_count{half_day}{$op})) { + $saved_values{$day_len}{$op}{saved_values} = 1 ; + $saved_values{$day_len}{$op}{supplier_workings_event} = $i{"supplier_workings_event_$_"} ; + $saved_values{$day_len}{$op}{ref_nr_workings_event} = $i{"ref_nr_workings_event_$_"} ; + $saved_values{$day_len}{$op}{remarks_workings_event} = $i{"remarks_workings_event_$_"} ; + $saved_values{$day_len}{$op}{vat_workings_event} = $i{"vat_workings_event_$_"} ; + $saved_values{$day_len}{$op}{excl_workings_event} = $i{"excl_workings_event_$_"} ; + # $saved_values{$day_len}{$op}{amount_usd_workings_event} = $i{"amount_usd_workings_event_$_"} if $day_len eq "other" ; + } + } + $i{"description_workings_event_$_"} = "" ; + $i{"operator_workings_event_$_"} = "" ; + $i{"qty_workings_event_$_"} = "" ; + $i{"amount_usd_workings_event_$_"} = "" ; + $i{"amount_ttl_workings_event_$_"} = "" ; + $i{"excl_workings_event_$_"} = "1"; + $i{"vat_workings_event_$_"} = "" ; + $i{"supplier_workings_event_$_"} = "" ; + $i{"ref_nr_workings_event_$_"} = "" ; + $i{"remarks_workings_event_$_"} = "" ; + + } + + my $row_cnt = 0 ; + + foreach my $len (sort keys %operator_day_count) { + + foreach $op_id (sort keys %{$operator_day_count{$len}}) { + + $row_cnt++ ; + $i2{description_workings_event} .= '14;' ; + $i2{operator_workings_event} .= "$op_id;" ; + $i2{qty_workings_event} .= "$operator_day_count{$len}{$op_id};" ; + + # my $custom_saved_amnt = $saved_values{"other"}{$op_id}{amount_usd_workings_event} ; + + $i2{amount_usd_workings_event} .= ($len eq "full_day") ? '1000.00' : ($len eq "half_day") ? '750.00' : '0.00' ; + $i2{amount_usd_workings_event} .= qq~;~ ; + my $amnt = ($len eq "full_day") ? 1000 * $operator_day_count{$len}{$op_id} * $i{roe} : ($len eq "half_day") ? 750 * $operator_day_count{$len}{$op_id} * $i{roe} : 0 ; + $amnt = sprintf ("%0.2f",$amnt) ; + + $i2{amount_workings_event} .= "$amnt;" ; + $i{sub_total_workings_event} += $amnt if !$saved_values{$len}{$op_id}{excl_workings_event} ; + if ($saved_values{$len}{$op_id}{saved_values}) { + foreach (keys %{$saved_values{$len}{$op_id}}) { + $i2{$_} .= qq~$saved_values{$len}{$op_id}{$_};~ if $_ ne "saved_values" ; + $i{vat_total_workings_event} += $amnt*0.15 if !$saved_values{$len}{$op_id}{excl_workings_event} && $saved_values{$len}{$op_id}{vat_workings_event} && $_ eq "vat_workings_event" ; + } + } else { + $i2{supplier_workings_event} .= ";" ; + $i2{ref_nr_workings_event} .= ";" ; + $i2{remarks_workings_event} .= ";" ; + $i2{vat_workings_event} .= "1;" ; + $i2{excl_workings_event} .= "0;" ; + $i{vat_total_workings_event} += $amnt*0.15 ; + } + } + } + + for (1 .. 50) { + + if ($iii{"description_workings_event_$_"} && $iii{"description_workings_event_$_"} ne '14') { + $row_cnt++ ; + $i2{"excl_workings_event"} .= qq~$iii{"excl_workings_event_$_"};~ ; + $i2{"description_workings_event"} .= qq~$iii{"description_workings_event_$_"};~ ; + $i2{"operator_workings_event"} .= qq~$iii{"operator_workings_event_$_"};~ ; + $i2{"remarks_workings_event"} .= qq~$iii{"remarks_workings_event_$_"};~ ; + $i2{"supplier_workings_event"} .= qq~$iii{"supplier_workings_event_$_"};~ ; + $i2{"ref_nr_workings_event"} .= qq~$iii{"ref_nr_workings_event_$_"};~ ; + $i2{"qty_workings_event"} .= qq~$iii{"qty_workings_event_$_"};~ ; + $i2{"amount_usd_workings_event"} .= qq~$iii{"amount_usd_workings_event_$_"};~ ; + $i2{"amount_workings_event"} .= qq~$iii{"amount_ttl_workings_event_$_"};~ ; + $i2{"vat_workings_event"} .= qq~$iii{"vat_workings_event_$_"};~ ; + $iii{"amount_ttl_workings_event_$_"} =~ s/\,//g ; + $i{sub_total_workings_event} += $iii{"amount_ttl_workings_event_$_"} if !$iii{"excl_workings_event_$_"} ; + $i{vat_total_workings_event} += $iii{"amount_ttl_workings_event_$_"} * 0.15 if !$iii{"excl_workings_event_$_"} && $iii{"vat_workings_event_$_"} ; + + } + } + + unless ($row_cnt) { + $i2{excl_workings_event} = qq~~ ; + $i2{description_workings_event} = qq~~ ; + $i2{operator_workings_event} = qq~~ ; + $i2{remarks_workings_event} = qq~~ ; + $i2{supplier_workings_event} = qq~~ ; + $i2{ref_nr_workings_event} = qq~~ ; + $i2{qty_workings_event} = qq~~ ; + $i2{amount_usd_workings_event} = qq~~ ; + $i2{amount_workings_event} = qq~~ ; + $i2{vat_workings_event} = qq~~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub build_demos_min_fields_2 { + + $i{total_amount_workings_event} = sprintf("%0.2f",$ii{sub_total_workings_event}) ; + $i{total_vat_amount_workings_event} = sprintf("%0.2f",$ii{vat_total_workings_event}) ; + $i{total_grand_amount_workings_event} = sprintf("%0.2f",$ii{sub_total_workings_event}+$ii{vat_total_workings_event}) ; + +} #------------------------------------------------------------------------------------------ + +sub build_demos_min_fields_3 { + + for (1 .. 50) { + next unless $x{8}{$_} ; + $i{excl_workings_event} .= "$x{7}{$_};"; + $i{description_workings_event} .= "$x{8}{$_};"; + $i{operator_workings_event} .= "$x{9}{$_};"; + $i{remarks_workings_event} .= "$x{10}{$_};"; + $i{supplier_workings_event} .= "$x{11}{$_};"; + $i{ref_nr_workings_event} .= "$x{12}{$_};"; + $i{qty_workings_event} .= "$x{13}{$_};"; + $i{amount_usd_workings_event} .= "$x{14}{$_};"; + $i{amount_workings_event} .= "$x{15}{$_};"; + $i{vat_workings_event} .= "$x{16}{$_};"; + } + + $i{excl_workings_event} = "" unless $i{excl_workings_event} ; + $i{description_workings_event} = "" unless $i{description_workings_event} ; + $i{operator_workings_event} = "" unless $i{operator_workings_event} ; + $i{remarks_workings_event} = "" unless $i{remarks_workings_event} ; + $i{supplier_workings_event} = "" unless $i{supplier_workings_event} ; + $i{ref_nr_workings_event} = "" unless $i{ref_nr_workings_event} ; + $i{qty_workings_event} = "" unless $i{qty_workings_event} ; + $i{amount_usd_workings_event} = "" unless $i{amount_usd_workings_event} ; + $i{amount_workings_event} = "" unless $i{amount_workings_event} ; + $i{vat_workings_event} = "" unless $i{vat_workings_event} ; + +} #------------------------------------------------------------------------------------------ + +sub process_multi_select { + + my ($quote_accepted,$quote_rejected,$quote_cancelled) = @_ ; + + local @venueids = split(/\,/,$i{venueids}) ; + my $venueids = join(",",@venueids) ; + $venueids =~ s/\s//g; # remove white space + $ignore{venueids} = 1 ; + $i{venue_ids} = $venueids ; + $i{venue_ids} = 0 unless $i{venue_ids} ; + + $ignore{eventsoperatorallocated} = 1 ; + $i{events_operator_allocated} = $i{eventsoperatorallocated} ; + $i{events_operator_allocated} =~ s/\,/\;/g ; + $i{events_operator_allocated} =~ s/\s//g; # remove white space + + $i{sport_type_ids} = $i{sporttypeids} ; + $ignore{sporttypeids} = 1 ; + $i{sport_type_ids} =~ s/\s//g; # remove white space + +} #------------------------------------------------------------------------------------------ + +sub duplicate { + + unless ($i{id}) { + $error = qq~NO ID~ ; + return ; + } + + my $demo_orig_id = $i{id} ; + + &db_min_copy($table,$i{id}) ; + + my $demo_copy_id = $i{id} ; + + &db_min_ro('event_quotes','1,id',"demo_id='$demo_orig_id'","",1) ; + + my $orig_event_id = $db{event_quotes}{1}{id} ; + + $i{id} = $orig_event_id ; + + &db_min_copy('event_quotes',$db{event_quotes}{1}{id}) ; + + my $event_copy_id = $i{id} ; + + $i{id} = $orig_event_id ; + + &db_min_copy('event_quotes_min',$orig_event_id) ; + + my %ii = %i ; + + %i = () ; + + $i{demo_id} = $demo_copy_id ; + + &db_min_upd('event_quotes',"id='$event_copy_id'") ; + + %i = () ; + + $i{quote_nr} = $event_copy_id ; + + &db_min_upd('event_quotes_min',"id='$event_copy_id'") ; + + %i = %ii ; + + $i{id} = $demo_orig_id ; + +} #------------------------------------------------------------------------------------------ + +sub delete { + + unless ($i{id}) { $error = uc "NO ID" ; return ; } + + &db_min_ro('event_quotes','1,id',"demo_id = '$i{id}'",'','1') ; + + my $event_delete_id = $db{event_quotes}{1}{id} ; + + &db_min_delete('demos',"`id`='$i{id}'") ; + &db_min_delete('event_quotes',"`id`='$event_delete_id'") ; + &db_min_delete('event_quotes_min',"`id`='$event_delete_id'") ; + +} #------------------------------------------------------------------------------------------ + +sub process_upload_ifields { + + foreach (keys %uploads_file) { $i{$_} = $uploads_file{$_} ; $ignore{$_} = '' ; } + +} #------------------------------------------------------------------------------------------ + +sub set_default_i_vals { + +} #---------------------------------------------------------------------------------------- + +sub list_screen { + + &db_min_ro('event_type_details','id,name','','','') ; + &db_min_ro('event_quotes_categories','id,category','','','') ; + &db_min_ro('event_systems','id,name,description,system_type','','','') ; + &db_min_ro('clubs','id,name','','','') ; + &db_min_ro('cities','id,city,province','','','') ; + + &db_min_ro('users','id,username,name,email','','','') ; + foreach my $_id (keys %{$db{users}}) { + $username{$_id} = $db{users}{$_id}{username} ; + $name{$_id} = $db{users}{$_id}{name} ; + $email{$_id} = $db{users}{$_id}{email} ; + } + + &db_min_ro('sport_types','*','','','') ; + + &db_min_ro('organisations','id,name','','','') ; + foreach my $_id (keys %{$db{organisations}}) { $organisation{$_id} = $db{organisations}{$_id}{name} ; } + + if ($iaction eq 'completed' or $i{options} eq 'completed') { push @report_sql, "q.quote_completed='1'" ; } + if ($iaction eq 'accepted' or $i{options} eq 'accepted') { push @report_sql, "q.quote_accepted='1'" ; } + if ($iaction eq 'rejected' or $i{options} eq 'rejected') { push @report_sql, "q.quote_rejected='1'" ; } + if ($iaction eq 'closed' or $i{options} eq 'closed') { push @report_sql, "(q.quote_cancelled='1' OR (q.quote_expiry<'$now_year-$now_mm-$now_dd' AND q.quote_accepted<>'1'))" ; } + if ($iaction eq 'pending' or $i{options} eq 'pending') { push @report_sql, "q.quote_pending='1'" ; } + if ($iaction eq 'list' or $i{options} eq 'list') { push @report_sql, "q.quote_cancelled<>'1'" ; } + + my $t1 = 'event_quotes'; + my $t2 = 'cities' ; + my $t3 = 'customers' ; + my $t4 = 'regions' ; + my $t5 = 'demos' ; + my $t6 = 'event_types' ; + my $t7 = 'demo_tenants' ; + + our $tables = "$t1,$t2,$t3,$t4,$t5,$t6,$t7" ; + + if ($is_schools_manager || $is_operator) { + @report_sql_or = () ; + foreach $_reg_id (keys %{$glob_regids{$userid}}) { + push @report_sql_or, "q.region_id = '$_reg_id'" + } + my $sql_or = join(' OR ',@report_sql_or) ; + push @report_sql, "($sql_or)" if $sql_or ; + push @report_sql, "(q.quote_created='1')" if $is_schools_manager ; + # push @report_sql, "(q.user_id='$userid')" if $is_schools_manager ; + push @report_sql, "(q.quote_accepted='1')" if $is_operator && !$i{options} ; + } + + push @report_sql, "(q.quote_completed <> '1')" if $iaction eq 'list' ; + push @report_sql, "(q.demo_id <> '0')" if $iaction eq 'list' ; + + my $srch_where_sql = join(' AND ', @report_sql) ; my $sql_where = ($srch_where_sql) ? "WHERE $srch_where_sql" : '' ; + + &db_min_raw(" + SELECT + q.id AS 'quote_id', + q.quote_nr, + q.sport_type_ids, + q.organisation_ids, + q.date_from, + q.date_to, + q.ref, + q.qty, + q.quote_date, + q.activetab, + q.user_id, + q.operator_ids, + q.event_system_id_multiple, + q.club_ids, + q.demo_id, + q.quote_accepted, + q.quote_pending, + q.quote_cancelled, + q.quote_completed, + q.quote_created, + q.quote_rejected, + et.name AS 'event_type', + t.name AS 'customer', + y.city, + y.province, + r.code AS 'reg_code', + r.name AS 'region', + dt.name AS 'tenant', + demo.location_id AS 'location_id', + demo.events_operator_allocated + FROM $t1 q + LEFT JOIN $t2 y ON q.city_id = y.id + LEFT JOIN $t3 t ON q.quote_to = t.id + LEFT JOIN $t4 r ON q.region_id = r.id + LEFT JOIN $t5 demo ON q.demo_id = demo.id + LEFT JOIN $t6 et ON q.type = et.id + LEFT JOIN $t7 dt ON demo.tenant_id = dt.id + $sql_where ; + "); + + foreach $row (@$rows_array_ref) { + for (0 .. $col_cnt){ + # &common_debug("[$_] $col_name{$_} -> @$row[$_]") ; + $db{$tables}{@$row[0]}{$col_name{$_}} = @$row[$_] ; + } + } + + # &tab_hash ; # load for PDF links + "e_list ; # load for PDF links + + if ($iaction eq 'update' or $iaction eq 'save'){ + &common_min_extra_crumb("list-$lcpage\s","List $ucfirstpage\s") ; + } + + our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +} #------------------------------------------------------------------------------------------ + +sub quote_list { + + # our @sql_col_display = ("nr","date","customer","user","event","venue","location","sports_type","date_from","date_to","days","type") ; + # our @sql_col_display = ("nr","event_start","event_end","date_added","customer","user","event","venue","location","sports_type","days","type") ; + + our @col_display_excel = () ; our @sql_col_display = () ; + + if ($usertype eq 'support') { + @sql_col_display = ("nr","event_start","days","event","location","sport","system_name","club_names","operators") ; + # @col_display_excel = @sql_col_display ; + } else { + @sql_col_display = ("nr","event_start","event_end","days","date_added","customer","event","venue","location","sport","tenant","operators") ; + if ($userid eq '24') { + # if ($glod_user_level > 3) { + push @sql_col_display, "amount" ; + push @sql_col_display, "invoice_nr" ; + } + # @col_display_excel = ("nr","event","event_start","event_end","days","type_of_system","system_details","system_name","sport_type","cities","region","venue","club_names","operators","client","poc_name","poc_contact_nr","category_1","category_1_details","category_2","category_2_details","format_of_title") ; + } + + @col_display_excel = @sql_col_display ; + + push @sql_col_display, "" ; + + &report_xlsx_export_header("Demos",'demos') ; + + my @month_fullname = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") ; # if ($i{export_to_excel}) { &report_xls_export_header("Event Quotes",'event_quotes') ; } + my @day_of_week_text = ("", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") ; + + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) { + + next unless $id ; + + my $quote_expiry = $db{$tables}{$id}{quote_expiry} ; $quote_expiry =~ s/\-//iog ; + my $invoice_nr = $db{$tables}{$id}{invoice_nr} ; + our $quote_accepted = $db{$tables}{$id}{quote_accepted} ; + our $quote_pending = $db{$tables}{$id}{quote_pending} ; + our $quote_cancelled = $db{$tables}{$id}{quote_cancelled} ; + our $quote_completed = $db{$tables}{$id}{quote_completed} ; + our $quote_created = $db{$tables}{$id}{quote_created} ; + our $quote_rejected = $db{$tables}{$id}{quote_rejected} ; + my $demo_completed = $db{$tables}{$id}{demo_completed} ; + my @cat_details = split('\|;\|',$db{$tables}{$id}{category_details}) ; + + if ($usertype eq 'support') { + next unless $quote_accepted && !$quote_completed ; + } + + $print_tbody .= qq~~ ; + + $xlsxcol=0; + + my $quote_nr = $db{$tables}{$id}{quote_nr} ; +# ("nr","event_start","event_end","days","date_added","customer","event","venue","location","sport","type","operators") + foreach (@sql_col_display) { + + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$tables}{$id}{$_} ; + my $align = qq~ class="dt-center"~ ; + my $nowrap = '' ; + my $val_xlsx = '' ; + my $formating = $format_event_data_2 ; + + if ($_ eq 'event_end') { + my $sort_val = $db{$tables}{$id}{date_to} =~ s/[\-:\s]//gr; + $val_xlsx = &common_min_date_as_string(substr($db{$tables}{$id}{date_to},0,16)) ; + $val = qq~$sort_val~ . $val_xlsx ; $align = qq~ class="dt-center"~ ; $nowrap = 'nowrap' ; + } elsif ($_ eq 'event_start') { + my $sort_val = $db{$tables}{$id}{date_from} =~ s/[\-:\s]//gr; + $val_xlsx = &common_min_date_as_string(substr($db{$tables}{$id}{date_from},0,16)) ; + $val = qq~$sort_val~ . $val_xlsx ; + # my ($dy,$dm,$dd,$th,$tm,$ts) = &common_min_split_sql_date_time($db{$tables}{$id}{date_from}) ; my $sccyymmddhrmnsc = $dy . $dm . $dd . $th . $tm . $ts ; $val = "$sortprefix$sccyymmddhrmnsc" . substr($db{$tables}{$id}{date_from},0,16) ; + $nowrap = 'nowrap' ; + } elsif ($_ eq 'event') { + $val = $db{$tables}{$id}{ref} ; + # $val_xlsx = $val ; + $nowrap = '' ; + } elsif ($_ eq 'customer') { + $nowrap = 'nowrap' ; + $val = "***PLEASE SELECT A CUSTOMER!!!***" unless $val ; + # $val_xlsx = $val ; + } elsif ($_ eq 'date_added') { + my $sort_val = $db{$tables}{$id}{quote_date} =~ s/[\-:\s]//gr; + $val_xlsx = &common_min_date_as_string($db{$tables}{$id}{quote_date}) ; + $val = qq~$sort_val~ . $val_xlsx ; + $val = qq~$val~ ; + $nowrap = 'nowrap' ; + } elsif ($_ eq 'curr') { + $val = $db{$tables}{$id}{currency} ; + } elsif ($_ eq 'location') { + # $val = ($db{$tables}{$id}{city} & $db{$tables}{$id}{reg_code}) ? "$db{$tables}{$id}{city}, $db{$tables}{$id}{reg_code}" : ($db{$tables}{$id}{city}) ? $db{$tables}{$id}{city} : $db{$tables}{$id}{reg_code} ; + $nowrap = 'nowrap' ; + $val = ($db{$tables}{$id}{location_id} eq '1') ? "In Country" : ($db{$tables}{$id}{location_id} eq '2') ? "Out of Country" : "" ; + } elsif ($_ eq 'country_id') { + $val = $db{$tables}{$id}{country} ; + } elsif ($_ eq 'days') { + $val = $db{$tables}{$id}{qty} ; + # $val_xlsx = $val ; + } elsif ($_ eq 'type') { + my $txt = uc substr($db{$tables}{$id}{event_type},0,1) ; + $val_xlsx = $db{$tables}{$id}{event_type} ; + $val = qq~$txt~ if $val_xlsx ; + $nowrap = 'nowrap' ; + } elsif ($_ eq 'tenant') { + $val = $db{$tables}{$id}{tenant} ; + $nowrap = 'nowrap' ; + } elsif ($_ eq 'amount') { + my $ttl = sprintf("%0.2f",($db{$tables}{$id}{grand_total})) ; + $val = &common_commify($ttl) ; + } elsif ($_ eq 'system_name') { + $val = join("
    ", map { "$db{event_systems}{$_}{name} [$db{event_systems}{$_}{description}]" } split(/\;/,$db{$tables}{$id}{event_system_id_multiple})) ; + } elsif ($_ eq 'club_names') { + $val = join("
    ", map { "$db{clubs}{$_}{name}" } split(/\;/,$db{$tables}{$id}{club_ids})) ; + } elsif ($_ eq 'operators') { + $val = '' ; my $op_cnt = 0 ; my $op_cnt_2 = 0 ; + my %seen_op_id = () ; + # my $ops_orig = $db{$tables}{$id}{operator_ids} ; + $db{$tables}{$id}{operator_ids} =~ s/\,/\;/g ; + my @op_ids = split(/\;/,$db{$tables}{$id}{events_operator_allocated} . ';' . $db{$tables}{$id}{operator_ids}) ; + my @system_ids = split(/\;/,';'.$db{$tables}{$id}{event_system_id_multiple}) ; + my @club_ids = split(/\,/,';'.$db{$tables}{$id}{club_ids}) ; + $valxlsx = '' ; + for my $op_id (@op_ids) { + $op_cnt_2++ ; + next if $seen_op_id{$op_id} || !$op_id ; + $seen_op_id{$op_id} = 1 ; + if (($system_ids[$op_cnt_2-1] || $club_ids[$op_cnt_2-1] && $op_cnt_2 > 1) || $op_cnt_2 == 1) { + $op_cnt++; + $valxlsx .= qq~$name{$op_id};~ ; + } + } + chop $valxlsx if $valxlsx ; + if ($valxlsx) { + $valxlsx =~ s/\;/\
    /g ; + # $val = qq~~ if $val ; + $glyph_icon = ($op_cnt > 1) ? qq~~ : qq~~ ; + $val = qq~$glyph_icon~ ; + } + $db{$tables}{$id}{operator_ids} = $ops_orig ; + } elsif ($_ eq 'venue') { + $nowrap = '' ; + $val = join("
    ", map { $organisation{$_} } split(/\,/,$db{$tables}{$id}{organisation_ids})) ; + } elsif ($_ eq 'sport') { + $val = join("
    ", map { $db{sport_types}{$_}{name} } split(/\,/,$db{$tables}{$id}{sport_type_ids})) ; + } elsif ($_ eq 'nr') { + $sort_val = sprintf("%06d",$db{$tables}{$id}{demo_id}) ; + $sort_val = ($demo_completed) ? qq~4~ : ($quote_accepted) ? qq~5~ . $sort_val : ($quote_completed) ? qq~4~ . $sort_val : ($quote_pending) ? qq~3~ . $sort_val : ($quote_rejected) ? qq~2~ . $sort_val : ($quote_cancelled) ? qq~1~ . $sort_val : qq~0~ . $sort_val ; + + if ($quote_completed) { + $formating = $format80 ; + } elsif ($quote_accepted) { + $formating = $format77 ; + } elsif ($quote_rejected) { + $formating = $format102 ; + } elsif ($quote_cancelled) { + $formating = $format81 ; + } elsif ($quote_pending) { + $formating = $format79 ; + } + + my $tt = qq~data-toggle="tooltip" data-placement="right" data-title="$tt_txt"~; + + $val_xlsx = $db{$tables}{$id}{demo_id} ; + + $val = qq~$sort_val~ ; + # $val .= qq~$db{$tables}{$id}{demo_id}~ ; + + # my $demo_id = $db{$tables}{$id}{id} ; + # $db{$tables}{$val_xlsx}{id} = $db{$tables}{$id}{demo_id} ; + + $val .= &common_min_get_event_quote_button($val_xlsx,$tables,'demos') ; + $val .= qq~~ ; + + # $db{$tables}{$val_xlsx}{id} = $demo_id ; + + } + + $val_xlsx = $val if $val && !$val_xlsx ; + + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$formating) ; + $xlsxcol++ ; + + $print_tbody .= qq~$val~ ; + } + $xlsxrow++ ; + + my $start_date = substr($db{$tables}{$id}{date_from},0,10); + my $end_date = substr($db{$tables}{$id}{date_to},0,10); + # my @event_dates = () ; + + my $year = substr($db{$tables}{$id}{date_from}, 0, 4) ; + my $month = substr($db{$tables}{$id}{date_from}, 5, 2) ; + my $day = substr($db{$tables}{$id}{date_from}, 8, 2) ; + + my $year_end = substr($db{$tables}{$id}{date_to}, 0, 4 ) ; + my $month_end = substr($db{$tables}{$id}{date_to}, 5, 2 ) ; + my $day_end = substr($db{$tables}{$id}{date_to}, 8, 2 ) ; + + my $row_count = 0; + # for my $event_date (sort @event_dates) { + $xlsxcol = 0 ; + $row_count++ ; + + my $quote_nr = $quote_nr ; $quote_nr =~ s/'//iog; unless ($quote_nr) { $quote_nr = $id ; } + my $edit_butt = qq~~ ; + my $delete_butt = qq~~ ; + + my $copy_butt = qq~~ ; + + my %emailed_op_ids = () ; my $all_op_ids = 1 ; my $cnt_op_ids = 0 ; + foreach my $op_id (split(/\;/,$db{$tables}{$id}{emailed_op_ids})) { + $emailed_op_ids{$op_id} = 1 ; + } + + foreach my $op_id2 (split(/\,/,$db{$tables}{$id}{operator_ids})) { + $all_op_ids = 0 if $op_id2 and not $emailed_op_ids{$op_id2} ; + $cnt_op_ids++ if $op_id2 ; + } + + if ($all_op_ids and $cnt_op_ids) { + $trigger_jquery_raw .= qq~ + \$("#email_$id").css({ + "background-color": "lightgrey", + "border-color": "lightgrey" + }); + ~ ; + } + + if ($glod_user_level < 3) { + $delete_butt = '' ; + if ($quote_completed || $quote_cancelled || $quote_rejected) { + $edit_butt = '' ; + } + } + + $edit_butt = qq~$edit_butt ~ if $edit_butt ; + $copy_butt = qq~$copy_butt ~ if $copy_butt ; + $delete_butt = qq~$delete_butt ~ if $delete_butt ; + $pdf_butt = qq~$pdf_butt ~ if $pdf_butt ; + $email_butt = qq~$email_butt ~ if $email_butt ; + + if ($quote_created and not $quote_completed and not $quote_accepted) { + $pdf_butt = qq~~ ; $email_butt = qq~~ ; + } + + $print_tbody .= qq~ $edit_butt$copy_butt$delete_butt$pdf_butt$email_butt~ ; + } + + $worksheet{$ws}->set_column(0,0,10) ; + $worksheet{$ws}->set_column(1,1,50) ; + $worksheet{$ws}->set_column(2,3,20) ; + $worksheet{$ws}->set_column(4,4,10) ; + $worksheet{$ws}->set_column(5,10,30) ; + $worksheet{$ws}->set_column(11,11,75) ; + $worksheet{$ws}->set_column(12,21,30) ; + + &report_xlsx_export_footer('L',15,'demos') ; + + if ($usertype eq 'support') { + $fnsortcol = 1 ; # start date + $fnsortorder = 'asc' ; + } + + &common_min_extra_crumb("filter-$lcpage\s","Search Screen") if $glod_user_level > 3 ; + +} #------------------------------------------------------------------------------- + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub add_db_fields { + + &hidden_fields ; + $hidden{id} = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &hidden_fields ; + $hidden{id} = 1 ; + + # $readonly{ref} = 'READONLY' ; + +} #------------------------------------------------------------------------------------------ + +sub view_db_fields { + + &hidden_fields ; + $hidden{id} = 1 ; + $label{ref} = 1 ; + $label{qty} = 1 ; + $label{date_from} = 1 ; + $label{date_to} = 1 ; + $label{sport_type_ids} = 1 ; + $label{region_id} = 1 ; + $label{city_id} = 1 ; + $label{organisation_ids} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub hidden_fields { + + $ignore{custom_selected_region} = 1 ; + $ignore{custom_selected_country} = 1 ; + $ignore{region_id} = 1 ; + $ignore{iaction} = 1 ; + $ignore{name} = 1 ; + $ignore{date_from} = 1 ; + $ignore{date_to} = 1 ; + $ignore{event_system_id_multiple} = 1 ; + $ignore{club_ids} = 1 ; + $ignore{operator_ids} = 1 ; + $ignore{venue_ids} = 1 ; + $ignore{sport_type_ids} = 1 ; + $ignore{qty} = 1 ; + $ignore{slip} = 1 ; + $ignore{iattachslip} = 1 ; + $ignore{notes} = 1 ; + $ignore{office_notes} = 1 ; + $ignore{email} = 1 ; + $ignore{tel} = 1 ; + $ignore{address} = 1 ; + $ignore{contact_name} = 1 ; + $ignore{demo_completed} = 1 ; + $ignore{demo_accepted} = 1 ; + $ignore{demo_rejected} = 1 ; + $ignore{demo_cancelled} = 1 ; + $ignore{demo_pending} = 1 ; + $ignore{currency} = 1 ; + $ignore{roe} = 1 ; + $ignore{country_id} = 1 ; + $ignore{quote_to} = 1 ; + $ignore{quote_nr} = 1 ; + $ignore{quote_date} = 1 ; + $ignore{custom_set} = 1 ; + # $ignore{quote_to} = 1 ; + # $ignore{datetime} = 1 ; + # $ignore{ref} = 1 ; + # $ignore{times_from} = 1 ; + # $ignore{last_update} = 1 ; + + $ignore{quote_accepted} = 1 ; + $ignore{quote_pending} = 1 ; + $ignore{quote_cancelled} = 1 ; + $ignore{quote_completed} = 1 ; + $ignore{quote_created} = 1 ; + $ignore{quote_rejected} = 1 ; + + + $required{quote_nr} = 1 ; + $readonly{quote_nr} = 'READONLY' ; + $required{quote_to} = 1 ; + $required{region_id} = 1 ; + $required{country_id} = '' ; + $required{currency} = 1 ; + $required{roe} = 1 ; + + for my $event_day (1 .. 20) { + + $ignore{"time_from_$event_day"} = 1 ; + $ignore{"time_to_$event_day"} = 1 ; + $ignore{"day_$event_day"} = 1 ; + + } + + $required{currency} = 1 ; + $required{roe} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + + our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + + &select_opts('') ; + + $db{$table}{''}{quote_nr} = &db_min_get_max($table,'id') ; + $db{$table}{''}{qty} = 1 ; + + our $savjqy = 1 ; # incorporate jquery into the save event to accommodate the multiple chosen options + + &add_db_fields ; + + &build_boxes_edit ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes_edit { + + my ($id) = @_ ; + + &edit_db_fields ; + + # $allow_deselect{"demo_type_id"} = 1 ; + # $allow_deselect{"part_number"} = 1 ; + # $allow_deselect{"customer_id"} = 1 ; + # $allow_deselect{"rma_status_id"} = 1 ; + + our %cntxt = () ; + + $cntxt{1} = 'one' ; + $cntxt{2} = 'two' ; + $cntxt{3} = 'three' ; + + my %tabnames = () ; + + $tabnames{1} = 'Admin' ; + $tabnames{2} = 'Demo Details' ; + $tabnames{3} = 'Expenses' ; + + foreach our $col (keys %required) { + &common_min_forms_required ; + } + + $print_box_content_rows .= &common_min_forms_start($table) ; + + $print_box_content_rows .= qq~ +
    +
    ~ ; + &build_boxes_top($id); + $print_box_content_rows .= qq~ +
    +
    + ~ ; + + $print_box_content_rows .= qq~ +
    +
    + ~ ; + + $print_box_content_rows .= qq( + +
    + ); + + foreach (sort {$a<=>$b} keys %cntxt) { + + my $active = ($_==1) ? 'active' : '' ; + + my $colsleft = 12 ; my $showright = '' ; + + if ($cntxt{$_} eq 'one') { + $colsleft = 6 ; + $showright = 1 ; + } + + $print_box_content_rows .= qq~ +
    ~; + $print_box_content_rows .= qq~ +
    ~ ; + $print_box_content_rows .= qq~ +
    ~ ; + &build_boxes_left($id,$_,1); + $print_box_content_rows .= qq~ +
    ~ ; + if ($showright) { + $print_box_content_rows .= qq~ +
    ~ ; + &build_boxes_right($id,$_); + $print_box_content_rows .= qq~ +
    ~ ; + } + + $print_box_content_rows .= qq~ +
    ~ ; + $print_box_content_rows .= qq~ +
    ~ ; + + } + + $print_box_content_rows .= qq~ +
    ~ ; + # &build_boxes_right($id); + $print_box_content_rows .= qq~ +
    +
    +
    ~ ; + + $print_box_content_rows .= qq~~ ; + + $print_box_content_rows .= ($id) ? &common_min_forms_end($id,$table,'update',$skip) : &common_min_forms_end($id,$table,'save',$skip) ; + + my $all_select_ids_str = join(",",@all_select_ids) ; + + $trigger_jquery_raw .= qq~\$("#demos-form select[id^='select']:not(#selectCurrency,#selectQuote_to,#selectCountry_id,#selectTenant_id)").chosen({ allow_single_deselect: true });~ ; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_left { + + my ($id,$tab,$demo_page) = @_ ; + + if ($tab == 1) { # Cusotmer Details + &event_tabs_build_qt_left($id,$tab,'',$demo_page) + + } elsif ($tab == 2) { + + our ($lcol,$fcol) = &common_min_columns(2,4) ; + + my $sec = '_demo_details' ; + + my ($sec_name,$sec_cnt,$sec_col) = &tab_sec_det($sec) ; + + $add_form_fields = '' ; + + $preferred_title{quote_to} = "Client" ; + $add_form_fields .= &common_min_form_select('quote_to',$db{$table}{$id}{quote_to},'') ; + + $add_form_fields .= qq~~ ; + $add_form_fields .= qq~~ ; + + # $dlg{quote_to} = qq~ + # + # ~ ; + + $trigger_jquery_raw .= qq~ + + let map_region_to_country = {} ; + + const \$clientSelect = \$("#selectQuote_to") ; + const \$countrySelect = \$("#selectCountry_id") ; + const \$regionSelect = \$("#selectRegion_id") ; + const \$venuesSelect = \$("#selectVenue_ids") ; + + let prev_region = \$regionSelect.val() ; + let prev_country = \$countrySelect.val() ; + + const updateChosen = \$el => \$el.trigger("chosen:updated"); + + const getClientId = () => { + const val = \$clientSelect.val(); + return val ? val.toString().split(":")[0] : null; + } ; + + const fetchJSON = async url => { + try { + const res = await fetch(url); + if (!res.ok) throw new Error(`Request failed: \${res.status}`); + return await res.json(); + } catch (err) { + console.error("Fetch error:", err); + return []; + } + }; + + const populateSelect = (\$field,json_list,getLabel,defaultSelected = () => "") => { + let isSelected ; + if (typeof defaultSelected === "function") { + isSelected = defaultSelected; + } else if (Array.isArray(defaultSelected)) { + isSelected = data => defaultSelected.includes(data.id) ? "selected" : ""; + } else { + isSelected = data => data.id == defaultSelected ? "selected" : ""; + } + + json_list.forEach(data => { + \$field.append(``); + }); + + updateChosen(\$field); + return json_list.length; + }; + + const getInputValue = name => \$(`input[name='\${name}']`).val(); + + const getMultiSelectSplitNumbers = (\$field) => { + + let field_ = \$field.chosen().val() ; + field_ = String(field_); + return field_.split(',') ; + + } ; + + const clearSelect = (\$el) => { + \$el.empty(); + \$el.append(``).trigger("chosen:updated"); + }; + + async function update_region_drop_down_from_country (countryId) { + + clearSelect(\$regionSelect) ; + + const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}` ; + + const regions = await fetchJSON(regionUrl); + + for (const data of regions) { + map_region_to_country[data.id] = countryId ; + } + + const regionCount = populateSelect(\$regionSelect, regions, r => r.code ? `\${r.name} [\${r.code}]` : r.name , "") ; + + // let selectedRegionId = 0 ; + + if (regionCount === 1) { + \$regionSelect.val(regions[0].id) + } else if (regionCount === 0 && \$countrySelect.val()) { + // selectedRegionId = 13 ; + \$regionSelect.append(``) ; + } + updateChosen(\$regionSelect) ; + + const regionId = \$regionSelect.val() ; + + if (regionId != prev_region) { + await update_cities_from_region_and_country(regionId,countryId) ; + await update_venues_from_region_and_country(regionId,countryId) ; + } + prev_region = regionId ; + + } + + async function update_cities_from_region_and_country (regionId,countryId="") { + + } + + async function update_venues_from_region_and_country (regionId,countryId="") { + + let splittedNumbers2 = getMultiSelectSplitNumbers(\$venuesSelect) ; + clearSelect(\$venuesSelect) ; + url = `$useropts{scripts}/get/get_venues_from_region.pl?region_id=\${regionId}&country_id=\${countryId}` ; + const venues = await fetchJSON(url); + const venuesCount = populateSelect(\$venuesSelect, venues, r => r.venue_name , r => splittedNumbers2.includes(r.id) ? "selected" : "" ) ; + // if (venuesCount == 1) \$venuesSelect.val(venues[0].id).trigger("chosen:updated") ; + + } + + \$clientSelect.change( async function() { + + dispCustomer() ; + let clientId = getClientId() ; + + // __________________________________________________________________ update_country_region_from_client + + const hasCustomRegion = !!getInputValue('custom_selected_region'); + const hasCustomCountry = !!getInputValue('custom_selected_country'); + + if (clientId) { + let url1 = `$useropts{scripts}/get/get_region_country_from_client.pl?client_id=\${clientId}` ; + console.log("1 clientId : "+clientId) ; + + if (!hasCustomRegion || !hasCustomCountry) { + + const data = await fetchJSON(url1); + data.forEach(async ({region_id,country_id}) => { + + if (!hasCustomCountry && country_id && country_id != '0') { + + \$countrySelect.val(country_id).trigger("chosen:updated") ; + if (!hasCustomRegion) await update_region_drop_down_from_country(country_id) ; + if (!region_id || region_id == '0') { + await update_cities_from_region_and_country(0,country_id) ; + await update_venues_from_region_and_country(0,country_id) ; + } + } + + if (!hasCustomRegion && region_id && region_id != '0') { + \$regionSelect.val(region_id).trigger("chosen:updated") ; + await update_cities_from_region_and_country(region_id) ; + await update_venues_from_region_and_country(region_id) ; + } + + // if (!hasCustomCountry && country_id && country_id != '0') + // if (!hasCustomRegion && region_id && region_id != '0') \$regionSelect.val(region_id).trigger("chosen:updated") ; + + }); + } + } else { + if (!hasCustomCountry) \$countrySelect.val("").trigger("chosen:updated") ; + if (!hasCustomRegion) { + \$regionSelect.val("").trigger("chosen:updated") ; + let region_option_count = \$regionSelect.find("option").length ; + if (region_option_count <= 2) { + await update_region_drop_down_from_country(clientId) ; + } + } + } + + // __________________________________________________________________ update_country_region_from_client + + }) ; + + \$countrySelect.change( async function() { + + \$("input[name='custom_selected_country']").val("1") ; + await update_region_drop_down_from_country(\$countrySelect.val()) ; + + }) ; + + \$regionSelect.change( async function() { + + \$("input[name='custom_selected_region']").val("1") ; + \$("input[name='custom_selected_country']").val("1") ; + const regionId = \$regionSelect.val() ; + await update_country_from_region(regionId,1) ; + await update_cities_from_region_and_country(regionId) ; + await update_venues_from_region_and_country(regionId) ; + + }); + + async function update_country_from_region (regionId,update_country=0) { + + if (map_region_to_country[regionId] || regionId == '13') { + \$countrySelect.val(map_region_to_country[regionId]).trigger("chosen:updated") ; + } else if (!\$("input[name='custom_selected_country']").val() || update_country) { + const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=®ion_id=\${regionId}`; + console.log("update_country_from_region lookupUrl : "+lookupUrl) ; + const regionMeta = await fetchJSON(lookupUrl); + const { country_id } = regionMeta[0] ?? {} ; + if (country_id) { + map_region_to_country[regionId] = country_id; + \$countrySelect.val(country_id).trigger("chosen:updated"); + } + } + } + + ~ ; + + $preferred_title{name} = "Demo Name" ; + + $add_form_fields .= &common_min_form_input('name',$db{$table}{$id}{name}) ; + + $opts{demo_type_id} = qq~~ ; + if ($db{$table}{$id}{demo_type_id}) { + $opts{demo_type_id} =~ s/value="$db{$table}{$id}{demo_type_id}"/value="$db{$table}{$id}{demo_type_id}" SELECTED/g ; + } + + # $allow_deselect{demo_type_id} = 1 ; + # $allow_deselect{location_id} = 1 ; + # $allow_deselect{events_operator_required} = 1 ; + # $allow_deselect{events_operator_allocated} = 1 ; + # $allow_deselect{calibrator_required} = 1 ; + + $add_form_fields .= &common_min_form_select('demo_type_id',$db{$table}{$id}{demo_type_id}) ; + + $add_form_fields .= &common_min_form_textarea('brief_description',$db{$table}{$id}{brief_description}) ; + + $preferred_title{date_from} = "Demo Date/Time From" ; + $preferred_title{date_to} = "Demo Date/Time To" ; + + my $current_day_of_week = Day_of_Week($now_year,$now_mm,$now_dd) ; + + my $delta_days = 6 - $current_day_of_week ; + $delta_days = 7 unless $delta_days ; + $delta_days = 6 if $delta_days < 0 ; + + my ($def_year,$def_mon,$def_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,$delta_days) ; + $def_mon = sprintf("%02d",$def_mon) ; + $def_day = sprintf("%02d",$def_day) ; + + $db{$table}{$id}{date_from} = "$def_year-$def_mon-$def_day 08:00:00" unless $db{$table}{$id}{date_from} ; + $db{$table}{$id}{date_to} = "$def_year-$def_mon-$def_day 17:00:00" unless $db{$table}{$id}{date_to} ; + + $add_form_fields .= &common_min_form_datetimepicker('date_from',$db{$table}{$id}{date_from}) ; + + $add_form_fields .= &common_min_form_datetimepicker('date_to',$db{$table}{$id}{date_to}) ; + + $preferred_title{qty} = 'Actual Days' ; $dont_end_row{qty} = 1 ; + + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { $readonly{qty} = "READONLY" ; } + + my @times_from = split(/\;/,";$db{$table}{$id}{times_from}") ; + my @times_to = split(/\;/,$db{$table}{$id}{times_to}) ; + + my @default = () ; my $saved_time_from = qq~~ ; my $saved_time_to = qq~~ ; + + my $year = ($db{$table}{$id}{date_from}) ? substr($db{$table}{$id}{date_from},0,4) : $now_year ; + my $month = ($db{$table}{$id}{date_from}) ? substr($db{$table}{$id}{date_from},5,2) : $now_mm ; + my $day = ($db{$table}{$id}{date_from}) ? substr($db{$table}{$id}{date_from},8,2) : $now_dd ; + + $fcol = 1 ; + + $radio_opts{event_length} = "Full Day+Half Day" ; + + my @timepicker_ids = () ; my @day_ids = () ; + + my %default_days_selected = () ; our %default_active_event_dates = () ; + + my ($year1,$month1,$day1) = split(/\-/,substr($db{$table}{$id}{date_from},0,10)); + my ($year2,$month2,$day2) = split(/\-/,substr($db{$table}{$id}{date_to},0,10)); + + our $final_day = Delta_Days($year1,$month1,$day1,$year2,$month2,$day2) + 1 ; + + our @defaut_days_active = split(/\;/,$db{$table}{$id}{days_active}) ; + + my $event_without_saved_defaults = 0 ; + + if (!$db{$table}{$id}{days_active}) { + $event_without_saved_defaults = 1 ; + for (1 .. $final_day) { + $db{$table}{$id}{days_active} .= "1;" ; + } + } + + my @default_event_length = split(/\;/,$db{$table}{$id}{event_length}) ; my %calc_default_event_length = () ; + + my @days_active = split(/\;/,$db{$table}{$id}{days_active}) ; + + my $cnt = 0 ; + # my $final_day = 0 ; + my $no_event_days_cnt = 0 ; + + my $hide_rows_1 = (substr($db{$table}{$id}{date_from},0,10) eq substr($db{$table}{$id}{date_to},0,10)) ? "style='display:none;'" : "" ; + my $hide_rows_2 = ($final_day <= 10) ? "style='display:none;'" : "" ; + + my %time_label_header_row = () ; + + $time_label_header_row{1} = qq~
    ~ ; + $time_label_header_row{2} = qq~
    ~ ; + + my $nr_of_active_days = 0 ; + + for (1 .. 20) { + + my $cnt_row = ($_ <= 10) ? 1 : 2 ; + + $default_days_selected{blank}{$_} = "SELECTED" unless $days_active[$_ - 1] ; + $default_days_selected{1}{$_} = "SELECTED" if $days_active[$_ - 1] ; + + $nr_of_active_days++ if $days_active[$_ - 1] ; + + push @timepicker_ids,"#timepickerTime_from_$_" ; + push @timepicker_ids,"#timepickerTime_to_$_" ; + push @day_ids,"#day_$_" ; + + my ($new_year,$new_month,$new_day) = ($_ > 1) ? Add_Delta_Days($year,$month,$day,$_-1) : ($year,$month,$day) ; + $new_day = sprintf("%02s",$new_day) ; + $new_month = sprintf("%02s",$new_month) ; + + # $default_active_event_dates{$_} = "$new_year-$new_month-$new_day" if $days_active[$_ - 1] ; + $default_active_event_dates{$_} = "$new_year-$new_month-$new_day" if $_ <= $final_day ; + + my $field = "time_from_$_" ; + $default[$_ - 1] = $times_from[$_ - 1] ; + $default[$_ - 1] = substr($db{$table}{$id}{date_from},11) if $db{$table}{$id}{date_from} && (!$times_from[$_ - 1] || $_ == 1) ; + my $default1 = $default[$_ - 1] ; + + $custom_style{$field} = ((!$event_without_saved_defaults && !$defaut_days_active[$_ - 1]) || $_ == 1 || ($_ > $final_day)) ? qq~display:none;~ : '' ; + # $days_time_row .= ($glod_user_level > 2) ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} ne "READONLY" || ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~ ; + $days_time_row{$cnt_row} .= ($readonly{qty} ne "READONLY") ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} eq "READONLY" && ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~; + + $trigger_jquery_raw .= qq~\$("#timepickerTime_from_1").css("display","none");~ ; + + # $default_time_from .= qq~"$_":"$default[$_ - 1]",~ ; + $saved_time_from .= qq~"$_":"$times_from[$_ - 1]",~ if $times_from[$_ - 1] ; + # $final_day = $_ if $times_from[$_ - 1] ; + $field = "time_to_$_" ; + + + $custom_style{$field} = ((!$event_without_saved_defaults && !$defaut_days_active[$_ - 1]) || $_ >= $final_day) ? qq~display:none;~ : '' ; + $default[$_ - 1] = $times_to[$_ - 1] ; + $default[$_ - 1] = substr($db{$table}{$id}{date_to},11) if $db{$table}{$id}{date_to} && (!$times_to[$_ - 1] || $_ == 6) ; + #___ + # $days_time_row_2 .= ($readonly{qty} ne "READONLY") ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($final_day >= $_ && !$custom_style{$field}) ? &common_min_form_input_col($field,$default[$_ - 1],'',0) : qq~
    ~ ; + + # $days_time_row_2 .= ($glod_user_level > 2) ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} ne "READONLY" || ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~; + $days_time_row_2{$cnt_row} .= ($readonly{qty} ne "READONLY") ? &common_min_form_timepicker_col($field,$default[$_ - 1],'',1) : ($readonly{qty} eq "READONLY" && ($final_day >= $_ && !$custom_style{$field})) ? qq~
    ~ : qq~
    ~ ; + #___ + + # if ($default_event_length[$_ - 1] eq '1' && $days_active[$_ - 1]) { + # $def_nr_of_full_days++ ; + # } elsif ($default_event_length[$_ - 1] eq '2' && $days_active[$_ - 1]) { + # $def_nr_of_half_days++ ; + # } + + if (!$db{$table}{$id}{event_length}) { + + my ($h1,$m1,$s1) = ($_ == 1 || !$times_from[$_ - 1]) ? split(/\:/,substr($db{$table}{$id}{date_from},11)) : split(/\:/,$times_from[$_ - 1]) ; + my ($h2,$m2,$s2) = split(/\:/,substr($db{$table}{$id}{date_to},11)) ; + my $time_diff = 3600*($h2-$h1) + 60*($m2-$m1) + ($s2-$s1) ; + + if ($time_diff >= 18000) { + $calc_default_event_length{$_} = 1 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_1").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_full_days++ if $default_event_length[$_ - 1] ; + } elsif ($time_diff >= 0 && $time_diff < 18000) { + $calc_default_event_length{$_} = 2 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_2").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_half_days++ if $default_event_length[$_ - 1] ; + } + + $trigger_jquery .= qq~ + \$("#day_$_").val("1") ; + \$("#day_$_").trigger("chosen:updated") ; + ~ if $_ <= $final_day && $readonly{qty} ne "READONLY" ; + + } elsif ($_ <= $final_day) { + + # $days_active[$_ - 1 + + # my ($h1,$m1,$s1) = split(/\:/,$times_from[$_ - 1]) ; + # my ($h2,$m2,$s2) = split(/\:/,$times_to[$_ - 1]) ; + # my $time_diff = 3600*($h2-$h1) + 3600*($m2-$m1) + ($s2-$s1) ; + if ($default_event_length[$_ - 1]) { + if ($default_event_length[$_-1] eq "1") { + $trigger_jquery .= qq~ + // \$("input[name='selected_$_\_event_length']").val("1") ; + \$("#radio_$_\_1").prop('checked',true) ; + ~ ; + # $def_nr_of_full_days++ ; + } elsif ($default_event_length[$_-1] eq "2") { + $trigger_jquery .= qq~ + // \$("input[name='selected_$_\_event_length']").val("2") ; + \$("#radio_$_\_2").prop('checked',true) ; + ~ ; + # $def_nr_of_half_days++ ; + } + } else { + my ($h1,$m1,$s1) = split(/\:/,substr($db{$table}{$id}{date_from},11)) ; + my ($h2,$m2,$s2) = split(/\:/,substr($db{$table}{$id}{date_to},11)) ; + my $time_diff = 3600*($h2-$h1) + 60*($m2-$m1) + ($s2-$s1) ; + + if ($time_diff >= 18000) { + $calc_default_event_length{$_} = 1 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_1").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_full_days++ ; + } elsif ($time_diff >= 0 && $time_diff < 18000) { + $calc_default_event_length{$_} = 2 ; + $trigger_jquery .= qq~ + \$("#radio_$_\_2").prop('checked',true) ; + ~ if $readonly{qty} ne "READONLY" ; + # $def_nr_of_half_days++ ; + } + } + } + + if ((!$days_active[$_ - 1] && $_ > $final_day) || ($db{$table}{$id}{days_active} == ";;;;;") || (!$days_active[$_ - 1] && $_ <= $final_day)) { + $trigger_jquery .= qq~\$("#radio_$_\_1").css("display","none") ; ~ ; + $trigger_jquery .= qq~\$("#radio_$_\_2").css("display","none") ; ~ ; + } + + $saved_time_to .= qq~"$_":"$times_to[$_ - 1]",~ if $times_to[$_ - 1] ; + + $field = "day_$_" ; + $custom_style{$field} = ($final_day < $_ || $final_day == 1) ? qq~display:none;~ : '' ; + + if ($readonly{qty} ne "READONLY") { + + $trigger_jquery .= qq~\$("#day_$_\_chosen").css("display","none");~ if $_ > $final_day || $final_day == 1 ; + + $time_label_header_row{$cnt_row} .= qq~ +
    + +
    + ~ ; + + } else { + + $time_label_header_row{$cnt_row} .= (!$default_days_selected{1}{$_}) ? qq~ +
    + ~ : qq~ +
    +
    + ~ ; + + } + } + + $event_length_rows{1} .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'',10,$final_day,"",1) ; + my $final_day_second = $final_day - 10 ; + $final_day_second = -1 if $final_day_second <= 0 ; + $event_length_rows{2} .= &common_min_form_radio_col('event_length',$db{$table}{$id}{event_length},'',10,$final_day_second,"radio_row_id_2",2) ; + + $add_form_fields .= qq~$time_label_header_row{1}
    ~ ; + $add_form_fields .= qq~
    $days_time_row{1}
    ~ ; + $add_form_fields .= qq~
    $days_time_row_2{1}
    ~ ; + $add_form_fields .= qq~$event_length_rows{1}~ ; + + $add_form_fields .= qq~$time_label_header_row{2}
    ~ ; + $add_form_fields .= qq~
    $days_time_row{2}
    ~ ; + $add_form_fields .= qq~
    $days_time_row_2{2}
    ~ ; + $add_form_fields .= qq~$event_length_rows{2}~ ; + + $db{$table}{$id}{qty} = 1 if $iaction eq 'add' ; + + # $trigger_jquery .= qq~~ ; + + # $add_form_fields .= &common_min_form_input('qty',$db{$table}{$id}{qty},'',1) ; + + # $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= qq~~ ; + + $trigger_jquery_raw .= qq~\$("#timepickerTime_to_$final_day").css("display","none");~ if $final_day ; + + my $day_ids_string = join(",",@day_ids) ; + + my $day_ids_chosen_string = join(",", map { "#day_$_\_chosen" } (1 .. $nr_of_active_days) ) ; + + $trigger_jquery .= qq~ + // \$("$day_ids_chosen_string").css("width","100%") ; + \$("#two [id^='day_']").css("width","100%") ; + ~ ; + + $trigger_jquery_raw .= qq~ + + let saved_time_from = {$saved_time_from} ; + let saved_time_to = {$saved_time_to} ; + + // \$("$day_ids_string").change( function (e) { + \$("#two [id^='day_']").change( function (e) { + + const id = this.id ; + let col_nr = get_row_nr(id) ; + + let nr_days = \$("input[name='qty']").val() ; + + let nr_of_active_days = calc_nr_of_active_days() ; + + let datesBetween ; + + let date_counter = 0 ; let dates_map = {} ; + + datesBetween = getDatesBetween(\$("input[name='date_from']").val(),\$("input[name='date_to']").val(),0) ; + for (const date of datesBetween) { + date_counter++ ; + dates_map[date_counter] = date ; + } + + let def_val = 0 ; + + let hide_this_1 = '' ; + let hide_this_2 = '' ; + + if (!\$\(this).val()) { + + \$("#timepickerTime_from_"+col_nr+"").css("display","none") ; + \$("#timepickerTime_to_"+col_nr+"").css("display","none") ; + \$("#radio_"+col_nr+"_1").css("display","none") ; + \$("#radio_"+col_nr+"_2").css("display","none") ; + nr_days = nr_days - 1 ; + + } else { + + if (col_nr != "1") { + \$("#timepickerTime_from_"+col_nr).css("display","") ; + } + \$("#radio_"+col_nr+"_1").css("display","") ; + \$("#radio_"+col_nr+"_2").css("display","") ; + if (col_nr < date_counter ) { + \$("#timepickerTime_to_"+col_nr).css("display","") ; + } + nr_days = parseInt(nr_days) + 1 ; + + } + + \$("input[name='qty']").val(nr_days) ; + + }) ; + + ~ if $readonly{qty} ne "READONLY" ; + + my $timepicker_ids_string = join(",",@timepicker_ids) ; + + # $trigger_jquery_raw .= qq~ \$("$timepicker_ids_string").datetimepicker({language:'pt-BR',pickDate:false});~ ; + + if ($readonly{qty} ne "READONLY") { + $trigger_jquery_raw .= qq~ + + function set_full_half_day (beforeUnderscore,afterUnderscore) { + + let start_time = \$("input[name='time_from_"+afterUnderscore+"']").val() ; + let end_time = \$("input[name='time_to_"+afterUnderscore+"']").val() ; + + let seconds1 = timeStringToSeconds(start_time) ; + let seconds2 = timeStringToSeconds(end_time) ; + + let diffSeconds = seconds2 - seconds1 ; + + let changed_a_full_half_day_toggle = 0 ; + if (diffSeconds >= 18000) { + if (\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + // nr_days["half"]-- ; + } + if (!\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + \$("#radio_"+afterUnderscore+"_1").prop('checked',true) ; + changed_a_full_half_day_toggle = 1 ; + // nr_days["full"]++ ; + } + } else if (diffSeconds >= 0 && diffSeconds < 18000) { + if (\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + // nr_days["full"]-- ; + } + if (!\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + \$("#radio_"+afterUnderscore+"_2").prop('checked',true) ; + changed_a_full_half_day_toggle = 1 ; + // nr_days["half"]++ ; + } + } else { + if (\$("#radio_"+afterUnderscore+"_1").is(":checked")) { + \$("#radio_"+afterUnderscore+"_1").prop('checked',false) ; + changed_a_full_half_day_toggle = 1 ; + // nr_days["full"]-- ; + } + + + if (\$("#radio_"+afterUnderscore+"_2").is(":checked")) { + \$("#radio_"+afterUnderscore+"_2").prop('checked',false) ; + changed_a_full_half_day_toggle = 1 ; + // nr_days["half"]-- ; + } + if (beforeUnderscore == 'timepickerTime_from') { + \$("input[name='time_from_"+afterUnderscore+"']").val(end_time) ; + } else if (beforeUnderscore == 'timepickerTime_to') { + \$("input[name='time_to_"+afterUnderscore+"']").val(start_time) ; + } + } + if (changed_a_full_half_day_toggle == 1) { + // changed_radio_cnt++ ; + } + + + } + + // \$("$timepicker_ids_string").datetimepicker({language:'pt-BR',pickDate:false}); + \$("#two [id^='timepickerTime_']").datetimepicker({language:'pt-BR',pickDate:false}); + + // \$("#timepickerTime_from_1").on('changeDate', function() { + // let dateString1 = \$("input[name='time_from").val() ; + // }) ; + + // \$("$timepicker_ids_string").on('changeDate', function() { + \$("#two [id^='timepickerTime_']").on('changeDate', function() { + + // const id = this.id ; + // const lastIndex = id.lastIndexOf('_'); + // const beforeUnderscore = id.substring(0,lastIndex); + // let afterUnderscore = id.substring(lastIndex+1); + // afterUnderscore = parseInt(afterUnderscore) ; + + // if (id.includes("timepickerTime_from_")) { + // saved_time_from[afterUnderscore] = \$("input[name='time_from_"+afterUnderscore+"']").val() ; + // } else if (id.includes("timepickerTime_to_")) { + // saved_time_to[afterUnderscore] = \$("input[name='time_to_"+afterUnderscore+"']").val() ; + // } + // changed_radio_cnt = 0 ; + + // set_full_half_day(beforeUnderscore,afterUnderscore) ; + + + const id = this.id ; + const lastIndex = id.lastIndexOf('_'); + const beforeUnderscore = id.substring(0,lastIndex); + let afterUnderscore = id.substring(lastIndex+1); + afterUnderscore = parseInt(afterUnderscore) ; + if (beforeUnderscore == 'from' && afterUnderscore == 1) { + + let dateString = \$("input[name='time_from").val() ; + let timePart = dateString.split(' ')[1]; + \$("input[name='time_from_1']").val(timePart) ; + return ; + } + if (beforeUnderscore == 'to') { + let dateString1 = \$("input[name='time_from").val() ; + let dateString2 = \$("input[name='time_to").val() ; + const count_dates = getDatesBetween(dateFromInput,dateToInput,1) ; + if (afterUnderscore == count_dates) { + let timePart = dateString.split(' ')[1]; + \$("input[name='time_to_"+count_dates+"']").val(timePart) ; + return ; + } + } + + set_full_half_day(beforeUnderscore,afterUnderscore) ; + + }) ; + ~ ; + } + # $trigger_jquery_raw .= qq~ + + # \$("$timepicker_ids_string").datetimepicker({language:'pt-BR',pickDate:false}); + + # ~ ; + # } + + $trigger_jquery_raw .= qq~ + + let prev_date_part_from = \$("input[name='date_from']").val() ; + prev_date_part_from = prev_date_part_from.split(' ')[0] ; + let prev_date_part_to = \$("input[name='date_to']").val() ; + prev_date_part_to = prev_date_part_to.split(' ')[0] ; + + \$('#datetimepickerDate_from,#datetimepickerDate_to').on('changeDate', function(e) { + let from_to = get_row_nr(this.id) ; + if (this.id == "datetimepickerDate_from") { + let date_new = \$("input[name='date_from']").val() ; + let time_part = date_new.split(' ')[1]; + \$("input[name='time_from_1']").val(time_part) ; + } + calc_date_diff_in_days(this.id) ; + }) ; + + function calc_date_diff_in_days (from_to) { + + let dateFromInput = \$("input[name='date_from']").val(); + let dateToInput = \$("input[name='date_to']").val() ; + + let date_part_from = dateFromInput.split(' ')[0]; + let date_part_to = dateToInput.split(' ')[0]; + + let time_part_from = dateFromInput.split(' ')[1]; + let time_part_to = dateToInput.split(' ')[1]; + + if (prev_date_part_from == date_part_from && date_part_to == prev_date_part_to) { + + changed_radio_cnt = 0 ; + + const datesBetween = getDatesBetween(dateFromInput,dateToInput,0) ; let date_counter = 0 ; + + for (const date of datesBetween) { + + date_counter++ ; + + if (date_counter > 20) { date_counter = 20 ; break ; } + + if (((!saved_time_to[date_counter] || datesBetween.length == date_counter) && from_to.includes("Date_to")) || (date_counter > 1 && !saved_time_from[date_counter] && from_to.includes("Date_from"))) { + + if (from_to.includes("Date_from")) { + \$("input[name='time_from_"+date_counter+"']").val(time_part_from) ; + } else { + \$("input[name='time_to_"+date_counter+"']").val(time_part_to) ; + } + + set_full_half_day('',date_counter) ; + + } + } + if (from_to.includes("Date_to")) { + saved_time_to[date_counter] = time_part_to ; + } else { + saved_time_from["1"] = time_part_from ; + } + + return ; + } + + prev_date_part_from = date_part_from ; + prev_date_part_to = date_part_to ; + + const date1 = new Date(dateFromInput); + const date2 = new Date(dateToInput); + + let hide_date_names = "#1" ; + + let glod_user_level = parseInt("$glod_user_level") ; + + let y1 = date1.getFullYear() ; let m1 = date1.getMonth() ; let d1 = date1.getDate() ; let y2 = date2.getFullYear() ; let m2 = date2.getMonth() ; let d2 = date2.getDate() ; + + m1 = m1 + 1 ; + if (m1 < 10) { + m1 = "0"+m1.toString() ; + } + m2 = m2 + 1 ; + if (m2 < 10) { + m2 = "0"+m2.toString() ; + } + + if ((y1 == y2 && m1 == m2 && d1 == d2) || date1 > date2) { + + if (date1 > date2 && from_to == "datetimepickerDate_from") { + let date_part_from = dateFromInput.split(' ')[0] ; + \$("#datetimepickerDate_to").datetimepicker("setDate",date_part_from+" "+time_part_to) ; + \$("#day_1_name label.control-label").text(date_part_from) ; + } else if (date1 > date2 && from_to == "datetimepickerDate_to") { + let date_part_to = dateToInput.split(' ')[0] ; + \$("#datetimepickerDate_from").datetimepicker("setDate",date_part_to+" "+time_part_from) ; + \$("#day_1_name label.control-label").text(date_part_to) ; + } + + \$("input[name='time_from_1']").val(time_part_from) ; + \$("input[name='time_to_1']").val(time_part_to) ; + + // changed_radio_cnt = 0 ; + + set_full_half_day('',1) ; + + \$("#radio_1_1").css("display",""); + \$("#radio_1_2").css("display",""); + + \$("#radio_row_id_2_1").hide() ; + \$("#radio_row_id_2_2").hide() + + if (!\$("#days_drop_downs_1").is(":hidden")) { + \$("#start_times_row_1").hide() ; + \$("#end_times_row_1").hide() ; + \$("#days_drop_downs_1").hide() ; + } + + if (!\$("#days_drop_downs_2").is(":hidden")) { + \$("#start_times_row_2").hide() ; + \$("#end_times_row_2").hide() ; + \$("#days_drop_downs_2").hide() ; + } + + let reduced_nr_of_days = 0 ; + + for (let i=2; i<=20; i++) { + + \$("#day_"+i+"_chosen").css("display","none") ; + + if (\$("#day_"+i).val()) { + \$("#day_"+i).val("") ; + \$("#day_"+i).trigger("chosen:updated") ; + \$("#radio_"+i+"_1").css("display","none") ; + \$("#radio_"+i+"_2").css("display","none") ; + } + } + + if (!\$("#day_1").val()) { + \$("#day_1").val("1") ; + \$("#day_1").trigger("chosen:updated") ; + } + \$("#inputQty").val("1") ; + + if (!\$("#days_drop_downs_1").is(":hidden")) { + \$("#days_drop_downs_1").hide() ; + } + if (!\$("#start_times_row_1").is(":hidden")) { + \$("#start_times_row_1").hide() ; + } + if (!\$("#end_times_row_1").is(":hidden")) { + \$("#end_times_row_1").hide() ; + } + + if (!\$("#days_drop_downs_2").is(":hidden")) { + \$("#days_drop_downs_2").hide() ; + } + if (!\$("#start_times_row_2").is(":hidden")) { + \$("#start_times_row_2").hide() ; + } + if (!\$("#end_times_row_2").is(":hidden")) { + \$("#end_times_row_2").hide() ; + } + + return ; + } + + if (\$("#days_drop_downs_1").is(":hidden")) { + \$("#days_drop_downs_1").css("display","") ; + \$("#start_times_row_1").css("display","") ; + \$("#end_times_row_1").css("display","") ; + } + + \$("input[name='time_from_1']").val(time_part_from) ; + + const datesBetween = getDatesBetween(dateFromInput,dateToInput,0) ; + let date_counter = 0 ; let dates_count = 0 ; let count_days = 0 ; + + let count_days_after = 0 ; let nr_of_active_days = 0 ; + + let dates_map = {} ; + + for (const date of datesBetween) { + + date_counter++ ; + + dates_map[date_counter] = date ; + + if (date_counter > 20) { date_counter = 20 ; break ; } + if (date_counter > 1 && !saved_time_from[date_counter]) { + \$("input[name='time_from_"+date_counter+"']").val(time_part_from) ; + } + + if (!saved_time_to[date_counter]) { + \$("input[name='time_to_"+date_counter+"']").val(time_part_to) ; + } + + set_full_half_day('',date_counter) ; + + if (\$("#day_"+date_counter+"_chosen").is(":hidden")) { + + \$("#radio_"+date_counter+"_1").css("display",""); + \$("#radio_"+date_counter+"_2").css("display",""); + \$("#day_"+date_counter).val("1") ; + \$("#day_"+date_counter).trigger("chosen:updated") ; + \$("#day_"+date_counter+"_chosen").css("display","") ; + \$("#day_"+date_counter+"_chosen").css("width","100%") ; + \$("#day_"+date_counter).val('1') ; + \$("#day_"+date_counter).trigger("chosen:updated") ; + if (date_counter > 1) { + // console.log("1 . display timepickerTime_from_"+date_counter) ; + \$("#timepickerTime_from_"+date_counter).css("display","") ; + } + } + + if (\$("#day_"+date_counter).val()) { + \$("#timepickerTime_to_"+date_counter).css("display","") ; + nr_of_active_days++ ; + } + + \$("#day_"+date_counter+" option[value='1']").text(date) ; + \$("#day_"+date_counter+" option[value='1']").trigger("chosen:updated") ; + + if (\$("#day_"+date_counter).val()) { + count_days++ ; + } + } + + // \$("input[name='time_to_"+date_counter+"']").val(time_part_to) ; + + if (\$("#days_drop_downs_2").is(":hidden") && date_counter > 10) { + // if (glod_user_level > 3) { + \$("#days_drop_downs_2").css("display","") ; + \$("#start_times_row_2").css("display","") ; + \$("#end_times_row_2").css("display","") ; + \$("#radio_row_id_2_1").css("display","") ; + \$("#radio_row_id_2_2").css("display","") ; + } else if (!\$("#days_drop_downs_2").is(":hidden") && date_counter <= 10) { + \$("#days_drop_downs_2").css("display","none") ; + \$("#start_times_row_2").css("display","none") ; + \$("#end_times_row_2").css("display","none") ; + \$("#radio_row_id_2_1").css("display","none") ; + \$("#radio_row_id_2_2").css("display","none") ; + } + + if (count_days_after) { + date2.setDate(date2.getDate() - count_days_after); + \$("#datetimepickerDate_to").datetimepicker("setDate",date2) ; + } + + let select_raw ; + + let select_chosen_ids_1 = '#1' ; + let select_chosen_ids_2 = '#2' ; + let names_to_display = '#3' ; + + let def_val = 0 ; + + \$("#inputQty").val(count_days) ; + + \$("#timepickerTime_to_"+date_counter).css("display","none") ; + + if (date_counter <= 20) { + for (let j=date_counter+1;j<=20;j++) { + if (\$("#day_"+j).val()) { + \$("#day_"+j).val("") ; + \$("#day_"+j).trigger("chosen:updated") ; + } + if (!\$("#day_"+j+"_chosen").is(":hidden")) { + \$("#day_"+j+"_name label.control-label").text('') ; + \$("#day_"+j+"_name").css("display","none") ; + \$("#radio_"+j+"_1").css("display","none") ; + \$("#radio_"+j+"_2").css("display","none") ; + \$("#day_"+j+"_chosen").css("display","none") ; + } + if (!\$("#timepickerTime_from_"+j).is(":hidden")) { + \$("#timepickerTime_from_"+j).css("display","none") ; + } + if (!\$("#timepickerTime_to_"+j).is(":hidden")) { + \$("#timepickerTime_to_"+j).css("display","none") ; + } + } + } + } + + function timeStringToSeconds(timeString) { + const [hours, minutes, seconds] = timeString.split(':').map(Number); + return hours * 3600 + minutes * 60 + seconds; + } + + function getDatesBetween(startDateStr,endDateStr,count_dates) { + if (!startDateStr || !endDateStr) { + return ; + } + const dates = []; + let currentDate = new Date(startDateStr); + let endDate = new Date(endDateStr) ; + currentDate.setHours(+2); + currentDate.setMinutes(0); + currentDate.setSeconds(0); + endDate.setHours(+2); + endDate.setMinutes(59); + endDate.setSeconds(59); + + // console.log("2 . currentDate : "+currentDate.toISOString().split('T')[0]) ; + while (currentDate < endDate) { + // console.log("3 . currentDate : "+currentDate.toISOString().split('T')[0]) ; + dates.push(currentDate.toISOString().split('T')[0]); + currentDate.setDate(currentDate.getDate() + 1); + if (count_dates) { count_dates++ ; } + } + if (count_dates) { + count_dates-- ; + return count_dates; + } else { + return dates; + } + } + + ~ ; + + $preferred_title{location_id} = "Demo Location" ; + + $selected{events_operator_required}{$db{$table}{$id}{location_id}} = 'SELECTED' ; + + $opts{location_id} = qq~~ ; + + # $fcol = 3 ; + + $fcol = 4 ; + + $add_form_fields .= &common_min_form_select('location_id') ; + + $preferred_title{venue_ids} = "Demo Venue" ; + + $multiple{venue_ids} = 1 ; + + if ($db{$table}{$id}{venue_ids}) { + foreach (split(/\,/,$db{$table}{$id}{venue_ids})) { + $opts{venue_ids} =~ s/value="$_"/value="$_" SELECTED/g ; + } + } + + $dlg{venue_ids} .= qq~
    ~ ; + + $add_form_fields .= qq~~ . &common_min_form_select('venue_ids') ; + + $opts{tenant_id} =~ s/value="$db{$table}{$id}{tenant_id}"/value="$db{$table}{$id}{tenant_id}" SELECTED/g ; + + # $allow_deselect{tenant_id} = 1 ; + + $dlg{tenant_id} = qq~
    ~ ; + + $add_form_fields .= &common_min_form_select('tenant_id') ; + + $selected{events_operator_required}{$db{$table}{$id}{events_operator_required}} = 'SELECTED' ; + + $opts{events_operator_required} = qq~~ ; + + $add_form_fields .= &common_min_form_select('events_operator_required') ; + + $fcol = 3 ; + + $dlg{events_operator_allocated} = qq~~ ; + + $dlg{events_operator_allocated} .= qq~
    ~ ; + + if ($db{$table}{$id}{events_operator_allocated} && $db{$table}{$id}{events_operator_allocated} =~ /;/) { + foreach (split(";",$db{$table}{$id}{events_operator_allocated})) { ## split(";", OR split(/\;/, + $opts{events_operator_allocated} =~ s/value="$_"/value="$_" SELECTED/g ; + } + } elsif ($db{$table}{$id}{events_operator_allocated}) { + $opts{events_operator_allocated} =~ s/value="$db{$table}{$id}{events_operator_allocated}"/value="$db{$table}{$id}{events_operator_allocated}" SELECTED/g ; + } + + $multiple{events_operator_allocated} = 1 ; + + my $events_operator_allocated_def = $db{$table}{$id}{events_operator_allocated} ; + $events_operator_allocated_def =~ s/\;/\,/g ; + + $add_form_fields .= qq~~ . &common_min_form_select('events_operator_allocated',$db{$table}{$id}{events_operator_allocated}) ; + + $trigger_jquery_raw .= qq~ + \$("#selectEvents_operator_allocated").on("change", function () { + let sel_val = \$(this).chosen().val() ; + \$("input[name='eventsoperatorallocated']").val(sel_val) ; + }) ; + ~ ; + + $fcol = 4 ; + + $add_form_fields .= &common_min_form_textarea('additional_requirements_from_events_dept',$db{$table}{$id}{additional_requirements_from_events_dept}) ; + + $selected{calibrator_required}{$db{$table}{$id}{calibrator_required}} = 'SELECTED' ; + + $opts{calibrator_required} = qq~~ ; + + $fcol = 3 ; + + $add_form_fields .= &common_min_form_select('calibrator_required',$db{$table}{$id}{calibrator_required}) ; + + $fcol = 4 ; + + $add_form_fields .= &build_system_name_form($db{$table}{$id}{event_system_id_multiple},$db{$table}{$id}{club_ids},$db{$table}{$id}{operator_ids},$quote_accepted,$quote_rejected,$quote_cancelled,$db{$table}{$id}{quote_completed}) ; + + # $fcol = 6 ; + + $lcol = 2 ; $fcol = 4 ; + + $dlg{sport_type_ids} .= qq~
    ~ ; + + $multiple{sport_type_ids} = 1 ; $preferred_title{sport_type_ids} = "Sport Type(s)" ; + + $trigger_jquery_raw .= qq~ + \$("#selectSport_type_ids").change( function () { + let sel_vals = \$(this).chosen().val() ; + \$("input[name='sporttypeids']").val(sel_vals) ; + }) ; + ~ ; + + $add_form_fields .= qq~~ . &common_min_form_select('sport_type_ids','') ; + + $add_form_fields .= &common_min_form_textarea('additional_requirements_from_support_dept',$db{$table}{$id}{additional_requirements_from_support_dept}) ; + + $add_form_fields .= &common_min_form_textarea('pre_demo_testing_requirements',$db{$table}{$id}{pre_demo_testing_requirements}) ; + + # $print_box_content_rows .= &common_min_box_top('',' Demo Details',$box_right_bg); #film + # $print_box_content_rows .= $add_form_fields ; + # $print_box_content_rows .= &common_min_box_foot; + + &event_tabs_content_box($sec_name,$sec_col); + + $print_box_content_rows .= qq~ +
    +
    +
    +
    ~ ; # fixes row highlighting issue + + $print_box_content_rows .= qq~
    ~ ; # fixes row highlighting issue + + $trigger_jquery .= qq~ + // \$("#two [id^='select']").css("width","100%") ; + \$("#two [id^='select']").filter( function() { + return this.id.endsWith("_chosen"); + }).css("width", "100%"); + ~ ; + + } elsif ($tab == 3) { # Workings + + # --------------- START Working ---------------------------------------------------------------------------------------------------------------- + + $add_form_fields = '' ; + + $lcol = 1 ; + $fcol = 2 ; + + my @docs = ('Slip') ; + + $add_form_fields .= qq~ +
    + ~ ; + + foreach (@docs) { + my $doc = lc $_ ; $doc =~ s/ /\_/ ; $doc =~ s/&/\_/ ; + $event_uploads = &common_get_field_uploads($id,"$doc",'id','delete-attached-slip') ; + if ($event_uploads) { + $add_form_fields .= qq~ +
    + $event_uploads +
    + ~; + } else { + $add_form_fields .= qq~ +
    +
    + + +

    Upload file from PC.

    +
    +
    + ~ ; + } + } + + $trigger_jquery_raw .= qq~ + \$('#delete-attached-slip').click(function (e) { + BootstrapDialog.confirm({ + title: 'Confirm Delete', + message: 'Are you sure you want to delete $doc?', + type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + callback: function(result) { + if (result) { + var url = "$useropts{scripts}/get/get_delete_attach.pl?slips/$db{event_quotes}{$id}{id}&$db{event_quotes}{$id}{slip}&event_quotes&$db{event_quotes}{$id}{id}&slip" ; + \$.get(url) ; + \$('#attach-$id-1').hide() ; // CHECK THAT THE FILE CNT IS ALWAYS ONE + \$('#delete-attached-slip').hide() ; + } else { + // alert('Nope.'); + } + } + }); + }); + ~ ; + + $event_uploads = '' ; + # $add_form_fields .= &common_min_form_label_col("Custom Set") ; + + my $custom_set_checked = ($db{$table}{$id}{custom_set}) ? "CHECKED" : "" ; + + $add_form_fields .= qq~ +
    + + +
    + ~ ; # class="control-label" + # $add_form_fields .= &common_min_form_checkbox_col('custom_set','') ; + + $add_form_fields .= qq~ +
    + ~ ; + + our %sec_cnt = ('a_event' => "50-List Expenses") ; + + my $sec = 'workings' ; + my ($sec_name,$sec_cnt_workings,$sec_col) = &tab_sec_det($sec) ; + + $sec_name = "Demo Expenses" if $demo_page ; ; + + $ret_pdf_link_sec .= $sec . '+' . $sec_cnt_workings . '|' ; + + return if $ret ; + + &db_min_ro('event_cost_items','id,name,rates,full_half_day',"excl_from_expenses < 1 AND name NOT LIKE 'Mobile %' AND name NOT LIKE 'Fixed %' AND name NOT LIKE 'Cricket %'") ; + our %event_list_name_array_expenses = () ; + + foreach my $iid (keys %{$db{event_cost_items}}) { + $event_list_name_array_expenses{$iid} = $db{event_cost_items}{$iid}{name} ; + } + # &tab_load_vars ; + + if ($demo_page) { + + $lcol = 1; + $fcol = 2; + + if ($db{$table}{$id}{currency}) { + $selected{currency}{$db{$table}{$id}{currency}} = 'SELECTED' ; + } else { + $selected{currency}{ZAR} = 'SELECTED' ; + } + + $opts{currency} = qq~ + + + + + ~ ; + + $preferred_title{currency} = 'Currency' ; + $allow_deselect{currency} = "" ; + # $required{currency} = 1 ; + # $required{roe} = 1 ; + + $req_glyph{currency} = qq~~ ; + $req_glyph{roe} = qq~~ ; + + $add_form_fields .= &common_min_form_select('currency',$db{$table}{$id}{currency},1) ; # don't end row + $trigger_jquery .= qq~\$("#selectCurrency_chosen").css( "width", "96%" );~ ; + $preferred_title{roe} = ' ROE ' ; $fcol=1; # $fcol=2 ; + $add_form_fields .= &common_min_form_label_col('roe') ; + $db{$table}{$id}{roe} = 1 unless $db{$table}{$id}{roe} ; + $add_form_fields .= &common_min_form_input_col('roe',$db{$table}{$id}{roe},1) ; + $add_form_fields .= qq~
    ~ ; + + } + + &event_tabs_build_sec($sec,$tab) ; + + foreach (sort keys %sec_cnt) { + $_k = substr($_, 1) ; + my @parts = split(/\-/, $sec_cnt{$_}) ; + $add_form_fields .= qq~ +
    +
    +

    + $parts[1] : +

    +
    +
    + ~ if $parts[1] ne 'Operators'; + + $add_form_fields .= qq~ +
    +
    +
    +

    + $parts[1] : +

    +
    + $icon_casuals +
    +
    + ~ if $parts[1] eq 'Operators' ; + + &tab_build_qt_col_headers_workings("$sec$_k") ; + # # # &db_min_ro('event_quotes_min', 'id, remarks_workings_event, supplier_workings_event, ref_nr_workings_event, qty_workings_event, amount_usd_workings_event, amount_workings_event, vat_workings_event, description_workings_event', "id = $id", '', '') if $id ; + + &event_tabs_build_costs_forms($db{event_quotes}{$id}{id},$tab,$parts[0],"$sec$_k") ; + } + + $add_form_fields .= qq~ +
    +
    +   +
    +
    ~ ; + $add_form_fields .= qq~ +
    +
    +   +
    + ~ ; + + my @ttlarr = ("sub_total", "vat_total", "grand_total") ; + $lcol = 1; + $fcol = 1; + foreach (@ttlarr) { + $lcol = 1; + $add_form_fields .= &common_min_form_label_col($_) ; + } + + $add_form_fields .= qq~
    ~ ; + + $trigger_jquery_raw .= qq~ + \$("#textareaAdditional_notes").change(function () { + if (\$(this).val()) { + \$('label[for="additional_notes_expenses"]').text('Additional Notes : ') ; + \$("#textareaAdditional_notes_expenses_input").html(\$(this).val()) ; + } else if (!\$(this).val() && \$('label[for="additional_notes_expenses"]').text()) { + \$('label[for="additional_notes_expenses"]').text('') ; + \$("#textareaAdditional_notes_expenses_input").html('') ; + } + }) ; + ~ ; + + my $add1 = ($db{$table}{$id}{additional_notes}) ? "Additional Notes : " : "" ; + my $add2 = ($db{$table}{$id}{additional_notes}) ? "$db{$table}{$id}{additional_notes}" : "" ; + + $add_form_fields .= qq~

    $add2

    ~ ; + $lcol = 2; + $add_form_fields .= &common_min_form_label_col('Total') ; + $lcol = 1; + + if ($demo_page) { + my @ttlarr = ("sub_total","vat_total","grand_total"); + foreach (@ttlarr) { + my $field_name = "$_\_workings_event" ; + $readonly{$field_name} = "READONLY"; + my $val = ($db{$table}{$id}{$field_name}) ? $db{$table}{$id}{$field_name} : '0.00' ; + $add_form_fields .= &common_min_form_input_col($field_name,$val) ; + } + } else { + my @ttlarr = ("total_amount_workings_event","total_vat_amount_workings_event","total_grand_amount_workings_event"); + $lcol = 1 ; $fcol = 1 ; + + my %renamed_totals = ("total_amount_workings_event" => "sub_total_workings_event", "total_vat_amount_workings_event" => "vat_total_workings_event" , "total_grand_amount_workings_event" => "grand_total_workings_event") ; + foreach (@ttlarr) { + $readonly{$renamed_totals{$_}} = "READONLY"; + $input_style{$renamed_totals{$_}} = qq~style="text-align:right;"~ ; + my $val = $db{$table}{$id}{$_} ? $db{$table}{$id}{$_} : '0.00' ; + $add_form_fields .= &common_min_form_input_col($renamed_totals{$_},$val) ; + } + } + + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= qq~ +
    +
    +   +
    +
    ~ ; + + &event_tabs_content_box($sec_name,$sec_col) ; + + &event_tabs_build_forms_jquery(1) ; + + # --------------- END WORKING ---------------------------------------------------------------------------------------------------------------- + } + +} #---------------------------------------------------------------------------------------- + +sub event_tabs_build_forms_jquery { + + my ($demo_page) = @_ ; + + my $description_options_costing = $opts{"description_costing_event_1"} ; + $description_options_costing =~ s/\SELECTED//g ; + $description_options_costing =~ s/\"/\'/g ; + + my $tab_name_part = "workings_event" ; + + my $description_options_workings = $opts{"description_$tab_name_part\_1"} ; + $description_options_workings =~ s/\SELECTED//g ; + $description_options_workings =~ s/\"/\'/g ; + + our $operator_options = $opts{"operator_$tab_name_part\_1"} ; + $operator_options =~ s/\SELECTED//g ; + $operator_options =~ s/\"/\'/g ; + + my $btn_ids_string = join(",",@btn_ids) ; + + my $excl_field_ids_string = join(",",@excl_field_ids) ; + my $description_field_ids_string = join(",",@description_field_ids) ; + my $operator_field_ids_string = join(",",@operator_field_ids) ; + my $vat_field_ids_string = join(",",@vat_field_ids) ; + my $qty_field_ids_string = join(",",@qty_field_ids) ; + my $amount_usd_field_ids_string = join(",",@amount_usd_field_ids) ; + + $trigger_jquery_raw .= qq~ + + function get_tab (id) { + let tab = "" ; + if (id.includes("_workings_event")) { + tab = "workings_event" ; + } else if (id.includes("_costing_event")) { + tab = "costing_event" ; + } + return tab ; + } + + function changed_vat (id) { + let tab = get_tab (id) ; + let row_nr = get_row_nr(id) ; + calc_totals(row_nr,tab) ; + } + + function changed_others (id) { + + let row_nr = get_row_nr(id) ; + let firstIndex = id.indexOf('_'); + let col = id.substring(0,firstIndex); + let tab = get_tab (id) ; + if (col == "inputAmount") { + let inp = parseFloat(\$("#"+id).val()) ; + inp = parseFloat(inp) ; + \$("#"+id).val(inp.toFixed(2)) ; + } else if (\$("#selectDescription_"+tab+"_"+row_nr).val() && \$("#selectDescription_"+tab+"_"+row_nr).val() != 14 && \$("#selectOperator_"+tab+"_"+row_nr).val()) { + // \$("#selectOperator_"+tab+"_"+row_nr).val("") ; + // \$("#selectOperator_"+tab+"_"+row_nr).trigger("chosen:updated") ; + } + // else if (col == "selectOperator" && \$("#selectDescription"+tab+"_"+row_nr).val() != 14) { + + // } + + if (col == "selectOperator") { // || (col == "selectDescription" && \$("#selectDescription_"+tab+"_"+row_nr).val( + return ; + } + calc_totals(row_nr,tab) ; + } + + // \$("$vat_field_ids_string").change(function() { + \$("#myTabContent").on("change","[id^='checkboxVat_']", function () { + const id = this.id ; + changed_vat(id) ; + }) ; + + \$("#myTabContent").on("change","[id^='checkboxExcl_'],[id^='selectDescription_'],[id^='inputQty_'],[id^='inputAmount_usd_'],[id^='inputAmount_ttl_']", function () { + // \$("$excl_field_ids_string,$description_field_ids_string,$qty_field_ids_string,$amount_usd_field_ids_string,$operator_field_ids_string").change(function() { + const id = this.id ; + changed_others(id) ; + }) ; + + ~ ; + + my $event_quotes_jquery = qq~~ ; + + if (!$demo_page) { + $event_quotes_jquery .= qq~ + let profit_loss = parseFloat(\$("input[name='income']").val().replace(/,/g, '')) - parseFloat(\$("input[name='expenses']").val().replace(/,/g, '')) ; + \$("input[name='profit_loss']").val(profit_loss.toFixed(2)) ; + ~ ; + } + + $trigger_jquery_raw .= qq~ + + \$("#myTabContent").on("click","[id^='btn_']", function () { + + // \$("$btn_ids_string").click(function () { + + const id = this.id ; + let tab = get_tab (id) ; + let row_nr = get_row_nr(id) ; + \$("#"+tab+"_"+row_nr).show(); + let row_html = "" ; + if (tab == "workings_event") { + row_html = add_quote_expenses_row(row_nr,tab,"$description_options_workings","$operator_options") ; + } else if (tab == "costing_event") { + row_html = add_quote_expenses_row(row_nr,tab,"$description_options_costing","") ; + } + \$("#"+tab+"_"+row_nr).html(row_html); + // \$("#$suffix\_"+row_nr).trigger("chosen:updated") ; + + \$("#selectDescription_"+tab+"_"+row_nr).chosen({ allow_single_deselect:true }) ; + + if (tab == "workings_event") { + \$("#selectOperator_"+tab+"_"+row_nr).chosen({ allow_single_deselect:true }); + \$("#inputRemarks_"+tab+"_"+row_nr).css("text-align","") ; + \$("#inputSupplier_"+tab+"_"+row_nr).css("text-align","") ; + \$("#inputRef_nr_"+tab+"_"+row_nr).css("text-align","") ; + } + + \$("#btn_"+tab+"_"+row_nr).hide(); + var v = row_nr + 1 ; + + // \$("#btn_$suffix\_"+v).css("padding-left","16px") ; + \$("#btn_"+tab+"_"+v).html("") ; + \$("#btn_"+tab+"_"+v).show(); + \$("#btn_row_"+tab+"_"+v).show() ; + \$("#2_"+tab+"_"+row_nr).show() ; + + \$("#checkboxExcl_"+tab+"_"+row_nr).prop('checked',false) ; + + }); + + ~ if $btn_ids_string ; + + $trigger_jquery_raw .= qq~ + + \$("#selectCurrency").change(function () { + + }) ; + + \$("input[name='roe']").change(function () { + + let roe = \$(this).val() ; + if (roe < 0 || !roe) { + roe = 1 ; + } + \$(this).val(parseFloat(roe).toFixed(2)) ; + + var sub_total = 0 ; var vat_total = 0 ; var sub_total_quote = 0 ; var vat_total_quote = 0 ; + + [sub_total,vat_total] = add_up_totals("workings_event",50,roe,1) ; + [sub_total_quote,vat_total_quote] = add_up_totals("costing_event",30,roe,1) ; + + // // // \$("input[name='income']").val((sub_total_quote+vat_total_quote).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("input[name='income']").val((sub_total_quote+vat_total_quote).toFixed(2)) ; + \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + update_overall_totals(sub_total,vat_total,"workings_event") ; + update_overall_totals(sub_total_quote,vat_total_quote,"costing_event") ; + + }) ; + + function add_up_totals (tab,nr_of_rows,roe,recalc_totals) { + + let sub_total = 0 ; let vat_total = 0 ; + for (let i=1; i<=nr_of_rows; i++) { + if (!\$("#"+tab+"_"+i).html()) { break ; } + if (\$("#selectDescription_"+tab+"_"+i).val()) { + if (\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { continue ; } + let ttl = 0 ; + if (recalc_totals) { + ttl = parseFloat(\$("#inputAmount_usd_"+tab+"_"+i).val()) * parseFloat(\$("#inputQty_"+tab+"_"+i).val()) * parseFloat(roe) ; + } else { + ttl = parseFloat(\$("#inputAmount_ttl_"+tab+"_"+i).val().replace(/,/g, '')) + } + // // // // \$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("#inputAmount_ttl_"+tab+"_"+i).val(ttl.toFixed(2)) ; + if (!\$("#inputAmount_ttl_"+tab+"_"+i).val() || \$("#inputAmount_ttl_"+tab+"_"+i).val() == "NaN") { + \$("#inputAmount_ttl_"+tab+"_"+i).val("0.00") ; + ttl = 0 ; + } + sub_total += ttl ; + if (\$("#checkboxVat_"+tab+"_"+i).is(":checked")) { + vat_total += ttl*0.15 ; + } + } else if (!\$("#checkboxExcl_"+tab+"_"+i).is(":checked")) { + \$("#checkboxExcl_"+tab+"_"+i).prop('checked',true) ; + } + } + return [sub_total,vat_total] ; + } + + // function getNum(val) { + + // if (isNaN(val)) { + // return 0; + // } + // return val; + // } + + function calc_totals (row_cnt,tab) { + + var qty = \$("#inputQty_"+tab+"_"+row_cnt) ; + var usd = \$("#inputAmount_usd_"+tab+"_"+row_cnt) ; + var conv = \$("#inputAmount_ttl_"+tab+"_"+row_cnt) ; + var excl = \$("#checkboxExcl_"+tab+"_"+row_cnt) ; + var item = \$("#selectDescription_"+tab+"_"+row_cnt) ; + + if (!usd.val() && !conv.val() && !usd.val()) { + // console.log("skip calc_totals_workings") ; + if (!item.val()) { + excl.prop("checked",true) ; + } + return ; + } + + var vat = \$("#checkboxVat_"+tab+"_"+row_cnt) ; + + if (!item.val()) { + + excl.prop("checked",true) ; + vat.prop("checked",true) ; + qty.val("") ; + usd.val("") ; + conv.val(""); + if (tab == "workings_event") { + var rem = \$("#inputRemarks_"+tab+"_"+row_cnt) ; + var sup = \$("#inputSupplier_"+tab+"_"+row_cnt) ; + var ref = \$("#inputRef_nr_"+tab+"_"+row_cnt) ; + var op = \$("#selectOperator_"+tab+"_"+row_cnt) ; + rem.val("") ; + sup.val("") ; + ref.val("") ; + op.val("") ; + op.trigger("chosen:updated") ; + } + } else if (excl.is(":checked") && item.val() && conv.val() == "0.00") { + excl.prop("checked",false) ; + } + + if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) ; } + + let roe = parseFloat(\$("#inputRoe").val()) ; + + let ttl = usd.val() * qty.val() * roe ; + + // // // conv.val(ttl.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + conv.val(ttl.toFixed(2)) ; + + let sub_total = 0 ; let vat_total = 0 ; + + let nr_of_rows = 50 ; + if (tab == "costing_event") { + nr_of_rows = 30 ; + } + + [sub_total,vat_total] = add_up_totals (tab,nr_of_rows,roe,0) ; + + console.log("add_up_totals : "+sub_total) ; + + if (tab == "workings_event") { + // // // \$("input[name='expenses']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("input[name='expenses']").val((sub_total+vat_total).toFixed(2)) ; + update_overall_totals(sub_total,vat_total,tab) ; + } else { + // // // \$("input[name='income']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + \$("input[name='income']").val((sub_total+vat_total).toFixed(2)) ; + update_overall_totals(sub_total,vat_total,tab) ; + // update_overall_totals_costings(sub_total,vat_total) ; + } + } + + function update_overall_totals (sub_total,vat_total,tab) { + + $event_quotes_jquery + + // // // \$("input[name='profit_loss']").val(profit_loss.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='sub_total_"+tab+"']").val(sub_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='vat_total_"+tab+"']").val(vat_total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + // // // \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})) ; + + \$("input[name='sub_total_"+tab+"']").val(sub_total.toFixed(2)) ; + \$("input[name='vat_total_"+tab+"']").val(vat_total.toFixed(2)) ; + \$("input[name='grand_total_"+tab+"']").val((sub_total+vat_total).toFixed(2)) ; + } + + function add_quote_expenses_row (row_nr,tab,options1,options2) { + + let tindex = $tindex ; + tindex = parseInt(tindex) ; + row_nr = parseInt(row_nr) ; + tindex = tindex - 10*(1+50-row_nr) ; + + let row = add_checkbox(row_nr,"excl_"+tab+"_"+row_nr,"checkboxExcl_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + + row = row+add_select(row_nr,"description_"+tab+"_"+row_nr,"selectDescription_"+tab+"_"+row_nr,"Select Description "+row_nr,options1,tindex,2,90,'','') ; tindex++ ; + if (tab == "workings_event") { + row = row+add_select(row_nr,"operator_workings_event_"+row_nr,"selectOperator_"+tab+"_"+row_nr,"Select Operator "+row_nr,options2,tindex,2,90,'','') ; tindex++ ; + row = row+add_input(row_nr,"remarks_workings_event_"+row_nr,"inputRemarks_"+tab+"_"+row_nr,"Remarks "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"supplier_workings_event_"+row_nr,"inputSupplier_"+tab+"_"+row_nr,"Supplier "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"ref_nr_workings_event_"+row_nr,"inputRef_nr_"+tab+"_"+row_nr,"Ref Nr "+row_nr,tindex,'',1) ; tindex++ ; + } + row = row+add_input(row_nr,"qty_"+tab+"_"+row_nr,"inputQty_"+tab+"_"+row_nr,"Qty "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"amount_usd_"+tab+"_"+row_nr,"inputAmount_usd_"+tab+"_"+row_nr,"Amount "+row_nr,tindex,'',1) ; tindex++ ; + row = row+add_input(row_nr,"amount_ttl_"+tab+"_"+row_nr,"inputAmount_ttl_"+tab+"_"+row_nr,"Total Amount "+row_nr,tindex,"readonly",1) ; tindex++ ; + row = row+add_checkbox(row_nr,"vat_"+tab+"_"+row_nr,"checkboxVat_"+tab+"_"+row_nr,tindex,1) ; tindex++ ; + return row ; + } + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes_right { + +my ($id,$tab) = @_ ; + +tab_build_qt_right($id,$tab) ; + +} #---------------------------------------------------------------------------------------- + +sub view_screen { + + &edit_screen ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + unless ($i{id}) { $warning = qq(NO ID) ; return ; } + + our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + # called from common_add_screen + + &select_opts($i{id}) ; + + our $savjqy = 1 ; # incorporate jquery into the save event to accommodate the multiple chosen options + + &build_boxes_edit($i{id}) ; + + &common_min_extra_crumb("search-$lcpage\s","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes_bottom { + + my ($id) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(2,2) ; + + $add_form_fields = '' ; + + # --------------- START GRAND TOTAL ---------------------------------------------------------------------------------------------------------------------- + + $print_box_content_rows .= &common_min_form_input('activetab',$db{$table}{$id}{activetab},'hidden') ; + + # --------------- END RAND TOTAL ------------------------------------------------------------------------------------------------------------------------ + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_top { + + my ($id) = @_ ; + + &event_tabs_build_boxes_top($id,1) ; + +} #---------------------------------------------------------------------------------------- + +sub build_extra_name_row_1 { + + my ($row_cnt,$display) = @_ ; + my $count_dates_in_first_extra_row = 0 ; + $display = ($display) ? "style='display:none;'" : "" ; + my $extra_row_hearders_1 = qq~
    ~ ; + for (1 .. 20) { + $count_dates_in_first_extra_row++ if $days_active_arr[$_ - 1] ; + $date_is_displayed_in_first_extra_row{$_} = 1 if $days_active_arr[$_ - 1] && $count_dates_in_first_extra_row <= 10 ; + $extra_row_hearders_1 .= ($days_active_arr[$_ - 1] && $count_dates_in_first_extra_row <= 10 && $some_row_has_daily_op_1) ? qq~
    ~ : qq~~ ; + } + $extra_row_hearders_1 .= qq~
    ~ ; + return $extra_row_hearders_1 ; + +} #---------------------------------------------------------------------------------------- + +sub build_extra_name_row_2 { + + my ($row_cnt,$display) = @_ ; + $display = ($display) ? "style='display:none;'" : "" ; + my $extra_row_hearders_2 = qq~
    ~ ; + for (11 .. 20) { + $extra_row_hearders_2 .= ($some_row_has_daily_op_2 && $days_active_arr[$_ - 1] && !$date_is_displayed_in_first_extra_row{$_}) ? qq~
    ~ : qq~~ ; + } + $extra_row_hearders_2 .= qq~
    ~ ; + return $extra_row_hearders_2; + +} #---------------------------------------------------------------------------------------- + +sub build_system_name_form { + + my ($system_ids,$club_ids,$op_ids,$quote_accepted,$quote_rejected,$quote_cancelled,$quote_completed) = @_ ; + + my @system_name_ids = split(/\;/,$system_ids) ; + my @club_ids = split(/\;/,$club_ids) ; + # our @days_active_arr = split(/\;/,$days_active) ; + my @table_op_ids = ($op_ids =~ /;/) ? split(/\;/,$op_ids) : split(/\,/,$op_ids) ; + + local $system_count = 0 ; local $system_day_cnt = 0 ; my %row_has_daily_op = () ; my $some_row_has_daily_op = 0 ; our $some_row_has_daily_op_1 = 0 ; our $some_row_has_daily_op_2 = 0 ; my $active_days_count = 0 ; + + foreach my $row (split(/\|/,$daily_operator_ids)) { + $system_count++ ; + + next unless $row ; + $system_day_cnt = 0 ; + foreach my $default_op (split(/\;/,$row)) { + $system_day_cnt++ ; + # next if !$days_active_arr[$system_day_cnt-1] ; + # $active_days_count++ ; + # $default_op_ids{$system_count}{$system_day_cnt} = $default_op if $default_op ; + } + } + + # $active_days_count = 0 ; my $total_days = 0 ; + + # foreach (@days_active_arr) { + # $active_days_count++ if $_ ; + # $total_days++ ; + # } + + # $some_row_has_daily_op = 0 if $active_days_count > 6 ; + + $fcol = 2 ; $lcol = 2 ; + + # $dlg_add_club = ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) ? '
    ' : qq~
    ~ ; + $dlg_add_club = ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) ? '
    ' : qq~
    ~ ; + + # if ($glod_user_level > 2 || ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled))) { + $add_form_fields .= qq~ +
    +
    + +
    +
    +
    +
    + +
    +
    + +
    + $dlg_add_club +
    + +
    +
    +
    +
    + ~ ; + + our %date_is_displayed_in_first_extra_row = () ; + + # if ($active_days_count <= 6) { + + # for (1 .. 20) { + # $add_form_fields .= ($some_row_has_daily_op && $days_active_arr[$_ - 1]) ? qq~
    ~ : ($some_row_has_daily_op && !$days_active_arr[$_ - 1] && $final_day >= $_) ? qq~~ : + # qq~~ ; + # } + # $add_form_fields .= qq~
    ~ ; + + # } else { + # for (1 .. 20) { + # $add_form_fields .= qq~~ ; + # } + # $add_form_fields .= qq~
    ~ ; + # } + + my $note_display_butt = qq~~ ; + + my $system_name_id = "" ; my $club_name_id = "" ; + + my @plus_button_ids = () ; my @event_system_ids = () ; my @event_club_ids = () ; my @event_operator_ids = () ; my @overall_op_ids = () ; + + my @table_system_name_ids = () ; my @table_club_name_ids = () ; my @table_operator_calibration_ids = () ; + + my $old_op_opts = $opts{operator_ids} ; + $opts{operator_ids} =~ s/\SELECTED//g ; + + for my $row_cnt (1 .. $nr_of_system_names_and_clubs) { + + my $select_sys_name = 0 ; my $select_club_name = 0 ; + + $add_form_fields .= qq~~ if $row_cnt > 1 and not $system_name_ids[$row_cnt - 1] and not $club_ids[$row_cnt - 1] ; + $add_form_fields .= qq~
    ~ if $row_cnt == 1 or $system_name_ids[$row_cnt - 1] or $club_ids[$row_cnt - 1] ; + + push @plus_button_ids,"#btn_system_name_$row_cnt" ; + + my $input_fields_dates_1 = qq~~ ; + my $input_fields_1 = qq~~ ; + my $input_fields_dates_2 = qq~~ ; + my $input_fields_2 = qq~~ ; + + if ($row_cnt == 1 || $row_has_daily_op{$row_cnt} || $system_name_ids[$row_cnt - 1] || $club_ids[$row_cnt - 1]) { + + # if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { + + $system_name_id = "inputSystem_name_" ; $club_name_id = "inputClub_name_" ; + $readonly{"system_name_$row_cnt"} = "READONLY" ; $readonly{"club_name_$row_cnt"} = "READONLY" ; $readonly{"operator_id_calibration_$row_cnt"} = "READONLY" ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $fcol = 4 ; + $add_form_fields .= &common_min_form_input_col("system_name_$row_cnt",$db{event_systems}{$system_name_ids[$row_cnt - 1]}{name}) ; + $add_form_fields .= &common_min_form_input_col("club_name_$row_cnt",$db{clubs}{$club_ids[$row_cnt - 1]}{name}) ; + $add_form_fields .= &common_min_form_input_col("operator_id_calibration_$row_cnt",$db{users}{$table_op_ids[$row_cnt - 1]}{name}) ; + $add_form_fields .= qq~
    ~ ; + + } else { + + $system_name_id = "selectSystem_name_" ; $club_name_id = "selectClub_name_" ; $op_name_id = "selectOperator_id_calibration_" ; + + push @event_system_ids,"#$system_name_id$row_cnt\_chosen" ; + push @event_club_ids,"#$club_name_id$row_cnt\_chosen" ; + push @event_operator_ids,"#$op_name_id$row_cnt\_chosen" ; + push @overall_op_ids,"#selectOperator_id_calibration_$row_cnt" ; + + $opts{"system_name_$row_cnt"} = $opts{event_system_id} ; $opts{"club_name_$row_cnt"} = $opts{club_ids} ; $opts{"operator_id_calibration_$row_cnt"} = $opts{operator_ids} ; + # $allow_deselect{"system_name_$row_cnt"} = 1 ; $allow_deselect{"club_name_$row_cnt"} = 1 ; $allow_deselect{"operator_id_calibration_$row_cnt"} = 1 ; + + my $sys_name_id = $system_name_ids[$row_cnt - 1] ; + if ($sys_name_id) { + $trigger_jquery_raw .= qq~\$("#selectSystem_name_$row_cnt").val('$sys_name_id') ; \$("#selectSystem_name_$row_cnt").trigger("chosen:updated") ; ~ ; + } else { + push @table_system_name_ids,"#selectSystem_name_$row_cnt" ; + } + + my $club_id = $club_ids[$row_cnt - 1] ; + if ($club_id) { + $trigger_jquery_raw .= qq~\$("#selectClub_name_$row_cnt").val('$club_id') ; \$("#selectClub_name_$row_cnt").trigger("chosen:updated") ; ~ ; + } else { + push @table_club_name_ids,"#selectClub_name_$row_cnt" ; + } + + my $op_id = $table_op_ids[$row_cnt - 1] ; + + $preferred_title{"operator_id_calibration_$row_cnt"} = "Operator $row_cnt" ; + + $fcol = 4 ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= &common_min_form_select_col("system_name_$row_cnt",$system_name_ids[$row_cnt - 1]) if $row_cnt == 1 ; + $add_form_fields .= &common_min_form_select_col("system_name_$row_cnt",'') if $row_cnt > 1 ; + $add_form_fields .= &common_min_form_select_col("club_name_$row_cnt",$club_ids[$row_cnt - 1]) if $row_cnt == 1 ; + $add_form_fields .= &common_min_form_select_col("club_name_$row_cnt",'') if $row_cnt > 1 ; + $add_form_fields .= &common_min_form_select_col("operator_id_calibration_$row_cnt",'') ; + + $add_form_fields .= qq~
    ~ ; + + $fcol = 2 ; + + my $clicked_op_butt = ($row_has_daily_op{$row_cnt}) ? qq~value="1"~ : qq~~ ; + + if (!$row_has_daily_op{$row_cnt} && $op_id) { + $trigger_jquery_raw .= qq~\$("#selectOperator_id_calibration_$row_cnt").val('$op_id') ; \$("#selectOperator_id_calibration_$row_cnt").trigger("chosen:updated") ; ~ ; + } else { + push @table_operator_calibration_ids,"#selectOperator_id_calibration_$row_cnt" ; + } + + for (1 .. 20) { + push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ; + } + + if ($active_days_count <= 6) { + + } else { + + } + $select_sys_name = $system_name_ids[$row_cnt] ; + $select_sys_name = '' unless $select_sys_name ; + } + $add_form_fields .= qq~
    ~ ; + } + + # $add_form_fields .= ($active_days_count > 6 && $some_row_has_daily_op_1 && ($row_cnt == 1 || $row_has_daily_op{$row_cnt} || $system_name_ids[$row_cnt - 1] || $club_ids[$row_cnt - 1] || $table_op_ids[$row_cnt - 1])) ? qq~
     
    ~ : qq~~ ; + + $note_display_butt = '' ; + + # if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { + $note_display_butt = qq~display:none;~ ; + } else { + if ($row_cnt > 1 and not $system_name_ids[$row_cnt-1] and not $club_ids[$row_cnt-1]) { + $note_display_butt = qq~display:none;~ ; + } + if ($system_name_ids[$row_cnt] or $club_ids[$row_cnt]) { + $note_display_butt = qq~display:none;~ ; + } + $add_form_fields .= qq~ +
    +
    +
    + + + +
    +
    + ~ ; + } + } + + $opts{operator_ids} = $old_op_opts ; + + my $table_system_name_ids_string = join(",",@table_system_name_ids) ; + my $table_club_name_ids_string = join(",",@table_club_name_ids) ; + my $table_operator_calibration_ids_string = join(",",@table_operator_calibration_ids) ; + + my @all_table_ids = () ; + push @all_table_ids,$table_system_name_ids_string if $table_system_name_ids_string ; + push @all_table_ids,$table_club_name_ids_string if $table_club_name_ids_string ; + push @all_table_ids,$table_operator_calibration_ids_string if $table_operator_calibration_ids_string ; + + my $all_table_ids_string = join(",",@all_table_ids) ; + + $trigger_jquery_raw .= qq~ + \$("$all_table_ids_string").val('') ; \$("$all_table_ids_string").trigger("chosen:updated") ; + ~ if $all_table_ids_string ; + + my $plus_button_ids_string = join(",",@plus_button_ids) ; + + # if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { + + } else { + + my $system_name_options = &fix_options_for_javascript($opts{"system_name_1"}) ; + my $club_name_options = &fix_options_for_javascript($opts{"club_name_1"}) ; + our $operator_options = &fix_options_for_javascript($opts{"operator_id_calibration_1"}) ; + my $event_system_ids_string = join(",",@event_system_ids) ; + my $event_club_ids_string = join(",",@event_club_ids) ; + my $event_operator_ids_string = join(",",@event_operator_ids) ; + my $daily_op_ids_string = join(",",@daily_op_ids) ; + my $overall_op_ids_string = join(",",@overall_op_ids) ; + $trigger_jquery .= qq~\$("$event_system_ids_string,$event_club_ids_string").css("width","100%");~ ; + $trigger_jquery .= qq~\$("$event_operator_ids_string").css("width","100%");~ ; + + my $table_plus_button_ids_string = join (",",@table_plus_button_ids) ; + # $table_plus_button_ids_string = "#selectCustom_operator_1_1,#selectCustom_operator_1_3,#selectCustom_operator_1_2" ; + # $table_plus_button_ids_string = "#selectCustom_operator_1_1,#selectCustom_operator_1_3,#selectCustom_operator_1_2" ; + + $trigger_jquery_raw .= qq~ + + function get_row_nr (id) { + let lastIndex = id.lastIndexOf('_'); + lastIndex = parseInt(lastIndex) ; + let row_nr = id.substring(1+lastIndex); + row_nr = parseInt(row_nr) ; + return row_nr ; + } + + function add_checkbox (row_nr,field_name,field_id,tindex,fcol) { + let checkbox = "
    " ; + return checkbox ; + } + + function add_input (row_nr,field_name,field_id,placeholder,tindex,readonly,fcol) { + let input = "
    " ; + return input ; + } + + function add_select (row_nr,field_name,field_id,placeholder,options,tindex,fcol,width,div_id,hide_div) { + let select = "
    " ; + select = select + add_select_raw(row_nr,field_name,field_id,placeholder,options,tindex,width) ; + select = select + "
    " ; + return select ; + } + + function add_select_raw (row_nr,field_name,field_id,placeholder,options,tindex,width) { + let select_raw = "
    " ; + return select_raw ; + } + + function add_event_system_extra_row (row_cnt,nr_of_active_days) { + + } + + function add_event_system_row (row_cnt,nr_of_active_days) { + + let new_row = "
    " ; + + new_row = new_row + add_select (row_cnt,"system_name_"+row_cnt,"selectSystem_name_"+row_cnt,"Select System Name "+row_cnt,"$system_name_options",-1,4,100,'','') ; + new_row = new_row + add_select (row_cnt,"club_name_"+row_cnt,"selectClub_name_"+row_cnt,"Select Club Name "+row_cnt,"$club_name_options",-1,4,100,'','') ; + new_row = new_row + add_select (row_cnt,"operator_id_calibration_"+row_cnt,"selectOperator_id_calibration_"+row_cnt,"Select Operator "+row_cnt,"$operator_options",-1,4,100,'','') ; + + // let glod_user_level = parseInt("$glod_user_level") ; + + // if (glod_user_level < 3) { return new_row ; } + + // new_row = new_row +"
    " ; + + // let extra_row_1,extra_row_2,extra_name_row_1,extra_name_row_2 ; + + // // if (nr_of_active_days <= 6) { + + // for (let col=1; col<=20; col++) { + // // if (\$("#day_"+col).val()) { + // // new_row = new_row + add_select (row_cnt,"custom_operator_"+row_cnt+"_"+col,"selectCustom_operator_"+row_cnt+"_"+col,"Select an Option","$operator_options",-1,1,100,"id='day_"+row_cnt+"_"+col+"'","style='display:none;'") ; + // // } else { + // new_row = new_row + "" ; + // // } + // } + + // new_row = new_row+"
    " ; + // extra_row_1 = " +~ ; + +# $extra_form_fields .= qq~~ ; + +$form .= &common_min_forms_end('','photo_uploads','update') ; + +$trigger_jquery_raw .= qq~ + +function deleteItem (uploadid,event_quote_id) { + + BootstrapDialog.confirm({ + title: 'Confirm Delete', + message: 'Are you sure you want to delete '+uploadid+'?', + type: BootstrapDialog.TYPE_WARNING, + callback: function(result) { + if (result) { + document.deleteform.event_quote_id.value = event_quote_id ; + document.deleteform.uploadid.value = uploadid ; + \$('#delete-form').submit(); + // parent.location.reload(); + } + } + }); +} + +~ ; + +# $trigger_jquery .= qq(var oTable = \$('#incidentuploads').dataTable(); oTable.fnSort( [ [1,'desc'] ] );) ; + +} #------------------------------------------------------------------------------------------ + +sub screen1 { + +$useropts{'common'}{'css'} .= qq(#incidentuploads .form-control { height:25px;padding:2px 5px;font-size:12px;color:#464545; }); + +&common_min_alert_type ; + +&common_min_footer('id','') ; + +&common_min_dialog ; + +print < + + + $alert + $print_top + +
    +
    + $form +
    + +
    +
    + +
    + +
    + + + + + + +$dialog{'common'}{'js'} + + + +
    + + + +
    + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + +if (($username eq 'rory') and ($testing)) { return ; } + +print < + + + + Truck Assist Gateway USA + + + + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use db ; +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/dialog/dcb_trackntrace.pl b/scripts/_FromProd/v1.0/dialog/dcb_trackntrace.pl new file mode 100644 index 0000000..e56be90 --- /dev/null +++ b/scripts/_FromProd/v1.0/dialog/dcb_trackntrace.pl @@ -0,0 +1,362 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); +use Fcntl qw(:flock) ; +use LWP::UserAgent; +use HTTP::Request; +use XML::Simple ; +use Date::Calc qw(Month_to_Text); + +require cfg ; + +print header; # CGI.pm method + +# unless ($useropts{admin}{$userid} eq $username) { require '401.pm' ; exit ; } + +# https://itvadmin.co.za/cgi-bin/scripts/dialog/dcb_track_trace.pl?debug=1&waybillnr= + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; +our $debug = $q -> param('debug') || '' ; +our $waybillnr = $q -> param('waybillnr') || '' ; + +# $debug = 0 ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our %trackntrace = () ; + +&dcb_trackntrace($waybillnr) ; +&view_form ; +&screen2 ; + +# &start_html ; + +# &reload_parent ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub view_form { + + $sort_field{1} = 'booking_date' ; + $sort_field{2} = 'comments' ; + $sort_field{3} = 'consignee_name' ; + $sort_field{4} = 'consignor_name' ; + $sort_field{5} = 'current_status' ; + $sort_field{6} = 'delivery_date' ; + $sort_field{7} = 'insured_value' ; + $sort_field{8} = 'number_of_parcels' ; + $sort_field{9} = 'receiver_address_line_1' ; + $sort_field{10} = 'receiver_address_line_2' ; + $sort_field{11} = 'receiver_city' ; + $sort_field{12} = 'receiver_contact_name' ; + $sort_field{13} = 'receiver_contact_tel_1' ; + $sort_field{14} = 'receiver_name' ; + $sort_field{15} = 'receiver_postal_code' ; + $sort_field{16} = 'receiver_suburb' ; + $sort_field{17} = 'sender_address_line_1' ; + $sort_field{18} = 'sender_address_line_2' ; + $sort_field{19} = 'sender_city' ; + $sort_field{20} = 'sender_contact_name' ; + $sort_field{21} = 'sender_contact_tel' ; + $sort_field{22} = 'sender_postal_code' ; + $sort_field{23} = 'sender_suburb' ; + $sort_field{24} = 'service_type_code' ; + $sort_field{25} = 'shipment_is_insured' ; + $sort_field{26} = 'shipper_reference' ; + $sort_field{27} = 'account_nr' ; + $sort_field{28} = 'additional_information' ; + $sort_field{29} = 'pod' ; + $sort_field{30} = 'tracking_detail_1' ; + $sort_field{31} = 'tracking_detail_2' ; + $sort_field{32} = 'waybill_date' ; + $sort_field{33} = 'waybill_number' ; + + $sort_field_additional_information{1} = 'additional_info_code' ; + $sort_field_additional_information{2} = 'additional_info_value' ; + $sort_field_additional_information{3} = 'waybill_number' ; + + $sort_field_tracking_detail{1} = 'event_code' ; + $sort_field_tracking_detail{2} = 'event_date' ; + $sort_field_tracking_detail{3} = 'event_description' ; + $sort_field_tracking_detail{4} = 'event_hub_code' ; + $sort_field_tracking_detail{5} = 'event_time' ; + + + $lcol = 2 ; $fcol = 8 ; + + foreach my $row_cnt (sort keys %sort_field) { + + my $row = $sort_field{$row_cnt} ; + my $val = $trackntrace{$row} ; + + if ($row eq 'booking_date'){ + # $val = '' ; + } elsif ($row_ eq 'comments') { + # $val = '' ; + } elsif ($row_ eq 'consignee_name') { + # $val = 'DEV' ; + } elsif ($row eq 'consignor_name') { + # $val = 'DARREN' ; + } elsif ($row eq 'current_status') { + # $val = 'Proof of delivery' ; + } elsif ($row eq 'delivery_date') { + # $val = '08052023' ; + if ($val) { + my ($day,$month,$year) = (substr($val,0,2),substr($val,2,2),substr($val,4,4)) ; + $day = sprintf("%02d",$day) ; $month = sprintf("%02d",$month) ; + $month = Month_to_Text($month) ; + $val = "$day $month $year" ; + } + } elsif ($row eq 'insured_value') { + # $val = '0.00' ; + } elsif ($row eq 'number_of_parcels') { + # $val = '1' ; + } elsif ($row eq 'receiver_address_line_1') { + # $val = '15 SIM ROAD' ; + } elsif ($row eq 'receiver_address_line_2') { + # $val = '' ; + } elsif ($row eq 'receiver_city') { + # $val = 'KEMPTON PARK' ; + } elsif ($row eq 'receiver_contact_name') { + # $val = 'DARREN' ; + } elsif ($row eq 'receiver_contact_tel_1') { + # $val = '0834752596' ; + } elsif ($row eq 'receiver_name') { + # $val = '' ; + } elsif ($row eq 'receiver_postal_code') { + # $val = '1619' ; + } elsif ($row eq 'receiver_suburb') { + # $val = 'POMONA' ; + $val = join(' ', map { ucfirst(lc($_)) } split(' ', $val)); + } elsif ($row eq 'sender_address_line_1') { + # $val = '' ; + } elsif ($row eq 'sender_address_line_2') { + # $val = '' ; + } elsif ($row eq 'sender_city') { + # $val = 'KEMPTON PARK' ; + $val = join(' ', map { ucfirst(lc($_)) } split(' ', $val)); + } elsif ($row eq 'sender_contact_name') { + # $val = 'DEV' ; + $val = join(' ', map { ucfirst(lc($_)) } split(' ', $val)); + } elsif ($row eq 'sender_contact_tel') { + # $val = '0112302085' ; + } elsif ($row eq 'sender_postal_code') { + # $val = '1619' ; + } elsif ($row eq 'sender_suburb') { + # $val = 'POMONA' ; + $val = join(' ', map { ucfirst(lc($_)) } split(' ', $val)); + } elsif ($row eq 'service_type_code') { + # $val = 'EC' ; + } elsif ($row eq 'shipment_is_insured') { + # $val = 'YES' ; + $val = ucfirst lc $val ; + } elsif ($row eq 'shipper_reference') { + # $val = '' ; + } elsif ($row eq 'account_nr') { + # $val = 'DCBDEVLP' ; + } elsif ($row eq 'additional_information') { + $print_box_content_rows .= &common_min_form_label($row,'') ; + $print_box_content_rows .= qq~
    ~ ; + foreach (sort keys %sort_field_additional_information) { + my $row2 = $sort_field_additional_information{$_} ; + my $val2 = $trackntrace{additional_information}{$row2} ; + if ($row2 eq 'additional_info_code') { + # $val2 = 'overrideDefaultSubcontractor' ; + } elsif ($row2 eq 'additional_info_value') { + # $val2 = 'no' ; + } elsif ($row2 eq 'waybill_number') { + # $val2 = 'Dn230505' ; + } + $row2 = ucfirst $row2 ; + $print_box_content_rows .= &common_min_form_view(" - $row2",$val2,'') ; + } + next ; + } + elsif ($row eq 'pod') { + # $val = '' ; + } elsif ($row =~ /tracking_detail/) { + my $tracking_detail_cnt = substr($row,-1) ; + $print_box_content_rows .= &common_min_form_label($row,'') ; + $print_box_content_rows .= qq~
    ~ ; + foreach (sort keys %sort_field_tracking_detail) { + my $row2 = $sort_field_tracking_detail{$_} ; + my $val2 = $trackntrace{tracking_detail}{$row2}{$tracking_detail_cnt} ; + if ($row2 eq 'event_code') { + # $val2 = ($tracking_detail_cnt eq '1') ? 'PODCRE' : 'WBLCRE' ; + } elsif ($row2 eq 'event_date') { + # $val2 = ($tracking_detail_cnt eq '1') ? '09052023' : '05052023' ; + if ($val2) { + my ($day,$month,$year) = (substr($val2,0,2),substr($val2,2,2),substr($val2,4,4)) ; + $day = sprintf("%02d",$day) ; $month = sprintf("%02d",$month) ; + $month = Month_to_Text($month) ; + $val2 = "$day $month $year" ; + } + + } elsif ($row2 eq 'event_description') { + # $val2 = ($tracking_detail_cnt eq '1') ? 'Waybill has been PODed' : 'Waybill Dn230505 created in import' ; + } elsif ($row2 eq 'event_hub_code') { + # $val2 = ($tracking_detail_cnt eq '1') ? 'JNB' : 'JNB' ; + } elsif ($row2 eq 'event_time') { + # $val2 = ($tracking_detail_cnt eq '1') ? '0719' : '0718' ; + } + $row2 = ucfirst $row2 ; + # $sort_field_tracking_detail{$_} = ucfirst $sort_field_tracking_detail{$_} ; + + print "\n sort_field_tracking_detail : $sort_field_tracking_detail{$_}" ; + + $print_box_content_rows .= &common_min_form_view(" - $sort_field_tracking_detail{$_}",$val2,'') ; + } + next ; + } elsif ($row eq 'waybill_date') { + # $val = '05052023' ; + } elsif ($row eq 'waybill_number') { + # $val = 'Dn230505' ; + } + + $print_box_content_rows .= &common_min_form_view($row,$val,'') ; + } + + + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + +$trigger_jquery_raw .= qq(\$("#savebutt").click(function() { + var sc_val = \$("#selectAssigned_users").chosen().val() ; + \$('#assigned-users').val(sc_val); + \$('#events-form').submit(); +});) ; + +&common_min_alert_type ; + +&common_min_footer('id','') ; + +&common_min_dialog ; + +print < + + + $print_top + +
    +
    + $events_content +
    + +
    + +
    +
    +
    +
    +

    $boxtitle DCB Track & Trace

    +
    +
    + $print_box_content_rows +
    +
    +
    +
    +
    + +
    + +
    + + + + + +$dialog{'common'}{'js'} + + + + + + +$print_footer_jscript +$print_footer_forms + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +sub start_html { + +print < + + + + $useropts{title} + + + +Fetching tickets..." + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +sub reload_parent { + +# my $jquery_raw = qq~parent.location.reload(); + # parent.\$("#alertbar").html(""); + # parent.BootstrapDialog.closeAll() ;~; + +if ($debug) { $jquery_raw = '' ; } + +print < + +\$(function () { + $jquery_raw +}); + + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use db ; +use dcb ; +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/dialog/email.pl b/scripts/_FromProd/v1.0/dialog/email.pl new file mode 100644 index 0000000..1d7a7bf --- /dev/null +++ b/scripts/_FromProd/v1.0/dialog/email.pl @@ -0,0 +1,448 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); +use LWP::Simple qw($ua get); +use Date::Calc qw(:all); +use MIME::Lite; +use Mail::Sendmail; +use File::Copy; +use File::Basename; + +require cfg ; + +print header; # CGI.pm method + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +my $wb_no = $ARGV[0] ; +my $mn_id = $ARGV[1] ; + +my ($q) = CGI -> new() ; +my $iaction = $q -> param('iaction') ; +my $iemail = $q -> param('iemail') ; +my $imsg = $q -> param('imsg') ; +my $isubject = $q -> param('isubject') ; + +$input{manifest} = $q -> param('manifest') ; +$input{invoice} = $q -> param('invoice') ; +$input{waybillmulti} = $q -> param('waybillmulti') ; + +my $iattach = $q->upload('iattach') ; + +# our $debug = 1 ; + +#------------------------------------------------------------------------------------------ + +&today ; + +if ($iaction eq ''){ + &read_db ; + &journey_attachments ; + &screen1 ; + } + +if ($iaction eq 'send'){ + &read_db ; + &send_email ; + &screen2 ; + } + +exit; + +#------------------------------------------------------------------------------------------ + +sub read_db { + +&db_load_airports ; + +&db_min_ro('users','*',"`id`='$userid'",'','') ; +foreach my $us_id (keys %{$db{users}}) { + $email{$us_id} = $db{users}{$us_id}{email} ; + } + +&db_min_ro('waybills','*',"`WaybillNo`='$wb_no'",'','') ; +foreach my $wb_id (keys %{$db{waybills}}) { + $client{$wb_id} = $db{waybills}{$wb_id}{Client} ; + # $mawb_no{$wb_id} = $db{waybills}{$wb_id}{MawbNo} ; + + # $origin_airp_code{$wb_id} = $airport_code{$db{waybills}{$wb_id}{OriginID}} ; + # $dest_airp_code{$wb_id} = $airport_code{$db{waybills}{$wb_id}{DestID}} ; + } + +&db_min_ro('clients','*',"`Client`='$client{$wb_no}'",'','') ; +foreach my $id (keys %{$db{clients}}) { + $client = $db{clients}{$id}{Client} ; + + $client_id{$wb_no} = $id ; + + $client_email1{$id} = $db{clients}{$id}{Email1} ; + $client_phoneno{$id} = $db{clients}{$id}{PhoneNo} ; + $client_contact1{$id} = $db{clients}{$id}{Contact1} ; + } + +&db_min_ro('manifests','*',"`ManifestID`='$mn_id'",'','') ; +foreach my $id (keys %{$db{manifests}}) { + # $mawb_no{$db{manifests}{$id}{WaybillNo}} = $db{manifests}{$id}{MawbNo} ; + $mawb_no{$mn_id} = $db{manifests}{$id}{MawbNo} ; + $mawb_from{$mn_id} = $db{manifests}{$id}{ManifestFrom} ; + $mawb_to{$mn_id} = $db{manifests}{$id}{ManifestTo} ; + } + +# our $mawb_subj = '' ; if ($mawb_no{$wb_no}) { $mawb_subj = " : MAWB $mawb_no{$wb_no}" ; } +our $mawb_subj = '' ; if ($mawb_no{$mn_id}) { $mawb_subj = " : MAWB $mawb_no{$mn_id}" ; } +# our $airp_subj = '' ; if (($origin_airp_code{$wb_no}) and ($dest_airp_code{$wb_no})) { $airp_subj = " - $origin_airp_code{$wb_no}-$dest_airp_code{$wb_no}" ; } +our $airp_subj = '' ; if (($airport_code{$mawb_from{$mn_id}}) and ($airport_code{$mawb_to{$mn_id}})) { $airp_subj = " - $airport_code{$mawb_from{$mn_id}}-$airport_code{$mawb_to{$mn_id}}" ; } + +# my ($inv_year,$inv_mm,$inv_dd) = split(/\-/,$inv_date{$inv_id}); + +# our $month_to_txt = Month_to_Text($inv_mm); + +# my $client_to = $client_contact1{$client_id{$wb_no}} ; unless ($client_to) { $client_to = $client_id{$wb_no} ; } + +$message = qq(Good day + +Please find attached Pre-alert. + +Kind Regards, + +-- + +Film Freight +Johannesburg: +27 11 706 0143 +Cape Town: +27 21 802 3456 +Email : filmfreight\@filmfreight.co.za +Website: www.filmfreight.co.za) ; + +} #------------------------------------------------------------------------------------------ + +sub send_email { + +my $bcc = 'vivian@filmfreight.co.za' ; + +if ($email{$userid}) { $bcc = $email{$userid} ; } + +if ($username eq 'rory') { $bcc = 'rory@kre8it.co.za' ; } + +# Subject => "Film Freight Pre-alert$mawb_subj$airp_subj", + +$msg = MIME::Lite -> new( + From => "Film Freight ", + To => $iemail, + Bcc => $bcc, + Subject => $isubject, + Type => 'multipart/mixed' +); + +$msg->attach( + Encoding => 'base64', + Type => 'image/png', + Path => "$htmlpath/img/email_logo.jpg", + Id => 'logo' + # Disposition => 'inline', +); + +$msg -> attach( + Type => 'TEXT', + Data => $imsg); + +# my $texto = "

    $imsg "; + +# $msg->attach( + # Type => 'text/html', + # Data => $texto, + # Encoding => 'quoted-printable' +# ); + +if ($input{manifest}){ + $attachfile = &check_attachments('manifest',$mn_id) ; + &add_attachments('manifest',$attachfile,'pdf') ; + } + +if ($input{invoice}){ + $attachfile = &check_attachments('invoice',$client_id{$wb_no}) ; + &add_attachments('invoice',$attachfile,'pdf') ; + } + +if ($input{waybillmulti}){ + $attachfile = &check_attachments('waybillmulti',$client_id{$wb_no}) ; + &add_attachments('waybillmulti',$attachfile,'pdf') ; + } + +for my $jcnt (0 .. 5) { + my $j = $q -> param("journeys_$jcnt") ; + # &common_debug("send_email : attach_journey [$j]"); + if ($j) { $attach_journey{$j} = 1 ; } + } + +&attach_journey_mawbs; + +# exit; + +# if ($input{journeys}){ + # &attach_journey_mawbs; + # } + +if ($iattach) { + +$msg -> attach ( +Type => 'AUTO', +FH => $iattach, +Filename => $iattach, +Disposition => 'attachment' +) or die "Error adding : $attachdoc $!\n"; + +} + +$msg -> send ('smtp','localhost', Debug=>0 ); + +} #------------------------------------------------------------------------------- + +sub add_attachments { + +my ($type,$attachfile,$path) = @_ ; + +unless ($attachfile) { print "no file to attach!" ; exit ; } + +my $attachdoc = $htmlpath . '/' . $path . '/' . $type . '/' . $attachfile ; + +unless (-e $attachdoc) { print "no file to attach : $attachdoc!" ; exit ; } + +$msg -> attach ( +Type => 'AUTO', +Path => $attachdoc, +Filename => $attachfile, +Disposition => 'attachment' +) or die "Error adding : $attachdoc $!\n"; + +} #------------------------------------------------------------------------------- + +sub attach_journey_mawbs { + +&db_load_hawb_journeys_detail($wb_no) ; + +foreach my $wb (keys %journeys) { + foreach my $jnid (sort {$a <=> $b} keys %{$journeys{$wb}}) { + %uploads_list = (); + + &common_get_uploads("journeys/$jnid") ; + + if ($uploads_list{'mawb'}) { + my @files = split(/\|/,$uploads_list{'mawb'}) ; + + foreach my $file (@files) { + # &common_debug("attach_journey_mawbs : add_attachments [$attach_journey{$file}] $file"); + unless ($attach_journey{$file}) { next ; } # skip if checkbox not selected + &add_attachments("journeys/$jnid",$file,'uploads') ; + } + } + } + } + +} #------------------------------------------------------------------------------- + +sub check_attachments { + +my ($type,$doc_id) = @_ ; + +my $docpath = $pdfpath . '/' . $type ; + +my $attachfile = '' ; + +opendir(DIR, "$docpath") or die "cant open directory: $invoicepath - $!\n"; + +while(defined($folder = readdir(DIR))) { + if (length $folder > 2) { + my ($file,$type) = split(/\./,$folder) ; + unless (lc $type eq 'pdf') { next ; } + my ($prefix,$doc_nr,$invtxt,$date) = split(/\-/,$file) ; + unless ($doc_nr eq $doc_id) { next ; } + $attachfile = $folder ; + } + } + +closedir(DIR) ; + +return($attachfile); + +} #------------------------------------------------------------------------------- + +sub journey_attachments { + +our @journeys = () ; our $jn_wb_list = '' ; + +&db_load_hawb_journeys($wb_no) ; + +foreach my $jn (@journeys) { + my ($wb_no,$jn_id) = split(/\:/,$jn); + + unless ($done_jn{$jn_id}) { + &common_get_uploads("journeys/$jn_id") ; + &db_load_journey($jn_id,'') ; + $done_jn{$jn_id} = 1 ; + foreach my $wb (@hawbs) { + unless ($done_wb{$wb}) { $jn_wb_list .= $wb . '|' ; $done_wb{$wb} = 1 ; } + } + } + } + +} #------------------------------------------------------------------------------- + +sub screen1 { + +unless ($jn_wb_list) { $jn_wb_list = $wb_no ; } + +&common_min_dialog ; + +$attach_pdf .= qq(  Invoice PDF); +$attach_pdf .= qq( ); +$attach_pdf .= qq(  Waybill PDF); +$attach_pdf .= qq( ); + +if ($mn_id) { + $attach_pdf .= qq(  Manifest PDF); + $attach_pdf .= qq( ); + } + +my @mawb_links = split(/\|/,$attach_link_split{'mawb'}) ; my $mawb_cnt = 0 ; +my @mawb_uploads = split(/\|/,$uploads_list{'mawb'}) ; + +foreach my $mawb_pdf (@mawb_links) { + $attach_pdf .= "  " . $mawb_pdf ; + $mawb_cnt++; + } + +# if ($attach_link{'mawb'}) { $attach_pdf .= "  " . $attach_link{'mawb'} ; } + +print < + +
    +
    Attach : $attach_pdf
    +
    +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    + +
     
    +
    +
    +   + +
    +
    +
     
    +
    +
    +
    +
    +
    +
    + + + + + + +$dialog{'common'}{'js'} + + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + +print < + + + + Film Freight Admin + + + + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use today ; +use common ; +use common_min ; +use db_min ; + +1; diff --git a/scripts/_FromProd/v1.0/dialog/event_email.pl b/scripts/_FromProd/v1.0/dialog/event_email.pl new file mode 100644 index 0000000..4fb01aa --- /dev/null +++ b/scripts/_FromProd/v1.0/dialog/event_email.pl @@ -0,0 +1,445 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); +use LWP::Simple qw($ua get); +use Date::Calc qw(:all); +use MIME::Lite; +use Mail::Sendmail; +use File::Copy; +use File::Basename; + +require cfg ; + +print header; # CGI.pm method + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +my $e_id = $ARGV[0] ; + +my ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') ; +our $iemail = $q -> param('iemail') ; +our $iotheremailaddress = $q -> param('iotheremailaddress') ; +our $imsg = $q -> param('imsg') ; +our $isubject = $q -> param('isubject') ; +our $iattach = $q -> upload('iattach') ; + +$input{event_details} = $q -> param('event_details') ; + +our $debug = 1 ; + +#------------------------------------------------------------------------------------------ + +&today ; + +&db_open_ro ; + $db_ignore_open_close = 1 ; + + if ($iaction eq '') { + &read_db ; + &screen1 ; + } + + if ($iaction eq 'send') { + &read_db ; + &send_email ; + &screen2 ; + } + + $db_ignore_open_close = 0 ; +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub read_db { + + our $message = qq~~ ; + + if ($iaction eq 'send') { + + &create_event_email_table($e_id) ; + + my %seen_email = () ; our $emails = qq~~ ; + + foreach (split(",",$iotheremailaddress)) { + next if $seen_email{$_} ; + $seen_email{$_} = 1 ; + $emails .= qq~$_,~ ; + } + + $emails .= qq~$iemail~ if not $seen_email{$iemail} and $iemail ; + chop $emails if $seen_email{$iemail} or not $iemail ; + + our %operator_email = () ; our %operator_name = () ; our %operator_email_to_id = () ; + $seen_email{$db{users}{$db{event_quotes}{1}{user_id}}{email}} = 1; + foreach (sort {$db{users}{$a}{email} cmp $db{users}{$b}{email}} keys %{$db{users}}) { + $operator_name{$db{users}{$_}{email}} = $db{users}{$_}{name} ; + if (substr($db{users}{$_}{user_type},0,6) eq 'casual') { + $operator_email{$db{users}{$_}{email}} = 1 ; + $operator_email_to_id{$db{users}{$_}{email}} = $_ ; + } + + } + + } elsif ($iaction eq '') { + + &db_min_ro('event_quotes','1,operator_ids,user_id,ref,date_from',"`id`='$e_id'",'','') ; + + foreach (split(",",$db{event_quotes}{1}{operator_ids})) { + $selected{email_other}{$_} = 'SELECTED' ; + } + # $selected{email_other}{$userid} = 'SELECTED' ; + + # &db_min_ro('users','id,email',"`user_type` LIKE 'casual%' OR `user_type` = 'schools_manager' OR `id` = '$userid'",'','') ; + &db_min_ro('users','id,email,user_type,name',"",'','') ; # `user_type` LIKE 'casual%' OR `id` = '$db{event_quotes}{1}{user_id}' + + my %seen_email = () ; + $seen_email{$db{users}{$db{event_quotes}{1}{user_id}}{email}} = 1; + foreach (sort {$db{users}{$a}{email} cmp $db{users}{$b}{email}} keys %{$db{users}}) { + next if $seen_email{$db{users}{$_}{email}} ; + $seen_email{$db{users}{$_}{email}} = 1 ; + if (substr($db{users}{$_}{user_type},0,6) eq 'casual') { + $operator_email{$db{users}{$_}{email}} = 1 ; + $opts{email_other} .= qq~~ if $db{event_quotes}{1}{user_id} ne $_ ; + } + + } + $message = qq~Good day + +Please find attached event details. +~ ; + + } + +} #------------------------------------------------------------------------------------------ + +sub send_email { + + &common_debug("\n iemail : $emails") ; + + my $bcc = "$email_events{1};$email_events{2}" ; + + if ($email{$userid}) { $bcc = $email{$userid} ; } + + if ($username eq 'rory') { $bcc = $email_it_1 ; } + if ($username eq 'handre') { $bcc = $email_it_2 ; } + + my $attachpath = "$pdfpath/event_details" ; $attachfile = "Event_Details-$e_id.pdf" ; + + if (not -f "$attachpath/$attachfile" || not $input{event_details}) { + $attachpath = '' ; $attachfile = '' ; + } + + $imsg =~ s/\n/
    /g; + + # my @email_adds = split(/\,/,$emails) ; + # my $email_adds = join(";",@email_adds) ; + + # &common_debug("\n iemail : $emails") ; + # exit ; + + # &common_send_smtp_mail('',$email_adds,'',$bcc,$isubject,$imsg,$table_message,1,'',$attachpath,$attachfile,'',$iattach) ; + + # $imsg =~ s/:/<\/td>:/g; + # $imsg = qq~$imsg~ ; + # &common_send_smtp_mail('',$iemail,'',$bcc,$isubject,$imsg,1,'',$attachpath,$attachfile,'') ; + + my $message_operator = qq~~ ; my $emailed_operators = qq~~ ; + + my $attach_flyer = 0 ; + $attach_flyer = 1 if $usertype eq 'schools_manager' or $username eq 'handre' ; + + foreach (split(",",$emails)) { + + if ($operator_email{$_}) { + $emailed_operators .= qq~$operator_email_to_id{$_};~ ; + } + + + if ($operator_email{$_} || $_ eq $email_it_2 || $_ eq $email_it_1) { + + my @cat_details = split('\|;\|',$db{event_quotes_min}{1}{category_details}) ; + + my $time_from = substr($db{event_quotes}{1}{date_from},11,5) ; + + $sports = uc $sports ; + + my $cat_1 = qq~~ ; my $cat_2 = qq~~ ; my $cat_1_sub = qq~~ ; my $cat_2_sub = qq~~ ; + + $cat_1 = qq~CAT1: $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_1}}{category}~ if $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_1}}{category} ; + $cat_1_sub = qq~SUB1: $cat_details[0]~ if $cat_details[0] ; + # $cat_1 .= qq~
    ~ if $cat_1 and not $cat_1_sub ; + $cat_2 = qq~CAT2: $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_2}}{category}~ if $db{event_quotes_categories}{$db{event_quotes}{1}{category_id_2}}{category} ; + $cat_2_sub = qq~SUB2: $cat_details[1]~ if $cat_details[1] ; + # Hi $operator_name{$_} + +# $db{event_quotes}{1}{ref} @$time_from + +# $sports + +# $cat_1 +# $cat_1_sub +# $cat_2 +# $cat_2_sub + $message_operator = qq~Hi $operator_name{$_} + +$db{event_quotes}{1}{ref} AT $time_from + +$sports + +$cat_1 +$cat_1_sub +$cat_2 +$cat_2_sub + +Please let me know if you need anything. + +Thanks, +$db{users}{$userid}{name}~ ; + +# +27 82 439 6656 +# Brandon Scullard + $message_operator =~ s/\n/
    /g ; + &common_send_smtp_mail('',$_,'',$bcc,$isubject,$message_operator,'',1,'',$attachpath,$attachfile,'',$iattach,$attach_flyer) ; + + } else { + &common_send_smtp_mail('',$_,'',$bcc,$isubject,$imsg,$table_message,1,'',$attachpath,$attachfile,'',$iattach,$attach_flyer) ; + } + + } + + chop $emailed_operators if $emailed_operators ; + + %i = () ; + $i{emailed_op_ids} = $emailed_operators ; + &db_min_upd('event_quotes',"`id`='$e_id'") ; + + +} #------------------------------------------------------------------------------- + +sub add_attachments { + + my ($path,$attachfile) = @_ ; + + unless ($attachfile) { print "no file to attach!" ; exit ; } + + my $attachdoc = $pdfpath . '/' . $path . '/' . $attachfile ; + + unless (-e $attachdoc) { print "no file to attach : $attachdoc!" ; exit ; } + + $msg -> attach ( + Type => 'AUTO', + Path => $attachdoc, + Filename => $attachfile, + Disposition => 'attachment' + ) or die "Error adding : $attachdoc $!\n" ; + +} #------------------------------------------------------------------------------- + +sub check_attachments { + + my ($path,$doc_id) = @_ ; + + my $docpath = $pdfpath . '/' . $path ; + + &common_debug("check_attachments : $attachfile") ; + + my $attachfile = '' ; + + opendir(DIR, "$docpath") or die "cant open directory: $invoicepath - $!\n"; + + while(defined($folder = readdir(DIR))) { + if (length $folder > 2) { + my ($file,$type) = split(/\./,$folder) ; + &common_debug("check_attachments : $file.$type") ; + unless (lc $type eq 'pdf') { next ; } + my ($prefix,$doc_nr,$invtxt,$date) = split(/\-/,$file) ; + &common_debug("check_attachments : $prefix,$doc_nr,$invtxt,$date [$doc_nr eq $doc_id]") ; + unless ($doc_nr eq $doc_id) { next ; } + $attachfile = $folder ; + } + } + + closedir(DIR) ; + + return($attachfile); + +} #------------------------------------------------------------------------------- + +sub screen1 { + +&common_min_dialog ; + +# https://itvadmin.co.za/cgi-bin/scripts/pdf/event_details_pdf_test.pl?5136&& + +$attach_pdf .= qq(  Event Details PDF); +$attach_pdf .= qq( ); + +$lcol = 3 ; $fcol = 8 ; +$multiple{email_other} = 1 ; +$preferred_title{email_other} = "Operators Email Addresses" ; +$print_box_content_rows .= &common_min_form_select('email_other','') ; + +my $date_from = $db{event_quotes}{1}{date_from} ; +my $event_from = Date_to_Text(substr($date_from,0,4),substr($date_from,5,2),substr($date_from,8,2)); + +# &common_debug("year : " . substr($date_from,0,4)) ; +# &common_debug("month : " . substr($date_from,5,2)) ; +# &common_debug("day : " . substr($date_from,8,2)) ; + +print < + +
    +
    +
    + Attach : $attach_pdf +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    + $print_box_content_rows + +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +   +
    +
    +
    +
    +   + +
    +
    +
    +
    +   +
    +
    +
    +
    +
    +
    +
    +
    + + + + + + + $dialog{'common'}{'js'} + + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + +my $jquery_raw = qq~parent.BootstrapDialog.closeAll() ;~ unless $username eq 'rory' ; + +print < + + + + $useropts{title} + + + + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use event_email ; +use today ; +use common ; +use common_min ; +use db_min ; + +1; diff --git a/scripts/_FromProd/v1.0/dialog/events.pl b/scripts/_FromProd/v1.0/dialog/events.pl new file mode 100644 index 0000000..4fa59be --- /dev/null +++ b/scripts/_FromProd/v1.0/dialog/events.pl @@ -0,0 +1,1870 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); +use Date::Calc qw(:all); +# use Date::Calc qw(Add_Delta_Days) ; + +require cfg ; + +print header; # CGI.pm method + +use POSIX; + +#------------------------------------------------------------------------------------------ + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); + +our $qid = $ARGV[0] ; +our $qaction = $ARGV[1] ; + +if ($qid eq 'event') { + $qid = $qaction ; + $qaction = 'view' ; +} + +our ($q) = CGI -> new() ; +$iaction = $q -> param('iaction') || $qaction ; +$id = $q -> param('id') || $qid ; + +our $dialog = 1 ; + +#------------------------------------------------------------------------------------------ +our $savjqy = 1 ; +our $addbkb = 1 ; +# our $testing = 1 ; +# our $debug = 1 ; +our $max_operators = 15 ; + +#------------------------------------------------------------------------------------------ + +# &common_debug("dialog/events.pl [$iaction]") ; + +&today ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +$table = 'events' ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +if ($iaction eq '') { + &load_events ; + &screen1 ; +} + +if ($iaction eq 'add') { + &add_form; + &screen2 ; +} + +if ($iaction eq 'edit') { + &common_min_load_params ; + &edit_form; + &screen2 ; +} + +if ($iaction eq 'save') { + &common_min_load_params ; + &insert_events ; + &screen3 ; +} + +if ($iaction eq 'update') { + &common_min_load_params ; + &update_events ; + &screen3 ; +} + +if ($iaction eq 'delete') { + &common_min_load_params ; + &delete_events ; + &screen3 ; +} + +if ($iaction eq 'view') { + &common_min_load_params ; + &view_form; + &screen2 ; +} + +if ($iaction eq 'available' or $iaction eq 'unavailable' or $iaction eq 'confirm') { + &common_min_load_params ; + &update_events_staff ; + &screen3 ; +} + +# if ($iaction eq 'saveoperator'){ + # &common_min_load_params ; + # &save_operator ; + # &screen3 ; + # } + +exit ; + +#------------------------------------------------------------------------------------------ + +# sub save_operator { + + # $ignore{iaction} = 1 ; + # $ignore{event_quote_nr} = 1 ; + + # &db_open_upd ; + # our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + # @operators_a = split(/\,/,$i{operators_type_a}) ; + # @operators_b = split(/\,/,$i{operators_type_b}) ; + + # my %selected_operator_a = () ; + # my %selected_operator_b = () ; + + # for (@operators_a) { + # $selected_operators{$_} = 1; + # } + # for (@operators_b) { + # $selected_operators{$_} = 1; + # } + # my %operator_type = () ; + # &db_min_ro('users','id,user_type',"user_type LIKE 'casual%'",'','') ; + # foreach (keys %{$db{users}}) { + # $operator_type{$_} = uc substr($db{users}{$_}{user_type},-1,1) ; + # } + + # # my @db_operators_a = () ; foreach (@operators_a) { push @db_operators_a, $_ ; } + # # my @db_operators_b = () ; foreach (@operators_b) { push @db_operators_b, $_ ; } + + # # my $operators_a = join(',',@db_operators_a) ; + # # my $operators_b = join(',',@db_operators_b) ; + + # $ignore{operators_type_a} = 1 ; + # $ignore{operators_type_b} = 1 ; + + # %exist_col = () ; + + # # for (1 .. $max_operators) { + # push @sql_fields, "operator_workings_event" ; + # push @sql_fields, "description_workings_event" ; + # push @sql_fields, "qty_workings_event" ; + # push @sql_fields, "amount_usd_workings_event" ; + # # } + + # my $select = join(",", @sql_fields) ; + + # &db_min_ro('event_quotes_min',"id,$select","quote_nr='$i{event_quote_nr}'",'','') ; + + # my %seen_operator = () ; + # my $first_avail_col = 0 ; + # my $col = 0 ; + # my @deselected_operator_a = () ; + # my @deselected_operator_b = () ; + + # # for (1 .. $max_operators) { + # # $col = $max_operators - $_ + 1 ; + # # last if $db{event_quotes}{$i{event_quote_nr}}{"description_$col\_workings_event"} ; + # # $first_avail_col = $col ; + # # } + # # for (1 .. $max_operators) { + # my $op_id = $db{event_quotes}{$i{event_quote_nr}}{"operator_$_\_workings_event"} ; + # if ($op_id and not $selected_operators{$op_id}){ + # $i{"operator_$_\_workings_event"} = '' ; + # $i{"description_$_\_workings_event"} = '' ; + # $i{"qty_$_\_workings_event"} = 0 ; + # $i{"amount_usd_$_\_workings_event"} = '0.00' ; + # # } + # # next unless $op_id ; + # # $seen_operator{$op_id} = 1 ; + # } + # # } + + # my @new_operators_a = () ; + # my @new_operators_b = () ; + + # for (@operators_a){ + # next if $seen_operator{$_} ; + # push @new_operators_a, $_ ; + # } + + # for (@operators_b){ + # next if $seen_operator{$_} ; + # push @new_operators_b, $_ ; + # } + + # for (@new_operators_a){ + # $i{"qty_workings_event"} = 1 ; + # $i{"amount_usd_workings_event"} = '0.00' ; + # $i{"operator_workings_event"} = $_ ; + # $i{"description_workings_event"} = '14' ; + # $first_avail_col++; + # } + # for (@new_operators_b){ + # $i{"qty_workings_event"} = 1 ; + # $i{"amount_usd_workings_event"} = '0.00' ; + # $i{"operator_workings_event"} = $_ ; + # $i{"description_workings_event"} = '14' ; + # $first_avail_col++; + # } + + # &db_min_upd('event_quotes',"quote_nr='$i{event_quote_nr}'") ; + + # # foreach (keys %i) { + # # if (substr($_,0,3) eq 'new') { next ; } + # # if ($ignore{$_}) { next ; } + # # if ($hidden{$_} == 1) { next ; } + # # if ($i{$_} =~ /\"/) { $set .= qq(`$_`='$i{$_}',) ; } elsif ($i{$_} eq 'NULL') { $set .= qq(`$_`=$i{$_},) ; } else { $set .= qq(`$_`="$i{$_}",) ; } + # # } + + # # &common_debug("UPDATE event_quotes SET $set WHERE quote_nr='$i{event_quote_nr}'") ; + + + + # # # for (1 .. $max_operators) { + # # for $op_cnt ($max_operators .. 1) { + # # my $ex_col = "operator_$op_cnt\_workings_event" ; + # # my $op_id = $db{event_quotes}{$eid}{$ex_col} ; + # # # next unless $op_id ; + # # $first_avail_col = $op_cnt unless $op_id ; + + # # foreach $op_a (@operators_a) { + # # if ($op_a eq $op_id) { + # # $exist_col{$op_a} = $ex_col ; + # # } + # # } + # # foreach $op_b (@operators_b) { + # # if ($op_b eq $op_id) { + # # $exist_col{$op_b} = $ex_col ; + # # } + # # } + # # } + # # } + + # # # return unless $exist_col ; + + # # local $avail_col = ($first_avail_col) ? $first_avail_col : 1 ; + + # # foreach (@operators_a) { + # # next if $exist_col{$_} ; + # # local $field = "operator_$avail_col\_workings_event" ; + # # $i{$field} = $_ ; + # # # &db_min_upd('event_quotes',"quote_nr='$i{event_quote_nr}'") ; + + # # $avail_col++ + # # } + + # # foreach (@operators_b) { + # # next if $exist_col{$_} ; + # # local $field = "operator_$avail_col\_workings_event" ; + # # $i{$field} = $_ ; + # # # &db_min_upd('event_quotes',"quote_nr='$i{event_quote_nr}'") ; + # # $avail_col++ + # # } + + # $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + # &db_close_conn ; + + # # exit ; + +# } #------------------------------------------------------------------------------------------ + +# sub process_operators { + +# @operators_a = split(/\,/,$i{operators_type_a}) ; +# @operators_b = split(/\,/,$i{operators_type_b}) ; + +# my @db_operators_a = () ; foreach (@operators_a) { push @db_operators_a, $_ ; } +# my @db_operators_b = () ; foreach (@operators_b) { push @db_operators_b, $_ ; } + +# my $operators_a = join(',',@db_operators_a) ; +# my $operators_b = join(',',@db_operators_b) ; + +# $ignore{operators_type_a} = 1 ; +# $ignore{operators_type_b} = 1 ; + +# # $i{operator_names_type_a} = $operators_a ; +# # $i{operator_names_type_b} = $operators_b ; + +# } #------------------------------------------------------------------------------------------ + +sub update_events_staff { + + # local $exist_col = '' ; + # local $avail_col = '' ; + + local $exists = '' ; + &db_min_ro('events','id,event_quote_nr',"event_quote_nr='$i{event_quote_nr}' AND user_id='$userid'",'','') ; + foreach my $eid (keys %{$db{events}}) { $exists = 1 if $db{events}{$eid}{event_quote_nr} eq $i{event_quote_nr} ; } + + # for (1 .. $max_operators) { + # push @sql_fields, "operator_$_\_workings_event" ; + # } + + # my $select = join(",", @sql_fields) ; + + # &db_min_ro('event_quotes',"id,$select","quote_nr='$i{event_quote_nr}'",'','') ; + # foreach my $eid (keys %{$db{event_quotes}}) { + # # for (1 .. $max_operators) { + # for ($max_operators .. 1) { + # my $ex_col = "operator_$_\_workings_event" ; + # my $op_id = $db{event_quotes}{$eid}{$ex_col} ; + # # next unless $op_id ; + # $avail_col = $ex_col unless $op_id ; + # if ($userid eq $op_id) { + # $exist_col = $ex_col ; + # # last ; + # } + # } + + # } + + # return unless $exist_col ; + + # if ($exist_col and $iaction eq 'unavailable') { + # $i{"$exist_col"} = '' ; # set unavailable + # &db_min_upd('event_quotes',"quote_nr='$i{event_quote_nr}'") ; + # } elsif ($iaction eq 'available' and $exist_col eq '' and $avail_col) { + # $i{"$avail_col"} = $userid ; # set available + # &db_min_upd('event_quotes',"quote_nr='$i{event_quote_nr}'") ; + # } + + $ignore{iaction} = 1 ; + + $i{date_time} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + + # $i{category} = 'available' if $iaction eq 'confirm' ; + + if ($exists) { + &db_min_upd('events',"event_quote_nr='$i{event_quote_nr}' AND user_id='$userid'") ; + } else { + &db_min_insert('events') ; + } + +} #------------------------------------------------------------------------------------------ + +sub update_events { + +unless ($i{id}) { $error = qq(NO ID) ; return ; } + +&hidden_fields ; + +$hidden{id} = 1 ; + +# $i{user_id} = $userid ; + +# if ($i{completed}) { $i{completeddate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; } else { $i{completed} = '0' ; } + +&db_min_upd('events',"id='$i{id}'") ; + +# &update_operators($i{event_quote_nr}) ; + +} #------------------------------------------------------------------------------------------ + +sub delete_events { + +unless ($i{id}) { $error = qq(NO ID) ; return ; } + +&db_min_delete('events',"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub insert_events { + +&hidden_fields ; + +# $i{id} = &db_min_get_max('events','id') ; + +# $i{user_id} = $userid ; + +# $i{operator_names_type_a} = ; + +$i{date_time} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&db_min_insert('events') ; + +# &update_operators($i{event_quote_nr}) ; + +} #------------------------------------------------------------------------------------------ + +# sub update_operators { + + # my ($iidd) = @_ ; + + # return unless $iidd ; + + # my $operators = qq~~ ; + # foreach (split(",",$i{operator_names_type_a})) { + # $operators .= qq~$_;~ ; + # } + + # foreach (split(",",$i{operator_names_type_b})) { + # $operators .= qq~$_;~ ; + # } + + # chop $operators if $operators ; + # # my $iidd = ; + # %i = () ; + # $i{id} = $iidd ; + # $i{operators_workings_event} = $operators ; + + # &db_common_upd('event_quotes_min',"id='$i{id}'") ; + +# } #------------------------------------------------------------------------------------------ + +sub hidden_fields { + +$textarea{notes} = 1 ; +# $required{title} = 1 ; +$required{category} = 1 ; + +if ($db{$table}{$id}{category} eq 'leave') { + $required{days} = 9 ; +} else { + $ignore{days} = 1 ; + $ignore{type} = 1 ; +} + +$datetimepicker{startdate} = 1 ; +$datetimepicker{enddate} = 1 ; + +$ignore{iaction} = 1 ; +$ignore{completed} = 1 ; +$ignore{title} = 1 ; +$ignore{operator_names_type_a} = 1 ; +$ignore{operator_names_type_b} = 1 ; + +$hidden{id} = 2 ; +# $hidden{user_id} = 2 ; +$hidden{date_time} = 2 ; + +# $checkbox{completed} = 2 ; + +$selected{category}{$db{$table}{$id}{category}} = 'SELECTED' ; + +$select{category} = 1 ; + +if ($db{$table}{$id}{category} eq 'leave') { + $opts{category} .= qq(); +} else { + # $opts{category} .= qq() ; + $opts{category} .= qq() ; + $opts{category} .= qq() ; + $opts{category} .= qq() ; +} + +# $opts{category} .= qq() ; +# $opts{category} .= qq() ; + +&sort_fields ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + +$sort_field{1} = 'category' ; +$sort_field{2} = 'startdate' ; +$sort_field{3} = 'enddate' ; +$sort_field{4} = 'user_id' ; +$sort_field{5} = 'notes' ; + +} #------------------------------------------------------------------------------- + +sub sort_leave_fields { + +$sort_field{1} = 'category' ; +$sort_field{2} = 'startdate' ; +$sort_field{3} = 'enddate' ; +$sort_field{4} = 'days' ; +$sort_field{5} = 'type' ; +$sort_field{6} = 'user_id' ; +$sort_field{7} = 'notes' ; + +} #------------------------------------------------------------------------------- + +sub edit_form { + + $boxtitle = 'Edit' ; + + &db_min_ro($table,'*',"id='$i{id}'",'','') ; + + &hidden_fields ; + + if ($db{$table}{$id}{category} eq 'leave') { + $selected{'type'}{$db{$table}{$i{id}}{type}} = 'SELECTED' ; + &common_min_opts('leave_type','type',1) ; + &sort_leave_fields ; + } + + &common_min_select_opts('user_id','users','name',$db{$table}{$id}{user_id},1) ; + + &display_user; + + $print_box_content_rows = &common_min_edit_form($i{id},$table,'update') ; + +} #------------------------------------------------------------------------------------------ + +sub view_form { + + &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + # our @month_array = ( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ) ; + our @month_array = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") ; + + our @months = ( "" , "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ) ; + + # @month_array = @months ; + + $boxtitle = 'View' ; + + $table = 'event_quotes' ; + + # &db_min_ro($table,'quote_nr,nr,quote_date,customer,country_id,ref,date_from,date_to,qty,currency,grand_total,invoice_nr',"quote_nr='$id'",'','') ; + # &db_min_ro($table,'quote_nr,quote_date,country_id,ref,date_from,date_to,qty,currency,grand_total,invoice_nr',"quote_nr='$id'",'','') ; + + $sort_field{1} = 'quote_nr' ; + $sort_field{2} = 'ref' ; + $sort_field{3} = 'date_from' ; + $sort_field{4} = 'date_to' ; + $sort_field{5} = 'type_of_system' ; + $sort_field{6} = 'type_details' if $usertype ne 'schools_manager' ; + # $sort_field{7} = 'system_name' if $usertype ne 'schools_manager' ; + $sort_field{7} = 'system_details' if $usertype ne 'schools_manager' ; + # $sort_field{8} = 'club_name' ; + $sort_field{9} = 'days' ; + $sort_field{10} = 'operators' ; + $sort_field{11} = 'sport_type_ids' ; + $sort_field{12} = 'city' ; + $sort_field{13} = 'region' ; + $sort_field{14} = 'venue' ; + + # $sort_field{1} = 'quote_nr' ; + # $sort_field{2} = 'ref' ; + # $sort_field{3} = 'date_from' ; + # $sort_field{4} = 'date_to' ; + # $sort_field{5} = 'type' ; + # $sort_field{6} = 'sport_type_ids' ; + # # $sort_field{7} = 'ligr' ; + # $sort_field{8} = 'location' ; + # $sort_field{9} = 'city_id' ; + # $sort_field{10} = 'organisation_ids' ; + # # $sort_field{5} = 'country_id' ; + # $sort_field{11} = 'quote_to' ; + # $sort_field{12} = 'notes' ; + # $sort_field{13} = 'nr_of_casuals' ; + # $sort_field{14} = 'operator_names_type_a' ; + # $sort_field{15} = 'nr_of_casuals_2' ; + # $sort_field{16} = 'operator_names_type_b' ; + + $sort_field{17} = 'poc_name' ; + $sort_field{18} = 'poc_contact_nr' ; + $sort_field{19} = 'category_1' ; + $sort_field{20} = 'category_1_sub_categories' ; + $sort_field{21} = 'category_2' ; + $sort_field{22} = 'category_2_sub_categories' ; + $sort_field{23} = 'recipient_name' ; + $sort_field{24} = 'recipient_nr' ; + $sort_field{25} = 'additional_notes' ; + $sort_field{26} = 'format_of_title' ; + + $preferred_title{organisation_ids} = "Venue(s)" ; + $preferred_title{sport_type_ids} = "Sport Types(s)" ; + + foreach (sort {$a <=> $b} keys %sort_field) { push @sql_fields, $sort_field{$_} ; } + + for (1 .. $max_operators) { + push @sql_fields, "operator_$_\_workings_event" ; + } + + my $select = join(",", @sql_fields) ; + + &db_min_ro('event_quotes_poc','id,name,contact_nr','','','') ; + + &db_min_ro('event_quotes_categories','id,category','','','') ; + + &db_min_ro('event_systems','id,name,description','','','') ; + + &db_min_ro('sport_types','id,name','','','') ; + + &db_min_ro('regions','id,name','','','') ; + + &db_min_ro('cities','id,name','','','') ; + + &db_min_ro('organisations','id,name','','','') ; + + &db_min_ro('event_type_details','id,name','','','') ; + + # &db_min_ro($table,"$select,casual_worker,casual_worker_2,user_id","quote_nr='$id'",'','') ; + + &db_min_ro('analytics_event_bookings','id,event_quote_id,fixtures_saved_values,analytics_saved_values,start_date_time,sport_type_ids,event_name',"event_quote_id <> '0' AND event_quote_id = '$id'",'','') ; + + &db_switch_conn('sss') ; + + &db_min_ro('teams','id,name','','','') ; + + &db_switch_conn('aisa') ; + + my @fixtures_saved_values = () ; + my @analytics_saved_values = () ; + + my %analytics_saved_values = () ; + + # our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + our $analytics_table_body = qq~~ ; our $analytics_table = qq~~ ; our $analytics_event_exists = 0 ; + + my $analytics_required = 0 ; + + foreach my $id (sort { $b <=> $a } keys %{$db{analytics_event_bookings}}) { + + $analytics_event_exists = 1 ; + # $analytics_event_exists = 0 ; + # $db{analytics_event_bookings}{$id}{analytics_saved_values} = "" ; + # $db{analytics_event_bookings}{$id}{fixtures_saved_values} = "" ; + + $analytics_required = 1 if !$db{analytics_event_bookings}{$id}{analytics_saved_values} && !$db{analytics_event_bookings}{$id}{fixtures_saved_values} ; + + $sort_field{27} = 'fixture_date/Time_from' ; + $sort_field{28} = 'sport' ; + $sort_field{29} = 'team' ; + $sort_field{30} = 'home_vs_opp_team' ; + $sort_field{31} = 'stream_forwarding' ; + $sort_field{32} = 'stream_key' ; + $sort_field{33} = 'stream_URL' ; + + $db{analytics_event_bookings}{$id}{fixtures_saved_values} =~ s/\|+$// ; + + $db{analytics_event_bookings}{$id}{fixtures_saved_values} = ";;;" unless $db{analytics_event_bookings}{$id}{fixtures_saved_values} ; + + @fixtures_saved_values = split(/\|/,$db{analytics_event_bookings}{$id}{fixtures_saved_values}) ; + + my $fixtures_row_cnt = 0 ; + + foreach (@fixtures_saved_values) { + + my @abc = split(/\;/,$_) ; + $fixtures_row_cnt++ ; + $analytics_saved_values{$id}{$fixtures_row_cnt}{$sort_field{27}} = ($abc[0]) ? &common_min_date_as_string($abc[0]) : ($db{analytics_event_bookings}{$id}{start_date_time}) ? &common_min_date_as_string($db{analytics_event_bookings}{$id}{start_date_time}) : &common_min_date_as_string("$now_year-$now_mm-$now_dd 08:00:00") ; + $analytics_saved_values{$id}{$fixtures_row_cnt}{$sort_field{28}} = ($abc[1]) ? $db{sport_types}{$abc[1]}{name} : ($db{analytics_event_bookings}{$id}{sport_type_ids} && $db{analytics_event_bookings}{$id}{sport_type_ids} !~ /;/) ? $db{sport_types}{$db{analytics_event_bookings}{$id}{sport_type_ids}}{name} : "N/A" ; + $analytics_saved_values{$id}{$fixtures_row_cnt}{$sort_field{29}} = ucfirst $abc[2] . ' ' . uc $abc[3] ; + $analytics_saved_values{$id}{$fixtures_row_cnt}{$sort_field{30}} = ($abc[4] && $abc[6]) ? $db{teams}{$abc[4]}{name} . ' vs ' . $db{teams}{$abc[6]}{name} : ($abc[4]) ? $db{teams}{$abc[4]}{name} . ' vs N/A' : ($abc[6]) ? 'N/A vs ' . $db{teams}{$abc[6]}{name} : "" ; + + } + + @analytics_saved_values_arr = split(/\|/,$db{analytics_event_bookings}{$id}{analytics_saved_values}) ; + + my $analytics_row_cnt = 0 ; + + foreach (@analytics_saved_values_arr) { + my @abc = split(/\;/,$_) ; + $analytics_row_cnt++ ; + $analytics_saved_values{$id}{$analytics_row_cnt}{$sort_field{31}} = ($abc[0] eq '1') ? "Yes" : ($abc[0] eq "2") ? "No" : "" ; + $analytics_saved_values{$id}{$analytics_row_cnt}{$sort_field{32}} = $abc[1] ; + $analytics_saved_values{$id}{$analytics_row_cnt}{$sort_field{33}} = ($abc[2]) ? qq~Click Here~ : qq~~ ; + } + + if ($analytics_row_cnt > $fixtures_row_cnt) { + for ($fixtures_row_cnt + 1 .. $analytics_row_cnt) { + $analytics_saved_values{$id}{$_}{$sort_field{27}} = ($db{analytics_event_bookings}{$id}{start_date_time}) ? &common_min_date_as_string($db{analytics_event_bookings}{$id}{start_date_time}) : &common_min_date_as_string("$now_year-$now_mm-$now_dd 08:00:00") ; + $analytics_saved_values{$id}{$_}{$sort_field{28}} = ($db{analytics_event_bookings}{$id}{sport_type_ids} && $db{analytics_event_bookings}{$id}{sport_type_ids} !~ /;/) ? $db{sport_types}{$db{analytics_event_bookings}{$id}{sport_type_ids}}{name} : "N/A" ; + } + } + + } + + if ($analytics_event_exists) { + + $useropts{'common'}{'css'} .= qq~ + table { + border-collapse: separate ; + border-spacing: 12.5px ; + width: 100% ; + font-size: 1em ; + } + + tbody tr { + line-height: 0 ; + } + + thead th { + line-height: 0 ; + } + + tbody td { + background-color: rgb(238,238,238) ; + } + + ~ ; + + my $table_header = "" . join ("", map { join(" ", map { ucfirst $_ } split (/\_/, $sort_field{$_} ) ) } (27 .. 33) ) . "" ; + + foreach my $analytics_id (sort {$b <=> $a} keys %analytics_saved_values) { + + my $analytics_table_raw = qq~~ ; + + foreach my $row_counter (sort {$a <=> $b} keys %{$analytics_saved_values{$analytics_id}}) { + + last if $analytics_required ; + + $analytics_table_raw .= qq~ + + ~ ; + + foreach my $col_nr (27 .. 33) { + + my $nowrap = ($col_nr == 27) ? "nowrap" : "" ; + + $analytics_table_raw .= ($analytics_saved_values{$analytics_id}{$row_counter}{$sort_field{$col_nr}}) ? qq~ + $analytics_saved_values{$analytics_id}{$row_counter}{$sort_field{$col_nr}} + ~ : qq~ + + ~ ; + } + + $analytics_table_raw .= qq~ + + ~ ; + + } + + $analytics_table .= qq~$analytics_table_raw~ if $analytics_table_raw ; + + #
    + #

    Analytics Required

    + #
    + + if ($analytics_table_raw) { + + # $analytics_table_body .= qq~ + #
    + #   + #
    + #
    + #
    + # ~ ; + + $analytics_table_body .= qq~
    ~ if $analytics_table_body ; + + $analytics_table_body .= &common_min_box_top('tasks',"View Analytics - $db{analytics_event_bookings}{$analytics_id}{event_name} [$analytics_id]") ; + + $analytics_table_body .= qq~ + + $table_header + $analytics_table_raw +
    + ~ ; + + } + } + } + + &db_min_ro($table,"*","quote_nr='$id'",'','') ; + + if ($db{$table}{$id}{city_id} =~ /,/) { + $sort_field{12} = 'cities' ; + } else { + $sort_field{13} = '' ; + } + + &db_min_ro('event_quotes_min',"*","id='$id'",'','') ; + + &db_min_ro('users','id,name,user_type,phone',"user_type LIKE 'casual%'",'','') ; + foreach (keys %{$db{users}}) { + $casual_name{$_} = $db{users}{$_}{name} ; + # my $casual_type = $db{users}{$_}{user_type} ; $casual_type =~ s/_casual//g ; + $casual_type{$_} = uc substr($db{users}{$_}{user_type},-1,1) ; + } + # %col_name = () ; + # &db_min_ro('countries','id,name',"id=$db{$table}{$id}{country_id}",'','') if $db{$table}{$id}{country_id} ; + # foreach (keys %{$db{countries}}) { $country{$_} = $db{countries}{$_}{name} ; } + %col_name = () ; + &db_min_ro('event_types','id,name',"id=$db{$table}{$id}{type}",'','') if $db{$table}{$id}{type} ; + foreach (keys %{$db{event_types}}) { $event_type{$_} = $db{event_types}{$_}{name} ; } + %col_name = () ; + &db_min_ro('customers','id,name',"id=$db{$table}{$id}{quote_to}",'','') if $db{$table}{$id}{quote_to} ; + foreach (keys %{$db{customers}}) { $customers{$_} = $db{customers}{$_}{name} ; } + %col_name = () ; + # &db_min_ro('events','id,event_quote_nr,category,user_id',"event_quote_nr='$id'",'','') ; + + # my $user_id = $db{$table}{$id}{user_id} ; + my $quote_nr = $db{$table}{$id}{quote_nr} ; + my $start = $db{$table}{$id}{date_from} ; + my $end = $db{$table}{$id}{date_to} ; + my $date_start = substr($start,0,10); + my $date_end = substr($end,0,10); + + # for (1 .. $max_operators) { + # local $field = "operator_$_\_workings_event" ; + # $op_id = $db{$table}{$id}{$field} ; + + my %selected_names = () ; + + # &common_debug("operator_workings_event : $db{event_quotes_min}{$id}{operator_workings_event} , id : $id") ; + + foreach my $op_id (split(";",$db{event_quotes_min}{$id}{operator_workings_event})) { + next unless $op_id ; + next if $done_op{$op_id}{$quote_nr} ; + $this_user_subscribed{$op_id} = 1 ; + $cat{$date_start}{$date_end}{$quote_nr}{$op_id} = 'assigned' ; + $ccnt{$date_start}{$date_end}{$casual_type{$op_id}}{$quote_nr}++ ; + $subscribed_names{$date_start}{$date_end}{$casual_type{$op_id}}{$quote_nr} .= "$casual_name{$op_id}, " ; + $done_op{$op_id}{$quote_nr} = 1 ; + # $selected_names{operator_names_type_a}{$op_id}{$id} = 'SELECTED' if $casual_type{$op_id} eq 'A' ; + # $selected_names{operator_names_type_b}{$op_id}{$id} = 'SELECTED' if $casual_type{$op_id} eq 'B' ; + + # &common_debug("op_id : $op_id , casual_type : $casual_type{$op_id} , id : $id") ; + + } + + &db_min_ro('events','id,event_quote_nr,category,user_id,startdate,enddate',"user_id='$userid' OR event_quote_nr='$id'",'','') ; + + # &db_min_ro('events','id,event_quote_nr,category,user_id,startdate,enddate',"(user_id='$userid' OR event_quote_nr='$id') AND startdate LIKE '$date_start%' AND enddate LIKE '$date_end%'",'','') ; + foreach (keys %{$db{events}}) { + my $start = $db{events}{$_}{startdate} ; my $edate_start = substr($start,0,10); + my $end = $db{events}{$_}{enddate} ; my $edate_end = substr($end,0,10); + $qnr = $db{events}{$_}{event_quote_nr} ; + $uid = $db{events}{$_}{user_id} ; + + if ($date_start ne $edate_start) { next ; } + if ($date_end ne $edate_end) { next ; } + + # $booked_this_one{$uid}{$qnr}{$db{events}{$_}{category}} = 1 ; + + $cat{$edate_start}{$edate_end}{$qnr}{$uid} = $db{events}{$_}{category} ; + # $ccnt{$edate_start}{$edate_end}{$casual_type{$uid}}{$qnr}++ if $cat{$edate_start}{$edate_end}{$qnr}{$uid} eq 'available' ; + # $subscribed_names{$edate_start}{$edate_end}{$casual_type{$uid}}{$qnr} .= "$casual_name{$uid}, " if $cat{$edate_start}{$edate_end}{$qnr}{$uid} eq 'available' ; + &check_dates_booked($qnr,$uid,$db{events}{$_}{startdate},$db{events}{$_}{enddate}) if $cat{$edate_start}{$edate_end}{$qnr}{$uid} eq 'available' ; + } + + my $casual_1_type = $db{$table}{$id}{casual_worker} ; + my $casual_2_type = $db{$table}{$id}{casual_worker_2} ; + + $preferred_title{date_from} = 'Date From' ; + $preferred_title{date_to} = 'Date To' ; + $preferred_title{quote_to} = 'Client' ; + $preferred_title{nr_of_casuals} = 'Nr of Operators' ; # . $casual_1_type ; + $preferred_title{nr_of_casuals_2} = 'Nr of Operators' ; # . $casual_2_type ; + $preferred_title{ref} = 'Event Name' ; + + $lcol = 2 ; $fcol = 8 ; + + # foreach (sort { $col_name{$a} cmp $col_name{$b} } keys %col_name) { + # $col = $col_name{$_} ; + + my $casuals_1_subscribed = sprintf("%0.0f",$ccnt{$date_start}{$date_end}{$casual_1_type}{$id}) ; + my $casuals_2_subscribed = sprintf("%0.0f",$ccnt{$date_start}{$date_end}{$casual_2_type}{$id}) ; + chop $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} ; chop $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} ; + chop $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} ; chop $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} ; + my $casual_1_names_subscribed = '[' . $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} . ']' if $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} ; + my $casual_2_names_subscribed = '[' . $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} . ']' if $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} ; + + # my $operator_id = 0 ; + # my %selected_names = () ; + # for (1 .. $max_operators) { + # $operator_id = $db{$table}{$id}{"operator_$_\_workings_event"} ; + # $selected_names{operator_names_type_a}{$operator_id}{$id} = 'SELECTED' if $operator_id and $casual_type{$operator_id} eq 'A' ; + # $selected_names{operator_names_type_b}{$operator_id}{$id} = 'SELECTED' if $operator_id and $casual_type{$operator_id} eq 'B' ; + # } + # $selected_names{operator_names_type_a}{48}{$id} = 'SELECTED' ; + + foreach my $casual_id (keys %casual_name){ + $opts{operator_names_type_a} .= qq() if $casual_type{$casual_id} eq 'A' ; + $opts{operator_names_type_b} .= qq() if $casual_type{$casual_id} eq 'B' ; + } + + my @club_ids_arr = () ; + foreach (split(";",$db{$table}{$id}{club_ids})) { + push @club_ids_arr , "`id` = '$_'" if $_ ; + } + my $club_ids_sql = join(" OR ",@club_ids_arr) ; + $club_ids_sql = "($club_ids_sql)" if $club_ids_sql ; + + &db_min_ro('clubs','id,name',"$club_ids_sql",'',''); + + if ($date_start eq $date_end) { + $sort_field{3} = 'date' ; + $sort_field{4} = '' ; + $preferred_title{date_from} = 'Date' ; + } + + my @times_from = split(/\;/,$db{$table}{$id}{times_from}) ; + my @times_to = split(/\;/,$db{$table}{$id}{times_to}) ; + my @times_from_com = () ; my @times_to_com = () ; + push @times_from_com,substr($db{$table}{$id}{date_from},11) ; + + my @days_active = split(/\;/,$db{$table}{$id}{days_active}) ; + + my %dates_hash = () ; + + for (1 .. 10) { + my ($year,$month,$day) = split(/\-/,substr($db{$table}{$id}{date_from},0,10)) ; + my ($new_year,$new_month,$new_day) = Add_Delta_Days($year,$month,$day,$_-1) ; + $new_day = sprintf("%02s",$new_day) ; $new_month = sprintf("%02s",$new_month) ; + $dates_hash{$_} = "$new_year-$new_month-$new_day" ; + push @times_from_com,$times_from[$_-2] if $times_from[$_-2] && $_ > 1 ; + push @times_from_com,substr($db{$table}{$id}{date_from},11) if !$times_from[$_-2] && $_ > 1 ; + last if substr($db{$table}{$id}{date_to},0,10) eq "$new_year-$new_month-$new_day" ; + push @times_to_com,$times_to[$_-1] if $times_to[$_-1] ; + push @times_to_com,substr($db{$table}{$id}{date_to},11) if !$times_to[$_-1] ; + } + + my $system_count = 0 ; my $system_day_cnt = 0 ; my %system_has_daily_op = () ; + + foreach my $system_row (split(/\|/,$db{$table}{$id}{daily_operator_ids})) { + $system_count++ ; + next unless $system_row ; + $system_day_cnt = 0 ; + foreach my $col (split(/\;/,$system_row)) { + $system_day_cnt++ ; + next unless $col ; + $default_op_ids{$system_count}{$system_day_cnt} = $col if $col ; + $system_daily_ops{$system_count} .= qq~Day $system_day_cnt : $db{users}{$col}{name}, ~ if $col ; + } + chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ; + chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ; + } + $system_count = 0 ; + + # push @times_to_com, substr($db{$table}{$id}{date_to},11) ; + + # my $system_count = 0 ; my $system_day_cnt = 0 ; my %system_has_daily_op = () ; + + # foreach my $system_row (split(/\|/,$db{$table}{$id}{daily_operator_ids})) { + # $system_count++ ; + # next unless $system_row ; + # $system_day_cnt = 0 ; + # foreach my $col (split(/\;/,$system_row)) { + # $system_day_cnt++ ; + # next unless $col ; + # $default_op_ids{$system_count}{$system_day_cnt} = $col if $col ; + # $system_daily_ops{$system_count} .= qq~Day $system_day_cnt : $db{users}{$col}{name}, ~ if $col ; + # } + # chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ; + # chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ; + # } + # $system_count = 0 ; + + foreach my $cnt (sort {$a <=> $b} keys %sort_field) { + + $col = $sort_field{$cnt} ; + + next if !$col || $col eq 'quote_nr' ; + + $val = $db{$table}{$id}{$col} ; + # next if not $val and $col ne 'operator_names_type_a' and $col ne 'operator_names_type_b' and $col ne 'category_1_sub-Categories' and $col ne 'category_2_sub-Categories' ; + # $val = $country{$val} if $col eq 'country_id' ; + $val = $customers{$val} if $col eq 'quote_to' ; + # $val = $event_type{$val} if $col eq 'type' ; + if ($col eq 'nr_of_casuals') { + $casuals_1_subscribed = 0 unless $casuals_1_subscribed ; + $db{$table}{$id}{nr_of_casuals} = 0 unless $db{$table}{$id}{nr_of_casuals} ; + $val = "$casuals_1_subscribed/$val $casual_1_names_subscribed" ; + $fully_substribed{$casual_1_type} = 1 if $casuals_1_subscribed >= $db{$table}{$id}{nr_of_casuals} ; + } elsif ($col eq 'nr_of_casuals_2') { + $casuals_2_subscribed = 0 unless $casuals_2_subscribed ; + $db{$table}{$id}{nr_of_casuals_2} = 0 unless $db{$table}{$id}{nr_of_casuals_2} ; + $val = "$casuals_2_subscribed/$val $casual_2_names_subscribed" ; + $fully_substribed{$casual_2_type} = 1 if $casuals_2_subscribed >= $db{$table}{$id}{nr_of_casuals_2} ; + } elsif ($col eq 'date_from' || $col eq 'date') { + $val = &process_date($db{$table}{$id}{date_from}) ; + $val .= qq~ to ~ . substr($times_to_com[0],0,5) ; + $val .= substr($db{$table}{$id}{date_to},11,5) if $col eq 'date' ; + } elsif ($col eq 'date_to') { + $val = &process_date($db{$table}{$id}{date_to}) ; + $val = substr($val,0,-5) . substr($times_from_com[-1],0,5) . qq~ to ~ . substr($val,-5,5) ; + } elsif ($col eq 'operator_names_type_a'){ + next unless $db{$table}{$id}{nr_of_casuals} ; + # $preferred_title{$col} = "Operator Names A" ; + # $fcol = 3 ; + # $multiple{$col} = 1 ; + # $setmultiple = 'multiple' ; + # $print_box_content_rows .= &common_min_form_select($col,'') ; + # $print_box_content_rows . "
    " ; + } elsif ($col eq 'operator_names_type_b') { + # next unless $db{$table}{$id}{nr_of_casuals_2} ; + # $preferred_title{$col} = "Operator Names B" ; + # $fcol = 3 ; + # $multiple{$col} = 1 ; + # $setmultiple = 'multiple' ; + # $print_box_content_rows .= &common_min_form_select($col,'') ; + } elsif ($col eq 'sport_type_ids') { + $val = qq~~ ; + foreach (split(",",$db{$table}{$id}{sport_type_ids})) { + $val .= qq~$db{sport_types}{$_}{name}, ~ ; + } + chop $val if $val ; chop $val if $val ; + } + # elsif ($col eq 'city_id') { + # $val = $db{cities}{$val}{city} ; + # $val .= qq~, $db{regions}{$db{$table}{$id}{region_id}}{name}~ if $db{$table}{$id}{region_id} ; + # } + # elsif ($col eq 'organisation_ids') { + # $val = qq~~ ; + # foreach (split(",",$db{$table}{$id}{organisation_ids})) { + # $val .= qq~$db{organisations}{$_}{name}, ~ ; + # } + # chop $val if $val ; chop $val if $val ; + # } + # event_quotes_poc','id,name,contact_nr + elsif ($col eq 'poc_name') { + $val = $db{event_quotes_poc}{$db{$table}{$id}{poc_id}}{name} ; + } elsif ($col eq 'poc_contact_nr') { + $val = $db{event_quotes_poc}{$db{$table}{$id}{poc_id}}{contact_nr} ; + $val =~ s/ //g ; + if (substr($val,0,2) eq '27' && length($val) == 11) { + $val = "+27 " . substr($val,2,2) . " " . substr($val,4,3) . " " . substr($val,7,4) ; + } elsif ((substr($val,0,2) eq '07' || substr($val,0,2) eq '08' || substr($val,0,2) eq '02') && length($val) == 10) { + $val = "+27 " . substr($val,1,2) . " " . substr($val,3,3) . " " . substr($val,6,4) ; + } else { + $val = $db{event_quotes_poc}{$db{$table}{$id}{poc_id}}{contact_nr} ; + } + + } elsif ($col eq 'category_1_sub_categories') { + my @a = split('\|;\|',$db{event_quotes_min}{$id}{category_details}) ; + $a[0] =~ s/\n/
    /g; + $a[0] = substr($a[0],0,-4) if substr($a[0],-4,4) eq '
    ' ; + $val = $a[0] ; + next unless $val ; + } elsif ($col eq 'category_2_sub_categories') { + my @a = split('\|;\|',$db{event_quotes_min}{$id}{category_details}) ; + $a[1] =~ s/\n/
    /g; + $a[1] = substr($a[1],0,-4) if substr($a[1],-4,4) eq '
    ' ; + $val = $a[1] ; + next unless $val ; + } elsif ($col eq 'category_1') { + $val = $db{event_quotes_categories}{$db{$table}{$id}{category_id_1}}{category} ; + } elsif ($col eq 'category_2') { + $val = $db{event_quotes_categories}{$db{$table}{$id}{category_id_2}}{category} ; + } elsif ($col eq 'type_details') { + # event_system_id_multiple + $val = qq~~ ; + foreach my $type_id (split(",",$db{$table}{$id}{type_details_id})) { + $val .= qq~$db{event_type_details}{$type_id}{name}, ~ ; + } + chop $val if $val ; chop $val if $val ; + + } elsif ($col eq 'system_details') { + # elsif ($col eq 'system_name') { + + $val = qq~~ ; + # my $cnt_sys = 0 ; + my @club_ids = split(";",$db{$table}{$id}{club_ids}) ; + my @operator_ids = ($db{$table}{$id}{operator_ids} =~ /;/) ? split(";",$db{$table}{$id}{operator_ids}) : split(",",$db{$table}{$id}{operator_ids}) ; + my $cnt_sys = -1 ; + + foreach my $event_id (split(/\;/,$db{$table}{$id}{event_system_id_multiple})) { + $cnt_sys++ ; + next if not $event_id and not $club_ids[$cnt_sys] ; + $event_id =~ s/f-//g ; + $val .= qq~$db{event_systems}{$event_id}{name} ~ if $event_id ; + $val .= qq~>>> ~ if $event_id and not $db{event_systems}{$event_id}{description} ; + $val .= qq~($db{event_systems}{$event_id}{description}) >>> ~ if $db{event_systems}{$event_id}{description} and $event_id ; + $val .= qq~NO SYSTEM >>> ~ unless $event_id ; + + $val .= qq~$db{clubs}{$club_ids[$cnt_sys]}{name} >>> ~ if $club_ids[$cnt_sys] ; + $val .= qq~NO CLUB >>> ~ unless $club_ids[$cnt_sys] ; + + $val .= qq~$db{users}{$operator_ids[$cnt_sys]}{name}~ if $operator_ids[$cnt_sys] ; + $cnt_sys++ ; + $val .= qq~[$system_daily_ops{$cnt_sys}]~ if $system_daily_ops{$cnt_sys} && !$operator_ids[$cnt_sys-1] ; + $cnt_sys-- ; + # $val .= qq~>>> $db{clubs}{$club_ids[$cnt_sys]}{name} ~ if $db{clubs}{$club_ids[$cnt_sys]}{name} ; + # $val .= qq~>>> $db{users}{$operator_ids[$cnt_sys]}{name} ~ if $db{users}{$operator_ids[$cnt_sys]}{name} ; + # $val .= qq~[$db{users}{$operator_ids[$cnt_sys]}{phone}] ~ if $db{users}{$operator_ids[$cnt_sys]}{name} && $db{users}{$operator_ids[$cnt_sys]}{phone} ; + $val .= qq~
    ~ ; + # $cnt_sys++ ; + } + # chop $val if $val ; chop $val if $val ; + $val = substr($val,0,-4) if $val ; + } + # elsif ($col eq 'club_name') { + # $val = '' ; + # foreach my $club_id (split(";",$db{$table}{$id}{club_ids})) { + # $val .= qq~$db{clubs}{$club_id}{name}
    ~ if $club_id ; + # } + # $val =~ s/\n/
    /g; + # $val = substr($val,0,-4) if substr($val,-4,-1) eq '/g; + } elsif ($col eq 'additional_notes') { + $val = $db{$table}{$id}{additional_notes} ; + $val =~ s/\n/
    /g; + } elsif ($col eq 'fixture_date/Time_from') { + + $val = join(",",map{"$analytics_saved_values{$col}{$_}"} sort {$a <=> $b} keys %{$analytics_saved_values{$col}}) ; + } elsif ($col eq 'sport') { + $val = join(",",map{"$analytics_saved_values{$col}{$_}"} keys %{$analytics_saved_values{$col}}) ; + } elsif ($col eq 'age_group') { + $val = join(",",map{"$analytics_saved_values{$col}{$_}"} sort {$a <=> $b} keys %{$analytics_saved_values{$col}}) ; + } elsif ($col eq 'team') { + $val = join(",",map{"$analytics_saved_values{$col}{$_}"} sort {$a <=> $b} keys %{$analytics_saved_values{$col}}) ; + } elsif ($col eq 'stream_forwarding') { + $val = join(",",map{"$analytics_saved_values{$col}{$_}"} sort {$a <=> $b} keys %{$analytics_saved_values{$col}}) ; + } elsif ($col eq 'stream_key') { + $val = join(",",map{"$analytics_saved_values{$col}{$_}"} sort {$a <=> $b} keys %{$analytics_saved_values{$col}}) ; + } elsif ($col eq 'stream_URL') { + $val = join(",",map{"$analytics_saved_values{$col}{$_}"} sort {$a <=> $b} keys %{$analytics_saved_values{$col}}) ; + } + + next unless $val ; + + $print_box_content_rows .= &common_min_form_view($col,$val,'') unless $col eq 'operator_names_type_a' or $col eq 'operator_names_type_b' ; + + if ($col eq 'date_from' && substr($db{$table}{$id}{date_from},0,10) ne substr($db{$table}{$id}{date_to},0,10)) { + for (2 .. 9) { + last if substr($db{$table}{$id}{date_to},0,10) eq $dates_hash{$_} ; + next if $db{$table}{$id}{days_active} && !$days_active[$_ - 1] ; + my ($new_year,$new_month,$new_day) = split(/\-/,$dates_hash{$_}) ; + $val = $new_day . "-" . $month_array[$new_month - 1] . "-" . $new_year . " @ " . substr($times_from_com[$_ - 1],0,5) . " to " . substr($times_to_com[$_ - 1],0,5) ; + $print_box_content_rows .= &common_min_form_view(" ",$val,'') ; + } + } + } + + $dialog = 0 ; + $addbkb = 0 ; + # $print_box_content_rows .= &common_min_forms_end('','','report') ; + + # my @assigned_users_a = split(/\,/,$db{$table}{$id}{operator_names_type_a}s) ; + # my @assigned_users_b = split(/\,/,$db{$table}{$id}{operator_names_type_b}) ; + # my %selected_names = () ; + # for (@assigned_users_a){ $selected_names{operator_names_type_a}{$_}{$id} = 'SELECTED'; } + # for (@assigned_users_b){ $selected_names{operator_names_type_b}{$_}{$id} = 'SELECTED'; } + + # + # + + # $print_box_content_rows .= qq~ + $form_for_save .= qq~ +
    + + + + +
    +
    +   +
    +
    +
    +
    +    +
    +
    +
    +
    +   +
    +
    +
    + ~ ; + + + $trigger_jquery_raw .= qq~\$("#savebuttcalender").click(function() { + + var op_a_val = \$("#selectOperator_names_type_a").chosen().val() ; + var op_b_val = \$("#selectOperator_names_type_b").chosen().val() ; + + // const selected_a = op_a_val.split(",") ; + // const selected_b = op_b_val.split(",") ; + + // let counter_a = 0 ; + // let counter_b = 0 ; + + // for (let i = 0; i < selected_a.length; i++) { + // counter_a++ ; + // } + + // for (let i = 0; i < selected_b.length; i++) { + // counter_b++ ; + // } + + // var max_ops_a = '$db{$table}{$id}{nr_of_casuals}' ; + // var max_ops_b = '$db{$table}{$id}{nr_of_casuals_2}' ; + + // if (max_ops_a < counter_a && max_ops_b < counter_b) { + // noty({text:'Operator A names exceed max nr allowed of '+max_ops_a+'! and Operator B names exceed max nr allowed of '+max_ops_b+'!',layout:"center",type:"error",timeout:3000}); + // return; + // } else if (max_ops_b < counter_b && max_ops_a >= counter_a) { + // noty({text:'Operator B names exceed max nr allowed of '+max_ops_b+'!',layout:"center",type:"error",timeout:3000}); + // return; + // } else if (max_ops_a < counter_a && max_ops_b >= counter_b) { + // noty({text:'Operator A names exceed max nr allowed of '+max_ops_a+'!',layout:"center",type:"error",timeout:3000}); + // return; + // } else { + \$('#operators-type-a').val(op_a_val); + \$('#operators-type-b').val(op_b_val); + \$('#$table-form').submit(); + // } + });~ ; + + # $trigger_jquery_raw .= qq~\$("#savebuttcalender").click(function() { + + # var max_allowed_a = $db{$table}{$id}{nr_of_casuals} ; + # var max_allowed_b = $db{$table}{$id}{nr_of_casuals_2} ; + + # if (max_allowed_a < counter_a && max_allowed_b < counter_b) { + # noty({text:'Operator A names exceed max nr allowed of '+max_allowed_a+'! and Operator B names exceed max nr allowed of '+max_allowed_b+'!',layout:"center",type:"error",timeout:3000}); + # return; + # } else if (max_allowed_b < counter_b && max_allowed_a >= counter_a) { + # noty({text:'Operator B names exceed max nr allowed of '+max_allowed_b+'!',layout:"center",type:"error",timeout:3000}); + # return; + # } else if (max_allowed_a < counter_a && max_allowed_b >= counter_b) { + # noty({text:'Operator A names exceed max nr allowed of '+max_allowed_a+'!',layout:"center",type:"error",timeout:3000}); + # return; + # } else { + # \$('#$table-form').submit(); + # } + # });~ ; + + # $print_box_content_rows . "
    " ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + + # my $saction = ($cat{$date_start}{$date_end}{$id}{$userid} eq 'available') ? 'unavailable' : 'available' ; my $butttxt = uc $saction ; my $buttcolor = ($saction eq 'available') ? 'success' : 'danger' ; + + my $buttcolor = ($saction eq 'available') ? 'success' : 'danger' ; + + if ($cat{$date_start}{$date_end}{$id}{$userid} eq 'available') { + $saction = 'unavailable' ; + } elsif ($cat{$date_start}{$date_end}{$id}{$userid} eq 'assigned') { + $saction = 'available' ; + # $buttcolor = 'info' ; + $buttcolor = 'success' ; + } elsif ($cat{$date_start}{$date_end}{$id}{$userid} eq 'unavailable') { + $saction = 'available' ; + $buttcolor = 'success' ; + } + + my $butttxt = uc $saction ; + + my ($dy1,$dm1,$dd1,$th1,$tm1,$ts1) = &common_split_sql_time($db{$table}{$id}{date_from}) ; + my ($dy2,$dm2,$dd2,$th2,$tm2,$ts2) = &common_split_sql_time($db{$table}{$id}{date_to}) ; + my $Dd = Delta_Days($dy1,$dm1,$dd1,$dy2,$dm2,$dd2); + + # my $nr_of_casuals_1_allowed = sprintf("%0.0f",$db{$table}{$id}{nr_of_casuals}) ; + # if ($casuals_1_subscribed >= $nr_of_casuals_1_allowed and $saction eq 'available') { return ; } # fully subscribed + + # my $nr_of_casuals_2_allowed = sprintf("%0.0f",$db{$table}{$id}{nr_of_casuals_2}) ; + # if ($casuals_2_subscribed >= $nr_of_casuals_2_allowed and $saction eq 'available') { return ; } # fully subscribed + + my $cnow = $now_ccyymmdd . $now_hour . $now_min . $now_sec ; + my $cstart = $db{$table}{$id}{date_from} ; $cstart =~ s/ //g ; $cstart =~ s/-//g ; $cstart =~ s/://g ; + my $cend = $db{$table}{$id}{date_to} ; $cend =~ s/ //g ; $cend =~ s/-//g ; $cend =~ s/://g ; + my $in_the_past = 0 ; + + our $files_attach = qq~~ ; + + + $files_attach .= qq~ +
    +
    + + + +
    +
    +
    ~ if $glod_user_level > 1 ; + + for (1 .. 3) { + + $working_uploads = &get_event_uploads($qid,"upload_$_",'id') ; + if ($working_uploads) { + $files_attach .= qq~ +
    +
    + $working_uploads +
    +
    +
    + ~ ; + } + } + # ;;;;6797|;;;;6797|;;;;6797|;8;;;6797 + if ($cstart < $cnow && $cend < $cnow) { # event in the past + # if (1) { # event in the past + + if ($analytics_event_exists) { + + if ($analytics_table) { + $analytics_table_body .= qq~ +
    +
    +
    + + Event has past + +
    +
    +
    + $files_attach +
    +
    +
    +   +
    +
    +
    +
    +
    +
    + ~ ; + } else { + $print_box_content_rows .= qq~ +
    +
    +
    + + Event has past + +
    +
    +
    + $files_attach +
    +
    +
    +   +
    +
    + ~ ; + } + + + } else { + $print_box_content_rows .= qq~ +
    +
    +
    + + Event has past + +
    +
    +
    + $files_attach +
    +
    +
    +   +
    +
    + ~ ; + } + + return ; + + } else { + + if ($analytics_event_exists) { + + if ($analytics_table) { + $analytics_table_body .= qq~ +
    +
    +
    +   +
    +
    +
    + $files_attach +
    +
    +
    +
    +
    + ~ ; + } else { + + $print_box_content_rows .= qq~ +
    +
    +
    + Analytics Required +
    +
    +
    + $files_attach +
    +
    +
    +   +
    +
    + ~ ; + + + } + + # my $analytics_required = ($analytics_table) ? qq~ ~ : qq~Analytics Required~ ; + + # my $close_button = (!$analytics_table) ? qq~ + #
    + #
    + #   + #
    + #
    + # ~ : qq~~ ; + + + + } else { + + $print_box_content_rows .= qq~ +
    +
    +
    +   +
    +
    +
    + $files_attach +
    + ~ ; + + } + + } + + + if ($time_subscribed{$userid}{"$dy1$dm1$dd1$th1"} and $cat{$date_start}{$date_end}{$id}{$userid} ne 'available') { $print_box_content_rows .= qq~You're already booked for an event during this time~; return ; } # busy on another event already, avoid double booking + if ($time_subscribed{$userid}{"$dy2$dm2$dd2$th2"} and $cat{$date_start}{$date_end}{$id}{$userid} ne 'available') { $print_box_content_rows .= qq~You're already booked for an event during this time~; return ; } # busy on another event already, avoid double booking + + return unless substr($usertype,0,6) eq 'casual' ; + + # my $is_operator = uc substr($usertype,0,6) ; + # unless (substr($usertype,0,6) eq 'casual') { $print_box_content_rows .= qq~$is_operator~; return ; } + + my $casual_type = uc substr($usertype,-1,1) ; + + # return if $fully_substribed{$casual_type} and $cat{$date_start}{$date_end}{$id}{$userid} and $cat{$date_start}{$date_end}{$id}{$userid} ne 'available' ; + # return if $fully_substribed{$casual_type} and $saction eq 'available' and $this_user_subscribed{$userid} != 1 ; + + return unless $butttxt ; + + $print_box_content_rows .= qq~
    ~ ; + +} #------------------------------------------------------------------------------------------ + +sub process_date { + + my ($date_string) = @_ ; + + my $year = substr($date_string, 0, 4) ; + my $month = substr($date_string, 5, 2) ; + $month = int($month); + $month = $month_array[$month - 1] ; + my $day = substr($date_string, 8, 2) ; + my $date_return = "$day-" ; + $date_return .= "$month-" ; + $date_return .= "$year" ; + $date_return .= " @ " . substr($date_string,11,5) ; + + return $date_return ; + +} #------------------------------------------------------------------------------------------ + +sub get_event_uploads { + + my ($id,$type,$folder) = @_ ; + + unless ($id and $type) { return() ; } + + my $uploads = '' ; my %uploads = () ; + + my $field = $type ; my ($doctype,$num) = split(/\_/,$field) ; $doctype .= 's' ; + + $table = $doctype unless $table ; + + my $doc = $db{$table}{$id}{$field} ; + + &common_debug("$doc") ; + + if ($doc){ + my $tooltip = qq~data-toggle="tooltip" data-placement="right" data-title="$doc"~ ; + my @docarr = split(/\./,$doc); my $ext = pop @docarr ; my $file = pop @docarr ; + my $dlg_title = uc substr($doc,0,4) . ' ' . $ext ; + $file_cnt++; + + my $test_icon_loc = qq~$htmlpath/img/icons/doc/$ext.png~; + my $icon_loc = qq~/img/icons/doc/$ext.png~; $icon_loc = qq~/img/icons/doc/def.png~ unless -f $test_icon_loc ; + + # $uploads{$type} .= qq~~ ; + $uploads{$type} .= qq~~ ; + + # $uploads .= qq~~; + } + + if ($uploads{$type}) { $uploads = $uploads{$type} ; } + + return ($uploads) ; + +} #------------------------------------------------------------------------------------------ + +sub check_dates_booked { + + my ($qnr,$uid,$startdate,$enddate) = @_ ; + + my ($dy1,$dm1,$dd1,$th1,$tm1,$ts1) = &common_split_sql_time($startdate) ; my $startccyymmdd = $dy1 . $dm1 . $dd1 ; $start_hour{$uid}{$startccyymmdd} = $th1 ; #my $startccyymmddhr = $startccyymmdd . $th1 ; + my ($dy2,$dm2,$dd2,$th2,$tm2,$ts2) = &common_split_sql_time($enddate) ; my $endccyymmdd = $dy2 . $dm2 . $dd2 ; $end_hour{$uid}{$endccyymmdd} = $th2 ; #my $endccyymmddhr = $endccyymmdd . $th2 ; + + my $array_date = $startccyymmdd ; + + while ($array_date < $endccyymmdd) { + + my $date_dd = substr($array_date,6,2) ; + my $date_mm = substr($array_date,4,2) ; + my $date_ccyy = substr($array_date,0,4) ; + + my ($ccyy,$month,$day) = Add_Delta_Days($date_ccyy,$date_mm,$date_dd,1) ; + $month = sprintf("%02s", $month) ; + $day = sprintf("%02s", $day) ; + + $array_date = "$ccyy$month$day" ; + + $start_hr = ($start_hour{$uid}{$array_date}) ? $start_hour{$uid}{$array_date} : 0 ; + $end_hr = ($end_hour{$uid}{$array_date}) ? $end_hour{$uid}{$array_date} : 23 ; + + for ($start_hr .. $end_hr) { + my $hr = sprintf("%02s", $_) ; + my ($year,$month,$day, $hour,$min,$sec) = Add_Delta_DHMS($date_ccyy,$date_mm,$date_dd,$hr,'00','00', 0,1,0,0); + + $time_subscribed{$uid}{"$array_date$hr"} = 1 ; + } + + # $day_subscribed{$uid}{$array_date} = 1 ; + } + +} #------------------------------------------------------------------------------------------ + +sub display_user { + + &db_min_ro('users','id,name,username','','','') ; + foreach my $id (keys %{$db{users}}) { + $user_name{$id} = $db{users}{$id}{name} ; + } + +} #------------------------------------------------------------------------------------------ + +sub add_form { + + $boxtitle = 'Add' ; + + @user_excl_sql = () ; + + foreach (keys %{$useropts{it}}) { + push @user_excl_sql, "username <> '$_'" ; + } + + my $user_excl_sql = join(" AND ", @user_excl_sql) ; + + &common_min_select_opts('user_id','users','name','',1,'',$user_excl_sql) ; + # &common_min_opts('leave_type','type',1) ; + + %col_name = () ; + + &db_min_ro($table,'*','id > 1 AND id < 10','','') ; + + &hidden_fields ; + + # $extra_form_fields = qq() ; + + $print_box_content_rows = &common_min_add_form('events','save') ; + +} #------------------------------------------------------------------------------------------ + +sub load_events { + + &db_min_ro($table,'*',"id='$id'",'','') ; + &common_min_dialog ; + &display_user; + + my $category = ucfirst $db{$table}{$id}{category} ; + + # my $title_row = qq(
    $db{$table}{$id}{title}
    ) ; + + if ($db{$table}{$id}{category} eq 'leave') { + # $title_row = '' ; + $category = ucfirst $db{$table}{$id}{type} . ' ' . $category + } + + if ($db{$table}{$id}{category} eq 'weekend_work') { + $category =~ s/\_/ /g ; + } + + $content = qq( +
    +
      +
    +
    +
    +
    +
    +
    +

    Item

    +
    +
    +
    +
    + $title_row +
    $user_name{$db{$table}{$id}{user_id}}
    +
    $category
    +
    $db{$table}{$id}{notes}
    +
    $db{$table}{$id}{startdate}
    +
    $db{$table}{$id}{enddate}
    +
    $db{$table}{$id}{date_time}
    +
    +
    +
    +
    +
    +
    + ) ; + +} #---------------------------------------------------------------------------------------- + +sub screen1 { + +my $buttons = '' ; + +if ($useropts{super}{lc $username}){ + $buttons = qq(  +   +  ); + } + +print < + + + $print_top + +
    +
    +
    + $content +
    +
    + +
    +
     
    +
    +
    +
    + + +
    +
    + $buttons +
    +
    +
     
    +
    +
    +
    +
    +
    +
    + + + + + +$dialog{'common'}{'js'} + + + + +ENDOFTEXT +# + +#
       
     
    + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + +$trigger_jquery_raw .= qq(\$("#savebutt").click(function() { + var sc_val = \$("#selectAssigned_users").chosen().val() ; + \$('#assigned-users').val(sc_val); + \$('#events-form').submit(); +});) ; + +&common_min_alert_type ; + +&common_min_footer('id','') ; + +&common_min_dialog ; + +print < + + + $print_top + +
    +
    + $events_content +
    + +
    + +
    +
    +
    +
    +

    $boxtitle Event

    +
    +
    + $print_box_content_rows +
    +
    +
    +
    + $analytics_table_body +
    + +
    + +
    + + + + + +$dialog{'common'}{'js'} + + + + + + +$print_footer_jscript +$print_footer_forms + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +sub screen3 { + +if (($username eq 'rory') and ($testing)) { return ; } + +print < + + + + $useropts{title} + + + + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use db ; +use db_min ; +use today ; +use common ; +use common_min ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/dialog/get_bank_transactions.pl b/scripts/_FromProd/v1.0/dialog/get_bank_transactions.pl new file mode 100644 index 0000000..9aa02d7 --- /dev/null +++ b/scripts/_FromProd/v1.0/dialog/get_bank_transactions.pl @@ -0,0 +1,298 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +&today ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use DBI; +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Excel::Writer::XLSX ; + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; +$date_from = $ARGV[1] ; +$date_to = $ARGV[2] ; + +our $only_update_number = ($action eq 'add_number_only') ? 1 : 0 ; + +# our $debug = 1 ; +our $table = 'bank_transactions' ; + +our ($q) = CGI -> new() ; +$iaction = $q -> param('iaction') || $action ; + +$iaction = "add" if $iaction eq 'add_number_only' ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +# &db_switch_conn('aisa') ; + +if ($iaction eq 'create') { + &common_min_add_screen ; + &build_excel ; + &screen2 ; +} + +# if ($iaction eq 'save') { + # &common_min_load_params ; + # &build_excel ; + # &screen2 ; +# } + +&common_min_action; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub insert { + +} #------------------------------------------------------------------------------------------ + +sub validate { + +} #------------------------------------------------------------------------------------------ + +sub build_excel { + + my @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + my ($year_input1,$month_input1,$day_input1,$year_input2,$month_input2,$day_input2) ; + + if ($date_from) { + ($year_input1,$month_input1,$day_input1) = split(/\-/,$date_from) ; + # push @report_results, "(TRANSACTION DATE AFTER '$day_input1 $months[$month_input1] $year_input1')" ; + push @report_sql, "(transaction_date >= '$date_from')" ; + } + + if ($date_to) { + ($year_input2,$month_input2,$day_input2) = split(/\-/,$date_to) ; + # push @report_results, "(TRANSACTION DATE BEFORE '$day_input2 $months[$month_input2] $year_input2')" ; + push @report_sql, "(transaction_date <= '$date_to')" ; + } + + # $report_results_msg = uc join(', ',@report_results) ; + my $srch_where_sql = join(' AND ', @report_sql) ; + + &load_list_vars("$srch_where_sql") ; + + our $xlsxheading = ($year_input1 ne $year_input2) ? "$day_input1 $months[$month_input1] $year_input1 TO $day_input2 $months[$month_input2] $year_input2" : + ($year_input1 eq $year_input2 && $month_input1 ne $month_input2) ? "$day_input1 $months[$month_input1] TO $day_input2 $months[$month_input2] $year_input2" : + ($year_input1 eq $year_input2 && $month_input1 eq $month_input2 && $day_input1 ne $day_input2) ? "$day_input1 TO $day_input2 $months[$month_input1] $year_input1" : + ($year_input1 eq $year_input2 && $month_input1 eq $month_input2 && $day_input1 eq $day_input2) ? "$day_input1 $months[$month_input1] $year_input1" : "" ; + + $xlsxheading = "Bank Transactions " . $xlsxheading ; + + &report_xlsx_export_header("Bank_Transactions",'bank_transactions') ; + + $xlsxrow = 2 ; + + $xlsxcol = 0 ; + foreach my $dc (sort { $b cmp $a } keys %bank_transaction_categories) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,uc $dc,$format117) ; + $xlsxrow++ ; + foreach my $cat_id (sort { $bank_transaction_categories{$dc}{$a} cmp $bank_transaction_categories{$dc}{$b} } keys %{$bank_transaction_categories{$dc}}) { + next if $cat_id == 27 ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$db{bank_transaction_categories}{$cat_id}{name},$format118) ; + $xlsxrow++ ; + my $start_row = $xlsxrow ; + foreach my $trans_id (keys %{$transactions_by_category{$cat_id}}) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,0,$trans_id,$format1) ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,1,substr($db{$table}{$trans_id}{transaction_date},8,2) . "/" . substr($db{$table}{$trans_id}{transaction_date},5,2) . "/" . substr($db{$table}{$trans_id}{transaction_date},0,4),$format1) ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,2,$db{$table}{$trans_id}{account_nr},$format1) ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,3,$db{$table}{$trans_id}{amount},$format120) ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,4,$db{$table}{$trans_id}{description},$format1) ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,5,$db{bank_transaction_categories}{$cat_id}{name},$format1) ; + $xlsxrow++ ; + } + $xlsxrow++ ; + &xlsxcreator_write_formula($ws,$xlsxrow,3,"=SUM(D$start_row:D$xlsxrow)",$format119) ; + $xlsxrow++ ; + } + } + + my $cat_id = 27 ; + + for (0 .. 5) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$_," ",$format121) ; + } + + my $start_row = $xlsxrow ; + + $xlsxrow++ ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$db{bank_transaction_categories}{$cat_id}{name},$format118) ; + $xlsxrow++ ; + my $start_row = $xlsxrow ; + foreach my $trans_id (keys %{$transactions_by_category{$cat_id}}) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,0,"",$format1) ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,1,substr($db{$table}{$trans_id}{transaction_date},8,2) . "/" . substr($db{$table}{$trans_id}{transaction_date},5,2) . "/" . substr($db{$table}{$trans_id}{transaction_date},0,4),$format1) ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,2,"",$format1) ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,3,$db{$table}{$trans_id}{amount},$format120) ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,4,$db{$table}{$trans_id}{description},$format1) ; + $xlsxrow++ ; + } + $xlsxrow++ ; + &xlsxcreator_write_formula($ws,$xlsxrow,3,"=SUM(D$start_row:D$xlsxrow)",$format119) ; + $xlsxrow++ ; + + for (0 .. 5) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$_," ",$format121) ; + } + + for ($start_row - 1 .. $xlsxrow) { + &xlsxcreator_write_xlsx($ws,$_,6," ",$format122) ; + } + + $worksheet{$ws}->set_column(1,3,20) ; + $worksheet{$ws}->set_column(4,5,30) ; + &report_xlsx_export_footer('F',15,'bank_transactions') ; + +} #------------------------------------------------------------------------------------------ + +sub load_list_vars { + + my ($where,$where_2) = @_ ; + + &db_min_ro($table,"*","$where",'','') ; + + our %transactions_by_category = () ; + + foreach (keys %{$db{$table}}) { + $transactions_by_category{$db{$table}{$_}{category_id}}{$_} = 1 ; + } + + &db_min_ro('bank_transaction_categories',"*","",'','') ; + + our %bank_transaction_categories = () ; + + foreach (keys %{$db{bank_transaction_categories}}) { + + if ($db{bank_transaction_categories}{$_}{income_source}) { + $bank_transaction_categories{income}{$_} = $db{bank_transaction_categories}{$_}{name} ; + } else { + $bank_transaction_categories{expenses}{$_} = $db{bank_transaction_categories}{$_}{name} ; + } + } + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + + $box_header_title = 'Get Bank Transactions' ; + $hidden_action = 'search' ; + $head_col_width = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + $ignore{iaction} = 1 ; + $ignore{id} = 1 ; + $required{date_from} = 1 ; + $required{date_to} = 1 ; + $datepicker{date_from} = 1 ; + $datepicker{date_to} = 1 ; + $sort_field{1} = 'date_from' ; + $sort_field{2} = 'date_to' ; + $db{$table}{''}{date_from} = "$now_year-01-01" ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub screen1 { + + # $trigger_jquery_raw .= qq~ + # \$('#btn-close-customer').click(function (e) { + # parent.BootstrapDialog.closeAll() ; + # }); + # ~ ; + + &dialog_load_screen ; + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + + $xlsxpath =~ s|/var/www/html/||; + + $trigger_jquery_raw = qq~ + let url = "https://$useropts{web}/$xlsxpath" + "/" + "$xlsxname" ; + \$.get(url) ; + parent.BootstrapDialog.closeAll() ; + ~; + + &common_min_dialog_save_screen ; + +} #------------------------------------------------------------------------------------------ + +sub dialog_load_screen { + +&dialog_common ; + +print < + + + $alert + +
    +
    +
    +
    + $print_box_content_rows +
    +
    +
    +
    + +
    + +
    + + + + + + + + + + + + + + +ENDOFTEXT +# + +exit; + +} #------------------------------------------------------------------------------------------ + +use today ; +use dialog ; +use common ; +use common_min ; +use report ; +use xlsxcreator ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/dialog/getmail.pl b/scripts/_FromProd/v1.0/dialog/getmail.pl new file mode 100644 index 0000000..5a0562b --- /dev/null +++ b/scripts/_FromProd/v1.0/dialog/getmail.pl @@ -0,0 +1,92 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); +use Mail::POP3Client; +use MIME::Parser; +use Fcntl qw(:flock) ; +use MIME::Lite; +use Mail::Sendmail; + +require cfg ; + +print header; # CGI.pm method + +# unless ($useropts{admin}{$userid} eq $username) { require '401.pm' ; exit ; } + +# https://itvadmin.co.za/cgi-bin/scripts/dialog/getmail.pl?debug=1 + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; +our $debug = $q -> param('debug') || '' ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- +&start_html ; + +&getmail_fetch; + +&reload_parent ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub start_html { + +print < + + + + $useropts{title} + + + +"Fetching tickets..." + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +sub reload_parent { + +my $jquery_raw = qq~parent.location.reload(); + parent.\$("#alertbar").html(""); + parent.BootstrapDialog.closeAll() ;~; + +if ($debug) { $jquery_raw = '' ; } + +print < + +\$(function () { + $jquery_raw +}); + + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use db ; +use common ; +use today ; +use getmail ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/dialog/import.pl b/scripts/_FromProd/v1.0/dialog/import.pl new file mode 100644 index 0000000..2e25396 --- /dev/null +++ b/scripts/_FromProd/v1.0/dialog/import.pl @@ -0,0 +1,576 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); +use LWP::Simple qw($ua get); +use Date::Calc qw(:all); +use MIME::Lite; +use Mail::Sendmail; +use Time::Piece ; + +require cfg ; + +print header; # CGI.pm method + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +my $type = $ARGV[0] ; + +our ($q) = CGI -> new() ; +my $iaction = $q -> param('iaction') ; +my $iattachdoc = $q -> param('iattachdoc') ; + +# our $debug = 1 ; + +#------------------------------------------------------------------------------------------ + +&today ; + +if ($iaction eq '') { + + &screen1 ; + +} elsif ($iaction eq 'upload') { + + &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &read_import ; + &read_db ; + &process ; + &screen3 ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + +} elsif ($iaction eq 'save') { + + &common_min_load_params ; + &db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &read_read_import_lines ; + &update ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + &screen2 ; +} + +exit; + +#------------------------------------------------------------------------------------------ + +sub read_read_import_lines { + + our $max_unmatched_id = 0 ; + + my $upload_filehandle = $q->upload('iattachdoc') ; + + if ($type eq 'csv') { + + &db_min_ro('event_production_time_unmatched','id,unmatched_line','','','') ; + + foreach (keys %{$db{event_production_time_unmatched}}) { + my $event_code = substr($db{event_production_time_unmatched}{$_}{unmatched_line},-8) ; + $unmatched_event_lines{$event_code} = $db{event_production_time_unmatched}{$_}{unmatched_line} ; + $max_unmatched_id = $_ if !$max_unmatched_id || ($max_unmatched_id && $max_unmatched_id < $_) ; + $event_code_unmatched_id{$event_code} = $_ ; + } + + # # # $max_unmatched_id++ ; + + # while ( <$upload_filehandle> ) { + # # foreach (@imported_file_data) { + # chomp; + + # next if !$_ || ($_ !~ /\d+/ && $_ !~ /[a-zA-Z]/) ; + + # chop $_ ; + + # my @linex = split(/\;/,$_) ; + + # my $event_code = substr($linex[-1],-8) ; + + # $event_lines{$event_code} = $_ ; + + # } + } + +} #------------------------------------------------------------------------------------------ + +sub update { + + my %ii = () ; my %iii = %i ; + + &db_min_ro('event_production_time','quote_id,id,event_system_production_seconds,event_system_cloud_recording_seconds,matched_events',"") ; + + my $max_id = 0 ; + + foreach my $event_id (keys %{$db{event_production_time}}) { + + $max_id = $db{event_production_time}{$event_id}{id} if !$db{event_production_time}{$event_id}{id} || int($db{event_production_time}{$event_id}{id}) > int($max_id) ; + + if ($db{event_production_time}{$event_id}{event_system_production_seconds}) { + foreach (sort split(/\|/,$db{event_production_time}{$event_id}{event_system_production_seconds})) { + my @abc = split(":",$_) ; + $ii{$event_id}{$abc[0]}{event_system_production_seconds} += $abc[1] ; + } + } + + if ($db{event_production_time}{$event_id}{event_system_cloud_recording_seconds}) { + foreach (sort split(/\|/,$db{event_production_time}{$event_id}{event_system_cloud_recording_seconds})) { + my @abc = split(":",$_) ; + $ii{$event_id}{$abc[0]}{event_system_cloud_recording_seconds} += $abc[1] ; + } + } + + $ii{$event_id}{NA}{matched_events} = $db{event_production_time}{$event_id}{matched_events} ; + + } + + foreach (sort keys %i) { + + my @get_row = split("_",$_) ; + + my $row_nr = $get_row[-1] ; + + my $system_field = "system_$row_nr" ; + + my $event_code_field = "event_code_$row_nr" ; + + if ($_ !~ /event_code_/ && $_ =~ /event_/ && (!$i{$_} || !$i{$system_field}) && !$unmatched_event_lines{$i{$i{$event_code_field}}}) { + + $max_unmatched_id++ ; + $i{$i{$event_code_field}} =~ s/\'//g ; + + my %iiii = %i ; + + %i = () ; + + $i{id} = $max_unmatched_id ; + $i{unmatched_line} = $iiii{$iiii{$event_code_field}} ; + + &db_min_insert('event_production_time_unmatched') ; + + # print "\n INSERT INTO event_production_time_unmatched (id,unmatched_line) VALUES ($max_unmatched_id,'$i{unmatched_line}') ; " ; + + %i = %iiii ; + + } elsif ($_ !~ /event_code_/ && $_ =~ /event_/ && $i{$_} && $i{$system_field} && $unmatched_event_lines{$i{$event_code_field}}) { + + # print "\n DELETE FROM event_production_time_unmatched WHERE id = '$event_code_unmatched_id{$i{$event_code_field}}' " ; + + &db_min_delete('event_production_time_unmatched',"`id`='$event_code_unmatched_id{$i{$event_code_field}}'") ; + + } + + next if $_ =~ /event_code_/ || $_ !~ /event_/ || ($_ =~ /event_/ && $_ !~ /event_code_/ && !$i{$_}) ; + + my $system_field = "system_$row_nr" ; + + my $event_code_field = "event_code_$row_nr" ; + + next unless $i{$system_field} ; + + my $production_seconds = $i{"time_$row_nr"} ; + + my $cloud_recording_seconds = $i{"cloud_time_$row_nr"} ; + + next if $ii{$i{$_}}{NA}{matched_events} =~ /$i{$event_code_field}/ ; + + $ii{$i{$_}}{$i{$system_field}}{event_system_production_seconds} += $production_seconds ; + $ii{$i{$_}}{$i{$system_field}}{event_system_cloud_recording_seconds} += $cloud_recording_seconds ; + $ii{$i{$_}}{NA}{matched_events} .= ($ii{$i{$_}}{NA}{matched_events}) ? qq~|$i{$event_code_field}~ : qq~$i{$event_code_field}~ ; + + } + + foreach my $event_id (sort keys %ii) { + + %i = () ; + + foreach my $system_id (sort keys %{$ii{$event_id}}) { + next if $system_id eq 'NA' ; + $i{event_system_production_seconds} .= qq~$system_id:$ii{$event_id}{$system_id}{event_system_production_seconds}|~ ; + $i{event_system_cloud_recording_seconds} .= qq~$system_id:$ii{$event_id}{$system_id}{event_system_cloud_recording_seconds}|~ ; + } + + chop $i{event_system_production_seconds} if $i{event_system_production_seconds} ; + chop $i{event_system_cloud_recording_seconds} if $i{event_system_cloud_recording_seconds} ; + + $i{matched_events} = $ii{$event_id}{NA}{matched_events} ; + + next if !$i{event_system_production_seconds} && !$i{event_system_cloud_recording_seconds} && !$i{matched_events} ; + + $ignore{event_system_production_seconds} = ($i{event_system_production_seconds} && $i{event_system_production_seconds} eq $db{event_production_time}{$event_id}{event_system_production_seconds}) ? 1 : 0 ; + $ignore{event_system_cloud_recording_seconds} = ($i{event_system_cloud_recording_seconds} && $i{event_system_cloud_recording_seconds} eq $db{event_production_time}{$event_id}{event_system_cloud_recording_seconds}) ? 1 : 0 ; ; + $ignore{matched_events} = ($i{matched_events} && $i{matched_events} eq $db{event_production_time}{$event_id}{matched_events}) ? 1 : 0 ; + + next if $ignore{event_system_production_seconds} && $ignore{event_system_cloud_recording_seconds} && $ignore{matched_events} ; + + next unless $i{matched_events} ; + + if ($db{event_production_time}{$event_id}{quote_id}) { + # print "\n UPDATE event_production_time SET event_system_production_seconds='$i{event_system_production_seconds}',event_system_cloud_recording_seconds='$i{event_system_cloud_recording_seconds}',matched_events='$i{matched_events}'" ; + &db_min_upd('event_production_time',"quote_id='$event_id'") ; + } else { + $i{quote_id} = $event_id ; + + $max_id ++ ; + $i{id} = $max_id ; + + # print "\n INSERT INTO event_production_time (id,event_system_production_seconds,event_system_cloud_recording_seconds,matched_events,quote_id) VALUES ($i{id},$i{event_system_production_seconds},$i{event_system_cloud_recording_seconds},$i{matched_events},$i{quote_id})" ; + + &db_min_insert('event_production_time') ; + + } + + } + + %i = %iii ; + +} #------------------------------------------------------------------------------------------ + +sub read_import { + + my $upload_filehandle = $q->upload('iattachdoc') ; + + unless ($upload_filehandle) { + &screen1 ; + } + + &db_min_ro('event_production_time_unmatched','id,unmatched_line','','','') ; + + foreach (keys %{$db{event_production_time_unmatched}}) { + my $event_code = substr($db{event_production_time_unmatched}{$_}{unmatched_line},-8) ; + $event_code_unmatched_id{$event_code} = $_ ; + } + + &db_min_ro('event_production_time','id,matched_events',"","","") ; + + our %matched_event = () ; + + foreach my $quote_id (keys %{$db{event_production_time}}) { + foreach my $event_code (split(/\|/,$db{event_production_time}{$quote_id}{matched_events})) { + $matched_event{$event_code} = 1 ; + } + } + + # our $start_date = ($upload_filehandle =~ /August/) ? "$now_year-08-01" : ($upload_filehandle =~ /September/) ? "$now_year-09-01" : "" ; + # our $end_date = ($upload_filehandle =~ /August/) ? "$now_year-08-31" : ($upload_filehandle =~ /September/) ? "$now_year-09-30" : "" ; + + # &db_open_upd ; + # our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + # $print_tbody .= qq~~ ; + + our %csv_line = () ; my $line_cnt = 0 ; + + if ($type eq 'csv') { + + while ( <$upload_filehandle> ) { + # foreach (@imported_file_data) { + chomp; + + next if !$_ || ($_ !~ /\d+/ && $_ !~ /[a-zA-Z]/) ; + + # ClubName;StartDate;EndDate;Production Hours;Production Seconds;CloudRecording HD Duration(Sec);Event Name;Event Type;event_code + $_ =~ s/"(\d+),(\d+)"/$1$2/g; + # $_=~ s/\,/\;/g ; + + $_ =~ s/\R\z// ; # Removes any line-ending character (\n, \r\n, or \r) + + my @linex = split(/\;/,$_) ; + + next if $linex[0] eq 'ClubName' ; + + $ProductionHours = $linex[3] ; + $ProductionSeconds = $linex[-5] ; + $CloudRecordingDur = $linex[-4] ; + $EventName = $linex[-3] ; + $EventType = $linex[-2] ; + $event_code = $linex[-1] ; + + # $ProductionHours = $linex[3] ; + # $ProductionSeconds = $linex[4] ; + # $CloudRecordingDur = $linex[5] ; + # $EventName = $linex[6] ; + # $EventType = $linex[7] ; + # $EventID = $linex[8] ; + + # $event_code =~ s/\R\z// ; # Removes any line-ending character (\n, \r\n, or \r) + + $event_code = substr($event_code,-8) ; + + $event_code_to_line{$event_code} = $_ ; + + next if $matched_event{$event_code} || $event_code_unmatched_id{$event_code} ; + + $ClubName = $linex[0] ; + $StartDate = $linex[1] ; + + next unless $StartDate ; + + my ($event,$system) = split("-",$ClubName) ; # Gymnastics Competition 148 - AISA_SOLO_10 + $event =~ s/ $//g; $system =~ s/^ //g; # remove whitespace + + my @eventdetails = split(/ /,$event) ; # Gymnastics Competition 148 + + $system = 'none' unless $system ; + + my ($sdate,$stime,$ampm) = split(/ /,$StartDate) ; + my @sdateparts = split(/\//,$sdate) ; + my @stimeparts = split(/\:/,$stime) ; $stimeparts[0] += 12 if $ampm eq 'PM' && $stimeparts[0] < 12 ; + + # $stimeparts[0] -= 12 if $pmam eq 'PM' && $stimeparts[0] > 11 ; + + my $shr = sprintf("%02s", $stimeparts[0]) ; + my $smn = sprintf("%02s", $stimeparts[1]) ; + my $ss = sprintf("%02s", $stimeparts[2]) ; + my $smm = sprintf("%02s", $sdateparts[0]) ; + my $sdd = sprintf("%02s", $sdateparts[1]) ; + my $sccyy = $sdateparts[2] ; + + my $startccyymmdd = $sccyy . $smm . $sdd ; + + $EndDate = $linex[2] ; + + next unless $EndDate ; + + my ($edate,$etime,$pmam) = split(/ /,$EndDate) ; + my @edateparts = split(/\//,$edate) ; + my @etimeparts = split(/\:/,$etime) ; $etimeparts[0] += 12 if $pmam eq 'PM' ; + + $etimeparts[0] -= 12 if $pmam eq 'PM' && $etimeparts[0] > 11 ; + + my $ehr = sprintf("%02s", $etimeparts[0]) ; + my $emn = sprintf("%02s", $etimeparts[1]) ; + my $es = sprintf("%02s", $etimeparts[2]) ; + my $emm = sprintf("%02s", $edateparts[0]) ; + my $edd = sprintf("%02s", $edateparts[1]) ; + my $eccyy = $edateparts[2] ; + + my $endccyymmdd = $eccyy . $emm . $edd ; + + # &common_debug("$StartDate->$EndDate [$startccyymmdd,$endccyymmdd]") ; + + if (!$last_start_ccyymmdd || $last_start_ccyymmdd > $startccyymmdd) { + $last_start_ccyymmdd = $startccyymmdd ; + $start_sql = "$sccyy-$smm-$sdd 00:00:00" ; + } + + if (!$last_end_ccyymmdd || $last_end_ccyymmdd < $endccyymmdd) { + $last_end_ccyymmdd = $endccyymmdd ; + $end_sql = "$eccyy-$emm-$edd 23:59:59" ; + } + + $csv_line{$event_code}{club_name} = $ClubName ; + $csv_line{$event_code}{event_name} = $EventName ; + $csv_line{$event_code}{production_hours} = $ProductionHours ; + $csv_line{$event_code}{production_seconds} = $ProductionSeconds ; + $csv_line{$event_code}{cloud_seconds} = $CloudRecordingDur ; + $csv_line{$event_code}{start_time} = "$sccyy-$smm-$sdd $shr:$smn:$ss" ; + $csv_line{$event_code}{end_time} = "$eccyy-$emm-$edd $ehr:$emn:$es" ; + + $csv_line{$event_code}{production_hours} =~ s/ //g ; + $csv_line{$event_code}{production_seconds} =~ s/ //g ; + $csv_line{$event_code}{cloud_seconds} =~ s/ //g ; + + $line_cnt++ ; + + $csv_line{$event_code}{line_cnt} = $line_cnt ; + + # $description =~ s/^\s+|\s+$//g ; # remove whitespace at beginning and end + + # &common_date_array($startccyymmdd,$endccyymmdd); + + # foreach (@common_date_array) { + # $pixellot_system{$_}{"$shr:$smn-$ehr:$emn"}{$system} = $EventName ; + + # $times_in_csv{$_}{"$shr:$smn-$ehr:$emn"}{$EventName} += 1 ; + + # $pixellot_system{$_}{"$shr:$smn-$ehr:$emn"}{$EventName} = "$system|$eventdetails[-1]|$ProductionHours|$ProductionSeconds|$CloudRecordingDur|$ClubName|$EventName|$event_code|" ; + + # &common_debug("pixellot_system : {$_}{$shr:$smn-$ehr:$emn} [$system|$ProductionHours|$ProductionSeconds|$CloudRecordingDur|$EventName|]") ; + + # } + + $x++; + + # $i{category_id} = 37 if $amount < 0 && ($description =~ /WOOLWORTHS/iog || $description =~ /CHECKERS/iog || ($description =~ /KwikSpar/iog && $description =~ /food/iog)) && $account_nr != 62547665945 ; # Office Supplies + # last if $x > 10; + } + } + + # $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + # &db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +sub read_db { + + if (!$last_start_ccyymmdd && !$last_end_ccyymmdd) { + print "All The Data In This File Is Already Matched Or Saved As Unmatched!!!" ; + exit ; + } + + &production_time_read_db_to_match_events_and_systems ; + +} #------------------------------------------------------------------------------------------ + +sub process { + + &production_time_process_matched_events_and_systems ; + +} #------------------------------------------------------------------------------------------ + +sub screen1 { + + &common_min_dialog ; + + $print_box_content_rows .= qq~
    ~; + + # my $date_inputs = &common_min_form_datepicker() ; + + print < + +
    +
    +
    +
    +
    +
    +
    + + +

    Upload file from PC.

    +
    +
    +
    +
    + +
     
    +
    +
    +   + +
    +
    +
     
    +
    +
    +
    +
    +
    +
    + + + + + + + $dialog{'common'}{'js'} + + + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + + # + + my $jquery = qq~parent.\$("#alertbar").html(""); + parent.location.reload(); + parent.BootstrapDialog.closeAll() ;~ unless $debug ; + + print < + + + + $useropts{title} + + + + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +sub screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# my $page = "$lcpage\s" ; + +my $page = "event-quotes" ; + +if ($s{no}) { $page = $lcpage ; } + +&common_min_thead ; + +# &common_min_table('id',$page,'list') ; + +$print_box_content_rows .= qq~ + + $print_thead + + $print_tbody + +
    +~ ; + +&common_min_table_select_jquery("#itv-table td:nth-last-child(2),#itv-table td:nth-last-child(10)") ; + +# our $savjqy = 1 ; + +# &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ; + +# $extra_form_fields .= qq~~ ; + + # + # + # + # + # + # +# ~ ; + +$print_box_content_rows .= &common_min_forms_end('','','save') ; + +require _blank_4 ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +use today ; +use common ; +use production_time ; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/dialog/import_analytics_fixtures.pl b/scripts/_FromProd/v1.0/dialog/import_analytics_fixtures.pl new file mode 100644 index 0000000..bbc460e --- /dev/null +++ b/scripts/_FromProd/v1.0/dialog/import_analytics_fixtures.pl @@ -0,0 +1,676 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ) ; +use CGI::Carp qw(fatalsToBrowser) ; +use LWP::Simple qw($ua get) ; +use Date::Calc qw(:all) ; +use MIME::Lite ; +use Mail::Sendmail ; +use Time::Piece ; +use Spreadsheet::ParseXLSX ; +use File::Temp qw(tempfile) ; + +require cfg ; + +print header; # CGI.pm method + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +my $type = $ARGV[0] ; + +our ($q) = CGI -> new() ; +my $iaction = $q -> param('iaction') ; +my $iattachdoc = $q -> param('iattachdoc') ; + +# our $debug = 1 ; +# our $testing = 1 ; + +#------------------------------------------------------------------------------------------ + +&today ; + +if ($iaction eq '') { + &screen1 ; +} elsif ($iaction eq 'upload') { + &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &read_import ; + &screen2 ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; +} + +exit ; + +#------------------------------------------------------------------------------------------ + +sub read_read_import_lines { + + our $max_unmatched_id = 0 ; + + my $upload_filehandle = $q->upload('iattachdoc') ; + +} #------------------------------------------------------------------------------------------ + +sub read_import { + + $print_box_content_rows .= &common_min_forms_start('import-analytics-fixtures') ; + + my $upload_filehandle = $q->upload('iattachdoc') ; + + unless ($upload_filehandle) { + $warning = "PLEASE UPLOAD AN EXCEL FILE!!!" ; + &common_min_alert_type ; + &screen1 ; + } + + our %totals = () ; my $line_cnt = 0 ; my %event_cnt = () ; + + if ($upload_filehandle !~ /.xlsx/) { + $error = "PLEASE UPLOAD AN EXCEL TYPE FILE!!!" ; + &common_min_alert_type ; + &screen1 ; + } + + my $file_total_amnt = 0 ; my $file_nr_of_rows = 0 ; + + our %coding_type = ("s" => "Standard","p" => "Premium") ; + our %footage_type = ("s" => "SSS","r" => "Raw") ; + + our %coding_type2 = ("standard" => "s","premium" => "p") ; + our %footage_type2 = ("sss" => "s","raw" => "r") ; + + our %fixtures_input_vals = () ; + + our $suffix = "fixtures" ; + + if ($type eq 'xlsx') { + + &db_min_ro('analytics_ht_colors','id,name','','','') ; + + foreach (keys %{$db{analytics_ht_colors}}) { + $analytics_ht_colors_name_to_id{lc $db{analytics_ht_colors}{$_}{name}} = $_ ; + } + + &db_min_ro('sport_types','id,name','','','') ; + + foreach (keys %{$db{sport_types}}) { + $sport_type_name_to_id{lc $db{sport_types}{$_}{name}} = $_ ; + } + $sport_type_name_to_id{"waterpolo"} = 4 ; + + &db_switch_conn('sss'); + + &db_min_ro('teams','id,name','','','') ; + + foreach (keys %{$db{teams}}) { + $team_name_to_id{lc $db{teams}{$_}{name}} = $_ ; + } + + &db_switch_conn('aisa'); + + my %seen_col_val = () ; + + if ($type eq 'csv') { + + while ( <$upload_filehandle> ) { + # foreach (@imported_file_data) { + + next if $_ !~ /\d+/ ; + + $file_nr_of_rows++ ; + + chomp $_ ; + + $_ =~ s/\R\z// ; # Removes any line-ending character (\n, \r\n, or \r) + $_ =~ s/\"//g ; + + my @def_split = split(/\;/,$_) ; + + push @rows, \@def_split; + + } + } else { + + my ($tmpfh, $tmpfilename) = tempfile(SUFFIX => '.xlsx', UNLINK => 1); + + binmode $upload_filehandle ; + binmode $tmpfh ; + while (my $bytesread = read($upload_filehandle, my $buffer, 8192)) { + print $tmpfh $buffer ; + } + close $tmpfh ; + + my $parser = Spreadsheet::ParseXLSX->new() ; + my $workbook = $parser->parse($tmpfilename) ; + + unless ($workbook) { + $error = "Failed to parse Excel file: " . $parser->error() ; + &common_min_alert_type ; + &screen1 ; + } + + my $worksheet = ($workbook->worksheets())[0] ; + my ($row_min,$row_max) = $worksheet->row_range() ; + my ($col_min,$col_max) = $worksheet->col_range() ; + + for my $row ($row_min .. $row_max) { + + my @def_split = (); + for my $col ( $col_min .. $col_max ) { + my $cell = $worksheet->get_cell( $row, $col ); + my $val = $cell ? $cell->value() : ''; + push @def_split, $val; + } + push @rows, \@def_split if grep { /\S/ } @def_split; # skip empty + } + + } + + my $row_cnt = 0 ; my $table_row_cnt = 0 ; + + foreach my $def_split_ref (@rows) { + + $row_cnt++; + my @def_split = @$def_split_ref; + + my %seen_row = () ; + + for my $col_cnt (1 .. 12) { + + my $val = $def_split[$col_cnt - 1] ; + + next if !$val + || $val =~ /Analytics-Fixtures/ + || $val =~ /Fixture Date/ + || $val =~ /Time From/ + || $val =~ /Sport/ + || $val =~ /Team/ + || $val =~ /HT Colour/ + || $val =~ /Away Team/ + || $val =~ /Coding Type/ + || $val =~ /Footage Type/ + || $val =~ /Age Group/ + || $val =~ /Stream Forwarding/ + || $val =~ /Stream Key/ + || $val =~ /Stream URL/ + ; + + $table_row_cnt++ unless $seen_row{$row_cnt} ; + $seen_row{$row_cnt} = 1 ; + + if ($col_cnt == 1) { + $val =~ s/\T//g ; + } elsif ($col_cnt == 2) { + $val = $sport_type_name_to_id{lc $val} ; + } elsif ($col_cnt == 3 || $col_cnt == 4) { + $val = lc $val ; + } elsif ($col_cnt == 5 || $col_cnt == 7) { + $val = $team_name_to_id{lc $val} ; + } elsif ($col_cnt == 6) { + $val = $analytics_ht_colors_name_to_id{lc $val} ; + } elsif ($col_cnt == 8) { + $val = $coding_type2{lc $val} ; + } elsif ($col_cnt == 9) { + $val = $footage_type2{lc $val} ; + } elsif ($col_cnt == 10) { + $val = (lc $val eq 'yes') ? 1 : (lc $val eq 'no') ? 2 : 0 ; + } + + $fixtures_input_vals{$table_row_cnt}{$col_cnt} = $val if $val; + + } + + } + + } + + our %col_cnt_field_id = () ; + + $col_cnt_field_id{1} = "datetimepickerStart_date_time_fixtures_" ; + $col_cnt_field_id{2} = "selectReadonly_sport_fixtures_" ; + $col_cnt_field_id{3} = "selectAge_group_fixtures_" ; + $col_cnt_field_id{4} = "selectTeam_fixtures_" ; + $col_cnt_field_id{5} = "selectHome_team_fixtures_" ; + $col_cnt_field_id{6} = "selectHt_colour_fixtures_" ; + $col_cnt_field_id{7} = "selectAway_team_fixtures_" ; + $col_cnt_field_id{8} = "selectCoding_type_fixtures_" ; + $col_cnt_field_id{9} = "selectFootage_type_fixtures_" ; + $col_cnt_field_id{10} = "selectStream_forwarding_fixtures_" ; + $col_cnt_field_id{11} = "textareaStream_key_fixtures_" ; + $col_cnt_field_id{12} = "textareaStream_URL_fixtures_" ; + + our $col_cnt_field_id_str = qq~~ ; + + our $col_cnt_field_id_str2 = qq~"10":"selectStream_forwarding_analytics_","11":"textareaStream_key_analytics_","12":"textareaStream_URL_analytics_"~ ; + + foreach (keys %col_cnt_field_id) { + $col_cnt_field_id_str .= qq~"$_":"$col_cnt_field_id{$_}",~ ; + } + chop $col_cnt_field_id_str ; + + our $max_row_cnt = 0 ; + + our $fixtures_input_vals_str = qq~~ ; + + our %add_select_options = () ; + + foreach my $row_cnt (sort {$a <=> $b} keys %fixtures_input_vals) { + + $max_row_cnt = $row_cnt if !$max_row_cnt || $row_cnt > $max_row_cnt ; + $fixtures_input_vals_str .= qq~"$row_cnt":{~ ; + foreach my $col_cnt (sort {$a <=> $b} keys %{$fixtures_input_vals{$row_cnt}}) { + $fixtures_input_vals_str .= qq~"$col_cnt":"$fixtures_input_vals{$row_cnt}{$col_cnt}",~ ; + if ($col_cnt == 2) { + $add_select_options{selectReadonly_sport_fixtures}{$fixtures_input_vals{$row_cnt}{$col_cnt}} = $db{sport_types}{$fixtures_input_vals{$row_cnt}{$col_cnt}}{name} ; + } elsif ($col_cnt == 5) { + $add_select_options{selectHome_team_fixtures}{$fixtures_input_vals{$row_cnt}{$col_cnt}} = $db{teams}{$fixtures_input_vals{$row_cnt}{$col_cnt}}{name} ; + } elsif ($col_cnt == 7) { + $add_select_options{selectAway_team_fixtures}{$fixtures_input_vals{$row_cnt}{$col_cnt}} = $db{teams}{$fixtures_input_vals{$row_cnt}{$col_cnt}}{name} ; + } elsif ($col_cnt == 10) { + + } + } + chop $fixtures_input_vals_str ; + $fixtures_input_vals_str .= qq~},~ ; + } + + chop $fixtures_input_vals_str ; + + return unless $max_row_cnt ; + +} #------------------------------------------------------------------------------------------ + +sub screen1 { + + &common_min_dialog ; + + $print_box_content_rows .= qq~
    ~; + + # my $date_inputs = &common_min_form_datepicker() ; + + print < + + + $alert + +
    +
    +
    +
    +
    +
    +
    + + +

    Upload file from PC.

    +
    +
    +
    +
    + +
     
    +
    +
    +   + +
    +
    +
     
    +
    +
    +
    +
    +
    +
    + + + + + + + $dialog{'common'}{'js'} + + + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + + $trigger_jquery_raw .= qq~let value_exists ;~ ; + + my $sport_options = qq~~ ; + foreach (keys %{$add_select_options{selectReadonly_sport_fixtures}}) { + $sport_options = qq~"$_",~ ; + } + chop $sport_options if $sport_options ; + + foreach my $field (keys %add_select_options) { + + my %seen_value = () ; + $trigger_jquery_raw .= qq~parent.\$("#selectSport_type_ids").val([$sport_options]).trigger("chosen:updated") ;~ if $field eq "selectReadonly_sport_fixtures" && $sport_options ; + + foreach my $value (keys %{$add_select_options{$field}}) { + + $trigger_jquery_raw .= qq~ + value_exists = \$("#$field"+"_1 option[value='$value']").length > 0 ; + if (!value_exists) { + parent.\$("#$field"+"_1").append("").trigger("chosen:updated") ; + for (let k = 2; k <= 100; k++) { + if (!parent.\$("#fixtures_"+k).html()) { break ; } + parent.\$("#$field"+"_"+k).append("").trigger("chosen:updated") ; + } + } + ~ unless $seen_value{$value} ; + + $seen_value{$value} = 1 ; + + } + } + + $trigger_jquery_raw .= qq~ + + let col_cnt_field_id = {$col_cnt_field_id_str} ; + let col_cnt_field_id2 = {$col_cnt_field_id_str2} ; + let fixtures_input_vals = {$fixtures_input_vals_str} ; + let max_row_cnt = parseInt("$max_row_cnt") ; + let default_val ; + let earliest_date ; let latest_date ; + + if (!max_row_cnt) { + parent.BootstrapDialog.closeAll() ; + } + + for (let j = 1; j <= max_row_cnt; j++) { + + if (!parent.\$("#fixtures_"+j).html()) { + add_row(j) ; + } else if (parent.\$("#fixtures_"+j).css("display") === "none" && parent.\$("#fixtures_"+j).html()) { + parent.\$("#fixtures_"+j).show() ; + } + + default_val = (fixtures_input_vals[j][1]) ? fixtures_input_vals[j][1] : parent.\$("input[name='start_date_time']").val() ; + + parent.\$("#"+col_cnt_field_id[1]+""+j).datetimepicker("setDate",default_val) ; + + if (fixtures_input_vals[j][1]) { + parent.\$("input[name='changed_fixtures_date_"+j+"']").val("1") ; + let this_date = new Date(fixtures_input_vals[j][1]) ; + this_date = new Date(this_date.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours + earliest_date = (!earliest_date || (earliest_date && earliest_date > this_date)) ? this_date : earliest_date ; + latest_date = (!latest_date || (latest_date && latest_date < this_date)) ? this_date : latest_date ; + } else { + parent.\$("input[name='changed_fixtures_date_"+j+"']").val("") ; + } + + if (fixtures_input_vals[j][2]) { + parent.\$("input[name='sport_fixtures_"+j+"']").val(fixtures_input_vals[j][2]) ; + } else { + parent.\$("input[name='sport_fixtures_"+j+"']").val("") ; + } + + if (fixtures_input_vals[j][4]) { + parent.\$("input[name='changed_home_team_"+j+"']").val("1") ; + } else { + parent.\$("input[name='changed_home_team_"+j+"']").val("") ; + } + + for (let col_cnt = 2; col_cnt <= 9; col_cnt++) { + if (fixtures_input_vals[j][col_cnt]) { + parent.\$("#"+col_cnt_field_id[col_cnt]+""+j).val(fixtures_input_vals[j][col_cnt]).trigger("chosen:updated"); + } + } + for (let col_cnt = 10; col_cnt <= 12; col_cnt++) { + if (fixtures_input_vals[j][col_cnt]) { + parent.\$("#"+col_cnt_field_id[col_cnt]+""+j).val(fixtures_input_vals[j][col_cnt]).trigger("chosen:updated"); + if (parent.\$("#analytics_"+j).html()) { + parent.\$("#"+col_cnt_field_id2[col_cnt]+""+j).val(fixtures_input_vals[j][col_cnt]).trigger("chosen:updated"); + } + } + } + } + + let start_date = new Date(parent.\$("input[name='start_date_time']").val()) ; + let end_date = new Date(parent.\$("input[name='end_date_time']").val()) ; + + start_date = new Date(start_date.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours + end_date = new Date(end_date.getTime() + 2 * 60 * 60 * 1000) ; // Add 2 hours + + if (earliest_date) { + + if (earliest_date < start_date) { + + parent.\$("#datetimepickerStart_date_time").datetimepicker("setDate",earliest_date) ; + + for (let h = 1; h <= 100; h++) { + if (!\$("#fixtures_"+h).html()) { + break ;changed_fixtures_date_4 + } + if (\$("input[name='changed_fixtures_date_"+h+"']").val() || h == row_nr) { + continue ; + } + \$("#datetimepickerStart_date_time_fixtures_"+h).datetimepicker("setDate",earliest_date) ; + } + } + let earliest = new Date(earliest_date); + parent.\$("#datetimepickerStart_date_time").datetimepicker("setEndDate",earliest); + + } + if (latest_date) { + if (latest_date > end_date) { + parent.\$("#datetimepickerEnd_date_time").datetimepicker("setDate",latest_date) ; + } else { + + } + let latest = new Date(latest_date); + parent.\$("#datetimepickerEnd_date_time").datetimepicker("setStartDate",latest); + } + + ~ ; + + if ($max_row_cnt) { + $trigger_jquery_raw .= qq~ + parent.\$("#selectTotal_fixtures").val(max_row_cnt).trigger("chosen:updated") ; + for (let k = max_row_cnt+1; k <= 100; k++) { + if (!parent.\$("#fixtures_"+k).html()) { + break ; + } else { + parent.\$("#fixtures_"+k).css("display","none") ; + } + } + ~ ; + } + + $trigger_jquery_raw .= qq~ + + function add_row (i) { + + let html = "
    " ; + + html += "" ; + html += "" ; + + html += "
    " ; + + html += add_datetimepicker(i,"start_date_time_$suffix",1,6,\$("input[name='start_date_time']").val()) ; + html += add_select(i,"readonly_sport_$suffix\_" + i, "selectReadonly_sport_$suffix\_" + i, "Select Sport "+i, "", 2, 4, 100, "", "") ; + html += "" ; + html += add_select(i,"age_group_$suffix\_" + i,"selectAge_group_$suffix\_" + i,"Select Age Group "+i,"",3,2,100,"","") ; + + html += "
    " ; + + html += "
    " ; + + html += add_select(i,"team_$suffix\_" + i, "selectTeam_$suffix\_" + i, "Select Team "+i, "", 4, 1, 100, "", "") ; + html += add_select(i,"home_team_$suffix\_" + i, "selectHome_team_$suffix\_" + i, "Select Home Team "+i, "", 5, 3, 100, "", "") ; + html += add_select(i,"ht_colour_$suffix\_" + i, "selectHt_colour_$suffix\_" + i, "Select Ht Colour "+i, "", 6, 2, 100, "", "") ; + html += add_select(i,"away_team_$suffix\_" + i, "selectAway_team_$suffix\_" + i, "Select Away Team "+i, "", 7, 3, 100, "", "") ; + html += add_select(i,"coding_type_$suffix\_" + i, "selectCoding_type_$suffix\_" + i, "Select Coding Type "+i,"", 8, 2, 100, "", "") ; + html += add_select(i,"footage_type_$suffix\_" + i, "selectFootage_type_$suffix\_" + i, "Select Footage Type "+i, "", 9, 1, 100, "", "") ; + + html += "
    " ; + + html += add_select(i,"stream_forwarding_$suffix\_" + i, "selectStream_forwarding_$suffix\_" + i, "Select Stream Forwarding "+i,"", 10, 1, 100, "", "") ; + html += add_textarea (i,"stream_key_$suffix\_"+i,"textareaStream_key_$suffix\_"+i,"Stream Key "+i,11,"",1) ; + html += add_textarea (i,"stream_URL_$suffix\_"+i,"textareaStream_URL_$suffix\_"+i,"Stream URL "+i,12,"",1) ; + + html += "
    " ; + + parent.\$("#fixtures_table").append(html).trigger("chosen:updated") ; + + parent.\$('#datetimepickerStart_date_time_$suffix\_'+i).datetimepicker({language: 'pt-BR'}) ; + + let options ; + + ~ ; + + foreach (keys %col_cnt_field_id) { + + next if $_ == 1 ; + + $trigger_jquery_raw .= qq~ + + options = parent.\$("#$col_cnt_field_id{$_}"+"1").children().clone(); + parent.\$("#$col_cnt_field_id{$_}"+i).append(options).trigger("chosen:updated") ; + + ~ ; + + } + + $trigger_jquery_raw .= qq~ + + parent.\$("#selectAge_group_$suffix\_"+i+",#selectTeam_$suffix\_"+i+",#selectStream_forwarding_$suffix\_"+i).chosen({ allow_single_deselect:false }) ; + parent.\$("#selectReadonly_sport_$suffix\_"+i+",#selectHome_team_$suffix\_"+i+",#selectHt_colour_$suffix\_"+i+",#selectAway_team_$suffix\_"+i+",#selectCoding_type_$suffix\_"+i+",#selectFootage_type_$suffix\_"+i).chosen({ allow_single_deselect:false }) ; + parent.\$("#selectReadonly_sport_$suffix\_"+i+"_chosen,#selectAge_group_$suffix\_"+i+"_chosen,#selectTeam_$suffix\_"+i+"_chosen,#selectHome_team_$suffix\_"+i+"_chosen,#selectHt_colour_$suffix\_"+i+"_chosen,#selectAway_team_$suffix\_"+i+"_chosen,#selectCoding_type_$suffix\_"+i+"_chosen,#selectFootage_type_$suffix\_"+i+"_chosen").css("width","100%") ; + + } + + function get_row_nr (id) { + let lastIndex = id.lastIndexOf('_') ; + lastIndex = parseInt(lastIndex) ; + let row_nr = id.substring(1+lastIndex) ; + row_nr = parseInt(row_nr) ; + return row_nr ; + } + + function add_textarea (row_nr,field_name,field_id,placeholder,tindex,readonly,fcol,default_val="",width="100",height="22.5",hide="") { + let textarea = "
    " ; + return textarea ; + } + + function add_input (row_nr,field_name,field_id,placeholder,tindex,readonly,fcol,default_val) { + let input = "
    " ; + return input ; + } + + function add_select (row_nr,field_name,field_id,placeholder,options,tindex,fcol,width,div_id,hide_div) { + let select = "
    " ; + select = select + add_select_raw(row_nr,field_name,field_id,placeholder,options,tindex,width) ; + select = select + "
    " ; + return select ; + } + + function add_select_raw (row_nr,field_name,field_id,placeholder,options,tindex,width) { + let select_raw = "
    " ; + return select_raw ; + } + + function add_datetimepicker (row_nr,field_name,tindex,fcol,default_val) { + let ucfirst_field_name = ucfirst(field_name) ; + let datetimepicker = "
    " ; + return datetimepicker ; + } + + function ucfirst(str) { + if (!str) return str; // Handle empty string + return str.charAt(0).toUpperCase() + str.slice(1) ; + } + + parent.BootstrapDialog.closeAll() ; + + ~ ; + + + # + + # $trigger_jquery_raw .= qq~ + # parent.\$("#alertbar").html(""); + # parent.location.reload(); + # parent.BootstrapDialog.closeAll() ; + # ~ unless $debug ; + + &common_min_dialog_save_screen ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_dialog_save_screen_test { + +print < + + + + ITV Admin + + + + + + + + + + + + + + + + + + + + + + + + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + + +use today ; +use common ; +use common_min ; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/dialog/import_bank_trans.pl b/scripts/_FromProd/v1.0/dialog/import_bank_trans.pl new file mode 100644 index 0000000..67ee2ec --- /dev/null +++ b/scripts/_FromProd/v1.0/dialog/import_bank_trans.pl @@ -0,0 +1,492 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); +use LWP::Simple qw($ua get); +use Date::Calc qw(:all); +use MIME::Lite; +use Mail::Sendmail; +use Time::Piece ; + +require cfg ; + +print header; # CGI.pm method + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +my $type = $ARGV[0] ; + +our ($q) = CGI -> new() ; +my $iaction = $q -> param('iaction') ; +my $iattachdoc = $q -> param('iattachdoc') ; + +# our $debug = 1 ; +# our $testing = 1 ; + +#------------------------------------------------------------------------------------------ + +&today ; + +# my $string = qq~6565,2,328.00~ ; + +if ($iaction eq '') { + + &screen1 ; + +} elsif ($iaction eq 'upload') { + + &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &read_import ; + &read_db ; + &process ; + &screen4 ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + +} +# elsif ($iaction eq 'save') { + + # &common_min_load_params ; + # &db_open_upd ; + # our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + # &read_read_import_lines ; + # &update ; + # $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + # &db_close_conn ; + # &screen2 ; +# } + +exit; + +#------------------------------------------------------------------------------------------ + +sub read_read_import_lines { + + our $max_unmatched_id = 0 ; + + my $upload_filehandle = $q->upload('iattachdoc') ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + # &db_min_ro('logistics_costs','event_nr,amounts,file_name_ids,cost_type',"",'','') ; + + # &db_min_ro('logistics_costs_tables',"1,MAX(id)+1 AS 'max_id'","",'','') ; + # $db{logistics_costs_tables}{1}{max_id} = 1 unless $db{logistics_costs_tables}{1}{max_id} ; + + # my %ii = %i ; my $updated_logistics_costs_tables = 0 ; my $file_id = 0 ; my %cost_types = () ; my %event_has_diff_cost_types = () ; my %prev_cost_type = () ; + + # foreach (keys %ii) { + # if ($_ =~ /costtype_/) { + # my ($NA,$event_id,$amnt_cnt) = split(/\_/,$_) ; + # $event_id = ($event_id =~ /\d+/) ? $event_id : -1 ; + # $cost_types{$event_id}{$amnt_cnt} = $ii{$_} ; + # if ($prev_cost_type{$event_id} && $prev_cost_type{$event_id} ne $ii{$_}) { + # $event_has_diff_cost_types{$event_id} = 1 ; + # } + # $prev_cost_type{$event_id} = $ii{$_} ; + # } + # } + + # foreach (keys %ii) { + # if ($_ =~ /breakdownamnts_/) { + # unless ($updated_logistics_costs_tables) { + # $updated_logistics_costs_tables = 1 ; + # %i = () ; + # $i{id} = $db{logistics_costs_tables}{1}{max_id} ; + # $file_id = $i{id} ; + # $i{file_name} = $ii{uploaded_file_name} ; + # $i{file_total} = $ii{uploaded_file_total} ; + # $i{file_total} = sprintf("%.0f",$i{file_total}) ; + # $i{file_nr_of_unique_events} = $ii{file_nr_of_unique_events} ; + # $i{file_nr_of_rows} = $ii{file_nr_of_rows} ; + # $i{date_uploaded} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + # $i{uploaded_by} = $userid ; + # # &db_min_insert('logistics_costs_tables') ; + + # } + + # my ($NA,$event_id) = split(/\_/,$_) ; + + # %i = () ; + + # $i{event_nr} = ($event_id =~ /\d+/) ? $event_id : -1 ; + + # $i{cost_type} = ($db{logistics_costs}{$i{event_nr}}{cost_type}) ? "$db{logistics_costs}{$i{event_nr}}{cost_type}::" : "" ; + + # my $added_to_cost_type = 0 ; + + # foreach my $amnt_cnt (sort {$a <=> $b} keys %{$cost_types{$i{event_nr}}}) { + # $added_to_cost_type = 1 ; + # $i{cost_type} .= qq~$cost_types{$i{event_nr}}{$amnt_cnt};;~ ; + # last unless $event_has_diff_cost_types{$i{event_nr}} ; + # } + + # $i{cost_type} = substr($i{cost_type},0,-2) if $added_to_cost_type ; + + # # $i{cost_type} = ($db{logistics_costs}{$i{event_nr}}{cost_type} ) ? "$db{logistics_costs}{$i{event_nr}}{cost_type}::" . $ii{"costtype_$event_id"} : $ii{"costtype_$event_id"} ; + # $i{file_name_ids} = ($db{logistics_costs}{$i{event_nr}}{file_name_ids}) ? "$db{logistics_costs}{$i{event_nr}}{file_name_ids}:$file_id" : "$file_id" ; + # $i{amounts} = ($db{logistics_costs}{$i{event_nr}}{amounts} ) ? "$db{logistics_costs}{$i{event_nr}}{amounts}:$ii{$_}" : "$ii{$_}" ; ; + + # $i{amounts} =~ s/\,//g ; + # $i{amounts} =~ s/\.00//g ; + + # if ($i{event_nr} && $db{logistics_costs}{$i{event_nr}}{event_nr}) { + # $ignore{event_nr} = 1 ; + # # &db_min_upd('logistics_costs',"event_nr='$i{event_nr}'") ; + # } else { + # &db_min_ro('logistics_costs',"1,MAX(id)+1 AS 'max_id'","",'','') ; + # $db{logistics_costs}{1}{max_id} = 1 unless $db{logistics_costs}{1}{max_id} ; + # $i{id} = $db{logistics_costs}{1}{max_id} ; + # # &db_min_insert('logistics_costs') ; + # } + # } + # } + +} #------------------------------------------------------------------------------------------ + +sub read_import { + + $print_box_content_rows .= &common_min_forms_start('import-bank-transactions-form') ; + + my $upload_filehandle = $q->upload('iattachdoc') ; + + unless ($upload_filehandle) { + $warning = "PLEASE UPLOAD A CSV FILE!!!" ; + &common_min_alert_type ; + &screen1 ; + } + + our %totals = () ; my $line_cnt = 0 ; my %event_cnt = () ; + + if ($upload_filehandle !~ /.csv/) { + $error = "PLEASE UPLOAD A CSV TYPE FILE!!!" ; + &common_min_alert_type ; + &screen1 ; + } + + my $file_total_amnt = 0 ; my $file_nr_of_rows = 0 ; + + &db_min_ro('bank_transactions','id','','','') ; + + if ($type eq 'csv') { + + while ( <$upload_filehandle> ) { + # foreach (@imported_file_data) { + + next if $_ !~ /\d+/ ; + + $file_nr_of_rows++ ; + + chomp $_; + $_ =~ s/\R\z// ; + + my @data_arr = split(/\,/,$_) ; + + next if $db{bank_transactions}{$data_arr[0]}{id} ; + + $data{$data_arr[0]}{date_time} = $data_arr[1] ; + $data{$data_arr[0]}{transaction_date} = $data_arr[2] ; + $data{$data_arr[0]}{amount} = $data_arr[3] ; + $data{$data_arr[0]}{balance} = $data_arr[4] ; + $data{$data_arr[0]}{description} = $data_arr[5] ; + $data{$data_arr[0]}{account_nr} = $data_arr[6] ; + $data{$data_arr[0]}{category_id} = $data_arr[7] ; + $data{$data_arr[0]}{client_id} = $data_arr[8] ; + $data{$data_arr[0]}{invoice_nr} = $data_arr[9] ; + + } + } + + foreach my $id (sort {$a <=> $b} keys %data) { + %i = () ; + $i{id} = $id ; + foreach my $col (keys %{$data{$id}}) { + $i{$col} = $data{$id}{$col} ; + } + &db_min_insert('bank_transactions') ; + } + + # my $col_names = "id,date_time,transaction_date,amount,balance,description,account_nr,category_id,client_id,invoice_nr" ; + + # my $values = join("\n,",map{ "($_,'$data{$_}{date_time}','$data{$_}{transaction_date}','$data{$_}{amount}','$data{$_}{balance}','$data{$_}{description}','$data{$_}{account_nr}',$data{$_}{category_id},$data{$_}{client_id},'$data{$_}{invoice_nr}')" } keys %data) ; + + # print "\n INSERT INTO bank_transactions ($col_names) VALUES \n $values ;" if $values ; + + return ; + + # $file_total_amnt = sprintf("%.0f",$file_total_amnt) ; + + # our @sql_col_display = ("event_nr","cost_type","logistics_totals") ; + + # my $file_total = 0 ; my $file_nr_of_unique_events = 0 ; + + # &db_min_ro('event_quotes','id,quote_completed,quote_accepted,fixed_system_overall_status,event_system_id_multiple,quote_rejected,quote_cancelled,quote_created,quote_pending,sss_quote_nr',"",'','') ; + + # &db_min_ro('event_systems',"*",'','','') ; + + # my %seen_event = () ; + + # foreach my $event_id (sort {$a <=> $b} keys %totals) { + + # next if $event_id eq 'breakdown' ; + + # my $amnt_cnt = 0 ; + + # foreach my $sep_amnt (split(/\;/,$totals{breakdown}{$event_id})) { + + # $print_tbody .= qq~~ ; + + # $amnt_cnt++ ; + + # foreach (@sql_col_display) { + # my $val = '' ; + # my $class = qq~class="dt-center"~ ; + # if ($_ eq 'event_nr') { + # $val = ($event_id eq 'IBT') ? &common_min_get_event_quote_button("N/A") : &common_min_get_event_quote_button($event_id) ; + # $file_nr_of_unique_events++ unless $seen_event{$event_id} ; + # } elsif ($_ eq 'cost_type') { + # $val = ($event_id eq 'IBT') ? $event_id : "" ; + # $val = ($val) ? &common_min_table_input("costtype_$event_id\_$amnt_cnt",$val) : "" ; + # } elsif ($_ eq 'logistics_totals') { + # chop $totals{breakdown}{$event_id} if $totals{breakdown}{$event_id} ; + + # # my $seperate_amnts_tooltip = ($totals{breakdown}{$event_id} =~ /:/) ? $totals{breakdown}{$event_id} : qq~~ ; + # # $seperate_amnts_tooltip =~ s/\:/\
    /g ; + # # $seperate_amnts_tooltip = qq~title data-toggle="tooltip" data-placement="right" data-original-title="Seperate Amounts :
    $seperate_amnts_tooltip"~ if $seperate_amnts_tooltip ; + + # my $breakdownamnts = ($seen_event{$event_id}) ? qq~~ : qq~~ ; + # # + + # # $totals{seperate}{$event_id}{$event_cnt{$event_id}} + + # # $totals{seperate}{$event_id}{$amnt_cnt} = &common_commify(sprintf("%.02f",$totals{seperate}{$event_id}{$amnt_cnt})) ; + + # $val = qq~$breakdownamnts~ . qq~~ . $totals{seperate}{$event_id}{$amnt_cnt} . qq~~ ; + + # $file_total += $totals{$event_id} unless $seen_event{$event_id} ; + # } + # # style="display:none; + + # $print_tbody .= qq~$val~ ; + # } + # $print_tbody .= qq~~ ; + + # $seen_event{$event_id} = 1 ; + + # } + + # } + + # &db_min_ro('logistics_costs_tables',"1,id","`file_total`='$file_total_amnt' AND `file_nr_of_unique_events`='$file_nr_of_unique_events' AND `file_nr_of_rows`='$file_nr_of_rows'",'','') ; + + # if ($db{logistics_costs_tables}{1}{id}) { + # $warning = "THE FILE UPLOADED HAVE ALREADY BEEN SAVED!!!" ; + # &common_min_alert_type ; + # # &screen1 ; + # # $print_box_content_rows .= qq~~ ; + # } + + # $file_total = sprintf("%.02f",$file_total) ; + + # $print_box_content_rows .= qq~~ ; + # $print_box_content_rows .= qq~~ ; + # $print_box_content_rows .= qq~~ ; + # $print_box_content_rows .= qq~~ ; + + # # $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + # # &db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +sub read_db { + +} #------------------------------------------------------------------------------------------ + +sub process { + +} #------------------------------------------------------------------------------------------ + +sub screen1 { + + &common_min_dialog ; + + $print_box_content_rows .= qq~
    ~; + + # my $date_inputs = &common_min_form_datepicker() ; + + print < + + + $alert + +
    +
    +
    +
    +
    +
    +
    + + +

    Upload file from PC.

    +
    +
    +
    +
    + +
     
    +
    +
    +   + +
    +
    +
     
    +
    +
    +
    +
    +
    +
    + + + + + + + $dialog{'common'}{'js'} + + + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +# sub screen2 { + + # # + + # my $jquery = qq~parent.\$("#alertbar").html(""); + # parent.location.reload(); + # parent.BootstrapDialog.closeAll() ;~ unless $debug ; + + # print < + # + # + # + # $useropts{title} + # + # + # + # + # + # +# ENDOFTEXT +# # + +# } #------------------------------------------------------------------------------------------ + +# sub screen3 { + +# &thead; + +# if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# # my $page = "$lcpage\s" ; + +# my $page = "event-quotes" ; + +# if ($s{no}) { $page = $lcpage ; } + +# &common_min_thead ; + +# # &common_min_table('id',$page,'list') ; + +# $print_box_content_rows .= qq~ + # + # $print_thead + # + # $print_tbody + # + #
    +# ~ ; + +# # &common_min_table_select_jquery("#itv-table td:nth-last-child(2),#itv-table td:nth-last-child(10)") ; + +# # our $savjqy = 1 ; + +# # &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ; + +# # $extra_form_fields .= qq~~ ; + + # # + # # + # # + # # + # # + # # +# # ~ ; + +# our $savjqy = 1 ; + +# $trigger_jquery_raw .= qq~ + # \$("#savebutt").click( function () { + # \$("#import-bank-transactions-form").submit() ; + # }) ; +# ~ ; + +# $print_box_content_rows .= &common_min_forms_end('','','save') ; + +# require _blank_4 ; + +# exit ; + +# } #------------------------------------------------------------------------------------------ + +sub screen4 { + + $trigger_jquery_raw .= qq~ + if ("$i{analytics}" == "1") { + parent.\$("#$i{sel_field}").append(""); + parent.\$("#$i{sel_field}").trigger("chosen:updated"); + } + parent.BootstrapDialog.closeAll() ; + + ~; + + &common_min_dialog_save_screen ; + +} #------------------------------------------------------------------------------------------ + +use today ; +use common ; +# use production_time ; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/dialog/import_bank_trans_cat.pl b/scripts/_FromProd/v1.0/dialog/import_bank_trans_cat.pl new file mode 100644 index 0000000..ea2b1ee --- /dev/null +++ b/scripts/_FromProd/v1.0/dialog/import_bank_trans_cat.pl @@ -0,0 +1,479 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); +use LWP::Simple qw($ua get); +use Date::Calc qw(:all); +use MIME::Lite; +use Mail::Sendmail; +use Time::Piece ; + +require cfg ; + +print header; # CGI.pm method + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +my $type = $ARGV[0] ; + +our ($q) = CGI -> new() ; +my $iaction = $q -> param('iaction') ; +my $iattachdoc = $q -> param('iattachdoc') ; + +# our $debug = 1 ; +# our $testing = 1 ; + +#------------------------------------------------------------------------------------------ + +&today ; + +# my $string = qq~6565,2,328.00~ ; + +if ($iaction eq '') { + &screen1 ; +} elsif ($iaction eq 'upload') { + &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &read_import ; + &read_db ; + &process ; + &screen4 ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; +} +# elsif ($iaction eq 'save') { + # &common_min_load_params ; + # &db_open_upd ; + # our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + # &read_read_import_lines ; + # &update ; + # $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + # &db_close_conn ; + # &screen2 ; +# } + +exit; + +#------------------------------------------------------------------------------------------ + +sub read_read_import_lines { + + our $max_unmatched_id = 0 ; + + my $upload_filehandle = $q->upload('iattachdoc') ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + # &db_min_ro('logistics_costs','event_nr,amounts,file_name_ids,cost_type',"",'','') ; + + # &db_min_ro('logistics_costs_tables',"1,MAX(id)+1 AS 'max_id'","",'','') ; + # $db{logistics_costs_tables}{1}{max_id} = 1 unless $db{logistics_costs_tables}{1}{max_id} ; + + # my %ii = %i ; my $updated_logistics_costs_tables = 0 ; my $file_id = 0 ; my %cost_types = () ; my %event_has_diff_cost_types = () ; my %prev_cost_type = () ; + + # foreach (keys %ii) { + # if ($_ =~ /costtype_/) { + # my ($NA,$event_id,$amnt_cnt) = split(/\_/,$_) ; + # $event_id = ($event_id =~ /\d+/) ? $event_id : -1 ; + # $cost_types{$event_id}{$amnt_cnt} = $ii{$_} ; + # if ($prev_cost_type{$event_id} && $prev_cost_type{$event_id} ne $ii{$_}) { + # $event_has_diff_cost_types{$event_id} = 1 ; + # } + # $prev_cost_type{$event_id} = $ii{$_} ; + # } + # } + + # foreach (keys %ii) { + # if ($_ =~ /breakdownamnts_/) { + # unless ($updated_logistics_costs_tables) { + # $updated_logistics_costs_tables = 1 ; + # %i = () ; + # $i{id} = $db{logistics_costs_tables}{1}{max_id} ; + # $file_id = $i{id} ; + # $i{file_name} = $ii{uploaded_file_name} ; + # $i{file_total} = $ii{uploaded_file_total} ; + # $i{file_total} = sprintf("%.0f",$i{file_total}) ; + # $i{file_nr_of_unique_events} = $ii{file_nr_of_unique_events} ; + # $i{file_nr_of_rows} = $ii{file_nr_of_rows} ; + # $i{date_uploaded} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + # $i{uploaded_by} = $userid ; + # # &db_min_insert('logistics_costs_tables') ; + + # } + + # my ($NA,$event_id) = split(/\_/,$_) ; + + # %i = () ; + + # $i{event_nr} = ($event_id =~ /\d+/) ? $event_id : -1 ; + + # $i{cost_type} = ($db{logistics_costs}{$i{event_nr}}{cost_type}) ? "$db{logistics_costs}{$i{event_nr}}{cost_type}::" : "" ; + + # my $added_to_cost_type = 0 ; + + # foreach my $amnt_cnt (sort {$a <=> $b} keys %{$cost_types{$i{event_nr}}}) { + # $added_to_cost_type = 1 ; + # $i{cost_type} .= qq~$cost_types{$i{event_nr}}{$amnt_cnt};;~ ; + # last unless $event_has_diff_cost_types{$i{event_nr}} ; + # } + + # $i{cost_type} = substr($i{cost_type},0,-2) if $added_to_cost_type ; + + # # $i{cost_type} = ($db{logistics_costs}{$i{event_nr}}{cost_type} ) ? "$db{logistics_costs}{$i{event_nr}}{cost_type}::" . $ii{"costtype_$event_id"} : $ii{"costtype_$event_id"} ; + # $i{file_name_ids} = ($db{logistics_costs}{$i{event_nr}}{file_name_ids}) ? "$db{logistics_costs}{$i{event_nr}}{file_name_ids}:$file_id" : "$file_id" ; + # $i{amounts} = ($db{logistics_costs}{$i{event_nr}}{amounts} ) ? "$db{logistics_costs}{$i{event_nr}}{amounts}:$ii{$_}" : "$ii{$_}" ; ; + + # $i{amounts} =~ s/\,//g ; + # $i{amounts} =~ s/\.00//g ; + + # if ($i{event_nr} && $db{logistics_costs}{$i{event_nr}}{event_nr}) { + # $ignore{event_nr} = 1 ; + # # &db_min_upd('logistics_costs',"event_nr='$i{event_nr}'") ; + # } else { + # &db_min_ro('logistics_costs',"1,MAX(id)+1 AS 'max_id'","",'','') ; + # $db{logistics_costs}{1}{max_id} = 1 unless $db{logistics_costs}{1}{max_id} ; + # $i{id} = $db{logistics_costs}{1}{max_id} ; + # # &db_min_insert('logistics_costs') ; + # } + # } + # } + +} #------------------------------------------------------------------------------------------ + +sub read_import { + + $print_box_content_rows .= &common_min_forms_start('import-bank-transaction-category') ; + + my $upload_filehandle = $q->upload('iattachdoc') ; + + unless ($upload_filehandle) { + $warning = "PLEASE UPLOAD A CSV FILE!!!" ; + &common_min_alert_type ; + &screen1 ; + } + + our %totals = () ; my $line_cnt = 0 ; my %event_cnt = () ; + + if ($upload_filehandle !~ /.csv/) { + $error = "PLEASE UPLOAD A CSV TYPE FILE!!!" ; + &common_min_alert_type ; + &screen1 ; + } + + my $file_total_amnt = 0 ; my $file_nr_of_rows = 0 ; + + &db_min_ro('bank_transaction_categories','id','','','') ; + + if ($type eq 'csv') { + + while ( <$upload_filehandle> ) { + # foreach (@imported_file_data) { + + next if $_ !~ /\d+/ ; + + $file_nr_of_rows++ ; + + chomp $_ ; + $_ =~ s/\R\z// ; + $_ =~ s/\","/\,/g ; + + my @ads = split(/\,/,$_) ; + + next if $db{bank_transaction_categories}{$ads[0]}{id} ; + + $ads[0] =~ s/^"//g ; + $ads[2] =~ s/"+$//g ; + + $data{name}{$ads[0]} = $ads[1] ; + $data{income_source}{$ads[0]} = ($ads[2] eq 'cr') ? '1' : '0' ; + + } + } + + my $cnt = 0 ; + + foreach (sort {$a <=> $b} keys %{$data{name}}) { + %i = () ; + $i{id} = $_ ; + $i{name} = $data{name}{$_} ; + $i{income_source} = $data{income_source}{$_} ; + &db_min_insert('bank_transaction_categories') ; + } + + return ; + + # $file_total_amnt = sprintf("%.0f",$file_total_amnt) ; + + # our @sql_col_display = ("event_nr","cost_type","logistics_totals") ; + + # my $file_total = 0 ; my $file_nr_of_unique_events = 0 ; + + # &db_min_ro('event_quotes','id,quote_completed,quote_accepted,fixed_system_overall_status,event_system_id_multiple,quote_rejected,quote_cancelled,quote_created,quote_pending,sss_quote_nr',"",'','') ; + + # &db_min_ro('event_systems',"*",'','','') ; + + # my %seen_event = () ; + + # foreach my $event_id (sort {$a <=> $b} keys %totals) { + + # next if $event_id eq 'breakdown' ; + + # my $amnt_cnt = 0 ; + + # foreach my $sep_amnt (split(/\;/,$totals{breakdown}{$event_id})) { + + # $print_tbody .= qq~~ ; + + # $amnt_cnt++ ; + + # foreach (@sql_col_display) { + # my $val = '' ; + # my $class = qq~class="dt-center"~ ; + # if ($_ eq 'event_nr') { + # $val = ($event_id eq 'IBT') ? &common_min_get_event_quote_button("N/A") : &common_min_get_event_quote_button($event_id) ; + # $file_nr_of_unique_events++ unless $seen_event{$event_id} ; + # } elsif ($_ eq 'cost_type') { + # $val = ($event_id eq 'IBT') ? $event_id : "" ; + # $val = ($val) ? &common_min_table_input("costtype_$event_id\_$amnt_cnt",$val) : "" ; + # } elsif ($_ eq 'logistics_totals') { + # chop $totals{breakdown}{$event_id} if $totals{breakdown}{$event_id} ; + + # # my $seperate_amnts_tooltip = ($totals{breakdown}{$event_id} =~ /:/) ? $totals{breakdown}{$event_id} : qq~~ ; + # # $seperate_amnts_tooltip =~ s/\:/\
    /g ; + # # $seperate_amnts_tooltip = qq~title data-toggle="tooltip" data-placement="right" data-original-title="Seperate Amounts :
    $seperate_amnts_tooltip"~ if $seperate_amnts_tooltip ; + + # my $breakdownamnts = ($seen_event{$event_id}) ? qq~~ : qq~~ ; + # # + + # # $totals{seperate}{$event_id}{$event_cnt{$event_id}} + + # # $totals{seperate}{$event_id}{$amnt_cnt} = &common_commify(sprintf("%.02f",$totals{seperate}{$event_id}{$amnt_cnt})) ; + + # $val = qq~$breakdownamnts~ . qq~~ . $totals{seperate}{$event_id}{$amnt_cnt} . qq~~ ; + + # $file_total += $totals{$event_id} unless $seen_event{$event_id} ; + # } + # # style="display:none; + + # $print_tbody .= qq~$val~ ; + # } + # $print_tbody .= qq~~ ; + + # $seen_event{$event_id} = 1 ; + + # } + + # } + + # &db_min_ro('logistics_costs_tables',"1,id","`file_total`='$file_total_amnt' AND `file_nr_of_unique_events`='$file_nr_of_unique_events' AND `file_nr_of_rows`='$file_nr_of_rows'",'','') ; + + # if ($db{logistics_costs_tables}{1}{id}) { + # $warning = "THE FILE UPLOADED HAVE ALREADY BEEN SAVED!!!" ; + # &common_min_alert_type ; + # # &screen1 ; + # # $print_box_content_rows .= qq~~ ; + # } + + # $file_total = sprintf("%.02f",$file_total) ; + + # $print_box_content_rows .= qq~~ ; + # $print_box_content_rows .= qq~~ ; + # $print_box_content_rows .= qq~~ ; + # $print_box_content_rows .= qq~~ ; + + # $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + # &db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +sub read_db { + +} #------------------------------------------------------------------------------------------ + +sub process { + +} #------------------------------------------------------------------------------------------ + +sub screen1 { + + &common_min_dialog ; + + $print_box_content_rows .= qq~
    ~; + + # my $date_inputs = &common_min_form_datepicker() ; + + print < + + + $alert + +
    +
    +
    +
    +
    +
    +
    + + +

    Upload file from PC.

    +
    +
    +
    +
    + +
     
    +
    +
    +   + +
    +
    +
     
    +
    +
    +
    +
    +
    +
    + + + + + + + $dialog{'common'}{'js'} + + + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +# sub screen2 { + + # # + + # my $jquery = qq~parent.\$("#alertbar").html(""); + # parent.location.reload(); + # parent.BootstrapDialog.closeAll() ;~ unless $debug ; + + # print < + # + # + # + # $useropts{title} + # + # + # + # + # + # +# ENDOFTEXT +# # + +# } #------------------------------------------------------------------------------------------ + +# sub screen3 { + +# &thead; + +# if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# # my $page = "$lcpage\s" ; + +# my $page = "event-quotes" ; + +# if ($s{no}) { $page = $lcpage ; } + +# &common_min_thead ; + +# # &common_min_table('id',$page,'list') ; + +# $print_box_content_rows .= qq~ + # + # $print_thead + # + # $print_tbody + # + #
    +# ~ ; + +# # &common_min_table_select_jquery("#itv-table td:nth-last-child(2),#itv-table td:nth-last-child(10)") ; + +# # our $savjqy = 1 ; + +# # &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ; + +# # $extra_form_fields .= qq~~ ; + + # # + # # + # # + # # + # # + # # +# # ~ ; + +# our $savjqy = 1 ; + +# $trigger_jquery_raw .= qq~ + # \$("#savebutt").click( function () { + # \$("#import-bank-transaction-category-form").submit() ; + # }) ; +# ~ ; + +# $print_box_content_rows .= &common_min_forms_end('','','save') ; + +# require _blank_4 ; + +# exit ; + +# } #------------------------------------------------------------------------------------------ + +sub screen4 { + + $trigger_jquery_raw .= qq~ + if ("$i{analytics}" == "1") { + parent.\$("#$i{sel_field}").append(""); + parent.\$("#$i{sel_field}").trigger("chosen:updated"); + } + parent.BootstrapDialog.closeAll() ; + + ~; + + &common_min_dialog_save_screen ; + +} #------------------------------------------------------------------------------------------ + +use today ; +use common ; +# use production_time ; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/dialog/import_logistics_costs.pl b/scripts/_FromProd/v1.0/dialog/import_logistics_costs.pl new file mode 100644 index 0000000..92bfe2b --- /dev/null +++ b/scripts/_FromProd/v1.0/dialog/import_logistics_costs.pl @@ -0,0 +1,483 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); +use LWP::Simple qw($ua get); +use Date::Calc qw(:all); +use MIME::Lite; +use Mail::Sendmail; +use Time::Piece ; + +require cfg ; + +print header; # CGI.pm method + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +my $type = $ARGV[0] ; + +our ($q) = CGI -> new() ; +my $iaction = $q -> param('iaction') ; +my $iattachdoc = $q -> param('iattachdoc') ; + +# our $debug = 1 ; +# our $testing = 1 ; + +#------------------------------------------------------------------------------------------ + +&today ; + +# my $string = qq~6565,2,328.00~ ; + +if ($iaction eq '') { + + &screen1 ; + +} elsif ($iaction eq 'upload') { + + &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &read_import ; + &read_db ; + &process ; + &screen3 ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + +} elsif ($iaction eq 'save') { + + &common_min_load_params ; + &db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &read_read_import_lines ; + &update ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + &screen2 ; +} + +exit; + +#------------------------------------------------------------------------------------------ + +sub read_read_import_lines { + + our $max_unmatched_id = 0 ; + + my $upload_filehandle = $q->upload('iattachdoc') ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + &db_min_ro('logistics_costs','event_nr,amounts,file_name_ids,cost_type',"",'','') ; + + &db_min_ro('logistics_costs_tables',"1,MAX(id)+1 AS 'max_id'","",'','') ; + $db{logistics_costs_tables}{1}{max_id} = 1 unless $db{logistics_costs_tables}{1}{max_id} ; + + my %ii = %i ; my $updated_logistics_costs_tables = 0 ; my $file_id = 0 ; my %cost_types = () ; my %event_has_diff_cost_types = () ; my %prev_cost_type = () ; + + foreach (keys %ii) { + if ($_ =~ /costtype_/) { + my ($NA,$event_id,$amnt_cnt) = split(/\_/,$_) ; + $event_id = ($event_id =~ /\d+/) ? $event_id : -1 ; + $cost_types{$event_id}{$amnt_cnt} = $ii{$_} ; + if ($prev_cost_type{$event_id} && $prev_cost_type{$event_id} ne $ii{$_}) { + $event_has_diff_cost_types{$event_id} = 1 ; + } + $prev_cost_type{$event_id} = $ii{$_} ; + } + } + + foreach (keys %ii) { + if ($_ =~ /breakdownamnts_/) { + unless ($updated_logistics_costs_tables) { + $updated_logistics_costs_tables = 1 ; + %i = () ; + $i{id} = $db{logistics_costs_tables}{1}{max_id} ; + $file_id = $i{id} ; + $i{file_name} = $ii{uploaded_file_name} ; + $i{file_total} = $ii{uploaded_file_total} ; + $i{file_total} = sprintf("%.0f",$i{file_total}) ; + $i{file_nr_of_unique_events} = $ii{file_nr_of_unique_events} ; + $i{file_nr_of_rows} = $ii{file_nr_of_rows} ; + $i{date_uploaded} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{uploaded_by} = $userid ; + &db_min_insert('logistics_costs_tables') ; + + } + + my ($NA,$event_id) = split(/\_/,$_) ; + + %i = () ; + + $i{event_nr} = ($event_id =~ /\d+/) ? $event_id : -1 ; + + $i{cost_type} = ($db{logistics_costs}{$i{event_nr}}{cost_type}) ? "$db{logistics_costs}{$i{event_nr}}{cost_type}::" : "" ; + + my $added_to_cost_type = 0 ; + + foreach my $amnt_cnt (sort {$a <=> $b} keys %{$cost_types{$i{event_nr}}}) { + $added_to_cost_type = 1 ; + $i{cost_type} .= qq~$cost_types{$i{event_nr}}{$amnt_cnt};;~ ; + last unless $event_has_diff_cost_types{$i{event_nr}} ; + } + + $i{cost_type} = substr($i{cost_type},0,-2) if $added_to_cost_type ; + + # $i{cost_type} = ($db{logistics_costs}{$i{event_nr}}{cost_type} ) ? "$db{logistics_costs}{$i{event_nr}}{cost_type}::" . $ii{"costtype_$event_id"} : $ii{"costtype_$event_id"} ; + $i{file_name_ids} = ($db{logistics_costs}{$i{event_nr}}{file_name_ids}) ? "$db{logistics_costs}{$i{event_nr}}{file_name_ids}:$file_id" : "$file_id" ; + $i{amounts} = ($db{logistics_costs}{$i{event_nr}}{amounts} ) ? "$db{logistics_costs}{$i{event_nr}}{amounts}:$ii{$_}" : "$ii{$_}" ; ; + + $i{amounts} =~ s/\,//g ; + $i{amounts} =~ s/\.00//g ; + + if ($i{event_nr} && $db{logistics_costs}{$i{event_nr}}{event_nr}) { + $ignore{event_nr} = 1 ; + &db_min_upd('logistics_costs',"event_nr='$i{event_nr}'") ; + } else { + &db_min_ro('logistics_costs',"1,MAX(id)+1 AS 'max_id'","",'','') ; + $db{logistics_costs}{1}{max_id} = 1 unless $db{logistics_costs}{1}{max_id} ; + $i{id} = $db{logistics_costs}{1}{max_id} ; + &db_min_insert('logistics_costs') ; + } + } + } + +} #------------------------------------------------------------------------------------------ + +sub read_import { + + $print_box_content_rows .= &common_min_forms_start('import-logistics-costs') ; + + my $upload_filehandle = $q->upload('iattachdoc') ; + + unless ($upload_filehandle) { + $warning = "PLEASE UPLOAD A CSV FILE!!!" ; + &common_min_alert_type ; + &screen1 ; + } + + our %totals = () ; my $line_cnt = 0 ; my %event_cnt = () ; + + if ($upload_filehandle !~ /.csv/) { + $error = "PLEASE UPLOAD A CSV TYPE FILE!!!" ; + &common_min_alert_type ; + &screen1 ; + } + + my $file_total_amnt = 0 ; my $file_nr_of_rows = 0 ; + + if ($type eq 'csv') { + + while ( <$upload_filehandle> ) { + # foreach (@imported_file_data) { + + next if $_ !~ /\d+/ ; + + $file_nr_of_rows++ ; + + chomp $_; + + $_ =~ s/\R\z// ; # Removes any line-ending character (\n, \r\n, or \r) + $_ =~ s/\"//g ; + # $_ =~ s/\,//g ; + # $_ =~ s/\s+$//g; + $_ =~ s/ //g ; + $_ =~ s/^,|(?<=\W),(?=\w)//g; + $_ =~ s/^(\d+),(\d+),(\d+\.\d+)/$1,$2$3/g; ## REWRITE 1,1,000.11 AS 1,1000.11 + $_ =~ s/^(\d+),(\d+),(\d+),(\d+\.\d+)/$1,$2$3$4/g; ## REWRITE 1,1,000,000.11 AS 1,1000000.11 + $_ =~ s/^(\d+),(\d+),(\d+),(\d+),(\d+\.\d+)/$1,$2$3$4$5/g; ## REWRITE 1,1,000,000,000.11 AS 1,1000000000.11 + $_ =~ s/^([^,]+),(\d+),(\d+\.\d+)/$1,$2$3/; ## REWRITE OTHER,1,000.11 AS OTHER,1000.11 + $_ =~ s/^([^,]+),(\d+),(\d+),(\d+\.\d+)/$1,$2$3$4/; ## REWRITE OTHER,1,000,000.11 AS OTHER,1000000.11 + $_ =~ s/^([^,]+),(\d+),(\d+),(\d+),(\d+\.\d+)/$1,$2$3$4$5/; ## REWRITE OTHER,1,000,000,000.11 AS OTHER,1000000000.11 + + my ($event_id,$total) = split(/\,/,$_) ; + $event_cnt{$event_id} += 1 ; + $totals{$event_id} += $total ; + $file_total_amnt += $total ; + + $total = &common_commify(sprintf("%.02f",$total)) ; + $totals{breakdown}{$event_id} .= qq~$total;~ ; + $totals{seperate}{$event_id}{$event_cnt{$event_id}} = $total ; + + + + } + } + + $file_total_amnt = sprintf("%.0f",$file_total_amnt) ; + + our @sql_col_display = ("event_nr","cost_type","logistics_totals") ; + + my $file_total = 0 ; my $file_nr_of_unique_events = 0 ; + + &db_min_ro('event_quotes','id,quote_completed,quote_accepted,fixed_system_overall_status,event_system_id_multiple,quote_rejected,quote_cancelled,quote_created,quote_pending,sss_quote_nr',"",'','') ; + + &db_min_ro('event_systems',"*",'','','') ; + + my %seen_event = () ; + + foreach my $event_id (sort {$a <=> $b} keys %totals) { + + next if $event_id eq 'breakdown' ; + + my $amnt_cnt = 0 ; + + foreach my $sep_amnt (split(/\;/,$totals{breakdown}{$event_id})) { + + $print_tbody .= qq~~ ; + + $amnt_cnt++ ; + + foreach (@sql_col_display) { + my $val = '' ; + my $class = qq~class="dt-center"~ ; + if ($_ eq 'event_nr') { + $val = ($event_id eq 'IBT') ? &common_min_get_event_quote_button("N/A") : &common_min_get_event_quote_button($event_id) ; + $file_nr_of_unique_events++ unless $seen_event{$event_id} ; + } elsif ($_ eq 'cost_type') { + $val = ($event_id eq 'IBT') ? $event_id : "" ; + $val = ($val) ? &common_min_table_input("costtype_$event_id\_$amnt_cnt",$val) : "" ; + } elsif ($_ eq 'logistics_totals') { + chop $totals{breakdown}{$event_id} if $totals{breakdown}{$event_id} ; + + # my $seperate_amnts_tooltip = ($totals{breakdown}{$event_id} =~ /:/) ? $totals{breakdown}{$event_id} : qq~~ ; + # $seperate_amnts_tooltip =~ s/\:/\
    /g ; + # $seperate_amnts_tooltip = qq~title data-toggle="tooltip" data-placement="right" data-original-title="Seperate Amounts :
    $seperate_amnts_tooltip"~ if $seperate_amnts_tooltip ; + + my $breakdownamnts = ($seen_event{$event_id}) ? qq~~ : qq~~ ; + # + + # $totals{seperate}{$event_id}{$event_cnt{$event_id}} + + # $totals{seperate}{$event_id}{$amnt_cnt} = &common_commify(sprintf("%.02f",$totals{seperate}{$event_id}{$amnt_cnt})) ; + + $val = qq~$breakdownamnts~ . qq~~ . $totals{seperate}{$event_id}{$amnt_cnt} . qq~~ ; + + $file_total += $totals{$event_id} unless $seen_event{$event_id} ; + } + # style="display:none; + + $print_tbody .= qq~$val~ ; + } + $print_tbody .= qq~~ ; + + $seen_event{$event_id} = 1 ; + + } + + } + + &db_min_ro('logistics_costs_tables',"1,id","`file_total`='$file_total_amnt' AND `file_nr_of_unique_events`='$file_nr_of_unique_events' AND `file_nr_of_rows`='$file_nr_of_rows'",'','') ; + + if ($db{logistics_costs_tables}{1}{id}) { + $warning = "THE FILE UPLOADED HAVE ALREADY BEEN SAVED!!!" ; + &common_min_alert_type ; + # &screen1 ; + # $print_box_content_rows .= qq~~ ; + } + + $file_total = sprintf("%.02f",$file_total) ; + + $print_box_content_rows .= qq~~ ; + $print_box_content_rows .= qq~~ ; + $print_box_content_rows .= qq~~ ; + $print_box_content_rows .= qq~~ ; + + # $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + # &db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +sub read_db { + +} #------------------------------------------------------------------------------------------ + +sub process { + +} #------------------------------------------------------------------------------------------ + +sub screen1 { + + &common_min_dialog ; + + $print_box_content_rows .= qq~
    ~; + + # my $date_inputs = &common_min_form_datepicker() ; + + print < + + + $alert + +
    +
    +
    +
    +
    +
    +
    + + +

    Upload file from PC.

    +
    +
    +
    +
    + +
     
    +
    +
    +   + +
    +
    +
     
    +
    +
    +
    +
    +
    +
    + + + + + + + $dialog{'common'}{'js'} + + + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + + # + + my $jquery = qq~parent.\$("#alertbar").html(""); + parent.location.reload(); + parent.BootstrapDialog.closeAll() ;~ unless $debug ; + + print < + + + + $useropts{title} + + + + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +sub screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# my $page = "$lcpage\s" ; + +my $page = "event-quotes" ; + +if ($s{no}) { $page = $lcpage ; } + +&common_min_thead ; + +# &common_min_table('id',$page,'list') ; + +$print_box_content_rows .= qq~ + + $print_thead + + $print_tbody + +
    +~ ; + +# &common_min_table_select_jquery("#itv-table td:nth-last-child(2),#itv-table td:nth-last-child(10)") ; + +# our $savjqy = 1 ; + +# &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ; + +# $extra_form_fields .= qq~~ ; + + # + # + # + # + # + # +# ~ ; + +our $savjqy = 1 ; + +$trigger_jquery_raw .= qq~ + \$("#savebutt").click( function () { + + let file_uploaded = "$db{logistics_costs_tables}{1}{id}" ; + + if (file_uploaded) { + BootstrapDialog.confirm({ + title: 'Confirm Upload', + message: 'Are you sure you want to uplad this file that may have already been saved?', + type: BootstrapDialog.TYPE_WARNING, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + callback: function(result) { + if (result) { + console.log("import-logistics-costs-form") ; + \$("#import-logistics-costs-form").submit() ; + } + } + }); + } else { + \$("#import-logistics-costs-form").submit() ; + } + }) ; +~ ; + +$print_box_content_rows .= &common_min_forms_end('','','save') ; + +require _blank_4 ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +use today ; +use common ; +use production_time ; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/dialog/import_unmatched.pl b/scripts/_FromProd/v1.0/dialog/import_unmatched.pl new file mode 100644 index 0000000..71fbf43 --- /dev/null +++ b/scripts/_FromProd/v1.0/dialog/import_unmatched.pl @@ -0,0 +1,532 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); +use LWP::Simple qw($ua get); +use Date::Calc qw(:all); +use MIME::Lite; +use Mail::Sendmail; +use Time::Piece ; + +require cfg ; + +print header; # CGI.pm method + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +my $type = $ARGV[0] ; +my $format = $ARGV[1] ; + +our ($q) = CGI -> new() ; +my $iaction = $q -> param('iaction') ; +my $iattachdoc = $q -> param('iattachdoc') ; + +# our $debug = 1 ; + +#------------------------------------------------------------------------------------------ + +&today ; + +if ($iaction eq '') { + + &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &read_import ; + &read_db ; + &process ; + &screen3 ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + +} elsif ($iaction eq 'save') { + + &common_min_load_params ; + &db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &read_read_import_lines ; + &update ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + &screen2 ; +} + +exit; + +#------------------------------------------------------------------------------------------ + +sub read_read_import_lines { + + # our $max_unmatched_id = 0 ; + + # if ($type eq 'csv') { + + &db_min_ro('event_production_time_unmatched','id,unmatched_line','','','') ; + + foreach (keys %{$db{event_production_time_unmatched}}) { + my $event_code = substr($db{event_production_time_unmatched}{$_}{unmatched_line},-8) ; + $unmatched_event_lines{$event_code} = $db{event_production_time_unmatched}{$_}{unmatched_line} ; + # $max_unmatched_id = $_ if !$max_unmatched_id || ($max_unmatched_id && $max_unmatched_id < $_) ; + $event_code_unmatched_id{$event_code} = $_ ; + } + + # # $max_unmatched_id++ ; + + # while ( <$upload_filehandle> ) { + # # foreach (@imported_file_data) { + # chomp; + + # next if !$_ || ($_ !~ /\d+/ && $_ !~ /[a-zA-Z]/) ; + + # chop $_ ; + + # print "\n line : $_" ; + + # my @linex = split(/\;/,$_) ; + + # my $event_code = substr($linex[-1],-8) ; + + # $event_lines{$event_code} = $_ ; + + # } + # } + +} #------------------------------------------------------------------------------------------ + +sub update { + + my %ii = () ; my %iii = %i ; + + &db_min_ro('event_production_time','quote_id,event_system_production_seconds,event_system_cloud_recording_seconds,matched_events',"") ; + + foreach my $event_id (keys %{$db{event_production_time}}) { + + if ($db{event_production_time}{$event_id}{event_system_production_seconds}) { + foreach (sort split(/\|/,$db{event_production_time}{$event_id}{event_system_production_seconds})) { + my @abc = split(":",$_) ; + $ii{$event_id}{$abc[0]}{event_system_production_seconds} += $abc[1] ; + } + } + + if ($db{event_production_time}{$event_id}{event_system_cloud_recording_seconds}) { + foreach (sort split(/\|/,$db{event_production_time}{$event_id}{event_system_cloud_recording_seconds})) { + my @abc = split(":",$_) ; + $ii{$event_id}{$abc[0]}{event_system_cloud_recording_seconds} += $abc[1] ; + } + } + + $ii{$event_id}{NA}{matched_events} = $db{event_production_time}{$event_id}{matched_events} ; + + } + + foreach (sort keys %i) { + + my @get_row = split("_",$_) ; + + my $row_nr = $get_row[-1] ; + + my $system_field = "system_$row_nr" ; + + my $event_code_field = "event_code_$row_nr" ; + + if ($_ !~ /event_code_/ && $_ =~ /event_/ && $i{$_} && $i{$system_field} && $unmatched_event_lines{$i{$event_code_field}}) { + + # print "\n DELETE FROM event_production_time_unmatched WHERE id = '$event_code_unmatched_id{$i{$event_code_field}}' " ; + + &db_min_delete('event_production_time_unmatched',"`id`='$event_code_unmatched_id{$i{$event_code_field}}'") ; + + + } + + next if $_ =~ /event_code_/ || $_ !~ /event_/ || ($_ =~ /event_/ && $_ !~ /event_code_/ && !$i{$_}) ; + + my $system_field = "system_$row_nr" ; + + my $event_code_field = "event_code_$row_nr" ; + + next unless $i{$system_field} ; + + my $production_seconds = $i{"time_$row_nr"} ; + + my $cloud_recording_seconds = $i{"cloud_time_$row_nr"} ; + + next if $ii{$i{$_}}{NA}{matched_events} =~ /$i{$event_code_field}/ ; + + $ii{$i{$_}}{$i{$system_field}}{event_system_production_seconds} += $production_seconds ; + $ii{$i{$_}}{$i{$system_field}}{event_system_cloud_recording_seconds} += $cloud_recording_seconds ; + $ii{$i{$_}}{NA}{matched_events} .= ($ii{$i{$_}}{NA}{matched_events}) ? qq~|$i{$event_code_field}~ : qq~$i{$event_code_field}~ ; + + } + + foreach my $event_id (sort keys %ii) { + + %i = () ; + + foreach my $system_id (sort keys %{$ii{$event_id}}) { + next if $system_id eq 'NA' ; + $i{event_system_production_seconds} .= qq~$system_id:$ii{$event_id}{$system_id}{event_system_production_seconds}|~ ; + $i{event_system_cloud_recording_seconds} .= qq~$system_id:$ii{$event_id}{$system_id}{event_system_cloud_recording_seconds}|~ ; + } + + chop $i{event_system_production_seconds} if $i{event_system_production_seconds} ; + chop $i{event_system_cloud_recording_seconds} if $i{event_system_cloud_recording_seconds} ; + + $i{matched_events} = $ii{$event_id}{NA}{matched_events} ; + + next if !$i{event_system_production_seconds} && !$i{event_system_cloud_recording_seconds} && !$i{matched_events} ; + + $ignore{event_system_production_seconds} = ($i{event_system_production_seconds} && $i{event_system_production_seconds} eq $db{event_production_time}{$event_id}{event_system_production_seconds}) ? 1 : 0 ; + $ignore{event_system_cloud_recording_seconds} = ($i{event_system_cloud_recording_seconds} && $i{event_system_cloud_recording_seconds} eq $db{event_production_time}{$event_id}{event_system_cloud_recording_seconds}) ? 1 : 0 ; ; + $ignore{matched_events} = ($i{matched_events} && $i{matched_events} eq $db{event_production_time}{$event_id}{matched_events}) ? 1 : 0 ; + + next if $ignore{event_system_production_seconds} && $ignore{event_system_cloud_recording_seconds} && $ignore{matched_events} ; + + next unless $i{matched_events} ; + + if ($db{event_production_time}{$event_id}{quote_id}) { + &db_min_upd('event_production_time',"quote_id='$event_id'") ; + # print "\n UPDATE event_production_time SET event_system_production_seconds='$i{event_system_production_seconds}',event_system_cloud_recording_seconds='$i{event_system_cloud_recording_seconds}',matched_events='$i{matched_events}'" ; + } else { + $i{quote_id} = $event_id ; + # print "\n INSERT INTO event_production_time (event_system_production_seconds,event_system_cloud_recording_seconds,matched_events,quote_id) VALUES ($i{event_system_production_seconds},$i{event_system_cloud_recording_seconds},$i{matched_events},$i{quote_id})" ; + &db_min_insert('event_production_time') ; + } + + } + + %i = %iii ; + + exit ; + +} #------------------------------------------------------------------------------------------ + +sub read_import { + + &db_min_ro('event_production_time','id,matched_events',"","","") ; + + our %matched_event = () ; + + foreach my $quote_id (keys %{$db{event_production_time}}) { + foreach my $event_code (split(/\|/,$db{event_production_time}{$quote_id}{matched_events})) { + $matched_event{$event_code} = 1 ; + } + } + + &db_min_ro('event_production_time_unmatched','id,unmatched_line','','','') ; + + # my $upload_filehandle = $q->upload('iattachdoc') ; + + # our $start_date = ($upload_filehandle =~ /August/) ? "$now_year-08-01" : ($upload_filehandle =~ /September/) ? "$now_year-09-01" : "" ; + # our $end_date = ($upload_filehandle =~ /August/) ? "$now_year-08-31" : ($upload_filehandle =~ /September/) ? "$now_year-09-30" : "" ; + + # &db_open_upd ; + # our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + # $print_tbody .= qq~~ ; + + our %csv_line = () ; my $line_cnt = 0 ; + + # if ($type eq 'csv') { + + foreach (keys %{$db{event_production_time_unmatched}}) { + + # foreach (@imported_file_data) { + chomp; + + next if !$db{event_production_time_unmatched}{$_}{unmatched_line} || ($db{event_production_time_unmatched}{$_}{unmatched_line} !~ /\d+/ && $db{event_production_time_unmatched}{$_}{unmatched_line} !~ /[a-zA-Z]/) ; + + # ClubName;StartDate;EndDate;Production Hours;Production Seconds;CloudRecording HD Duration(Sec);Event Name;Event Type;event_code + $db{event_production_time_unmatched}{$_}{unmatched_line} =~ s/"(\d+),(\d+)"/$1$2/g; + # $_=~ s/\,/\;/g ; + + my @linex = split(/\;/,$db{event_production_time_unmatched}{$_}{unmatched_line}) ; + + next if $linex[0] eq 'ClubName' ; + + $ProductionHours = $linex[3] ; + $ProductionSeconds = $linex[-5] ; + $CloudRecordingDur = $linex[-4] ; + $EventName = $linex[-3] ; + $EventType = $linex[-2] ; + $event_code = $linex[-1] ; + + # $ProductionHours = $linex[3] ; + # $ProductionSeconds = $linex[4] ; + # $CloudRecordingDur = $linex[5] ; + # $EventName = $linex[6] ; + # $EventType = $linex[7] ; + # $EventID = $linex[8] ; + # # # # chop $event_code ; + + $event_code = substr($event_code,-8) ; + + next if $matched_event{$event_code} ; + + $ClubName = $linex[0] ; + $StartDate = $linex[1] ; + + next unless $StartDate ; + + my ($event,$system) = split("-",$ClubName) ; # Gymnastics Competition 148 - AISA_SOLO_10 + $event =~ s/ $//g; $system =~ s/^ //g; # remove whitespace + + my @eventdetails = split(/ /,$event) ; # Gymnastics Competition 148 + + $system = 'none' unless $system ; + + my ($sdate,$stime,$ampm) = split(/ /,$StartDate) ; + my @sdateparts = split(/\//,$sdate) ; + my @stimeparts = split(/\:/,$stime) ; $stimeparts[0] += 12 if $ampm eq 'PM' && $stimeparts[0] < 12 ; + + # $stimeparts[0] -= 12 if $pmam eq 'PM' && $stimeparts[0] > 11 ; + + my $shr = sprintf("%02s", $stimeparts[0]) ; + my $smn = sprintf("%02s", $stimeparts[1]) ; + my $ss = sprintf("%02s", $stimeparts[2]) ; + my $smm = sprintf("%02s", $sdateparts[0]) ; + my $sdd = sprintf("%02s", $sdateparts[1]) ; + my $sccyy = $sdateparts[2] ; + + my $startccyymmdd = $sccyy . $smm . $sdd ; + + $EndDate = $linex[2] ; + + next unless $EndDate ; + + my ($edate,$etime,$pmam) = split(/ /,$EndDate) ; + my @edateparts = split(/\//,$edate) ; + my @etimeparts = split(/\:/,$etime) ; $etimeparts[0] += 12 if $pmam eq 'PM' ; + + $etimeparts[0] -= 12 if $pmam eq 'PM' && $etimeparts[0] > 11 ; + + my $ehr = sprintf("%02s", $etimeparts[0]) ; + my $emn = sprintf("%02s", $etimeparts[1]) ; + my $es = sprintf("%02s", $etimeparts[2]) ; + my $emm = sprintf("%02s", $edateparts[0]) ; + my $edd = sprintf("%02s", $edateparts[1]) ; + my $eccyy = $edateparts[2] ; + + my $endccyymmdd = $eccyy . $emm . $edd ; + + # &common_debug("$StartDate->$EndDate [$startccyymmdd,$endccyymmdd]") ; + + if (!$last_start_ccyymmdd || $last_start_ccyymmdd > $startccyymmdd) { + $last_start_ccyymmdd = $startccyymmdd ; + $start_sql = "$sccyy-$smm-$sdd 00:00:00" ; + } + + if (!$last_end_ccyymmdd || $last_end_ccyymmdd < $endccyymmdd) { + $last_end_ccyymmdd = $endccyymmdd ; + $end_sql = "$eccyy-$emm-$edd 23:59:59" ; + } + + $csv_line{$event_code}{club_name} = $ClubName ; + $csv_line{$event_code}{event_name} = $EventName ; + $csv_line{$event_code}{production_hours} = $ProductionHours ; + $csv_line{$event_code}{production_seconds} = $ProductionSeconds ; + $csv_line{$event_code}{cloud_seconds} = $CloudRecordingDur ; + $csv_line{$event_code}{start_time} = "$sccyy-$smm-$sdd $shr:$smn:$ss" ; + $csv_line{$event_code}{end_time} = "$eccyy-$emm-$edd $ehr:$emn:$es" ; + + $csv_line{$event_code}{production_hours} =~ s/ //g ; + $csv_line{$event_code}{production_seconds} =~ s/ //g ; + $csv_line{$event_code}{cloud_seconds} =~ s/ //g ; + + $line_cnt++ ; + + $csv_line{$event_code}{line_cnt} = $line_cnt ; + + # $description =~ s/^\s+|\s+$//g ; # remove whitespace at beginning and end + + # &common_date_array($startccyymmdd,$endccyymmdd); + + # foreach (@common_date_array) { + # $pixellot_system{$_}{"$shr:$smn-$ehr:$emn"}{$system} = $EventName ; + + # $times_in_csv{$_}{"$shr:$smn-$ehr:$emn"}{$EventName} += 1 ; + + # $pixellot_system{$_}{"$shr:$smn-$ehr:$emn"}{$EventName} = "$system|$eventdetails[-1]|$ProductionHours|$ProductionSeconds|$CloudRecordingDur|$ClubName|$EventName|$event_code|" ; + + # &common_debug("pixellot_system : {$_}{$shr:$smn-$ehr:$emn} [$system|$ProductionHours|$ProductionSeconds|$CloudRecordingDur|$EventName|]") ; + + # } + + $x++; + + # $i{category_id} = 37 if $amount < 0 && ($description =~ /WOOLWORTHS/iog || $description =~ /CHECKERS/iog || ($description =~ /KwikSpar/iog && $description =~ /food/iog)) && $account_nr != 62547665945 ; # Office Supplies + # last if $x > 10; + } + # } + + # $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + # &db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +sub read_db { + + if (!$last_start_ccyymmdd && !$last_end_ccyymmdd) { + print "No Unmatched Data!!!" ; + exit ; + } + + &production_time_read_db_to_match_events_and_systems ; + +} #------------------------------------------------------------------------------------------ + +sub process { + + &production_time_process_matched_events_and_systems ; + +} #------------------------------------------------------------------------------------------ + +sub screen1 { + + &common_min_dialog ; + + $print_box_content_rows .= qq~
    ~; + + # my $date_inputs = &common_min_form_datepicker() ; + + print < + +
    +
    +
    +
    +
    +
    +
    + + +

    Upload file from PC.

    +
    +
    +
    +
    + +
     
    +
    +
    +   + +
    +
    +
     
    +
    +
    +
    +
    +
    +
    + + + + + + + $dialog{'common'}{'js'} + + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + + # + + my $jquery = qq~parent.\$("#alertbar").html(""); + parent.location.reload(); + parent.BootstrapDialog.closeAll() ;~ unless $debug ; + + print < + + + + $useropts{title} + + + + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +sub screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# my $page = "$lcpage\s" ; + +my $page = "event-quotes" ; + +if ($s{no}) { $page = $lcpage ; } + +&common_min_thead ; + +# &common_min_table('id',$page,'list') ; + +$print_box_content_rows .= qq~ + + $print_thead + + $print_tbody + +
    +~ ; + +&common_min_table_select_jquery("#itv-table td:nth-last-child(2),#itv-table td:nth-last-child(10)") ; + +# our $savjqy = 1 ; + +# &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ; + +# $extra_form_fields .= qq~ + # + # + # + # + # + # +# ~ ; + +$print_box_content_rows .= &common_min_forms_end('','','save') ; + +require _blank_4 ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +use today ; +use common ; +use production_time ; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/dialog/manually_match_csv_row.pl b/scripts/_FromProd/v1.0/dialog/manually_match_csv_row.pl new file mode 100644 index 0000000..95252c8 --- /dev/null +++ b/scripts/_FromProd/v1.0/dialog/manually_match_csv_row.pl @@ -0,0 +1,316 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +&today ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use DBI; +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +our $event_id = $ARGV[0] ; +our $system_id = $ARGV[1] ; +our $production_seconds = $ARGV[2] ; +our $cloud_recording_seconds = $ARGV[3] ; +our $event_code = $ARGV[4] ; +our $date_from = $ARGV[5] ; +our $date_to = $ARGV[6] ; +our $row_cnt = $ARGV[7] ; +our $action = $ARGV[8] ; + +$date_from =~ s/T/ /g; +$date_to =~ s/T/ /g; + +# our $debug = 1 ; +our $table = 'event_production_time' ; + +our ($q) = CGI -> new() ; +$iaction = $q -> param('iaction') || $action ; + +our $savjqy = 1 ; +our $dialog = 1 ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +if ($iaction eq 'add') { + &common_min_add_screen ; + &screen1 ; +} + +if ($iaction eq 'save') { + &common_min_load_params ; + # &update ; + &screen2 ; +} + +&common_min_action; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub update { + + # &add_db_fields ; # $i{last_edited_by} = $userid ; $i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + + # &validate ; + + # $ignore{sel_field} = 1 ; + + # # $i{id} = &db_min_get_max($table,'id') ; + + # &db_min_upd($table,) ; + +} #------------------------------------------------------------------------------------------ + +# sub validate { + + # # called from common_min_action + + # my $exists = '' ; + + # $i{name} = &common_fix_str($i{name}) ; + + # &db_min_ro($table,'id,poc_name,poc_contact_nr',"`poc_name`='$i{poc_name}' AND `poc_contact_nr`='$i{poc_contact_nr}'",'','') ; + + # foreach my $id (keys %{$db{$table}}) { + # if ($db{$table}{$id}{poc_name} eq $i{poc_name} && $db{$table}{$id}{poc_contact_nr} eq $i{poc_contact_nr}) { + # $exists = 1 ; + # last ; + # } + # } + + # if ($exists) { + # $alert = &common_min_alert('warning',"POC ALREADY EXISTS!",'warning-sign') ; + # %col_name = () ; + # &common_min_add_screen; + # &screen1; + # } + +# } #------------------------------------------------------------------------------------------ + +sub add_screen { + + &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + $sort_field{1} = "event_id" ; + $sort_field{2} = "system" ; + # $sort_field{3} = "did_change_event" ; + # $sort_field{4} = "did_change_system" ; + # $sort_field{3} = "event_id" ; + $select{event_id} = 1 ; + $select{system} = 1 ; + $box_header_title = 'Manually Match' ; + $hidden_action = 'save' ; + $head_col_width = 2 ; + $allow_deselect{event_id} = 1 ; + $allow_deselect{system} = 1 ; + + # $input{did_change_event} = 1 ; + # $input{did_change_system} = 1 ; + + $extra_form_fields .= qq~~ ; #style="display:none;" + $extra_form_fields .= qq~~ ; #style="display:none;" + + &db_min_ro('event_systems','*',"",'','') ; + + foreach my $id (sort {$db{event_systems}{$b}{name} cmp $db{event_systems}{$a}{name}} keys %{$db{event_systems}}) { + + my $selected = ($id eq $system_id) ? 'SELECTED' : '' ; + $opts{system} .= qq~~ ; + } + #(date_from BETWEEN '$date_from' AND '$date_to') OR (date_to BETWEEN '$date_from' AND '$date_to') OR (date_from <= '$date_from' AND '$date_to' >= date_to) + &db_min_ro('event_quotes','id,ref',"",'','') ; + + foreach my $id (sort {$db{event_quotes}{$a}{ref} cmp $db{event_quotes}{$b}{ref}} keys %{$db{event_quotes}}) { + + my $selected = ($id eq $event_id) ? 'SELECTED' : '' ; + $opts{event_id} .= qq~~ ; + } + + $trigger_jquery_raw .= qq~ + + let input_event_id = "$event_id" ; + + if (parent.\$("#selectEvent_$row_cnt").val() != input_event_id) { + \$("#selectEvent_id").val(parent.\$("#selectEvent_$row_cnt").val()) ; + \$("#selectEvent_id").trigger("chosen:updated") ; + } + + let input_system_id = "$system_id" ; + + if (parent.\$("#selectSystem_$row_cnt").val() != input_system_id) { + \$("#selectSystem").val(parent.\$("#selectSystem_$row_cnt").val()) ; + \$("#selectSystem").trigger("chosen:updated") ; + } + + ~ ; + + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + + $trigger_jquery_raw .= qq~ + + let original_event = "$event_id" ; + let original_system = "$system_id" ; + + \$("#selectEvent_id").change( function () { + if (\$(this).val() != original_event) { + \$("input[name='did_change_event']").val("1") ; + } else { + \$("input[name='did_change_event']").val("0") ; + } + }) ; + + \$("#selectSystem").change( function () { + if (\$(this).val() != original_system) { + \$("input[name='did_change_system']").val("1") ; + } else { + \$("input[name='did_change_system']").val("0") ; + } + }) ; + + ~ ; + + # $trigger_jquery_raw .= qq~ + # // id="event_code_2" + # console.log("Hello World") ; + # var helloValue = \$(window.parent.document).find('input[name="event_code_$row_cnt"]').val(); + # console.log("helloValue : "+helloValue) ; + # ~ ; + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + $ignore{iaction} = 1 ; + $ignore{id} = 1 ; + $hidden{sel_field} = 2 ; + $required{system} = 1 ; + # $required{poc_contact_nr} = 1 ; + $required{event_id} = 1 ; + # $eventids =~ s/\,/\,#selectItem_/g ; + # $eventids = substr($eventids,1) ; + # $db{$table}{''}{sel_field} = $eventids if $eventids ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub screen1 { + + $trigger_jquery_raw .= qq~ + + \$('#savebutt').click(function (e) { + + \$("#event_production_time-form").submit() ; + + }) ; + + \$('#btn-close-customer').click(function (e) { + parent.BootstrapDialog.closeAll() ; + });~ ; + + &common_min_dialog_load_screen ; + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + + &db_min_ro('event_quotes','id,ref',"id='$i{event_id}'") ; + &db_min_ro('event_systems','id,name,description',"id='$i{system}'") ; + + $trigger_jquery_raw .= qq~ + + let similar_rows = \$(window.parent.document).find('input[name="similar_rows_$row_cnt"]').val(); + + let system_drop_down_exists = parent.\$("#matched_system_$row_cnt").find('#selectSystem_$row_cnt').length ; + let event_drop_down_exists = parent.\$("#matched_event_$row_cnt").find('#selectEvent_$row_cnt').length ; + + let did_change_system = "$i{did_change_system}" ; + let did_change_event = "$i{did_change_event}" ; + + if (similar_rows && similar_rows !== undefined && ((system_drop_down_exists && system_drop_down_exists !== undefined) || (event_drop_down_exists && event_drop_down_exists !== undefined))) { + + let similar_system_ids = similar_rows.split(',').filter(num => num !== '$row_cnt').map(num => '#selectSystem_' + num).join(','); + let similar_event_ids = similar_rows.split(',').filter(num => num !== '$row_cnt').map(num => '#selectEvent_' + num).join(','); + + if (did_change_system) { + + let select_system_option_exists = parent.\$("#selectSystem_$row_cnt").find("option[value='$i{system}']").length ; + + if (!select_system_option_exists) { + parent.\$(similar_system_ids).append("") ; + parent.\$(similar_system_ids).trigger("chosen:updated"); + } + + let similar_system_ids_arr = similar_system_ids.split(',') ; + for (let id1 in similar_system_ids_arr) { + // console.log("id1 ; "+similar_system_ids_arr[id1]) ; + if (!parent.\$(similar_system_ids_arr[id1]).val()) { + parent.\$(similar_system_ids_arr[id1]).val("$i{system}") ; + parent.\$(similar_system_ids_arr[id1]).trigger("chosen:updated"); + } + } + } + + if (did_change_event) { + + let select_event_option_exists = parent.\$("#selectEvent_$row_cnt").find("option[value='$i{event_id}']").length ; + if (!select_event_option_exists) { + parent.\$(similar_event_ids).append("") ; + parent.\$(similar_event_ids).trigger("chosen:updated"); + } + + let similar_event_ids_arr = similar_event_ids.split(',') ; + for (let id2 in similar_event_ids_arr) { + if (!parent.\$(similar_event_ids_arr[id2]).val()) { + parent.\$(similar_event_ids_arr[id2]).val("$i{event_id}") ; + parent.\$(similar_event_ids_arr[id2]).trigger("chosen:updated"); + } + } + } + } + + var url = "$useropts{scripts}/get/add_event_system_hours.pl?$i{event_id}&$i{system}&$production_seconds&$cloud_recording_seconds&$event_code" ; + + \$.get(url) ; + + // console.log("url : "+url) ; + + let matched_row_ids = similar_rows.split(',').filter(num => num !== '$row_cnt').map(num => '#matched_row_' + num).join(','); + let not_matched_ids = similar_rows.split(',').filter(num => num !== '$row_cnt').map(num => '#not_matched_' + num).join(','); + + parent.\$(matched_row_ids).removeClass('btn btn-danger btn-sm').addClass('btn btn-success btn-sm'); + parent.\$(matched_row_ids).html("") ; + parent.\$(not_matched_ids).val("") ; + parent.\$("#$row_cnt").css("display","none") ; + parent.\$("#final_col_$row_cnt").html('') ; + parent.\$("#matched_system_$row_cnt").html('') ; + parent.\$("#matched_event_$row_cnt").html('') ; + + parent.BootstrapDialog.closeAll() ; + + ~; + + &common_min_dialog_save_screen ; + +} #------------------------------------------------------------------------------------------ + +use today ; +use dialog ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/dialog/read_ticket.pl b/scripts/_FromProd/v1.0/dialog/read_ticket.pl new file mode 100644 index 0000000..cf615f6 --- /dev/null +++ b/scripts/_FromProd/v1.0/dialog/read_ticket.pl @@ -0,0 +1,377 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); +use Fcntl qw(:flock); +use MIME::Parser; +use MIME::Lite; +use Mail::Sendmail; +use Text::Unidecode; + +require cfg ; + +print header; # CGI.pm method + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our ($q) = CGI -> new() ; +my $uniqueid = $q -> param('uniqueid') ; +my $subject = $q -> param('subject') ; +my $from = $q -> param('from') ; +my $iaction = $q -> param('iaction') ; +my $iemail = $q -> param('iemail') ; +my $imsg = $q -> param('imsg') ; +my $suid = $q -> param('suid') ; +my $responded = $q -> param('responded') ; + +$subject =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; + +# our $debug = 1 ; +# &common_debug ("subject = [$subject]"); + +unless ($uniqueid) { print "No ticket id..." ; exit ; } + +# our $ticket_dir = "$mailpath/tickets/$uniqueid" ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +if ($iaction eq 'send'){ + &send_email ; + &screen3 ; +} else { + &process_ticket_data; + &screen2; +} + +exit; + +#------------------------------------------------------------------------------------------ + +sub process_ticket_data { + + my $table = 'tickets' ; + + &db_min_ro($table,'*',"unique_id='$uniqueid' OR suid='$suid' OR unique_id='$suid'",'','') ; + + foreach my $tid (sort {$b <=> $a} keys %{$db{$table}}) { + my $uid = $db{$table}{$tid}{unique_id} ; + my $tdir = "$mailpath/tickets/$uid" ; + &read_ticket_dir($tdir) ; + &create_message($tdir) ; + &create_attachment($uid) ; + } + +} #------------------------------------------------------------------------------------------ + +sub read_ticket_dir { + + my ($ticket_dir) = @_ ; + + our $found_msg = 'n' ; our $msgfile = '' ; + + our @attachment_array = () ; + + &common_debug ("read_ticket_dir = [$ticket_dir]"); + + opendir(DIR, $ticket_dir) or die "cant open directory : $ticket_dir : $!\n"; + + while(defined($folder = readdir(DIR))) { + if (length $folder < 3) { next ; } + + &common_debug ("folder = [$folder]"); + + if (substr($folder,0,4) eq 'msg-' && substr($folder,-4,4) eq '.txt') { + $msgfile = $folder ; + $found_msg = 'y' ; + &common_debug ("msgfile = [$msgfile]"); + } else { + push @attachment_array, $folder ; + } + } + + closedir(DIR) ; + + # IF NO TXT FILE FOUND, REPEAT, LOOKING FOR HTML MSG + + if ($found_msg eq 'n') { + opendir(DIR, $ticket_dir) or die "cant open directory : $ticket_dir : $!\n"; + while(defined($folder = readdir(DIR))) { + + if (length $folder < 3) { next ; } + if (substr($folder,0,4) eq 'msg-' && substr($folder,-5,5) eq '.html') { + $msgfile = $folder ; + $found_msg = 'y' ; + } + } + closedir(DIR) ; + } + +} #------------------------------------------------------------------------------------------ + +sub create_message { + + my ($ticket_dir) = @_ ; + + my $print_message = '' ; + + if ($found_msg eq 'y') { + + $messagefile = "$ticket_dir/$msgfile" ; + + &common_debug ("messagefile = [$messagefile]"); + + use open qw(:std :utf8); + + open (M1FILE, "$messagefile") or die "can't open $messagefile: $!" ; + flock (M1FILE, LOCK_SH) or die "can't lock $messagefile: $!" ; + + while () { + $print_message .= $_ ; + } + + close (M1FILE); + + $print_message =~ s/\n/
    /g; + + # These next two put in to bodge LTS emails coming in + $print_message =~ s/ / /g; + $print_message =~ s/font-size: 12pt;/font-size: 12px;/g; + + } else { + $print_message = "No message"; + } + + $print_box_content_rows .= qq~

    $print_message

    ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------~ if $print_message ; + +} #------------------------------------------------------------------------------------------ + +sub create_attachment { + + my ($unique_id) = @_ ; + + my $print_attachments = '' ; my $acnt = 0 ; + + foreach $attachment (@attachment_array) { + # $print_attachments .= qq~$attachment | ~; + $acnt++; + $print_attachments .= qq~ | ~ if $acnt > 1 ; + $print_attachments .= qq~$attachment~; + } + + $print_box_content_rows .= $print_attachments ; + +} #------------------------------------------------------------------------------------------ + +sub page_opts { + + our $glyphicon = 'envelope' ; + +} #------------------------------------------------------------------------------- + +sub send_email { + +# # my $bcc = 'accounts@kre8it.co.za;rory@mathew.za.net' ; + +# $msg = MIME::Lite -> new( + # # From => "ITV Support ", + # # From => "ITV Support ", + # From => "ITV Support ", + # To => $iemail, + # Bcc => $bcc, + # Subject => "$subject", + # Type => 'multipart/mixed' +# ); + +# $msg -> attach( + # Type => 'TEXT', + # Data => $imsg); + +# # &check_attachments ; +# # &add_attachments ; + +# $msg -> send ('smtp','localhost', Debug=>0 ); + +# &common_send_mail($iemail,'','','html','',"$imsg","$subject") ; +&common_send_mail($iemail,'','','','',"$imsg","$subject") ; + +$i{responded} = 1 ; +$i{suid} = $suid if $suid ; + +&db_min_upd('tickets',"unique_id='$uniqueid'") ; + +} #------------------------------------------------------------------------------- + +sub screen2 { + +&common_min_alert_type ; + +&common_min_dialog ; + +# &common_debug ("screen2 [suid=$suid]"); + +# my $resubject = "$subject #$uniqueid" ; +my $resubject = ($subject =~ /Re:/iog) ? '' : 'Re: ' ; +my $resubject .= "$subject ##$suid##" ; + +# unless ($suid) { +unless ($responded) { + $reply_section = qq~
    +
    +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    + + + + +
     
    +
    +
    + +   + +
    +
    +
     
    +
    +
    +
    ~ ; +} + +print < + + + $alert + + $reply_section + +
    +
    +
    +
    +

    Emails Correspondance

    +
    +
    + $print_box_content_rows
    +
    +
    +
    +
    + + + + + + + + + + + +$dialog{'common'}{'js'} + + + +$print_footer_jscript +$print_footer_forms + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +sub screen3 { + +print < + + + + $useropts{title} + + + + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use db ; +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/documents.pl b/scripts/_FromProd/v1.0/documents.pl new file mode 100644 index 0000000..e4e7af9 --- /dev/null +++ b/scripts/_FromProd/v1.0/documents.pl @@ -0,0 +1,624 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; +our $double_box_layout = 1 ; # box on the right layout included + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our $srchscr = 0 ; +our $fnsortcol = 0 ; +our $redirtype = 'search' ; + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + +# called from common_min_action + +# my $exists = '' ; + +# &db_min_ro($table,'*',"name='$i{name}'",'','') ; + +# foreach my $id (keys %{$db{$table}}) { + # if ($db{$table}{$id}{name} eq $i{name}) { + # $exists = 1 ; + # } + # } + +# if ($exists) { + # $alert = &common_min_alert('warning',"NAME ALREADY EXISTS!",'ok') ; + # %col_name = (); + # # &add_screen; + # # &screen1; + # &common_min_add_screen; + # &common_min_screen1; + # } + +} #------------------------------------------------------------------------------------------ + +sub insert { + +&add_db_fields ; + +$i{last_edited_by} = $userid ; +$i{user_id} = $userid ; + +$i{id} = &db_min_get_max($table,'id') ; + +&val_check ; + +$i{date_time} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; +$i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&common_upload_files("documents/$i{id}") ; +&process_upload_ifields; + +&db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + +unless ($i{id}) { $error = qq(NO ID) ; return ; } + +&edit_db_fields ; + +if ($userid) { $i{last_edited_by} = $userid ; } + +&val_check ; + +$i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&common_upload_files("documents/$i{id}") ; +&process_upload_ifields; + +&db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub val_check { + +unless ($i{quote_id}) { $i{quote_id} = '0' ; } + +} #------------------------------------------------------------------------------------------ + +sub report_ifields { + +# &db_open_ro ; + # our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + # &load_search_vars ; + # $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +# &db_close_conn ; + +# if ($i{document_id}) { + # push @report_sql, "(`id` = '$i{document_id}')" ; + # push @report_results, "document = $document_name{$i{document_id}}" ; + # $xlsreportname .= '-' . $i{document_id} ; + # our $acc_id_sql_where = "`document_id`='$i{document_id}'" + # } + +if ($i{date_added_from} and $i{date_added_to}) { # check dates + my $date_added_from_check = $i{date_added_from} ; + $date_added_from_check =~ s/\-//g ; + my $date_added_to_check = $i{date_added_to} ; + $date_added_to_check =~ s/\-//g ; + if ($date_added_from_check > $date_added_to_check) { $error = qq(DOCUMENTS FROM ($i{date_added_from}) > DOCUMENTS TO ($i{date_added_to})); &report_screen; } + } + +if ($i{date_added_from}) { + push @report_sql, "(`date_time` >= '$i{date_added_from} 00:00:00')" ; + push @report_results, "date_time >= $i{date_added_from}" ; + } + +if ($i{date_added_to}) { + push @report_sql, "(`date_time` <= '$i{date_added_to} 23:59:59')" ; + push @report_results, "date_time <= $i{date_added_to}" ; + } + +$report_results_msg = uc join(', ', @report_results) ; + +unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); &report_screen; } else { $isaved = qq(SELECT WHERE $report_results_msg) ; } + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + +# &db_min_ro('document','id,name','','','') ; +# foreach my $id (keys %{$db{document}}) { $document_name{$id} = $db{document}{$id}{name} ; } + +} #------------------------------------------------------------------------------------------ + +sub process_upload_ifields { + +foreach (keys %uploads_file) { $i{$_} = $uploads_file{$_} ; $ignore{$_} = '' ; } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +my $srch_where_sql = join(' AND ', @report_sql) ; + +our @sql_col_display = ("id","date_time","notes","quote_id","client_id","last_edited_by","last_updated","") ; + +&report_xls_export_header("Documents$xlsreportname",'documents') ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &load_list_vars($srch_where_sql) ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) { + + # if (($i{active} == 1) and ($document_id_in_use_for_devices{$id} < 1)) { next ; } # Active with devices + # if (($i{active} == 2) and ($document_id_in_use_for_devices{$id} > 0)) { next ; } # Active without devices + + $print_tbody .= qq() ; + + $xlscol=0; + + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$table}{$id}{$_} ; + my $align = '' ; + + # my $format = '' ; + + if ($_ eq 'last_edited_by') { $val = $user_name{$val} ; } + if ($_ eq 'client_id') { $val = $customers_name{$val} ; } + if ($_ eq 'quote_id') { $val = $val ? $val : '' ; } + + &report_xls_export_process_cell('','',$val) ; # ------------------------------------------------------------------------- HTML AFTER + $xlscol++; + + # my $green_tick = qq~2~ ; + # my $orange_tick = qq~1~ ; + # my $red_tick = qq~0~ ; + my $center = qq~ class="dt-center"~ ; + + # if ($_ eq 'active') { if ($val == 1) { $val = &set_tick('green', '') ; } else { $val = &set_tick('red', '') ; } $align = $center ; } + + $print_tbody .= qq($val) ; + } + + my $delete_butt = '' ; my $edit_butt = '' ; + + if ($useropts{boss}{$username} or $useropts{super}{$username}) { + $edit_butt = qq() ; + # $delete_butt = qq() ; + } + + # &common_debug("$id : $document_id_in_use_for_devices{$id}"); + + # if ($document_id_in_use_for_devices{$id}) { $delete_butt = '' ; } + + $print_tbody .= qq( $edit_butt $delete_butt) ; + $xlsrow++ ; + } + +&report_xls_export_footer('L',15,'documents') ; + +$fnsortcol = 8 ; # order by ol devices col + +$print_more_boxes .= qq(
    ) ; + +&common_min_extra_crumb("search-$lcpage\s","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub set_tick { + +my ($color,$tooltip) = @_ ; + +$tick{green} = qq~2~ ; +$tick{orange} = qq~1~ ; +$tick{red} = qq~0~ ; + +return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub load_list_vars { + +my ($where) = @_ ; + +&db_min_ro('users','*','','','') ; +foreach my $id (keys %{$db{users}}) { $user_name{$id} = $db{users}{$id}{name} ; } + +&db_min_ro('customers','*','','','') ; +foreach my $id (keys %{$db{customers}}) { $customers_name{$id} = $db{customers}{$id}{name} ; } + +# &db_min_ro('device_type','*','','','') ; +# foreach my $id (keys %{$db{device_type}}) { + # $is_mdvr{$id} = $db{device_type}{$id}{mdvr} ; + # $device_name{$id} = $db{device_type}{$id}{name} ; + # } + +# &db_min_ro('risk_profile_types','*','','','') ; +# foreach my $id (keys %{$db{risk_profile_types}}) { $risk_profile_type{$id} = $db{risk_profile_types}{$id}{name} ; } # document hash + +# &db_min_ro('protocol_actions','*',$acc_id_sql_where,'','') ; +# foreach my $id (keys %{$db{protocol_actions}}) { + # my $acc_id = $db{protocol_actions}{$id}{document_id} ; + # my $max = $db{protocol_actions}{$id}{max} ; + # my $show_max = '' ; if ($max) { $show_max = " > $max" ; } + + # $protocol_action{$acc_id} .= "$risk_profile_type{$db{protocol_actions}{$id}{risk_profile_type_id}}$show_max
    " ; + # } + +# &db_min_ro('device','id,document_id,online,type_id',$acc_id_sql_where,'','') ; +# foreach my $id (keys %{$db{device}}) { + # $document_id_in_use_for_devices{$db{device}{$id}{document_id}}++ ; + + # if ($db{device}{$id}{online}==1) { + # $document_online_devices{$db{device}{$id}{document_id}}++ ; + # } + + # my $dev_nam = $device_name{$db{device}{$id}{type_id}} ; + + # $cnt_dev_typ{$db{device}{$id}{document_id}}{$dev_nam}++ ; + # } + +&db_min_ro($table,'*',$where,'','') ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + +&common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub sort_fields { + +$sort_field{1} = 'title' ; +$sort_field{2} = 'client_id' ; +$sort_field{3} = 'quote_id' ; +$sort_field{4} = 'notes' ; + +} #------------------------------------------------------------------------------- + +sub hidden_db_fields { + +$ignore{iaction} = 1 ; + +for (1 .. 10) { $ignore{"document_$_"} = 1 ; $ignore{"iattachdocument_$_"} = 1 ; } + +$rquired{title} = 1 ; +$textarea{notes} = 1 ; $textarea_height{notes} = 250 ; + +$hidden{last_updated} = 2 ; +$hidden{last_edited_by} = 2 ; +$hidden{date_time} = 2 ; +$hidden{user_id} = 2 ; + +&sort_fields; + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + +&hidden_db_fields ; + +$hidden{id} = 2 ; + +# $required{document_nr} = 1 ; +# $textarea{notes} = 1 ; + +# $datepicker{date_time} = 1 ; +# $datepicker{date_delivered} = 1 ; + +if ($iaction eq 'add'){ &build_boxes_add ; } # can't be in add_screen, only works if here + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + +&hidden_db_fields ; + +$ignore{date_time} = 1 ; +$ignore{user_id} = 1 ; +# $ignore{document_nr} = 1 ; +$ignore{last_updated} = 1 ; + +# $info_glyph_tooltip{object_recognition} = qq() ; +$hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + +my ($id) = @_ ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &common_min_select_opts('client_id','customers','name',$db{$table}{$id}{client_id},1) ; + &common_min_select_opts('quote_id','quotes','heading',$db{$table}{$id}{quote_id},'') ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +# $trigger_jquery_raw .= qq( + # //gallery delete + # \$('.thumbnails').on('click', '.gallery-delete', function (e) { + # e.preventDefault(); + # // alert(\$(this).parents('.thumbnail').attr('id')); + # var imgid = \$(this).parents('.thumbnail').attr('id') ; + # var thumb = \$(this).parents('.thumbnail'); + # BootstrapDialog.confirm({ + # title: 'Confirm Delete', + # message: 'Are you sure you want to delete it?', + # type: BootstrapDialog.TYPE_WARNING, + # callback: function(result) { + # if(result) { + # var url = "$useropts{scripts}/get/get_db_delete_upload_common.pl?$i{id}&documents/$i{id}&document&"+imgid ; + # // alert(url); + # \$.get(url); + # thumb.fadeOut(); + # location.reload(); + # } + # } + # }); + + # }); + + # //gallery edit + # \$('.thumbnails').on('click', '.gallery-edit', function (e) { + # e.preventDefault(); + # //get image id + # alert('Delete document and re-upload!'); + # //alert(\$(this).parents('.thumbnail').attr('id')); + # //dlgMdl('/scripts/dialog/uploads.pl?$i{id}&document&'+\$(this).parents('.thumbnail').attr('id'),'Document Uploads','','medium-dialog'); + # }); + # ); + +} #------------------------------------------------------------------------------- + +sub add_screen { + +# called from common_add_screen + +# if ($user_type eq 'track_users') { + # $db{$table}{''}{document_id} = $client_id ; # set for input box + # } + +&select_opts('') ; + +# &build_boxes_add ; # can't do this here + +} #------------------------------------------------------------------------------------------ + +sub build_boxes_add { + +$print_box_content_rows .= &common_min_forms_start($table) ; + +$print_box_content_rows .= qq(
    ) ; +$print_box_content_rows .= &common_min_box_top('user',"  Document",$box_main_bg) ; +# $print_box_content_rows .= &common_add_form($table,'',3,9,1,1) ; +$print_box_content_rows .= &common_min_add_form($table,'save',3,9,1,1) ; +$print_box_content_rows .= &common_min_box_foot ; +$print_box_content_rows .= qq(
    ) ; + +&build_boxes_right; + +$print_box_content_rows .= qq(
    ) ; + +$print_box_content_rows .= &common_min_forms_end('',$table,'save') ; + +} #---------------------------------------------------------------------------------------- + +sub edit_screen { + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +# $selected{warranty_period}{$db{$table}{$id}{warranty_period}} = 'SELECTED'; + +&select_opts($i{id}) ; + +&build_boxes_edit($i{id}) ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes_edit { + +my ($id) = @_ ; + +$print_box_content_rows .= &common_min_forms_start($table) ; +$print_box_content_rows .= qq(
    ) ; +$print_box_content_rows .= &common_min_box_top('user',"  Document : $db{$table}{$id}{id}",$box_main_bg) ; +# $print_box_content_rows .= &common_edit_form($id,$table,'',3,9,1,1) ; +$print_box_content_rows .= &common_min_edit_form($i{id},$table,'update',3,9,1,1) ; +$print_box_content_rows .= &common_min_box_foot ; +$print_box_content_rows .= qq(
    ) ; + +&build_boxes_right($id); + +$print_box_content_rows .= qq(
    ) ; + +$print_box_content_rows .= &common_min_forms_end($id,$table,'update',$skip) ; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_right { + +my ($id) = @_ ; + +my $box_icon = '' ; + +$print_box_content_rows .= &common_min_box_top('picture','Document Upload',$box_right_bg,$box_icon) ; + +$print_box_content_rows .= qq(
     
    ); + +for (1 .. 10) { + # $document_uploads = &get_uploads($id,"document_$_") ; + $document_uploads = &common_get_field_uploads($id,"document_$_",'client_id') ; + if ($document_uploads) { + $print_box_content_rows .= qq~
    $document_uploads
    ~; + } + else + { + $print_box_content_rows .= qq~ +
    +
    + + +

    Upload file from PC.

    +
    +
    + ~; + } + } + +$print_box_content_rows .= qq~
    ~; + +$print_box_content_rows .= &common_min_box_foot ; + +} #---------------------------------------------------------------------------------------- + +# sub get_uploads { + +# my ($id,$type) = @_ ; + +# unless ($id and $type) { return() ; } + +# my $gallery = '' ; my %gallery = () ; + +# my $field = $type ; +# if ($db{$table}{$id}{$field}){ + # $tooltip = qq(data-toggle="tooltip" data-placement="top" title="$type" data-original-title="$type") ; + # $gallery{$type} .= qq(
  • + # $type + #
  • ) ; + # } + +# if ($gallery{$type}) { $gallery = '' ; } + +# return ($gallery) ; + +# } #------------------------------------------------------------------------------------------ + +sub page_opts { + +our $glyphicon = 'list' ; +our $lcpage = 'document' ; + +&common_page_name ; + +our $table = 'documents' ; + +$page_title = 'Document' ; + +&common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + +our $lcol = 3 ; +our $fcol = 5 ; + +my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-42); # 6 weeks back + +$set_month = sprintf("%02s", $set_month) ; +$set_day = sprintf("%02s", $set_day) ; + +# my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ; + +$print_box_content_rows .= &common_min_forms_start('report') ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + # &common_min_select_opts('document_id','documents','name',$i{document_id},'') ; + &common_min_select_opts('client_id','customers','name','','') ; + &common_min_select_opts('quote_id','quotes','heading','','') ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +# $print_box_content_rows .= &common_min_form_select('document_id',$i{document_id}) ; +$print_box_content_rows .= &common_min_form_select('client_id',$i{client_id}) ; +$print_box_content_rows .= &common_min_form_datepicker('date_added_from','') ; +$print_box_content_rows .= &common_min_form_datepicker('date_added_to','') ; + +# $print_box_content_rows .= &common_min_form_input('active',$i{active}) ; + +# $opts{active} = qq( +# +# ) ; +# $print_box_content_rows .= &common_min_form_select('active','','',1,'') ; + +$print_box_content_rows .= &common_min_forms_end('','','report') ; + +&common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +# sub send_email { + +# my ($email_subject,$email_msg) = @_ ; + +# unless ($email_msg) { return ; } + +# my %mail = () ; + +# my $to = 'duvan@kre8it.co.za' ; +# my $cc = 'rory@kre8it.co.za' ; + +# %mail = ( + # smtp => 'localhost', + # From => 'TruckAssist IT ', + # To => $to, + # Cc => $cc, + # Subject => $email_subject + # ); + +# $mail{body} = <>>>>>>>>" ; exit ; } +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; +# our $debug = 1 ; +# our $testing = 1 ; + +our $double_box_layout = 1 ; + +our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +if ($iaction eq 'update') { + &common_min_load_params ; + &validate ; + &update ; + &common_min_screen2 ; + exit ; +} + +&common_min_action ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub validate { + + my $exists = '' ; + + # $i{item_name} = lc $i{item_name} ; + # $i{item_name} =~ s/ //gi ; + + &db_min_ro($table,'*',"name = '$i{name}'",'name','') ; + + foreach my $id (keys %{$db{$table}}) { + next if $i{id} && $i{id} eq $id ; + if (lc $db{$table}{$id}{name} eq lc $i{name}) { + $exists = 1 ; + } + } + + if ($exists) { + $alert = &common_min_alert('warning',"'$i{name}' AS AN EVENT COST ITEM NAME ALREADY EXISTS!",'ok') ; + %col_name = (); + &common_min_error_screen; + &common_min_screen1; + } + + my %seen_full_half_day = () ; + + $seen_full_half_day{$i{full_half_day_add}} += 1 if $i{full_half_day_add}; + + my $full_day_rate = 0 ; my $half_day_rate = 0 ; + $full_day_rate = $i{rates_add} if $i{rate_add} && $i{full_half_day_add} eq '1' ; + $half_day_rate = $i{rates_add} if $i{rate_add} && $i{full_half_day_add} eq '2' ; + + for (1 .. 2) { + $seen_full_half_day{$i{"full_half_day_$_"}} += 1 if $i{"full_half_day_$_"} ; + $full_day_rate = $i{"rates_$_"} if $i{"rates_$_"} && $i{"full_half_day_$_"} eq '1' ; + $half_day_rate = $i{"rates_$_"} if $i{"rates_$_"} && $i{"full_half_day_$_"} eq '2' ; + } + + my $extra_full_half = '' ; + + if ($seen_full_half_day{1} > 1 || $seen_full_half_day{2} > 1) { + if ($seen_full_half_day{1} > 1) { + $extra_full_half = 'Full' ; + } + if ($seen_full_half_day{2} > 1) { + $extra_full_half = 'Half' ; + } + } + + if ($extra_full_half) { + $alert = &common_min_alert('warning',"ONLY SELECT A MAX OF ONE FULL AND HALF DAY!",'ok') ; + %col_name = (); + $i{id} = '' if $iaction eq 'save' ; + foreach (keys %i) { $db{$table}{''}{$_} = $i{$_} ; } + &common_min_add_screen ; + &common_min_screen1 ; + } + + if ($half_day_rate > $full_day_rate) { + $alert = &common_min_alert('warning',"HALF DAY RATE MUST BE LESS THAN FULL DAY!",'ok') ; + %col_name = (); + $i{id} = '' if $iaction eq 'save' ; + foreach (keys %i) { $db{$table}{''}{$_} = $i{$_} ; } + &common_min_add_screen ; + &common_min_screen1 ; + } + + # $now_ccyymmdd + + # &db_min_ro($table,'1,valid_from,valid_to,rates,full_half_day',"id='$i{id}'",'name','') ; + # &db_min_ro($table,'1,rates,full_half_day',"id='$i{id}'",'name','') ; + + # my $cnt1 = 0 ; + + # my $saved_valid_from_str = "$db{$table}{1}{valid_from};$i{valid_from_add}" ; + # my $saved_valid_to_str = "$db{$table}{1}{valid_to};$i{valid_to_add}" ; + # my $saved_rates_str = "$db{$table}{1}{rates};$i{rate_add}" ; + # my $saved_full_half_day_str = "$db{$table}{1}{full_half_day};$i{full_half_day_add}" ; + + # $saved_valid_from_str =~ s/\-//g ; + # $saved_valid_to_str =~ s/\-//g ; + + # my @saved_valid_from = split(/\;/,$saved_valid_from_str) ; + # my @saved_valid_to = split(/\;/,$saved_valid_to_str) ; + # my @saved_rates = split(/\;/,$saved_rates_str) ; + # my @saved_full_half_day = split(/\;/,$saved_full_half_day_str) ; + + # my $input_valid_from_str = qq~~ ; + # my $input_valid_to_str = qq~~ ; + # my $input_rates_str = qq~~ ; + # my $input_full_half_day_str = qq~~ ; + + # foreach (@saved_rates) { + # $cnt1++ ; + # $input_valid_from_str .= qq~$i{"valid_from_$cnt1"};~ ; + # $input_valid_to_str .= qq~$i{"valid_to_$cnt1"};~ ; + # $input_rates_str .= qq~$i{"rate_$cnt1"};~ ; + # $input_full_half_day_str .= qq~$i{"full_half_day_$cnt1"};~ ; + # } + + # my @input_valid_from_arr = split(/\;/,$input_valid_from_str) ; + # my @input_valid_to_arr = split(/\;/,$input_valid_to_str) ; + # my @input_rates_arr = split(/\;/,$input_rates_str) ; + # my @input_full_half_day_arr = split(/\;/,$input_full_half_day_str) ; + + # $cnt1 = 0 ; + + # foreach my $rate1 (@saved_rates) { + # my $cnt2 = 0 ; + # foreach my $rate2 (@input_rates_arr) { + # next if $cnt1 == $cnt2 ; + # if ((($input_valid_from_arr[$cnt2] <= $saved_valid_from[$cnt1] && $saved_valid_from[$cnt1] <= $input_valid_to_arr[$cnt2]) || ($input_valid_from_arr[$cnt2] <= $saved_valid_to[$cnt1] && $saved_valid_to[$cnt1] <= $input_valid_to_arr[$cnt2])) && $saved_full_half_day[$cnt1] eq $input_full_half_day_arr[$cnt2]) { + # $alert = &common_min_alert('warning',"YOUR INPUT RATE $rates[$cnt1] FOR THE PERIOD '$valid_from[$cnt1]' TO '$valid_to[$cnt1]' OVERLAPS WITH THE RATE $rates[$cnt2] FOR THE PERIOD '$valid_from[$cnt2]' TO '$valid_to[$cnt2]'!",'ok') ; + # %col_name = (); + # $i{id} = '' if $iaction eq 'save' ; + # foreach (keys %i) { $db{$table}{''}{$_} = $i{$_} ; } + # # $db{$table}{''}{} + # &common_min_add_screen ; + # &common_min_screen1 ; + # } + # $cnt2++ ; + # } + # $cnt1++ ; + # } + +} #------------------------------------------------------------------------------------------ + +sub insert { + + &add_db_fields ; + + # $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + + &process_rates ; + + $i{id} = &db_min_get_max($table,'id') ; + + &db_min_insert($table) ; + + # exit ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + unless ($i{id}) { + $error = qq(NO ID) ; + return ; + } + + &edit_db_fields ; + + unless ($i{excl_from_expenses}) { $i{excl_from_expenses} = '0' ; } + # $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{active} = '0' unless $i{active} ; + + &process_rates ; + + $ignore{id} = 1 ; + + &db_min_upd($table,"id='$i{id}'") ; + + # exit ; + +} #------------------------------------------------------------------------------------------ + +sub process_rates { + + # &db_min_ro($table,'1,valid_from,valid_to,rates,full_half_day',"id='$i{id}'",'','') if $i{id} ; + &db_min_ro($table,'1,rates,full_half_day',"id='$i{id}'",'','') if $i{id} ; + + our %ii = () ; + + # my @valid_from = split(/\;/,$db{$table}{1}{valid_from}) ; + # my @valid_to = split(/\;/,$db{$table}{1}{valid_to}) ; + my @rates = split(/\;/,$db{$table}{1}{rates}) ; + my @full_half_day = split(/\;/,$db{$table}{1}{full_half_day}) ; + + my $cnt_rate = 0 ; + + foreach (@rates) { + + $cnt_rate++ ; + + $ignore{"selected_$cnt_rate\_full_half_day"} = 1 ; + # $ignore{"valid_from_$cnt_rate"} = 1 ; + # $ignore{"valid_to_$cnt_rate"} = 1 ; + $ignore{"rates_$cnt_rate"} = 1 ; + $ignore{"full_half_day_$cnt_rate"} = 1 ; + $ignore{"full_half_day_readonly_$cnt_rate"} = 1 ; + + # if ($i{"valid_from_$cnt_rate"} && $i{"valid_from_$cnt_rate"} =~ /^\d{4}-\d{2}-\d{2}$/ && $i{"valid_to_$cnt_rate"} && $i{"valid_to_$cnt_rate"} =~ /^\d{4}-\d{2}-\d{2}$/ && $i{"rates_$cnt_rate"}) { + if ($i{"rates_$cnt_rate"}) { + + # &build_rates_fields("valid_from","$cnt_rate") ; + # &build_rates_fields("valid_to","$cnt_rate") ; + &build_rates_fields("rates","$cnt_rate") ; + &build_rates_fields("full_half_day","$cnt_rate") ; + + } + } + + $ignore{"selected_add_full_half_day"} = 1 ; + # $ignore{"valid_from_add"} = 1 ; + # $ignore{"valid_to_add"} = 1 ; + $ignore{"rates_add"} = 1 ; + $ignore{"full_half_day_add"} = 1 ; + + # if ($i{valid_from_add} && $i{valid_from_add} =~ /^\d{4}-\d{2}-\d{2}$/ && $i{valid_to_add} && $i{valid_to_add} =~ /^\d{4}-\d{2}-\d{2}$/ && $i{rates_add}) { + if ($i{rates_add}) { + + # &build_rates_fields("valid_from","add") ; + # &build_rates_fields("valid_to","add") ; + &build_rates_fields("rates","add") ; + &build_rates_fields("full_half_day","add") ; + %ii = () ; + + } + +} #------------------------------------------------------------------------------------------ + +sub build_rates_fields { + + my ($field_name,$row_cnt) = @_ ; + + # $ii{$field_name} = qq~$db{$table}{1}{$field_name}~ ; + $ii{$field_name} .= ';' if $ii{$field_name} ; + $ii{$field_name} .= qq~$i{"$field_name\_$row_cnt"}~ ; + $i{$field_name} = $ii{$field_name} ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + # &db_min_ro('event_quotes','DISTINCT(type)','','','') ; + + # foreach my $id (keys %{$db{event_quotes}}) { + # $type_id_used{$id} = 1 ; + # } + + my %seen_event_item_costing = () ; + my $delete_button = "" ; + # my $sql_columns = " id" ; + # for (1 .. 15 ){ + # $sql_columns .= ", item_$_\_costing_event" ; + # $sql_columns .= ", description_$_\_workings_event" ; + # } + + # &db_min_ro('event_quotes',$sql_columns,'','','') ; + + &db_min_ro('event_quotes_min','id,item_costing_event,description_workings_event',"",, '', '' ); + + my @item_cost = () ; + my @des_work = () ; + + foreach my $id (keys %{$db{event_quotes_min}}) { + + @item_cost = split(";",$db{event_quotes_min}{$id}{item_costing_event}) ; + @des_work = split(";",$db{event_quotes_min}{$id}{description_workings_event}) ; + foreach (@item_cost) { + next if $seen_event_item_costing{$_} ; + next if not $_ ; + $seen_event_item_costing{$_} = 1; + } + + foreach (@des_work){ + next if $seen_event_item_costing{$_} ; + next if not $_ ; + $seen_event_item_costing{$_} = 1 ; + } + + # for (1 .. 15) { + # next if $seen_event_item_costing{$db{'event_quotes'}{$id}{"item_$_\_costing_event"}} ; + # next if not $db{'event_quotes'}{$id}{"item_$_\_costing_event"} ; + # $seen_event_item_costing{$db{'event_quotes'}{$id}{"item_$_\_costing_event"}} = 1; + + # } + # for (1 .. 15) { + # next if $seen_event_item_costing{$db{'event_quotes'}{$id}{"description_$_\_workings_event"}} ; + # next if not $db{'event_quotes'}{$id}{"description_$_\_workings_event"} ; + # $seen_event_item_costing{$db{'event_quotes'}{$id}{"description_$_\_workings_event"}} = 1 ; + # } + } + + &db_min_ro($table,'*','','id','') ; + + my $excl = "" ; + + our @sql_col_display = ("id","name","excl_from_expenses","active","rate","") ; + + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + foreach my $id (keys %{$db{$table}}) { + + $seen_event_item_costing{$id} = 1 if $db{$table}{$id}{name} eq 'Temp Support' || $db{$table}{$id}{name} eq 'Troubleshoot Monitor Allocations' || $db{$table}{$id}{name} eq 'Temp Calibrator Allocations' || $db{$table}{$id}{name} eq 'Monitor Allocations' || $db{$table}{$id}{name} eq 'Logistics Shipments' ; + + # next if $id ne '30' ; + + # if ($type_id_used{$id}) { + # $edit_butt = qq~ ~ ; + # $del_butt = qq~ ~ ; + # } + # $excl = qq~~ ; + # $excl = qq~~ if not $db{$table}{$id}{excl_from_expenses} ; + + $print_tbody .= qq~~ ; + + # my @arr_valid_from = split(/\;/,$db{$table}{$id}{valid_from}) ; + # my @arr_valid_to = split(/\;/,$db{$table}{$id}{valid_to}) ; + my @arr_rates = split(/\;/,$db{$table}{$id}{rates}) ; + my @arr_full_half_day = split(/\;/,$db{$table}{$id}{full_half_day}) ; + + my $row_cnt = 0 ; + + my %default_val = () ; + + foreach (@arr_rates) { + + # my $valid_from = $arr_valid_from[$row_cnt] ; + # my $valid_to = $arr_valid_to[$row_cnt] ; + my $rate = $_ ; + my $full_half_day = $arr_full_half_day[$row_cnt] ; + $row_cnt++ ; + # $valid_from =~ s/\-//g ; + # $valid_to =~ s/\-//g ; + # if ($valid_from >= $now_ccyymmdd && $now_ccyymmdd <= $valid_to) { + # $default_val{$full_half_day}{valid_from} = $valid_from ; + # $default_val{$full_half_day}{valid_to} = $valid_to ; + $default_val{$full_half_day}{rates} = $rate ; + # } + + $default_val{$full_half_day}{rates} = $rate if $rate && $db{$table}{$id}{rates} !~ /;/ && !$valid_from && !$valid_to ; + + } + + foreach my $col (@sql_col_display) { + + $val = $db{$table}{$id}{$col} ; + my $nowrap = "" ; + my $align = qq~ class="dt-center"~ ; + + if ($col eq "id") { + $align = qq~ class="dt-left"~ ; + } elsif ($col eq "name") { + $align = qq~ class="dt-left"~ ; + } elsif ($col eq "excl_from_expenses") { + $val = qq~~ ; + $val .= ($db{$table}{$id}{excl_from_expenses}) ? qq~~ : qq~~ ; + } + # elsif ($col eq "valid_from") { + + # # print "\n valid_from ful : $default_val{1}{valid_from}" ; + # # print "\n valid_from half : $default_val{2}{valid_from}" ; + + # $default_val{1}{valid_from} = ($default_val{1}{valid_from}) ? substr($default_val{1}{valid_from},0,4) . '-' . substr($default_val{1}{valid_from},4,2) . '-' . substr($default_val{1}{valid_from},6,2) : "" ; + # $default_val{2}{valid_from} = ($default_val{2}{valid_from}) ? substr($default_val{2}{valid_from},0,4) . '-' . substr($default_val{2}{valid_from},4,2) . '-' . substr($default_val{2}{valid_from},6,2) : "" ; + # if ($default_val{1}{valid_from} && $default_val{2}{valid_from}) { + # my $val1 = &common_min_date_as_string($default_val{1}{valid_from}) ; + # my $val2 = &common_min_date_as_string($default_val{2}{valid_from}) ; + # $val = "Full Day : $val1
    Half Day : $val2" ; + # } else { + # $val = ($default_val{1}{valid_from}) ? $default_val{1}{valid_from} : $default_val{2}{valid_from} ; + # $val = "2000-01-01" unless $db{$table}{$id}{valid_from} ; + # $val = &common_min_date_as_string($val) ; + # } + # } elsif ($col eq "valid_to") { + # $default_val{1}{valid_to} = ($default_val{1}{valid_to}) ? substr($default_val{1}{valid_to},0,4) . '-' . substr($default_val{1}{valid_to},4,2) . '-' . substr($default_val{1}{valid_to},6,2) : "" ; + # $default_val{2}{valid_to} = ($default_val{2}{valid_to}) ? substr($default_val{2}{valid_to},0,4) . '-' . substr($default_val{2}{valid_to},4,2) . '-' . substr($default_val{2}{valid_to},6,2) : "" ; + # if ($default_val{1}{valid_to} && $default_val{2}{valid_to}) { + # my $val1 = &common_min_date_as_string($default_val{1}{valid_to}) ; + # my $val2 = &common_min_date_as_string($default_val{2}{valid_to}) ; + # $val = "Full Day : $val1
    Half Day : $val2" ; + # } else { + # $val = ($default_val{1}{valid_to}) ? $default_val{1}{valid_to} : $default_val{2}{valid_to} ; + # $val = "2000-01-01" unless $db{$table}{$id}{valid_to} ; + # $val = &common_min_date_as_string($val) ; + # } + # } + elsif ($col eq "active") { + $val = ($db{$table}{$id}{active}) ? qq~~ : qq~~ ; + } elsif ($col eq "rate") { + if ($default_val{1}{rates} && $default_val{2}{rates}) { + my $val1 = $default_val{1}{rates} ; + my $val2 = $default_val{2}{rates} ; + $val = "Full Day : $val1
    Half Day : $val2" ; + } else { + $val = ($default_val{3}{rates}) ? $default_val{3}{rates} : ($default_val{1}{rates}) ? $default_val{1}{rates} : $default_val{2}{rates} ; + } + + } elsif ($col eq '') { + $align = qq~ class="dt-left"~ ; + my $edit_butt = '' ; + my $del_butt = '' ; + if ($useropts{super}{$username}) { + $edit_butt = qq~ ~ ; + } + if ($useropts{boss}{$username} or $useropts{super}{$username}) { + $del_butt = qq~ ~ if not $seen_event_item_costing{$id}; + $del_butt = qq~ ~ if $seen_event_item_costing{$id}; + } + + $edit_butt = qq~ ~ if $id == 11 || $id == 18 || $id == 10 || $id == 12 || $id == 19 || $id == 20 ; + $del_butt = qq~ ~ if $id == 11 || $id == 18 || $id == 10 || $id == 12 || $id == 19 || $id == 20 ; + + $val = qq~$edit_butt$del_butt~ ; + } + $print_tbody .= qq~$val~ ; + } + $print_tbody .= qq~~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + # &sort_fields; + &hidden_db_fields; + # $ignore{id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + # &sort_fields; + &hidden_db_fields; + $hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + + $ignore{iaction} = 1 ; + # $readonly{name} = 'READONLY' ; + $required{name} = 1 ; + $checkbox{excl_from_expenses} = 1 ; + $checkbox{active} = 1 ; + # $required{description} = 1 ; + + # if (!$i{rate} || !$i{valid_from} || !$i{valid_to}) { + # $ignore{valid_from} = 1 ; + # $ignore{valid_to} = 1 ; + # $ignore{rate} = 1 ; + # } + + &sort_fields ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + our %sort_field = () ; + $sort_field{1} = 'name' ; + $sort_field{2} = 'excl_from_expenses' ; + $sort_field{3} = 'active' ; + + # $sort_field{4} = 'valid_from' ; + # $sort_field{5} = 'valid_to' ; + # $sort_field{6} = 'rate' ; + + # $checkbox{active} = 1 ; + # $checkbox{excl_from_expenses} = 1 ; + # $datepicker{valid_from} = 1 ; + # $datepicker{valid_to} = 1 ; + + # $db{$table}{$i{id}}{valid_from} = "2000-01-01" ; + # $db{$table}{$i{id}}{valid_to} = "2050-01-01" ; + + # $required{name} = 1 ; + +} #------------------------------------------------------------------------------- + +sub add_screen { + + &sort_fields ; + + # called from common_add_screen + &select_opts ; + + &build_boxes ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + &select_opts ; + + &build_boxes ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes { + + our ($lcol,$fcol) = &common_min_columns() ; + + $add_form_fields = '' ; + + $print_box_content_rows .= &common_min_forms_start($table,$skip) ; + + $print_box_content_rows .= qq~~ if $i{id} ; + + $fcol = 2 ; + + $db{$table}{''}{name} = $db{$table}{$i{id}}{name} ; + $db{$table}{''}{active} = $db{$table}{$i{id}}{active} ; + $db{$table}{''}{excl_from_expenses} = $db{$table}{$i{id}}{excl_from_expenses} ; + + foreach my $cnt (sort {$a <=> $b} keys %sort_field) { + $col = $sort_field{$cnt} ; + $add_form_fields .= &common_min_forms_loop($iid,$table,$ignore_colpart) ; + } + + #
    + # + #
    + #
    + # + #
    + + $add_form_fields .= qq~ +
    +
    + +
    +
    + +
    +
    + ~ ; + + $fcol = 2 ; my $row_cnt = 0 ; + + my @rates = split(/\;/,$db{$table}{$i{id}}{rates}) ; + # my @valid_from = split(/\;/,$db{$table}{$i{id}}{valid_from}) ; + # my @valid_to = split(/\;/,$db{$table}{$i{id}}{valid_to}) ; + my @full_half_day = split(/\;/,$db{$table}{$i{id}}{full_half_day}) ; + + my %full_half_day_hash = (1 => "  Full Day", 2 => "  Half Day", 3 => "  N/A") ; my @selected_radios = () ; my @rate_ids = () ; my $orig_rates = qq~~ ; my @dates_arr = () ; my $def_val = qq~~ ; + + my %full_half_day_is_used = () ; my %full_half_day_is_used_not_editable = () ; + + foreach (@rates) { + + $row_cnt++ ; + $add_form_fields .= qq~
    ~ ; + + if ($rates[$row_cnt - 1] && $rate_is_used{$full_half_day[$row_cnt - 1]}{$rates[$row_cnt - 1]}) { + $readonly{"valid_from_$row_cnt"} = "READONLY" ; + $readonly{"valid_to_$row_cnt"} = "READONLY" ; + $readonly{"rates_$row_cnt"} = "READONLY" ; + } + + # $add_form_fields .= (!$readonly{"valid_from_$row_cnt"}) ? &common_min_form_datepicker_col("valid_from_$row_cnt",$valid_from[$row_cnt - 1]) : &common_min_form_input_col("valid_from_$row_cnt",$valid_from[$row_cnt - 1]) ; + # $add_form_fields .= (!$readonly{"valid_to_$row_cnt"}) ? &common_min_form_datepicker_col("valid_to_$row_cnt",$valid_to[$row_cnt - 1]) : &common_min_form_input_col("valid_to_$row_cnt",$valid_to[$row_cnt - 1]) ; + + # push @dates_arr,"#datepickValid_to_$row_cnt" unless $readonly{"valid_to_$row_cnt"} ; + # push @dates_arr,"#datepickerValid_to_$row_cnt" unless $readonly{"valid_to_$row_cnt"} ; + # push @dates_arr,"#datepickValid_from_$row_cnt" unless $readonly{"valid_from_$row_cnt"} ; + # push @dates_arr,"#datepickerValid_from_$row_cnt" unless $readonly{"valid_from_$row_cnt"} ; + + if (($_ && $rate_is_used{$full_half_day[$row_cnt - 1]}{$_}) || $i{"full_half_day_readonly_$row_cnt"}) { + + $add_form_fields .= qq~ +
    + + + +
    + ~ ; + $readonly{"rates_$row_cnt"} = "READONLY" ; + $full_half_day_is_used{full} = 1 if $full_half_day[$row_cnt - 1] eq '1' ; + $full_half_day_is_used{half} = 1 if $full_half_day[$row_cnt - 1] eq '2' ; + $full_half_day_is_used{na} = 1 if $full_half_day[$row_cnt - 1] eq '3' ; + $full_half_day_is_used_not_editable{full} = 1 if $full_half_day[$row_cnt - 1] eq '1' ; + $full_half_day_is_used_not_editable{half} = 1 if $full_half_day[$row_cnt - 1] eq '2' ; + + } else { + $add_form_fields .= qq~
    ~ ; + $radio_opts{"full_half_day"} = "Full+Half+N/A" ; + $lcol = 2 ; $fcol = 2 ; + $def_val = ($i{"full_half_day_$row_cnt"}) ? $i{"full_half_day_$row_cnt"} : $full_half_day[$row_cnt-1] ; + $add_form_fields .= &common_min_form_radio_col("full_half_day",$def_val,'',1,'','','',$row_cnt) ; + $lcol = 2 ; $fcol = 2 ; + $add_form_fields .= qq~
    ~ ; + push @selected_radios, "#radio_$row_cnt\_$def_val" if $def_val ; + $full_half_day_is_used{full} = 1 if $def_val eq '1' ; + $full_half_day_is_used{half} = 1 if $def_val eq '2' ; + $full_half_day_is_used{na} = 1 if $def_val eq '3' ; + } + + $def_val = ($i{"rates_$row_cnt"}) ? $i{"rates_$row_cnt"} : $rates[$row_cnt-1] ; + $add_form_fields .= &common_min_form_input_col("rates_$row_cnt",$def_val) ; + push @rate_ids,"#inputRates_$row_cnt" ; + $add_form_fields .= qq~
    ~ ; + $orig_rates .= qq~"inputRates_$row_cnt":$rates[$row_cnt - 1],~ ; + } + + $orig_rates .= qq~"inputRates_add":""~ ; + + if (!$error && !$alert) { + $i{full_half_day_add} = '' ; + $i{rates_add} = '' ; + $i{full_half_day_add} = '2' if $full_half_day_is_used{full} ; + } + + if ((!$full_half_day_is_used{full} || !$full_half_day_is_used{half}) && !$full_half_day_is_used{na} && $row_cnt < 2) { + + $preferred_title{valid_from_add} = "Add Valid From" ; + $preferred_title{valid_to_add} = "Add Valid To" ; + $preferred_title{rates_add} = "Add Rate" ; + + $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= &common_min_form_datepicker_col("valid_from_add",$i{valid_from_add}) ; + # $add_form_fields .= &common_min_form_datepicker_col("valid_to_add",$i{valid_to_add}) ; + $radio_opts{"full_half_day"} = " Full+ Half+ N/A" ; + $add_form_fields .= qq~
    ~ ; + $lcol = 2 ; $fcol = 2 ; + $add_form_fields .= &common_min_form_radio_col("full_half_day",$i{full_half_day_add},'',1,'','','','add') ; + push @selected_radios, "#radio_add_$i{full_half_day_add}" if $i{full_half_day_add} ; + $lcol = 2 ; $fcol = 2 ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= &common_min_form_input_col("rates_add",$i{rates_add}) ; + push @rate_ids,"#inputRates_add" ; + $add_form_fields .= qq~
    ~ ; + } + + my $save_action = ($i{id}) ? 'update' : 'save' ; + + $add_form_fields .= &common_min_forms_end($iid,$table,$save_action,$skip) ; + + my $add_edit = ucfirst $iaction ; + + $print_box_content_rows .= &common_min_box_top(''," $add_edit : $i{id}",$box_right_bg) ; + $print_box_content_rows .= $add_form_fields ; + $print_box_content_rows .= &common_min_box_foot ; + + push @selected_radios, "#radio_add_1" ; + + my $selected_radios_str = join(",",@selected_radios) ; + my $rate_ids_str = join(",",@rate_ids) ; + my $dates_str = join(",",@dates_arr) ; + + $trigger_jquery_raw .= qq~ + + \$("$dates_str").change( function () { + console.log("date : "+this.id) ; + }) ; + + // function isDecimal(value) { + // // If it's a string, make sure it's a clean numeric string + // if (typeof value === 'string') { + // // This regex matches valid decimals (including optional sign and leading zero) + // const trimmed = value.trim(); + // const decimalRegex = /^[+-]?(\d*\.\d+|\d+\.\d*)$/; + // if (!decimalRegex.test(trimmed)) { + // return false; + // } else { + // return true ; + // } + // } + // } + + \$("$selected_radios_str").prop("checked",true); + + let orig_input_rate_add = {$orig_rates} ; + + \$("$rate_ids_str").change( function () { + + let val = \$("#"+this.id).val() ; + + if (val) { + val = parseFloat(val) ; + val = val.toFixed(2) ; + } + + let is_decimal = 1 ; // Show val is a decimal? + + if (is_decimal) { + \$("#"+this.id).val(val) ; + orig_input_rate_add[this.id] = \$("#"+this.id).val() ; + } else { + \$("#"+this.id).val(orig_input_rate_add[this.id]) ; + } + + // if (isDecimal(\$("#"+this.id).val())) { + // console.log("isDecimal") ; + // } else { + // console.log("isNotDecimal") ; + // } + + // \$("#"+this.id).val(orig_input_rate_add) ; + + // orig_input_rate_add[this.id] = \$("#"+this.id).val() ; + + // console.log("2 . orig_input_rate_add : "+orig_input_rate_add) ; + + }) ; + + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + + $readonly{name} = "READONLY" if $db{$table}{$i{id}}{name} eq 'Temp Support' || $db{$table}{$i{id}}{name} eq 'Temp Calibrator Allocations' || $db{$table}{$i{id}}{name} eq 'Monitor Allocations' || $db{$table}{$i{id}}{name} eq 'Logistics Shipments' ; + + our %rate_is_used = () ; + + $db{$table}{''}{active} = 1 ; + + $required{name} = 1 ; + $checkbox{excl_from_expenses} = 1 ; + $checkbox{active} = 1 ; + &sort_fields ; + + # if ($iaction eq 'edit' && $db{$table}{$i{id}}{rates} && $db{$table}{$i{id}}{valid_from} && $db{$table}{$i{id}}{valid_to} && $db{$table}{$i{id}}{full_half_day}) { + if ($iaction eq 'edit' && $db{$table}{$i{id}}{rates} && $db{$table}{$i{id}}{full_half_day}) { + + &db_min_ro('event_quotes','id,date_from',"",'','') ; + &db_min_ro('event_quotes_min','id,item_costing_event,usd_amnt_costing_event',"",'','') ; + + my $valid_from_str = $db{$table}{$i{id}}{valid_from} ; + my $valid_to_str = $db{$table}{$i{id}}{valid_to} ; + + $valid_from_str =~ s/\-//g ; + $valid_to_str =~ s/\-//g ; + + my @full_half_day = split(/\;/,$db{$table}{$i{id}}{full_half_day}) ; + my @rates = split(/\;/,$db{$table}{$i{id}}{rates}) ; + # my @valid_from = split(/\;/,$valid_from_str) ; + # my @valid_to = split(/\;/,$valid_to_str) ; + + my $cost_id = $i{id} ; + + foreach my $id (keys %{$db{event_quotes}}) { + + if ($db{event_quotes_min}{$id}{item_costing_event} =~ /\b$cost_id\b/) { + + my $date = $db{event_quotes}{$id}{date_from} ; $date =~ s/\-//g ; $date = int($date) ; + my $date_cnt = 0 ; + + my @saved_item_arr = split(/\;/,$db{event_quotes_min}{$id}{item_costing_event}) ; + my @saved_rate_arr = split(/\;/,$db{event_quotes_min}{$id}{usd_amnt_costing_event}) ; + + # foreach my $date_valid_from (@valid_from) { + + # next unless $date_valid_from ; + # if ($valid_from[$date_cnt] <= $date && $date <= $valid_to[$date_cnt]) { + my $save_cnt = 0 ; + foreach my $item_id (@saved_item_arr) { + if ($item_id eq $cost_id && $saved_rate_arr[$save_cnt] eq $rates[$date_cnt]) { + # $rate_is_used{$full_half_day[$date_cnt]}{$rates[$date_cnt]} = 1 ; + } + $save_cnt++ ; + } + # } + # $date_cnt++ ; + # } + + # my @costs = split(/\;/,$db{event_quotes_min}{$id}{description_costing_event}) ; + # my @anmts = split(/\;/,$db{event_quotes_min}{$id}{amount_usd_costing_event}) ; + + # my $cost_cnt = 0 ; + + # foreach (@costs) { + + # next unless $_ eq $cost_id ; + + # } + } + } + } + + # $required{based_in} = 1 ; + # $select{based_in} = 1 ; + # $opts{based_in} = qq() ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + # $print_thead = qq(IDNAMEEXCLUDED FROM EXPENSES ) ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'facetime-video' ; + our $lcpage = 'event-cost-item' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'event_cost_items' ; + &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/event_invoicing_report.pl b/scripts/_FromProd/v1.0/event_invoicing_report.pl new file mode 100644 index 0000000..50899ba --- /dev/null +++ b/scripts/_FromProd/v1.0/event_invoicing_report.pl @@ -0,0 +1,1609 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +# unless ($useropts{it}{$username}) { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; + +use Time::Piece; +use Time::Seconds; + +# my $start_time_str = "09:30:00" ; +# my $end_time_str = "17:45:00" ; + +# Create Time::Piece objects for start and end times +# my $start_time = Time::Piece->strptime($start_time_str, "%H:%M:%S"); +# my $end_time = Time::Piece->strptime($end_time_str, "%H:%M:%S"); + +# Calculate the difference in seconds and convert to hours +# my $time_diff_in_hours = (Time::Piece->strptime($end_time_str,"%H:%M:%S") - Time::Piece->strptime($start_time_str,"%H:%M:%S")) / ONE_HOUR; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $open_new_tab = qq~target="_blank"~ ; + +# our $debug = 1 ; +# our $testing = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $srchscr = 1 ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &report_screen if $iaction eq '' ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + + +if ($iaction eq 'report') { + &common_min_load_params ; + &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &report_ifields ; + &list_screen ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + &screen3 ; +} + +if ($iaction eq 'save') { + our $testing = ($username eq 'handre') ? 1 : 0 ; + &common_min_load_params ; + &db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &update ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + exit if $username eq 'handre' && $testing ; + &screen4 ; +} + +# &common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub update { + + my %ii = %i ; + local $min_id = 0 ; local $max_id = 0 ; + + foreach (sort keys %i) { + local @a = split("_") ; + if ($a[0] eq 'update') { + $min_id = $a[-2] if ($min_id and $a[-2] < $min_id) or not $min_id ; + $max_id = $a[-2] if $a[-2] > $max_id ; + } + } + + &db_min_ro('event_quotes_min',"id,item_costing_event","`id` <= '$max_id' AND `id` >= '$min_id'",'','') ; + + foreach my $id (keys %{$db{event_quotes_min}}) { + %i = () ; + my $cnt_item = -1 ; my $update = 0 ; + foreach (split /;/,$db{event_quotes_min}{$id}{item_costing_event}) { + $cnt_item++ ; + if ($ii{"update_$id\_$cnt_item"} and $ii{"invoice_nr_$id\_$cnt_item"}) { + $i{invoice_nr} = $ii{"invoice_nr_$id\_$cnt_item"} ; + $update = 1 ; + } + } + &db_min_upd("event_quotes","id='$id'") ; + } + + # foreach my $id (keys %{$db{event_quotes_min}}) { + # %i = () ; + # my $cnt_item = -1 ; my $update = 0 ; + # my @saved_invoice_nrs = split(/;/,$db{event_quotes_min}{$id}{invoice_nr_costing_event}) ; + # foreach (split /;/,$db{event_quotes_min}{$id}{item_costing_event}) { + # $cnt_item++ ; + # if ($ii{"update_$id\_$cnt_item"} and $ii{"invoice_nr_$id\_$cnt_item"}) { + # $i{invoice_nr_costing_event} .= qq~$ii{"invoice_nr_$id\_$cnt_item"};~ ; + # $update = 1 ; + # } elsif ($saved_invoice_nrs[$cnt_item]) { + # $i{invoice_nr_costing_event} .= qq~$saved_invoice_nrs[$cnt_item];~ ; + # } else { + # $i{invoice_nr_costing_event} .= qq~;~ ; + # } + # } + # next unless $update ; + + # chop $i{invoice_nr_costing_event} if $i{invoice_nr_costing_event} ; + + # # &common_debug("UPDATE event_quotes_min SET invoice_nr_costing_event = $i{invoice_nr_costing_event} WHERE id = '$id'") if $i{invoice_nr_costing_event} ; + + # &db_min_upd("event_quotes_min","id='$id'") ; + # } + + %i = %ii ; + +} #------------------------------------------------------------------------------------------ + +sub report_ifields { + + if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { + $error = qq~'$i{date_from}' > '$i{date_to}'~ ; &report_screen ; + } + push @report_sql, "((e.date_from >= '$i{date_from} 00:00:00' AND e.date_from <= '$i{date_to} 23:59:59') OR (e.date_to <= '$i{date_to} 23:59:59' AND e.date_to >= '$i{date_from} 00:00:00'))" ; + push @report_results, "(BETWEEN '$i{date_from}' AND '$i{date_to}')" ; + } elsif (not $i{date_from}) { + $error = qq~PLEASE ENTER A START DATE!~ ; + } elsif (not $i{date_to}) { + $error = qq~PLEASE ENTER A END DATE!~ ; + } + + our $where_min = qq~~ ; + + if ($i{event_costing_id} and $i{event_costing_id} ne 'all') { + &db_min_ro('event_cost_items','1,name',"`id` = '$i{event_costing_id}'",'','') ; + # $where_min = "m.item_costing_event LIKE '%;$i{event_costing_id};%' OR m.item_costing_event LIKE '$i{event_costing_id};%' OR m.item_costing_event LIKE '%;$i{event_costing_id}'" ; + $where_min = "FIND_IN_SET($i{event_costing_id},REPLACE(m.item_costing_event,';',','))" ; + push @report_results,"EVENT COSTING = $db{event_cost_items}{1}{name}" ; + } + + if ($i{client_id} and $i{client_id} ne 'all') { + &db_min_ro('customers','1,name',"`id`='$i{client_id}'",'','') ; + push @report_sql, "(e.quote_to = '$i{client_id}')" ; + push @report_results,"CLIENT = $db{customers}{1}{name}" ; + } + + if ($i{event_quote_id} and $i{event_quote_id} ne 'all') { + &db_min_ro('event_quotes','1,ref',"`id`='$i{event_quote_id}'",'','') ; + push @report_sql, "(e.id = '$i{event_quote_id}')" ; + push @report_results,"EVENT QUOTE = $db{event_quotes}{1}{ref}" ; + } + + if ($i{paid_status} eq 'paid') { + push @report_results,"COSTINGS ARE ALL PAID" ; + } elsif ($i{paid_status} eq 'outstanding') { + push @report_results,"COSTINGS PAY OUTSTANDING" ; + } + + $report_results_msg = uc join(', ',@report_results) ; + + if (not $report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); + &report_screen ; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + $print_box_content_rows .= &common_min_forms_start('invoice') ; + + push @report_sql, "(e.quote_completed = '1')" ; + + my $srch_where_sql = join(' AND ', @report_sql) ; + + our @sql_col_display = ("event_quote_nr","description","event_name","days","event_date_from","event_date_to","qty_full_day","qty_half_day","rate","total","production_hours","cloud_recording_hours","invoice_nr") ; + + my $table_colspan = 0 ; + + foreach (@sql_col_display) { + $table_colspan += 1 ; + } + + &report_xlsx_export_header("Event_Invoicing_Report$xlsreportname",'event_invoicing_report') ; + + &load_list_vars("$srch_where_sql","$where_min") ; + + my $field = "" ; my @qty_costing = () ; my @amnt_usd_work = () ; my @amnt_work = () ; my @op_work = () ; my @item = () ; + my @paid_work = () ; my $row_cnt = 0 ; my $first_id = 0 ; my $last_id = 0 ; my %row_cnt_to_id = () ; + + $fcol = 2 ; + + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= &common_min_form_input_col("date_from",$i{date_from}) ; #date_from_i_field + $print_box_content_rows .= &common_min_form_input_col("date_to",$i{date_to}) ; #date_to_i_field + $print_box_content_rows .= &common_min_form_input_col("event_costing_id",$i{event_costing_id}) ; #operator_id_i_field + $print_box_content_rows .= &common_min_form_input_col("event_quote_id",$i{event_quote_id}) ; + $print_box_content_rows .= &common_min_form_input_col("paid_status",$i{paid_status}) ; + $print_box_content_rows .= &common_min_form_input_col("client_id",$i{client_id}) ; + $print_box_content_rows .= qq~
    ~ ; + + $fcol = 12 ; my $val_min = 0 ; $row_cnt = 0 ; + + my $date_pay = qq~~ ; my $quote_ids_and_item_cnt = qq~~ ; my $op_ids = qq~~ ; + + push @sql_col_display,"update" ; + + my %totals_at_bottom = () ; my %seen_description = () ; my %xlsxrow_extra_sheets = () ; my %input_fields = () ; + + my $cnt_nr_of_events = 0 ; + + $seen_description{$ws} = 1 ; my %seen_month = () ; + + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + my %seen_item_in_quote = () ; my %total_hours = () ; + + foreach my $time_type (keys %total_seconds) { + foreach my $event_id (keys %{$total_seconds{$time_type}}) { + foreach my $system_id (keys %{$total_seconds{$time_type}{$event_id}}) { + + my $desc = $db{event_systems}{$system_id}{description} ; + my $sys_type = $db{event_systems}{$system_id}{system_type} ; + + $total_hours{$time_type}{mobile}{$event_id}{$system_id} += $total_seconds{$time_type}{$event_id}{$system_id} if $sys_type eq 'mobile' && $desc !~ 'SSS' && $desc !~ 'AISA' && lc $desc !~ /cricket/ ; + $total_hours{$time_type}{mobile_sss}{$event_id}{$system_id} += $total_seconds{$time_type}{$event_id}{$system_id} if $sys_type eq 'mobile' && $desc =~ 'SSS' && $desc !~ 'AISA' && lc $desc !~ /cricket/ ; + $total_hours{$time_type}{mobile_aisa}{$event_id}{$system_id} += $total_seconds{$time_type}{$event_id}{$system_id} if $sys_type eq 'mobile' && $desc !~ 'SSS' && $desc =~ 'AISA' && lc $desc !~ /cricket/ ; + $total_hours{$time_type}{solo}{$event_id}{$system_id} += $total_seconds{$time_type}{$event_id}{$system_id} if $sys_type eq 'solo' && $desc !~ 'SSS' && $desc !~ 'AISA' && lc $desc !~ /cricket/ ; + $total_hours{$time_type}{solo_sss}{$event_id}{$system_id} += $total_seconds{$time_type}{$event_id}{$system_id} if $sys_type eq 'solo' && $desc =~ 'SSS' && $desc !~ 'AISA' && lc $desc !~ /cricket/ ; + $total_hours{$time_type}{solo_aisa}{$event_id}{$system_id} += $total_seconds{$time_type}{$event_id}{$system_id} if $sys_type eq 'solo' && $desc !~ 'SSS' && $desc =~ 'AISA' && lc $desc !~ /cricket/ ; + $total_hours{$time_type}{cricket}{$event_id}{$system_id} += $total_seconds{$time_type}{$event_id}{$system_id} if lc $desc =~ /cricket/ ; + $total_hours{$time_type}{fixed}{$event_id}{$system_id} += $total_seconds{$time_type}{$event_id}{$system_id} if $sys_type eq 'fixed' && lc $desc !~ /cricket/ ; + } + } + } + + my %tooltip = () ; my %tooltip_total = () ; + + foreach my $time_type (keys %total_hours) { + foreach my $type (keys %{$total_hours{$time_type}}) { + foreach my $event_id (keys %{$total_hours{$time_type}{$type}}) { + foreach my $system_id (keys %{$total_hours{$time_type}{$type}{$event_id}}) { + $tooltip_total{$time_type}{$type}{$event_id} += $total_hours{$time_type}{$type}{$event_id}{$system_id} ; + $total_hours{$time_type}{$type}{$event_id}{$system_id} = sprintf("%.02f",$total_hours{$time_type}{$type}{$event_id}{$system_id}/3600) ; + $tooltip{$time_type}{$type}{$event_id} .= qq~$db{event_systems}{$system_id}{name} [$db{event_systems}{$system_id}{description}] : $total_hours{$time_type}{$type}{$event_id}{$system_id} HRS
    ~ ; + } + } + } + } + + my %seen_tooltip_data = () ; + + my $unique_invoice_nr_exists_with_blank_entries = "All_Invoice_Nrs_Blank" ; + + my $default_invoice_nrs = qq~~ ; + + # $db{$tables}{11320}{invoice_nr} = "Hello" ; + + foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) { + + # next if $id ne '9285' ; + + if ($i{client_id}) { + next unless $client{$i{client_id}} eq $quote_customer{$id} ; + } + # next unless $id == 8050 ; + $cnt_nr_of_events++ ; + + $cnt_in_stock = -1 ; + my $in_stock = "" ; + + @qty_costing = split(/;/,$db{$tables}{$id}{qty_costing_event}) ; + # @paid_costing = split(/;/,$db{$tables}{$id}{invoice_nr_costing_event}) ; + @item = split(/;/,$db{$tables}{$id}{item_costing_event}) ; + + @item_ttl = split(/;/,$db{$tables}{$id}{item_ttl_costing_event}) ; + @vat = split(/;/,$db{$tables}{$id}{vat_costing_event}) ; + @qty = split(/;/,$db{$tables}{$id}{qty_costing_event}) ; + # @qty_half = split(/;/,$db{$tables}{$id}{qty_half_day_costing_event}) ; + @qty_full = () ; + @qty_half = () ; + @price = split(/;/,$db{$tables}{$id}{usd_amnt_costing_event}) ; + + my $full_day_cnt = 0 ; + my $half_day_cnt = 0 ; + + if ($db{$tables}{$id}{event_length} eq 'full_day' || $db{$tables}{$id}{event_length} eq 'half_day'){ + my $full_half = ($db{$tables}{$id}{event_length} eq 'full_day') ? 1 : 2 ; + $db{$tables}{$id}{event_length} = qq~~ ; + for (1 .. $db{$tables}{$id}{qty}) { + $db{$tables}{$id}{event_length} .= qq~$full_half;~ ; + } + chop $db{$tables}{$id}{event_length} if $db{$tables}{$id}{event_length} ; + } elsif (!$db{$tables}{$id}{event_length} || $db{$tables}{$id}{event_length} !~ /(\d+)/g) { + my $start_time = substr($db{$tables}{$id}{date_from},11) ; + my $end_time = substr($db{$tables}{$id}{date_to},11) ; + my $time_diff = (Time::Piece->strptime($end_time,"%H:%M:%S") - Time::Piece->strptime($start_time,"%H:%M:%S"))/ONE_HOUR ; + my $full_half = ($time_diff >= 5) ? 1 : 2 ; + $db{$tables}{$id}{event_length} = qq~~ ; + for (1 .. $db{$tables}{$id}{qty}) { + $db{$tables}{$id}{event_length} .= qq~$full_half;~ ; + } + chop $db{$tables}{$id}{event_length} if $db{$tables}{$id}{event_length} ; + } + + @full_half_day = split(/;/,$db{$tables}{$id}{event_length}) ; + + if ($db{$tables}{$id}{days_active} !~ /(\d+)/g) { + $db{$tables}{$id}{days_active} = qq~~ ; + for (1 .. $db{$tables}{$id}{qty}) { + $db{$tables}{$id}{days_active} .= qq~1;~ ; + } + chop $db{$tables}{$id}{days_active} if $db{$tables}{$id}{days_active} ; + } + + @days_active = split(/;/,$db{$tables}{$id}{days_active}) ; + + @full_half_start = ($db{$tables}{$id}{times_from} =~ /(\d+)/g) ? split(/;/,substr($db{$tables}{$id}{date_from},11) . ';' . $db{$tables}{$id}{times_from}) : (substr($db{$tables}{$id}{date_from},11)) ; + @full_half_end = ($db{$tables}{$id}{times_to} =~ /(\d+)/g) ? split(/;/,$db{$tables}{$id}{times_to} . ';' . substr($db{$tables}{$id}{date_to},11)) : (substr($db{$tables}{$id}{date_to},11)) ; + + my $nr_of_hrs = 0 ; + my $full_day_hrs = 0 ; + my $half_day_hrs = 0 ; + my $day_cnt = 0 ; + + my %nr_of_hrs_cnt = () ; + + my $date_month = substr($db{$tables}{$id}{date_from},0,4) . substr($db{$tables}{$id}{date_from},5,2) ; + my $date_month_2 = substr($db{$tables}{$id}{date_to},0,4) . substr($db{$tables}{$id}{date_to},5,2) ; + + # foreach (@full_half_day) { + # $full_day_hrs + # $summary_table{$worksheet}{a_total_event_hours}{$date_month} += (Time::Piece->strptime($full_half_end[$day_cnt],"%H:%M:%S") - Time::Piece->strptime($full_half_start[$day_cnt],"%H:%M:%S"))/ONE_HOUR ; + # $day_cnt++ ; + # } + + # $day_cnt = 0 ; + + # foreach (@days_active) { + # $nr_of_hrs += (Time::Piece->strptime($full_half_end[$day_cnt],"%H:%M:%S") - Time::Piece->strptime($full_half_start[$day_cnt],"%H:%M:%S"))/ONE_HOUR if $_ ; + # $day_cnt++ ; + # } + + $day_cnt = 0 ; + + foreach (@full_half_day) { + + my $month = $date_month ; + + if ($date_month ne $date_month_2 && $day_cnt) { + my ($yr,$mn,$dd) = Add_Delta_Days(substr($db{$tables}{$id}{date_from},0,4),substr($db{$tables}{$id}{date_from},5,2),substr($db{$tables}{$id}{date_from},8,2),$day_cnt) ; + $mn = sprintf("%02d",$mn) ; + $month = $yr . $mn ; + } + + $summary_table{zzzzz_totals}{h_total_days_of_events}{$month} += 1 ; + + my $hours_diff = (Time::Piece->strptime($full_half_end[$day_cnt],"%H:%M:%S") - Time::Piece->strptime($full_half_start[$day_cnt],"%H:%M:%S"))/ONE_HOUR ; + + if ($_ eq '1') { + $full_day_cnt++ ; + $nr_of_hrs_cnt{full}{$month} += $hours_diff ; + } elsif ($_ eq '2') { + $half_day_cnt++ ; + $nr_of_hrs_cnt{half}{$month} += $hours_diff ; + } + + $day_cnt++ ; + + } + + my $cnt_item = -1 ; + + my %max_amnt_per_item = () ; my %item_pos = () ; + foreach my $item_id (@item) { + $cnt_item++ ; + next unless $item_id ; + $item_pos{$cnt_item} = $item_id ; + $max_amnt_per_item{$item_id} = $price[$cnt_item] if !$max_amnt_per_item{$item_id} || $max_amnt_per_item{$item_id} < $price[$cnt_item] ; + } + + my %second_max_amnt_per_item = () ; + $cnt_item = -1 ; + + foreach my $item_id (@item) { + $cnt_item++ ; + $second_max_amnt_per_item{$item_id} = $price[$cnt_item] if $price[$cnt_item] ne $max_amnt_per_item{$item_id} && (!$second_max_amnt_per_item{$item_id} || $second_max_amnt_per_item{$item_id} < $price[$cnt_item]) ; + } + + $cnt_item = -1 ; my %seen_quote_desc = () ; my %seen_item = () ; + + my $cnt_item_full = -1 ; my $cnt_item_half = -1 ; + + $summary_table{zzzzz_totals}{a_total_event_hours}{$date_month} += $nr_of_hrs_cnt{full}{$date_month} ; + $summary_table{zzzzz_totals}{a_total_event_hours}{$date_month} += $nr_of_hrs_cnt{half}{$date_month} ; + $summary_table{zzzzz_totals}{b_nr_of_half_day_events}{$date_month} += 1 if $db{$tables}{$id}{event_length} =~ /2/ ; + $summary_table{zzzzz_totals}{d_nr_of_full_day_events}{$date_month} += 1 if $db{$tables}{$id}{event_length} =~ /1/ ; + $summary_table{zzzzz_totals}{g_total_unique_events}{$date_month} += 1 ; + + if ($date_month_2 ne $date_month) { + $summary_table{zzzzz_totals}{a_total_event_hours}{$date_month_2} += $nr_of_hrs_cnt{full}{$date_month_2} ; + $summary_table{zzzzz_totals}{a_total_event_hours}{$date_month} += $nr_of_hrs_cnt{half}{$date_month_2} ; + $summary_table{zzzzz_totals}{b_nr_of_half_day_events}{$date_month_2} += 1 if $db{$tables}{$id}{event_length} =~ /2/ ; + $summary_table{zzzzz_totals}{d_nr_of_full_day_events}{$date_month_2} += 1 if $db{$tables}{$id}{event_length} =~ /1/ ; + $summary_table{zzzzz_totals}{g_total_unique_events}{$date_month_2} += 1 ; + } + + $summary_table_ytd{unique_events}{zzzzz_totals}{all} += 1 ; + $summary_table_ytd{unique_full_events}{zzzzz_totals}{all} += 1 if $db{$tables}{$id}{event_length} =~ /1/ ; + $summary_table_ytd{unique_half_events}{zzzzz_totals}{all} += 1 if $db{$tables}{$id}{event_length} =~ /2/ ; + + foreach my $item_id (@item) { + + # local $amnt_owed = $tot_amnt{$op_id} - $amnt_paid{$op_id} ; + $cnt_item++ ; + next if ($item_ttl[$cnt_item] eq '0.00' && $i{paid_status} eq 'outstanding') || ($i{paid_status} eq 'outstanding' && $db{$tables}{$id}{invoice_nr}) || ($i{paid_status} eq 'paid' && !$db{$tables}{$id}{invoice_nr}) ; + + my $hide_from_first_sheet = ($db{event_cost_items}{$item_id}{name} !~ /\bSolo\b/ && $db{event_cost_items}{$item_id}{name} !~ /\bMobile\b/ && $db{event_cost_items}{$item_id}{name} !~ /\bCricket\b/ && $db{event_cost_items}{$item_id}{name} !~ /\bFixed\b/) ? 1 : 0 ; + + $first_id = $id unless $first_id ; + $last_id = $id if $last_id < $id ; + + $amnt_owed = $item_ttl[$cnt_item] ; + $amnt_owed = 0 if $db{$tables}{$id}{invoice_nr} ; + $amnt_owed = sprintf("%.2f",$amnt_owed) ; + + $count_outstanding++ if $amnt_owed > 0 ; + + $op_ids .= qq~$op_id,~ ; + + $column_count++ ; + + $xlsxcol = 0 ; + $print_tbody .= qq~~ ; + $row_cnt++ ; + + my $extra_ws = $db{event_cost_items}{$item[$cnt_item]}{name} ; + + if (length($extra_ws) >= 31) { + $extra_ws = substr($extra_ws,0,28) . '...' ; + } + + # $extra_ws =~ s/ //g ; + unless ($seen_description{$extra_ws}) { + + &xlsxcreator_add_worksheet($extra_ws) ; + $xlsxrow_extra_sheets{$extra_ws} = 2 ; + @sql_col_display = grep { $_ ne "update" } @sql_col_display ; + &report_build_headings($report,$extra_ws,$title_heading,1,1) ; + push @sql_col_display,"update" ; + } + $seen_description{$extra_ws} = 1 ; + + $description_and_event{$extra_ws}{$id} = 1 ; + + # $summary_table{$extra_ws}{a_total_event_hours}{$date_month} += $nr_of_hrs ; + + # $totals_at_bottom{$worksheet}{a_total_event_hours} + # $totals_at_bottom{$worksheet}{b_nr_of_half_day_events} + # $totals_at_bottom{$worksheet}{c_total_of_half_day_events_ZAR} + # $totals_at_bottom{$worksheet}{d_nr_of_full_day_events} + # $totals_at_bottom{$worksheet}{e_total_of_full_day_events_ZAR} + # $totals_at_bottom{$worksheet}{f_total_ZAR} + # $totals_at_bottom{$worksheet}{g_total_unique_events} + + foreach (@sql_col_display) { + + next unless $_ ; # blank for the buttons column + $display = 1 ; + my $val = $db{$tables}{$id}{$_} ; + my $align = '' ; + my $center = qq~ class="dt-center"~ ; + $align = $center ; + + if ($_ eq 'event_quote_nr') { + + $val = &common_min_get_event_quote_button($id,$tables) ; + + } elsif ($_ eq 'event_name') { + $val = $db{$tables}{$id}{ref} ; + $align = qq~class="dt-left"~ ; + } elsif ($_ eq 'event_date_from' || $_ eq 'event_date_to') { + $val = ($_ eq 'event_date_from') ? &common_min_date_as_string(substr($db{$tables}{$id}{date_from},0,10)) : &common_min_date_as_string(substr($db{$tables}{$id}{date_to},0,10)) ; + } elsif ($_ eq 'days') { + $val = $db{$tables}{$id}{qty} ; + } elsif ($_ eq 'type_of_system') { + $val = $db{event_types}{$db{$tables}{$id}{type}}{name} ; + } elsif ($_ eq 'description') { + $val = $db{event_cost_items}{$item[$cnt_item]}{name} ; + } elsif ($_ eq 'production_hours' || $_ eq 'cloud_recording_hours') { + + my $desc = $db{event_cost_items}{$item[$cnt_item]}{name} ; + # my $desc = $db{event_systems}{$system_id}{description} ; + # my $sys_type = $db{event_systems}{$system_id}{system_type} ; + + my $type = + ($desc =~ /Mobile/ && $desc !~ /SSS/ && $desc !~ /AISA/ && $desc !~ /\bSolo\b/ && $desc !~ /Cricket/) ? 'mobile' : + ($desc =~ /Mobile/ && $desc =~ /SSS/ && $desc !~ /AISA/ && $desc !~ /\bSolo\b/ && $desc !~ /Cricket/) ? 'mobile_sss' : + ($desc =~ /Mobile/ && $desc !~ /SSS/ && $desc =~ /AISA/ && $desc !~ /\bSolo\b/ && $desc !~ /Cricket/) ? 'mobile_aisa' : + ($desc =~ /Cricket/) ? 'cricket' : + ($desc =~ /\bSolo\b/ && $desc !~ /SSS/ && $desc !~ /AISA/ ) ? 'solo' : + ($desc =~ /\bSolo\b/ && $desc =~ /SSS/ && $desc !~ /AISA/ ) ? 'solo_sss' : + ($desc =~ /\bSolo\b/ && $desc !~ /SSS/ && $desc =~ /AISA/ ) ? 'solo_aisa' : + ($desc =~ /Fixed/) ? 'fixed' : + '' + ; + + my $tooltip_data = ($tooltip{$_}{$type}{$id} && !$seen_tooltip_data{$_}{$type}{$id}) ? substr($tooltip{$_}{$type}{$id},0,-4) : ($tooltip{$_}{$type}{$id}) ? $tooltip{$_}{$type}{$id} : '' ; + + $seen_tooltip_data{$_}{$type}{$id} = 1 ; + + my $t_tot = sprintf("%.02f",$tooltip_total{$_}{$type}{$id}/3600) ; + + # $val = ($type && $tooltip_data) ? qq~~ : ($type && !$tooltip_data) ? "N/A" : qq~~ ; + $val = ($type && $tooltip_data) ? qq~$t_tot~ : ($type && !$tooltip_data) ? "N/A" : qq~~ ; + + $tooltip_data =~ s/
    /\;/g ; + + $val_min = ($tooltip_data) ? "$t_tot [$tooltip_data]" : "N/A" ; + + } elsif ($_ eq 'qty_full_day') { + + $summary_table{$extra_ws}{a_total_event_hours}{$date_month} += 0 ; + $summary_table{$extra_ws}{a_total_event_hours}{$date_month_2} += 0 ; + $summary_table{$extra_ws}{c_total_of_half_day_events_ZAR}{$date_month} += 0 ; + $summary_table{$extra_ws}{c_total_of_half_day_events_ZAR}{$date_month_2} += 0 ; + $summary_table{$extra_ws}{e_total_of_full_day_events_ZAR}{$date_month} += 0 ; + $summary_table{$extra_ws}{e_total_of_full_day_events_ZAR}{$date_month_2} += 0 ; + $summary_table{$extra_ws}{f_total_ZAR}{$date_month} += 0 ; + $summary_table{$extra_ws}{f_total_ZAR}{$date_month_2} += 0 ; + $summary_table{$extra_ws}{b_nr_of_half_day_events}{$date_month} += 0 ; + $summary_table{$extra_ws}{b_nr_of_half_day_events}{$date_month_2} += 0 ; + $summary_table{$extra_ws}{d_nr_of_full_day_events}{$date_month} += 0 ; + $summary_table{$extra_ws}{d_nr_of_full_day_events}{$date_month_2} += 0 ; + $summary_table{$extra_ws}{g_total_unique_events}{$date_month} += 0 ; + $summary_table{$extra_ws}{g_total_unique_events}{$date_month_2} += 0 ; + + unless ($seen_item{$item_id}) { + $summary_table_ytd{unique_events}{g_total_unique_events}{$extra_ws} += 1 ; + $summary_table_ytd{unique_full_events}{d_nr_of_full_day_events}{$extra_ws} += 1 if $db{$tables}{$id}{event_length} =~ /1/ ; + $summary_table_ytd{unique_half_events}{b_nr_of_half_day_events}{$extra_ws} += 1 if $db{$tables}{$id}{event_length} =~ /2/ ; + } + + my $full_not_half = 0 ; + + if ($max_amnt_per_item{$item_id} eq $price[$cnt_item] && $full_day_cnt && $item_pos{$cnt_item} eq $item_id) { + $cnt_item_full++ ; + $qty_full[$cnt_item] = $qty[$cnt_item] ; + $full_not_half = 1 ; + } elsif (($second_max_amnt_per_item{$item_id} eq $price[$cnt_item] || !$full_day_cnt) && $half_day_cnt) { + $cnt_item_half++ ; + $qty_half[$cnt_item] = $qty[$cnt_item] ; + $summary_table{$extra_ws}{a_total_event_hours}{$date_month} += $nr_of_hrs_cnt{half}{$date_month} ; + $summary_table{$extra_ws}{b_nr_of_half_day_events}{$date_month} += 1 if !$seen_quote_desc{$item_id}{half} ; + $summary_table{$extra_ws}{c_total_of_half_day_events_ZAR}{$date_month_2} += $item_ttl[$cnt_item] ; + $summary_table{zzzzz_totals}{c_total_of_half_day_events_ZAR}{$date_month_2} += $item_ttl[$cnt_item] ; + + if ($date_month ne $date_month_2) { + $summary_table{$extra_ws}{a_total_event_hours}{$date_month_2} += $nr_of_hrs_cnt{half}{$date_month_2} ; + $summary_table{$extra_ws}{b_nr_of_half_day_events}{$date_month_2} += 1 if !$seen_quote_desc{$item_id}{half} ; + } + + $seen_quote_desc{$item_id}{half} = 1 ; + # $item_price{$item[$cnt_item]}{$id}{half}{$price[$cnt_item]} = 1 ; + $seen_item_with_amnt{$item[$cnt_item]}{$id}{half}{$price[$cnt_item]} = 1 ; + $nr_unique_prices_per_item{$item[$cnt_item]}{half}++ unless $seen_item_price{$item[$cnt_item]}{half}{$price[$cnt_item]} ; + $seen_item_price{$item[$cnt_item]}{half}{$price[$cnt_item]} = 1 ; + } else { + $cnt_item_full++ ; + $qty_full[$cnt_item] = $qty[$cnt_item] ; + $full_not_half = 1 ; + } + + if ($full_not_half) { + $summary_table{$extra_ws}{a_total_event_hours}{$date_month} += $nr_of_hrs_cnt{full}{$date_month} ; + $summary_table{$extra_ws}{d_nr_of_full_day_events}{$date_month} += 1 if !$seen_quote_desc{$item_id}{full} ; + if ($date_month ne $date_month_2) { + $summary_table{$extra_ws}{a_total_event_hours}{$date_month_2} += $nr_of_hrs_cnt{full}{$date_month_2} ; + $summary_table{$extra_ws}{d_nr_of_full_day_events}{$date_month_2} += 1 if !$seen_quote_desc{$item_id}{full} ; + } + $summary_table{$extra_ws}{e_total_of_full_day_events_ZAR}{$date_month_2} += $item_ttl[$cnt_item] ; + $summary_table{zzzzz_totals}{e_total_of_full_day_events_ZAR}{$date_month_2} += $item_ttl[$cnt_item] ; + $seen_quote_desc{$item_id}{full} = 1 ; + $seen_item_with_amnt{$item[$cnt_item]}{$id}{full}{$price[$cnt_item]} = 1 ; + $nr_unique_prices_per_item{$item[$cnt_item]}{full}++ unless $seen_item_price{$item[$cnt_item]}{full}{$price[$cnt_item]} ; + $seen_item_price{$item[$cnt_item]}{full}{$price[$cnt_item]} = 1 ; + } + + $summary_table{$extra_ws}{f_total_ZAR}{$date_month_2} += $item_ttl[$cnt_item] ; + $summary_table{zzzzz_totals}{f_total_ZAR}{$date_month_2} += $item_ttl[$cnt_item] ; + $summary_table{$extra_ws}{g_total_unique_events}{$date_month} += 1 if !$seen_item{$item_id} ; + $summary_table{$extra_ws}{g_total_unique_events}{$date_month_2} += 1 if !$seen_item{$item_id} && $date_month ne $date_month_2 ; + + $seen_item{$item_id} = 1 ; + $seen_month{$date_month} = 1 ; + $val = $qty_full[$cnt_item] ; + $totals_at_bottom{$ws}{5} += $qty_full[$cnt_item] ; + $totals_at_bottom{$extra_ws}{5} += $qty_full[$cnt_item] ; + + } elsif ($_ eq 'qty_half_day') { + $val = $qty_half[$cnt_item] ; + $totals_at_bottom{$ws}{6} += $qty_half[$cnt_item] ; + $totals_at_bottom{$extra_ws}{6} += $qty_half[$cnt_item] ; + + } elsif ($_ eq 'rate') { + $val = &common_commify($price[$cnt_item]) ; + $val_min = $val ; + } elsif ($_ eq 'total') { + $val = &common_commify($item_ttl[$cnt_item]) ; + $val_min = $item_ttl[$cnt_item] ; + $totals_at_bottom{$ws}{1} += $item_ttl[$cnt_item] unless $hide_from_first_sheet ; + $totals_at_bottom{$ws}{4} += $item_ttl[$cnt_item] ; + $totals_at_bottom{$extra_ws}{1} += $item_ttl[$cnt_item] ; + } elsif ($_ eq 'vat') { + # $align = 'nowrap' ; + $totals_at_bottom{$ws}{2} += ($vat[$cnt_item]) ? $item_ttl[$cnt_item]*0.15 : 0 unless $hide_from_first_sheet ; + $totals_at_bottom{$extra_ws}{2} += ($vat[$cnt_item]) ? $item_ttl[$cnt_item]*0.15 : 0 ; + $val = ($vat[$cnt_item]) ? sprintf("%.2f",$item_ttl[$cnt_item]*0.15) : qq~  ~ ; + $val_min = ($vat[$cnt_item]) ? $item_ttl[$cnt_item]*0.15 : 0 ; + } elsif ($_ eq 'total_amount') { + + if ($vat[$cnt_item]) { + $val = $item_ttl[$cnt_item]*1.15 ; + $val = sprintf("%.2f",$val) ; + $totals_at_bottom{$ws}{3} += $val unless $hide_from_first_sheet ; + $totals_at_bottom{$extra_ws}{3} += $val ; + } else { + $val = $item_ttl[$cnt_item] ; + $totals_at_bottom{$ws}{3} += $val unless $hide_from_first_sheet ; + $totals_at_bottom{$extra_ws}{3} += $val ; + } + } elsif ($_ eq 'invoice_nr') { + + $val = ($amnt_owed > 0) ? &common_min_form_input_col("invoice_nr_$id\_$cnt_item",$db{$tables}{$id}{invoice_nr}) : "$db{$tables}{$id}{invoice_nr} " ; + $val_min = $db{$tables}{$id}{invoice_nr} ; + # $input_fields{$id} .= qq~input[name='invoice_nr_$id\_$cnt_item'],~ ; + $default_invoice_nrs .= qq~"$id\_$cnt_item":"$db{$tables}{$id}{invoice_nr}",~ if $amnt_owed > 0 && $db{$tables}{$id}{invoice_nr} ; + $unique_invoice_nr_exists_with_blank_entries = ( + $unique_invoice_nr_exists_with_blank_entries + && + $unique_invoice_nr_exists_with_blank_entries ne "All_Invoice_Nrs_Blank" + && + $db{$tables}{$id}{invoice_nr} + && + $unique_invoice_nr_exists_with_blank_entries ne $db{$tables}{$id}{invoice_nr} + ) ? "" : $unique_invoice_nr_exists_with_blank_entries ; + + } elsif ($_ eq 'update') { + if ($amnt_owed > 0) { + $val = &common_min_form_checkbox_col("update_$id\_$cnt_item",1) ; + # $trigger_jquery_raw .= qq~ + # \$("input[name='invoice_nr_$id\_$cnt_item']").change(function () { + # \$("#checkboxUpdate_$id\_$cnt_item").prop("checked",true) ; + # }) ; + # ~ ; + } else { + $val = '' ; + } + $val_min = "" ; + } + + $print_tbody .= qq~$val~ ; + + if ($_ ne 'event_quote_nr' && $_ ne 'days' && $_ ne 'qty_full_day' && $_ ne 'qty_half_day' && $_ ne 'total' && $_ ne 'rate' && $_ ne 'update' && $_ ne 'invoice_nr' && $_ ne 'event_name' && $_ ne 'vat' && $_ ne 'production_hours' && $_ ne 'cloud_recording_hours') { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format_management_report_data) unless $hide_from_first_sheet ; + &xlsxcreator_write_xlsx($extra_ws,$xlsxrow_extra_sheets{$extra_ws},$xlsxcol+1,$val,$format_management_report_data) ; + } elsif ($_ eq 'event_name') { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format_management_report_months_2) unless $hide_from_first_sheet ; + &xlsxcreator_write_xlsx($extra_ws,$xlsxrow_extra_sheets{$extra_ws},$xlsxcol+1,$val,$format_management_report_months_2) ; + } elsif ($_ eq 'event_quote_nr') { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$id,$format_management_report_data_ref_nr) unless $hide_from_first_sheet ; + &xlsxcreator_write_xlsx($extra_ws,$xlsxrow_extra_sheets{$extra_ws},$xlsxcol+1,$id,$format_management_report_data_ref_nr) ; + } elsif ($_ eq 'qty_full_day' || $_ eq 'qty_half_day' || $_ eq 'days') { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format_management_report_data_ref_nr) unless $hide_from_first_sheet ; + &xlsxcreator_write_xlsx($extra_ws,$xlsxrow_extra_sheets{$extra_ws},$xlsxcol+1,$val,$format_management_report_data_ref_nr) ; + } elsif ($_ eq 'production_hours' || $_ eq 'cloud_recording_hours') { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format_management_report_months_2) unless $hide_from_first_sheet ; + &xlsxcreator_write_xlsx($extra_ws,$xlsxrow_extra_sheets{$extra_ws},$xlsxcol+1,$val_min,$format_management_report_months_2) ; + } elsif ($_ eq 'invoice_nr') { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format_management_report_data_ref_nr) unless $hide_from_first_sheet ; + &xlsxcreator_write_xlsx($extra_ws,$xlsxrow_extra_sheets{$extra_ws},$xlsxcol+1,$val_min,$format_management_report_data_ref_nr) ; + } elsif ($_ eq 'total' or $_ eq 'rate') { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format7) unless $hide_from_first_sheet ; + &xlsxcreator_write_xlsx($extra_ws,$xlsxrow_extra_sheets{$extra_ws},$xlsxcol+1,$val_min,$format7) ; + } elsif ($_ ne 'update' or $_ ne 'vat') { + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$format_management_report_data) unless $hide_from_first_sheet ; + &xlsxcreator_write_xlsx($extra_ws,$xlsxrow_extra_sheets{$extra_ws},$xlsxcol+1,$val_min,$format_management_report_data) ; + } + $xlsxcol++; + # if ($_ eq 'ref_nr' or $_ eq 'camera_nr') { $val = &common_camera_links($tables,$id,$val) ;} + + } + $print_tbody .= qq~~ ; + $xlsxrow++ unless $hide_from_first_sheet ; + $xlsxrow_extra_sheets{$extra_ws}++ ; + $quote_ids_and_item_cnt .= qq~"$cnt_item\_$id":"1",~ if $item_id ; + } + + # if ($input_fields{$id}) { + # chop $input_fields{$id} ; + # $trigger_jquery_raw .= qq~ + # \$("$input_fields{$id}").change( function () { + # console.log("change input") ; + # selectAll($id,\$(this).val()) ; + # }) ; + # ~ ; + # } + + chop $op_ids if $op_ids ; + # $quote_ids_and_item_cnt .= qq~"$row_cnt_$id":[$op_ids],~ if $op_ids ; + + } + + $unique_invoice_nr_exists_with_blank_entries = ($unique_invoice_nr_exists_with_blank_entries eq "All_Invoice_Nrs_Blank") ? "" : $unique_invoice_nr_exists_with_blank_entries ; + + # $box_icon .= qq~
    ~ ; + + my $display_invoice_btn = ($unique_invoice_nr_exists_with_blank_entries) ? "" : "style='display:none;'" ; + + $box_icon .= qq~
    ~ ; + $box_icon .= qq~
    ~ ; + + my $table_id = "itv-table_wrapper" ; + + $table_id = $useropts{table_id} unless $table_id ; + + chop $default_invoice_nrs if $default_invoice_nrs ; + + $trigger_jquery_raw .= qq~ + + function default_invoice_nrs () { + return {$default_invoice_nrs} ; + } + + \$("#invoice-form [id^='inputInvoice_nr_']").on("change", function () { + + let row_nr = get_row_nr(this.id,2) ; + let def_vals = default_invoice_nrs() ; + let def_val = def_vals[row_nr] ; + if (typeof def_val === 'undefined') def_val = "" ; + + console.log("def_val : "+def_val) ; + console.log("this : "+\$(this).val()) ; + console.log("inputInvoice_nr_"+row_nr+" : "+this.id) ; + + let event_id = row_nr.split("_")[0] ; + + console.log("event_id : "+event_id) ; + + if (def_val != \$(this).val() || !\$(this).val()) { + selectAll(event_id,\$(this).val()) ; + } else if (def_val == \$(this).val() && \$("#checkboxUpdate_"+row_nr).is(":checked")) { + \$("#checkboxUpdate_"+row_nr).prop("checked",false) ; + } + + let unique_invoice_nr = get_unique_input_invoice_nrs () ; + + if ((unique_invoice_nr == "" || !unique_invoice_nr) && !\$("#auto_complete_invoice_nrs_btn").is(":hidden")) { + \$("#auto_complete_invoice_nrs_btn").hide() ; + } else if (unique_invoice_nr != "" && unique_invoice_nr && \$("#auto_complete_invoice_nrs_btn").is(":hidden")) { + \$("#auto_complete_invoice_nrs_btn").show() ; + \$("#delete_invoice_nrs_btn").show() ; + } + + }) ; + + function get_row_nr (id,nr_of_characters_in_id_to_determine_row) { + + let lastIndex = id.lastIndexOf('_'); + lastIndex = parseInt(lastIndex) ; + let row_nr_1 = id.substring(1+lastIndex); + + if (!nr_of_characters_in_id_to_determine_row || nr_of_characters_in_id_to_determine_row == 1) { + return row_nr_1 ; + } + + let id_2 = id.substring(0,lastIndex); + lastIndex = id_2.lastIndexOf('_'); + lastIndex = parseInt(lastIndex) ; + let row_nr_2 = id_2.substring(1+lastIndex); + + if (nr_of_characters_in_id_to_determine_row == 2) { + return row_nr_2+"_"+row_nr_1 ; + } + + } + + function delete_input_invoice_nrs() { + + const rowCount = \$("#$table_id tr").length ; + + for (let i = rowCount - 1; i >= 0; i--) { + const \$row = \$("#$table_id tr").eq(i) ; + const \$input = \$row.find("input[id^='inputInvoice_nr_']") ; + const id_attr = (\$input.length) ? \$input.attr("id") : "" ; + if (id_attr != "") { + let row_nr = get_row_nr(id_attr,2) ; + let def_vals = default_invoice_nrs() ; + let def_val = def_vals[row_nr] ; + if (typeof def_val === 'undefined') def_val = "" ; + console.log("def_val : "+def_val) ; + if (\$("#checkboxUpdate_"+row_nr).is(":checked") && def_val != \$("#"+id_attr).val()) { + \$("#inputInvoice_nr_"+row_nr).val(def_val) ; + \$("#checkboxUpdate_"+row_nr).prop("checked",false) ; + } + } + } + + \$("#auto_complete_invoice_nrs_btn").hide() ; + \$("#delete_invoice_nrs_btn").hide() ; + + } + + function selectAll(specific_event_id,given_input) { + + let jsObject = { + $quote_ids_and_item_cnt + } ; + + let find_input = '' ; + + if (!specific_event_id) { + for (let key in jsObject) { + let parts = key.split("_") ; + let event_id = parts[1] ; + if (specific_event_id && specific_event_id != event_id) { continue ; } + let item_cnt = parts[0] ; + + if (\$("input[name=invoice_nr_"+event_id+"_"+item_cnt+"]").val()) { + find_input = \$("input[name=invoice_nr_"+event_id+"_"+item_cnt+"]").val() ; + break ; + } + } + if (!find_input) { return ; } + } else { + find_input = given_input ; + } + + for (let key in jsObject) { + + let parts = key.split("_") ; + let event_id = parts[1] ; + if (specific_event_id && specific_event_id != event_id) { continue ; } + let item_cnt = parts[0] ; + \$(\$("#itv-table").dataTable().fnGetNodes()).find(\$("input[name=update_"+event_id+"_"+item_cnt+"]")).each(function () { + \$("input[name=invoice_nr_"+event_id+"_"+item_cnt+"]").val(find_input) ; + if (!\$(this).is(':checked')) { + \$(this).prop('checked',true); + } else if (\$(this).is(':checked') && !find_input) { + \$(this).prop('checked',false); + } + }) ; + } + } + + function selectAll2() { + + let unique_invoice_nr = get_unique_input_invoice_nrs() ; + if (unique_invoice_nr != "") { + const rowCount = \$("#$table_id tr").length ; let invoice_nr = "" ; let blank_invoice_nr_exists = "" ; + for (let i = rowCount - 1; i >= 0; i--) { + const \$row = \$("#$table_id tr").eq(i) ; + const \$input = \$row.find("input[id^='inputInvoice_nr_']") ; + const id_attr = (\$input.length) ? \$input.attr("id") : "" ; + if (id_attr == "" || !id_attr) continue ; + if (\$("#"+id_attr).val()) continue ; + \$("#"+id_attr).val(unique_invoice_nr) ; + let row_nr = get_row_nr(id_attr,2) ; + if (!\$("#checkboxUpdate_"+row_nr).is(':checked')) { + \$("#checkboxUpdate_"+row_nr).prop('checked',true); + } + } + return ; + } + return ; + } + + function get_unique_input_invoice_nrs () { + + const rowCount = \$("#$table_id tr").length ; let invoice_nr = "" ; let blank_invoice_nr_exists = "" ; + + for (let i = rowCount - 1; i >= 0; i--) { + const \$row = \$("#$table_id tr").eq(i) ; + const \$input = \$row.find("input[id^='inputInvoice_nr_']") ; + const id_attr = (\$input.length) ? \$input.attr("id") : "" ; + if (id_attr != "") { + if (invoice_nr == "") { + invoice_nr = \$("#"+id_attr).val() ; + } else if (invoice_nr != "" && \$("#"+id_attr).val() && \$("#"+id_attr).val() != "" && invoice_nr != \$("#"+id_attr).val()) { + return "" ; + } + } + } + return invoice_nr ; + + } + + ~ ; + + # $trigger_jquery_raw .= qq~ + + # function selectAll() { + + # let jsObject = { + # $quote_ids_and_item_cnt + # }; + + # for (let key in jsObject) { + # let op_id = jsObject[key]; + + # let parts = key.split("_") ; + # let event_id = parts[1] ; + + # \$(\$("#itv-table").dataTable().fnGetNodes()).find(\$("input[name=update_"+event_id+"_"+op_id+"]")).each(function () { + + # console.log("input[name=update_"+event_id+"_"+op_id+"]") ; + # if(\$(this).is(':checked')) { + # \$(this).prop('checked',false); + # } else { + # \$(this).prop('checked',true); + # } + # }) ; + # } + # } + # ~; + + $print_tbody .= qq~~ ; + + foreach my $worksheet (sort keys %seen_description) { + for (1 .. 6) { + $totals_at_bottom{$worksheet}{$_} = sprintf("%.02f",$totals_at_bottom{$worksheet}{$_}) if $_ <= 4; + $totals_at_bottom{$worksheet}{$_} = &common_commify($totals_at_bottom{$worksheet}{$_}) ; + } + } + + # $format_management_report_totals -> set_bottom('1') ; + + foreach (@sql_col_display) { + + if ($_ eq $sql_col_display[-9]) { + $print_tbody .= ($cnt_nr_of_events == 1) ? qq~-1TOTALS
    ($cnt_nr_of_events Event)
    ~ : qq~-1TOTALS
    ($cnt_nr_of_events Events)
    ~ ; + } elsif ($_ eq $sql_col_display[-5]) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,9,$totals_at_bottom{$ws}{1},$format_management_report_totals) ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,8,"",$format_management_report_totals) ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,7,$totals_at_bottom{$ws}{6},$format_management_report_totals_2) ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,6,$totals_at_bottom{$ws}{5},$format_management_report_totals_2) ; + foreach my $worksheet (sort keys %seen_description) { + &xlsxcreator_write_xlsx($worksheet,$xlsxrow_extra_sheets{$worksheet},10,$totals_at_bottom{$worksheet}{1},$format_management_report_totals) if $worksheet ne $ws ; + &xlsxcreator_write_xlsx($worksheet,$xlsxrow_extra_sheets{$worksheet},9,"",$format_management_report_totals) if $worksheet ne $ws ; + &xlsxcreator_write_xlsx($worksheet,$xlsxrow_extra_sheets{$worksheet},8,$totals_at_bottom{$worksheet}{6},$format_management_report_totals_2) if $worksheet ne $ws ; + &xlsxcreator_write_xlsx($worksheet,$xlsxrow_extra_sheets{$worksheet},7,$totals_at_bottom{$worksheet}{5},$format_management_report_totals_2) if $worksheet ne $ws ; + } + $print_tbody .= qq~-1$totals_at_bottom{$ws}{4}~ ; + } elsif ($_ eq $sql_col_display[-8]) { + $print_tbody .= qq~-1$totals_at_bottom{$ws}{5}~ ; + } elsif ($_ eq $sql_col_display[-7]) { + $print_tbody .= qq~-1$totals_at_bottom{$ws}{6}~ ; + } + # elsif ($_ eq $sql_col_display[-4]) { + # &xlsxcreator_write_xlsx($ws,$xlsxrow,10,$totals_at_bottom{2},$format_management_report_totals ) ; + # $print_tbody .= qq~-1$totals_at_bottom{2}~ ; + # } elsif ($_ eq $sql_col_display[-3]) { + # &xlsxcreator_write_xlsx($ws,$xlsxrow,11,$totals_at_bottom{3},$format_management_report_totals ) ; + # $print_tbody .= qq~-1$totals_at_bottom{3}~ ; + # } + else { + $print_tbody .= qq~-1~ ; + } + } + + # # foreach (@sql_col_display) { + + # # if ($_ eq $sql_col_display[-4]) { + # # $print_tbody .= qq~-1TOTALS ($cnt_nr_of_events Events)~ ; + # # } elsif ($_ eq $sql_col_display[-3]) { + # # &xlsxcreator_write_xlsx($ws,$xlsxrow,10,$totals_at_bottom{1},$format_management_report_totals ) ; + # # $print_tbody .= qq~-1$totals_at_bottom{1}~ ; + # # } elsif ($_ eq $sql_col_display[-1] || $_ eq $sql_col_display[-2]) { + # # $print_tbody .= qq~-1~ ; + # # } + + # # # elsif ($_ eq $sql_col_display[-4]) { + # # # &xlsxcreator_write_xlsx($ws,$xlsxrow,11,$totals_at_bottom{2},$format_management_report_totals ) ; + # # # $print_tbody .= qq~-1$totals_at_bottom{2}~ ; + # # # } elsif ($_ eq $sql_col_display[-3]) { + # # # &xlsxcreator_write_xlsx($ws,$xlsxrow,12,$totals_at_bottom{3},$format_management_report_totals ) ; + # # # $print_tbody .= qq~-1$totals_at_bottom{3}~ ; + # # # } + # # # else { + # # # $print_tbody .= qq~-1~ ; + # # # } + + # # } + + my %event_cnt_by_des = () ; + + my @months_of_year = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + foreach my $des (keys %description_and_event) { + foreach my $evnt (keys %{$description_and_event{$des}}) { + $event_cnt_by_des{$des}++ ; + } + } + + $xlsxrow++ ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,9,"TOTAL",$format_management_report_total) ; + my $event_word = ($cnt_nr_of_events == 1) ? "Event" : "Events" ; + &xlsxcreator_merge_xlsx($ws,"A$xlsxrow:F$xlsxrow","TOTAL ($cnt_nr_of_events $event_word)",$format_management_report_total) ; + + my $summary_ws = "Summary" ; + my $rates_ws = "Rates" ; + + &xlsxcreator_add_worksheet($rates_ws) ; + + # $seen_item_with_amnt{$item[$cnt_item]}{half}{$price[$cnt_item]} = 1 ; + + &xlsxcreator_write_xlsx($rates_ws,1,1,"Description",$format_management_report_headings) ; + &xlsxcreator_write_xlsx($rates_ws,1,2,"Rate - Full Day",$format_management_report_headings) ; + &xlsxcreator_write_xlsx($rates_ws,1,3,"Rate - Half Day",$format_management_report_headings) ; + + my $rates_row = 2 ; + + my %seen_item_fh = () ; my %cnt_item = () ; my %seen_item_price = () ; + + foreach my $item_id (sort {$db{event_cost_items}{$a}{name} cmp $db{event_cost_items}{$b}{name}} keys %seen_item_with_amnt) { + + next if $db{event_cost_items}{$item_id}{name} !~ /\bSolo\b/ && $db{event_cost_items}{$item_id}{name} !~ /\bMobile\b/ && $db{event_cost_items}{$item_id}{name} !~ /\bCricket\b/ && $db{event_cost_items}{$item_id}{name} !~ /\bFixed\b/ ; + + foreach my $event_id (sort {$b <=> $a} keys %{$seen_item_with_amnt{$item_id}}) { + + # my $nr_of_skipped_prices = 0 ; + + foreach my $full_or_half_day (sort keys %{$seen_item_with_amnt{$item_id}{$event_id}}) { + + my $rate = "" ; + my $rates_col = ($full_or_half_day eq 'full') ? 2 : 3 ; + + foreach my $item_price (sort {$a <=> $b} keys %{$seen_item_with_amnt{$item_id}{$event_id}{$full_or_half_day}}) { + + # $nr_of_skipped_prices++ if $seen_item_price{$item_id}{$full_or_half_day}{$item_price} ; + + next if $seen_item_price{$item_id}{$full_or_half_day}{$item_price} ; + $seen_item_price{$item_id}{$full_or_half_day}{$item_price} = 1 ; + + $item_price = &common_commify($item_price) ; + + if ((!$seen_item_price{$item_id}{half}{$item_price} && !$seen_item_price{$item_id}{full}{$item_price} && !$cnt_item{$item_id}) || ($nr_unique_prices_per_item{$item_id}{half} == 1 && $nr_unique_prices_per_item{$item_id}{full} == 1)) { + if ($nr_unique_prices_per_item{$item_id}{half} == 1 && $nr_unique_prices_per_item{$item_id}{full} == 1 && $full_or_half_day eq 'half') { + #Do Nothing + } else { + $rates_row++ ; + &xlsxcreator_write_xlsx($rates_ws,$rates_row,1,"$db{event_cost_items}{$item_id}{name}",$format98) ; + $cnt_item{$item_id}++ ; + } + } elsif (!$seen_item_price{$item_id}{half}{$item_price} || !$seen_item_price{$item_id}{full}{$item_price}) { + $cnt_item{$item_id}++ ; + $rates_row++ ; + &xlsxcreator_write_xlsx($rates_ws,$rates_row,1,"$db{event_cost_items}{$item_id}{name} ($cnt_item{$item_id})",$format98) ; + } else { + # $nr_of_skipped_prices++ + } + # $seen_item_fh{$item_id}{$full_or_half_day} = 1 ; + &xlsxcreator_write_xlsx($rates_ws,$rates_row,$rates_col,$item_price,$format7) ; + + } + } + } + } + + &xlsxcreator_add_worksheet($summary_ws) ; + + my $description_cnt = 3 ; + + # format_management_report_headings + + # &xlsxcreator_write_xlsx($summary_ws,0,0,"Description",$format_management_report_headings) ; + # &xlsxcreator_write_xlsx($summary_ws,0,1,"Total",$format_management_report_headings) ; + &xlsxcreator_merge_xlsx($summary_ws,"B2:C2","Summary",$format_management_report_headings) ; + my $mnt_cnt = 3 ; my $month_cnt = 0 ; + + foreach (sort keys %seen_month) { + my $month_name = $months_of_year[substr($_,4,2)] . '-' . substr($_,0,4) ; + &xlsxcreator_write_xlsx($summary_ws,1,$mnt_cnt,$month_name,$format_management_report_headings) ; + $mnt_cnt++ ; + } + + &xlsxcreator_write_xlsx($summary_ws,1,$mnt_cnt,"YTD Total",$format_management_report_headings) ; + &xlsxcreator_freeze_panes($summary_ws,2,0) ; + &xlsxcreator_freeze_panes($rates_ws,2,0) ; + + $format3->set_align('center'); + + # $totals_at_bottom{$worksheet}{a_total_event_hours} + # $totals_at_bottom{$worksheet}{b_nr_of_half_day_events} + # $totals_at_bottom{$worksheet}{c_total_of_half_day_events_ZAR} + # $totals_at_bottom{$worksheet}{d_nr_of_full_day_events} + # $totals_at_bottom{$worksheet}{e_total_of_full_day_events_ZAR} + # $totals_at_bottom{$worksheet}{f_total_ZAR_of_full_day_events} + # $totals_at_bottom{$worksheet}{g_total} + # $totals_at_bottom{$worksheet}{h_total_unique_events} + + my @small_words = qw(of); + + my $formatting = $format7 ; + + foreach my $worksheet (sort keys %summary_table) { + + if ($worksheet ne 'zzzzz_totals') { + + next if $worksheet eq $ws ; + $xlsxrow_extra_sheets{$worksheet}++ ; + $event_word = ($event_cnt_by_des{$worksheet} == 1) ? "Event" : "Events" ; + # &xlsxcreator_merge_xlsx($worksheet,"A$xlsxrow_extra_sheets{$worksheet}:J$xlsxrow_extra_sheets{$worksheet}","TOTAL ($event_cnt_by_des{$worksheet} $event_word)",$format_management_report_total) ; + $xlsxrow_extra_sheets{$worksheet}-- ; + # &xlsxcreator_write_xlsx($worksheet,$xlsxrow_extra_sheets{$worksheet},9,"TOTAL",$format_management_report_total) if $worksheet ne $ws ; + my $description_cnt_2 = $description_cnt+ 6 ; + + &xlsxcreator_merge_xlsx($summary_ws,"B$description_cnt:B$description_cnt_2","$worksheet",$format98) ; + + foreach my $category (sort keys %{$summary_table{$worksheet}}) { + + my $category_2 = substr($category,2) ; + $category_2 = join " ", map { my $word = lc($_); (grep { $_ eq $word } @small_words) ? $word : ucfirst($word) } split "_" , $category_2 ; + $category_2 =~ s/Zar/\[ZAR\]/g; + $description_cnt++ ; + + &xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,2,$category_2,$format98) ; + + my $month_cnt = 3 ; my $ytd_total = 0 ; + + $formatting = ($category eq 'c_total_of_half_day_events_ZAR' || $category eq 'e_total_of_full_day_events_ZAR' || $category eq 'f_total_ZAR' || ($category eq 'a_total_event_hours' && $summary_table{$worksheet}{$category}{$year_month} && $summary_table{$worksheet}{$category}{$year_month} ne int($summary_table{$worksheet}{$category}{$year_month}))) ? $format7 : $format99 ; + + foreach my $year_month (sort keys %seen_month) { + + $summary_table{$worksheet}{$category}{$year_month} = 0 unless $summary_table{$worksheet}{$category}{$year_month} ; + # my $month_name = $months_of_year[substr($year_month,4,2)] . '-' . substr($year_month,0,4) ; + &xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table{$worksheet}{$category}{$year_month},$formatting) ; + $month_cnt++ ; + $ytd_total += $summary_table{$worksheet}{$category}{$year_month} ; + + } + + + if ($category ne 'b_nr_of_half_day_events' && $category ne 'd_nr_of_full_day_events' && $category ne 'g_total_unique_events') { + &xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$ytd_total,$formatting) ; + } elsif ($category eq 'g_total_unique_events') { + &xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table_ytd{unique_events}{$category}{$worksheet},$formatting) ; + } elsif ($category eq 'd_nr_of_full_day_events') { + &xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table_ytd{unique_full_events}{$category}{$worksheet},$formatting) ; + } elsif ($category eq 'b_nr_of_half_day_events') { + &xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table_ytd{unique_half_events}{$category}{$worksheet},$formatting) ; + } + + # &xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$ytd_total,$formatting) ; + } + + # &xlsxcreator_write_xlsx($summary_ws,$description_cnt,3,"$summary_table{$worksheet}{1}",$format3) ; + $description_cnt++ ; + + } else { + + my $description_cnt_2 = $description_cnt+ 7 ; + + &xlsxcreator_merge_xlsx($summary_ws,"B$description_cnt:B$description_cnt_2","TOTALS",$format98) ; + + foreach my $category (sort keys %{$summary_table{$worksheet}}) { + + my $category_2 = substr($category,2) ; + $category_2 = join " ", map { my $word = lc($_); (grep { $_ eq $word } @small_words) ? $word : ucfirst($word) } split "_" , $category_2 ; + $category_2 =~ s/Zar/\[ZAR\]/g; + $description_cnt++ ; + + &xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,2,$category_2,$format98) ; + + my $month_cnt = 3 ; my $ytd_total = 0 ; + + $formatting = ($category eq 'c_total_of_half_day_events_ZAR' || $category eq 'e_total_of_full_day_events_ZAR' || $category eq 'f_total_ZAR' || ($category eq 'a_total_event_hours' && $summary_table{$worksheet}{$category}{$year_month} && $summary_table{$worksheet}{$category}{$year_month} ne int($summary_table{$worksheet}{$category}{$year_month}))) ? $format7 : $format99 ; + + foreach my $year_month (sort keys %seen_month) { + + $summary_table{$worksheet}{$category}{$year_month} = 0 unless $summary_table{$worksheet}{$category}{$year_month} ; + # my $month_name = $months_of_year[substr($year_month,4,2)] . '-' . substr($year_month,0,4) ; + &xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table{$worksheet}{$category}{$year_month},$formatting) ; + $month_cnt++ ; + $ytd_total += $summary_table{$worksheet}{$category}{$year_month} ; + + } + + if ($category ne 'b_nr_of_half_day_events' && $category ne 'd_nr_of_full_day_events' && $category ne 'g_total_unique_events') { + &xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$ytd_total,$formatting) ; + } elsif ($category eq 'g_total_unique_events') { + &xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table_ytd{unique_events}{zzzzz_totals}{all},$formatting) ; + } elsif ($category eq 'd_nr_of_full_day_events') { + &xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table_ytd{unique_full_events}{zzzzz_totals}{all},$formatting) ; + } elsif ($category eq 'b_nr_of_half_day_events') { + &xlsxcreator_write_xlsx($summary_ws,$description_cnt-2,$month_cnt,$summary_table_ytd{unique_half_events}{zzzzz_totals}{all},$formatting) ; + } + } + } + } + + $xlsxrow-- ; + + $worksheet{$rates_ws} -> set_column(0,0,1) ; + $worksheet{$summary_ws} -> set_column(0,0,1) ; + $worksheet{$summary_ws} -> set_column(1,2,30) ; + $worksheet{$summary_ws} -> set_column(3,$mnt_cnt,15) ; + $worksheet{$rates_ws} -> set_column(1,1,40) ; + $worksheet{$rates_ws} -> set_column(2,3,30) ; + + $print_tbody .= qq~~ ; + chop $quote_ids_and_item_cnt if $quote_ids_and_item_cnt ; + + # my @extra_columns = ("Validated Amount","Validated Total Amount","Difference Amount") ; + my @extra_columns = () ; + # my @extra_columns2 = ("Is Amount Difference","Month") ; + my @extra_columns2 = () ; + + # our @sql_col_display = ("event_quote_nr","event_name","event_date_from","event_date_to","days","type_of_system","description","production_hours","cloud_recording_hours","qty_half_day","qty_full_day","rate","total","invoice_nr") ; + # our @sql_col_display = ("event_quote_nr","description","event_name","days","event_date_from","event_date_to","qty_full_day","qty_half_day","rate","total","production_hours","cloud_recording_hours","invoice_nr") ; + + foreach my $sheet (sort keys %seen_description) { + + my $heading_row = ($sheet eq $ws) ? 2 : 1 ; + my $start_col = ($sheet eq $ws) ? 0 : 1 ; + + $worksheet{$sheet} -> set_row(0,30) if $sheet eq $ws ; + $worksheet{$sheet} -> set_column(0,0,1) if $sheet ne $ws ; + $worksheet{$sheet} -> set_row($heading_row,40) ; + # $worksheet{$sheet} -> set_column($start_col,$start_col,15) ; + # $worksheet{$sheet} -> set_column($start_col+1,$start_col+1,50) ; + # $worksheet{$sheet} -> set_column($start_col+2,$start_col+3,15) ; + # $worksheet{$sheet} -> set_column($start_col+4,$start_col+4,5) ; + # $worksheet{$sheet} -> set_column($start_col+5,$start_col+5,20) ; + # $worksheet{$sheet} -> set_column($start_col+6,$start_col+6,30) ; + # $worksheet{$sheet} -> set_column($start_col+7,$start_col+8,100) ; + # $worksheet{$sheet} -> set_column($start_col+9,$start_col+16,15) ; + + + $worksheet{$sheet} -> set_column($start_col,$start_col,15) ; + $worksheet{$sheet} -> set_column($start_col+2,$start_col+2,50) ; + $worksheet{$sheet} -> set_column($start_col+4,$start_col+5,15) ; + $worksheet{$sheet} -> set_column($start_col+3,$start_col+3,5) ; + # $worksheet{$sheet} -> set_column($start_col+5,$start_col+5,20) ; + $worksheet{$sheet} -> set_column($start_col+1,$start_col+1,30) ; + $worksheet{$sheet} -> set_column($start_col+10,$start_col+11,100) ; + $worksheet{$sheet} -> set_column($start_col+12,$start_col+12,15) ; + $worksheet{$sheet} -> set_column($start_col+6,$start_col+9,15) ; + + my $heading_cnt = $start_col+11 ; + foreach (@extra_columns) { + $heading_cnt++ ; + &xlsxcreator_write_xlsx($sheet,$heading_row,$heading_cnt,"$_",$format100) ; + } + + foreach (@extra_columns2) { + $heading_cnt++ ; + &xlsxcreator_write_xlsx($sheet,$heading_row,$heading_cnt,"$_",$format101) ; + } + + } + + $worksheet{$summary_ws} -> set_row(0,10) ; + $worksheet{$rates_ws} -> set_row(0,10) ; + + &report_xlsx_export_footer('L',15,'event_invoicing_report') ; + + $fnsortcol = 0; + $fnsortorder = 'desc' ; + &common_min_extra_crumb("$lcpage","Search Screen") ; + + my $savebuttjs = ($count_outstanding > 0) ? '$("#invoice-form").submit();' : 'noty({text:"There are no costings to pay!",layout:"center",type:"error",timeout:3000});return;' ; + + $trigger_jquery_raw .= qq~\$("#savebutt").click(function() { + $savebuttjs + }); + + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub set_tick { + + my ($color,$tooltip) = @_ ; + + $tick{green} = qq~2~ ; + $tick{orange} = qq~1~ ; + $tick{red} = qq~0~ ; + + return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub set_cross { + + my ($color,$tooltip) = @_ ; + + $tick{green} = qq~2~ ; + $tick{orange} = qq~1~ ; + $tick{red} = qq~0~ ; + + return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub load_list_vars { + + my ($where,$where_min) = @_ ; + + our %quote_status = () ; + + # &db_min_ro('event_quotes',"id, quote_cancelled, quote_accepted, if(concat(quote_expiry, ' 00:00:00') < now(), 1, 0) as 'expired', quote_pending","$where",'',''); + # &db_min_ro('event_quotes',"id, quote_cancelled, quote_accepted, quote_pending, quote_completed","$where",'',''); + + my $t1 = "$table" ; + my $t2 = 'event_quotes_min' ; + our $tables = "$t1,$t2" ; + + &db_min_raw("SELECT e.id,e.quote_cancelled,e.quote_accepted,e.quote_pending,e.quote_completed,e.quote_rejected FROM $t1 AS e WHERE $where;"); + + foreach $row (@$rows_array_ref) { + for (0 .. $col_cnt){ + $db{$table}{@$row[0]}{$col_name{$_}} = @$row[$_] ; + } + } + + foreach my $id (keys %{$db{$table}}) { + if ($db{$table}{$id}{quote_cancelled} == 1){ + $quote_status{$id} = 1 ; + } elsif ($db{$table}{$id}{quote_accepted} == 1 || $db{$table}{$id}{quote_completed} == 1){ + $quote_status{$id} = 2 ; + } elsif ($db{$table}{$id}{quote_rejected} == 1){ + $quote_status{$id} = 3 ; + } elsif ($db{$table}{$id}{quote_pending} == 1) { + $quote_status{$id} = 4 ; + } + } + + our %availability = () ; + + &db_min_raw(" + SELECT e.event_quote_nr, e.user_id, e.category FROM events e + LEFT JOIN ( + select id, name, user_type FROM users WHERE user_type like '%casual%' + ) u on u.id = e.user_id ; + ") ; + + foreach $row (@$rows_array_ref) { + if (@$row[2] eq 'available') { + $availability{@$row[0]}{@$row[1]} = "Available" ; + } elsif (@$row[2] ne 'available' and @$row[2]) { + $availability{@$row[0]}{@$row[1]} = "Not Available" ; + } + } + + our %type_a_users = () ; + our %type_b_users = () ; + our %casual_names_from_ids = () ; + + &db_min_ro('users','id,name,user_type',"user_type LIKE 'casual%'",'','') ; + foreach my $id (keys %{$db{'users'}}){ + $type_a_users{$id} = "A" if $db{'users'}{$id}{user_type} eq "casual_a" ; + $type_b_users{$id} = "B" if $db{'users'}{$id}{user_type} eq "casual_b" ; + + # &common_debug("[$db{'users'}{$id}{user_type}] $db{'users'}{$id}{name}") ; + + $casual_names_from_ids{$id} = $db{'users'}{$id}{name} ; + } + + my @event_quote_ids = () ; + + # &db_min_ro($table,'*',"$where",'','') ; + + # &db_min_ro('event_quotes_min','*',"$where_min",'','') ; + + $where .= " AND $where_min" if $where_min ; + + &db_min_raw("SELECT e.id,e.type,e.invoice_nr,e.qty,e.ref,e.date_from,e.date_to,e.quote_completed,e.event_length,e.times_from,e.times_to,m.* FROM $t1 e LEFT JOIN $t2 m ON e.id = m.id WHERE $where;"); + + foreach $row (@$rows_array_ref) { + for (0 .. $col_cnt){ + # &common_debug("[$_] $col_name{$_} -> @$row[$_]") ; + $db{$tables}{@$row[0]}{$col_name{$_}} = @$row[$_] ; + + } + } + + &db_min_ro('event_cost_items','id,name','','','') ; + + &db_min_ro('event_types','id,name','','','') ; + + &db_min_ro('event_systems','*','','','') ; + + &db_min_ro('event_production_time','quote_id,event_system_production_seconds,event_system_cloud_recording_seconds','','','') ; + + our %total_seconds = () ; + + foreach my $quote_id (keys %{$db{event_production_time}}) { + foreach (split(/\|/,$db{event_production_time}{$quote_id}{event_system_production_seconds})) { + my @a = split(":",$_) ; + $total_seconds{production_hours}{$quote_id}{$a[0]} += $a[1] ; + } + foreach (split(/\|/,$db{event_production_time}{$quote_id}{event_system_cloud_recording_seconds})) { + my @a = split(":",$_) ; + $total_seconds{cloud_recording_hours}{$quote_id}{$a[0]} += $a[1] ; + } + } + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + our $lcpage = 'event-invoicing-report' ; + + &common_page_name ; + + our $table = 'event_quotes' ; + $page_title = 'Event Invoicing' ; + + $box_icon .= qq~ +
    + + + +
    + +
    + + + +
    + ~ ; + + $trigger_jquery_raw .= qq~ + function importDoc(t,b) { + dlgMdl("$useropts{'scripts'}/dialog/import.pl?"+t+"&"+b,"Import CSV",'','max-dialog') ; + } + function importUnmatched(t,b) { + dlgMdl("$useropts{'scripts'}/dialog/import_unmatched.pl?"+t+"&"+b,"Match Unmatched",'','max-dialog') ; + } + ~; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + $opts{client_id} = qq~~ ; + &common_min_select_opts('client_id','customers',"name",5,'','','','','','','') ; + + $print_box_content_rows .= &common_min_form_select('client_id','') ; + + # &common_min_select_opts('operator_id','users',"name",$i{operator_id},'','',"user_type LIKE 'casual%'") ; + $opts{event_quote_id} = qq~~ ; + &common_min_select_opts('event_quote_id','event_quotes',"ref",$i{event_quote_id},'','',"") ; + + $first_day_month = sprintf("%02d",$first_day_month) ; $first_day = sprintf("%02d",$first_day) ; + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-$now_mm-01") unless $i{date_from} ; + + my $days_in_month = Days_in_Month($now_year,$now_mm) ; + + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$days_in_month") ; + + $opts{paid_status} .= qq~~ ; + $opts{paid_status} .= qq~~ ; + $opts{paid_status} .= qq~~ ; + + $opts{event_costing_id} = qq~~ ; + &common_min_select_opts('event_costing_id','event_cost_items',"name",'','','','','','','','') ; + + $print_box_content_rows .= &common_min_form_select('event_costing_id') ; + $print_box_content_rows .= &common_min_form_select('event_quote_id') ; + $print_box_content_rows .= &common_min_form_select('paid_status') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# my $page = "$lcpage\s" ; + +my $page = "event-quotes" ; + +if ($s{no}) { $page = $lcpage ; } + +&common_min_table('id',$page,'list') ; + +our $savjqy = 1 ; + +# &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ; + +$extra_form_fields .= qq~ + + + + + + +~ ; + +$print_box_content_rows .= &common_min_forms_end('','','save') ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub screen4 { + +&common_min_alert_type ; + +print < + + + + $useropts{title} + + + + + + +
    + + + + + + + + +
    + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +use common ; +use report ; +use xlsxcreator ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/event_quotes.pl b/scripts/_FromProd/v1.0/event_quotes.pl new file mode 100644 index 0000000..a75460e --- /dev/null +++ b/scripts/_FromProd/v1.0/event_quotes.pl @@ -0,0 +1,5636 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); + # use Digest::MD5 qw(md5_hex); + +require cfg ; + +print header; # CGI.pm method + +# unless ($username eq 'handre'or $username eq 'rory') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; +use LWP::Simple qw($ua get); +use JSON ; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $redirtype = 'search' ; + +# our $testing = 1 ; +# our $debug = 1 ; +# &common_debug("glod_user_level = $glod_user_level [$usertype]") ; + +# unless ($username eq 'rory') { print ">>>> DEVELOPMENT IN PROGRESS <<<<" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +if ($is_operator && $glod_user_level == 2) { $glod_user_level = 3 ; } # upgrade operators level 2&3 to 3&4 + +our $nr_of_system_names_and_clubs = 15 ; our @all_select_ids = () ; our $minify_jquery = 1 ; + +our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +&db_open_ro; + $db_ignore_open_close=1; + + &page_opts ; + + if ($iaction eq 'filter' || $iaction eq 'search' || $iaction eq 'report'){ + our $srchscr = 1 ; + our $savjqy = 0 ; + } + + #------------------------------------------------------------------------------------------------------------------------------------------------------------------ + + our $table = 'event_quotes'; + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # use File::Copy; + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # use File::Path 'make_path'; + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my $src_dir = "$htmlpath/uploads/uploads/7408"; + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my $dst_dir = "$htmlpath/uploads/uploads/test_copy"; + + + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # return unless -d $src_dir ; + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # mkdir $dst_dir unless -d $dst_dir ; + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # opendir(my $dh, $src_dir) or die "Can't open $src_dir: $!"; + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my $file_counter = 0 ; + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my @files = readdir($dh); + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # foreach my $file (@files) { + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # next if $file =~ /^\.\.?$/ ; + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my $src_file = "$src_dir/$file"; + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my $dst_file = "$dst_dir/$file"; + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # if(-f $src_file) { + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # copy("$src_file", " $dst_file") or die "File cannot be copied." ; + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # } + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # } + + # while (my $file = readdir($dh)) { + # next if $file =~ /^\.\.?$/; # Skip '.' and '..' + # last if !$file || $file_counter >= 3 ; + # my $src_file = "$src_dir/$file"; + # my $dst_file = "$dst_dir/$file"; + # # print "\n 21 copy : $src_file, $dst_file" ; + # # system("cp", $src_file, $dst_file) == 0 or die "Failed to copy $src_file to $dst_file: $!"; + # # print "Successfully copied $src_file to $dst_file\n"; + # # if (copy($src_file, $dst_file)) { + # # print "Successfully copied $src_file to $dst_file\n"; + # # } else { + # # print "\nFailed to copy $src_file to $dst_file: $!"; + # # } + # $file_counter++ ; + # } + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # closedir($dh); + + # while (1) { + # print "\n Hello World" ; + # last ; + # } + + # use File::Copy; + # use File::Path 'make_path'; + + # my $src_dir = "$htmlpath/uploads/uploads/7408"; + # my $dst_dir = "$htmlpath/uploads/uploads/test_copy"; + + # mkdir $dst_dir unless -d $dst_dir ; + + # opendir(my $dh, $src_dir) or die "Can't open $src_dir: $!"; + + # my $file_count = 0 ; + + # while (my $file = readdir($dh)) { + # next if $file =~ /^\.\.?$/; # Skip '.' and '..' + # $file_count++; + # last if $file_count == 3 ; + # } + + + + # print "\nfile $file_count" ; + # while (my $file = readdir($dh)) { + # my $src_file = "$src_dir/$file"; + # my $dst_file = "$dst_dir/$file"; + # # copy($src_dir, $dst_dir) or warn "Failed to copy $src_file to $dst_file: $!"; + # last ; + # } + + # closedir($dh); + + # for (7645 .. 20000) { + # my $src_dir = "$htmlpath/uploads/uploads/$_"; + # if (-d $src_dir) { + # rmdir $src_dir ; + # } + # } + + if ($iaction eq 'add') { + &add_screen ; + &common_min_screen1 ; + } elsif ($iaction eq 'edit') { + &common_min_load_params ; + &edit_screen ; + &common_min_screen1 ; + } elsif ($iaction eq 'save') { + # our $testing = 1 ; + &common_min_load_params ; + &insert ; + # &log_changes ; + &edit_or_list ; + } elsif ($iaction eq 'update') { + # our $testing = 1 ; + &common_min_load_params ; + &update ; + &log_changes ; + &edit_or_list ; + } elsif ($iaction eq 'copy') { + &common_min_load_params ; + &duplicate ; + &edit_screen ; + &common_min_screen1 ; + } elsif ($iaction eq 'delete') { + &common_min_load_params ; + &report_ifields ; + &delete ; + &common_min_screen2 ; + } + + &common_min_action ; + $db_ignore_open_close=0 ; +&db_close_conn ; +exit; + +#------------------------------------------------------------------------------------------ + +sub edit_or_list { + +exit if $testing && substr($username,0,4) eq 'rory' ; + +# if ($i{saveandexit} eq 'yes') { + # &list_screen ; + # &common_min_screen3; + # } +# else + # { + &edit_screen ; + &common_min_screen1; + # } + +} #------------------------------------------------------------------------------------------ + +sub insert { + + # &db_min_ro('users',"id,1 AS 'schools_manager'","`user_type`='schools_manager' AND `id`='$userid'",'','') ; + + # $i{quote_created} = 1 if $is_schools_manager ; + # $i{quote_created} = 1 if $glod_user_level < 4 ; + $i{quote_created} = 1 if $glod_user_level < 3 ; + $i{quote_pending} = 1 unless $i{quote_accepted} || $i{quote_cancelled} || $i{quote_completed} || $i{quote_rejected} ; + + our $i_quote_tab_default_full_half_items = qq~~ ; + + &process_cost_items_full_half_day ; + + &set_default_i_vals; + + my $quote_cancelled = $i{quote_cancelled} ; my $quote_accepted = $i{quote_accepted} ; my $quote_rejected = $i{quote_rejected} ; + + # $i{operator_ids} = '' ; + &build_event_details_fields($quote_accepted,$quote_rejected,$quote_cancelled) ; + &process_multi_select($quote_accepted,$quote_rejected,$quote_cancelled) ; + # &process_times_from ; + &add_db_fields ; + + $i{last_update} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{datetime} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{user_id} = $userid ; + + # &creat_db_cols; + + $i{id} = &db_min_get_max($table,'id') ; + + &upload_aisa_files ; + + &process_upload_ifields; + + &build_working_fields($i{id},$quote_accepted,$quote_rejected,$quote_cancelled) ; + + $i{quote_nr} = $i{id} ; + my $quote_nr = $i{quote_nr} ; + + $ignore{selected_event_length} = 1 ; + # $i{event_length} = $i{selected_event_length} ; + + $i{custom_set} = 0 unless $i{custom_set} ; + + foreach (keys %i) { + next if $ignore{$_} ; + &common_debug(" $_ : $i{$_}") ; + } + + &db_min_insert($table) ; + + &build_event_quotes_min_fields($quote_accepted,$quote_rejected,$quote_cancelled) ; + $i{quote_nr} = $quote_nr ; + + # our $line = qq~$now_year$now_year$now_mm$now_dd$now_hour$now_min$now_sec|$now_year-$now_mm-$now_dd $now_hour:$now_min:$now_sec|event_quote_id='$i{id}'|user_id=$userid|action='Add'|~ ; + # foreach (keys %i) { + # next if $hidden{$_} == 1 || $ignore{$_} ; + + # $line .= qq~$_='$i{$_}',~ ; + # } + + $i{quote_tab_default_full_half_items} = $i_quote_tab_default_full_half_items ; + + &db_min_insert('event_quotes_min') ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + unless ($i{id}) { + $error = qq(NO ID) ; + return ; + } + + our $i_quote_tab_default_full_half_items = qq~~ ; + + $i{operator_ids} = '' ; + + &process_cost_items_full_half_day ; + + our $quote_accepted = $i{quote_accepted} ; + our $status = &common_status_txt($i{quote_completed},$i{quote_accepted},$i{quote_pending},$i{quote_cancelled},$i{quote_rejected}) ; + + # &db_min_ro($table,"id,quote_accepted,grand_total,operator_ids,quote_cancelled,quote_rejected,demo_id,poc_id,recipient_id","`id`='$i{id}'",'','') ; + &db_min_ro($table,"*","`id`='$i{id}'",'','') ; + + &set_default_i_vals ; + + my $quote_cancelled = $db{$table}{$i{id}}{quote_cancelled} ; + my $quote_accepted = $db{$table}{$i{id}}{quote_accepted} ; + my $quote_rejected = $db{$table}{$i{id}}{quote_rejected} ; + + &build_event_details_fields($quote_accepted,$quote_rejected,$quote_cancelled) ; + + &process_multi_select($quote_accepted,$quote_rejected,$quote_cancelled) ; + &edit_db_fields ; + + # &creat_db_cols ; + + $i{last_update} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + + &upload_aisa_files ; + + &process_upload_ifields ; + # &process_times_from ; + + our $hidden_expenses_amounts_exist = 0 ; + + &build_working_fields($i{id},$quote_accepted,$quote_rejected,$quote_cancelled) ; + + $i{quote_nr} = $i{id} ; + my $quote_nr = $i{quote_nr} ; + + $ignore{selected_event_length} = 1 ; + # $i{event_length} = $i{selected_event_length} ; + + $i{custom_set} = 0 unless $i{custom_set} ; + + # &db_min_ro($table,"*","`id`='$i{id}'",'','') ; + + # our $line = qq~~ ; + + # my %col_to_be_updated = () ; my %ignore_for_now = () ; + + # foreach (keys %i) { + # $col_to_be_updated{$_} = 1 ; + # } + + # foreach my $col (keys %{$db{$table}{$i{id}}}) { + # next if $ignore{$col} or $hidden{$col} == 1 or substr($col,0,3) eq 'new' or not $col_to_be_updated{$col} ; + # if (($i{$col} or $db{$table}{$i{id}}{$col}) and $db{$table}{$i{id}}{$col} ne $i{$col}) { + # # $line .= qq~$col='$i{$col}',~ ; + # $line .= qq~$col='$db{$table}{$i{id}}{$col}',~ ; + # } elsif ((not $i{$col} and not $db{$table}{$i{id}}{$col}) or (($i{$col} or $db{$table}{$i{id}}{$col}) and $db{$table}{$i{id}}{$col} eq $i{$col})) { + # $ignore{$col} = 1 ; $ignore_for_now{$col} = 1 ; + # } + # } + + + # &db_min_upd($table,"id='$i{id}'") ; + + our $line = qq~~ ; + + &common_shared_log_update_changes($table) ; + + our %sss = %i if $db{$table}{$i{id}}{sss_quote_nr} ; + + &build_event_quotes_min_fields($quote_accepted,$quote_rejected,$quote_cancelled) ; + $i{quote_nr} = $quote_nr ; + + &common_shared_log_update_changes("event_quotes_min","event_quotes_changes","changes") ; + + # &db_min_ro('event_quotes_min','*',"id='$i{id}'",'','') ; + + # foreach (keys %i) { + # $col_to_be_updated{$_} = 1 ; + # } + + # foreach my $col (keys %{$db{event_quotes_min}{$i{id}}}) { + # next if $ignore{$col} or $hidden{$col} == 1 or substr($col,0,3) eq 'new' or not $col_to_be_updated{$col} ; + # if (($i{$col} or $db{event_quotes_min}{$i{id}}{$col}) and $db{event_quotes_min}{$i{id}}{$col} ne $i{$col}) { + # # $line .= qq~$col='$i{$col}',~ ; + # $line .= qq~$col='$db{event_quotes_min}{$i{id}}{$col}',~ ; + # } elsif ((not $i{$col} and not $db{event_quotes_min}{$i{id}}{$col}) or (($i{$col} or $db{event_quotes_min}{$i{id}}{$col}) and $db{event_quotes_min}{$i{id}}{$col} eq $i{$col})) { + # $ignore{$col} = 1 ; $ignore_for_now{$col} = 1 ; + # } + # } + + # $line = qq~$now_year$now_year$now_mm$now_dd$now_hour$now_min$now_sec|$now_year-$now_mm-$now_dd $now_hour:$now_min:$now_sec|event_quote_id='$i{id}'|user_id=$userid|changed_from|~ . $line if $line ; + + # $i{quote_tab_default_full_half_items} = $i_quote_tab_default_full_half_items ; + + # &db_min_upd('event_quotes_min',"id='$i{id}'") ; + + # foreach (keys %ignore_for_now) { + # $ignore{$_} = '' ; + # } + + &sync_to_sss ; + +} #------------------------------------------------------------------------------------------ + +sub upload_aisa_files { + + + my $attachmentdir = $htmlpath . "/uploads/uploads/$i{id}" ; + mkdir $attachmentdir if not -d $attachmentdir and ($i{iattachupload_1} or $i{iattachupload_2} or $i{iattachupload_3}) ; + + $ignore_attach{iattachslip} = 1 ; + + &common_upload_files("uploads/$i{id}") ; + + $attachmentdir = $htmlpath . "/uploads/slips/$i{id}" ; + mkdir $attachmentdir if not -d $attachmentdir and $i{iattachslip} ; + + $ignore_attach{iattachslip} = '' ; + $ignore_attach{iattachupload_1} = 1 ; + $ignore_attach{iattachupload_2} = 1 ; + $ignore_attach{iattachupload_3} = 1 ; + + &common_upload_files("slips/$i{id}") ; + +} #------------------------------------------------------------------------------------------ + +sub process_cost_items_full_half_day { + + # &db_min_ro('event_cost_items','id','','','') ; + &db_min_ro('event_cost_items','id',"excl_from_expenses < 1",'','') ; + + foreach (keys %{$db{event_cost_items}}) { + $ignore{"full_costing_event_$_"} = 1 ; + $ignore{"full_workings_event_$_"} = 1 ; + $ignore{"half_costing_event_$_"} = 1 ; + $ignore{"half_workings_event_$_"} = 1 ; + # $ignore{"prev_item_costing_event_$_"} = 1 ; + # $ignore{"prev_item_workings_event_$_"} = 1 ; + } + + for (1 .. 100) { + $ignore{"added_full_day_cost_item_$_"} = 1 ; + $ignore{"added_half_day_cost_item_$_"} = 1 ; + $i_quote_tab_default_full_half_items .= ($i{"added_full_day_cost_item_$_"}) ? qq~1:$i{"added_full_day_cost_item_$_"};~ : ($i{"added_half_day_cost_item_$_"}) ? qq~2:$i{"added_half_day_cost_item_$_"};~ :qq~;~ ; + } + + $i_quote_tab_default_full_half_items =~ s/;+$//; + +} #------------------------------------------------------------------------------------------ + +sub sync_to_sss { + + return unless $db{$table}{$i{id}}{sss_quote_nr} ; + + my $sss_quote_nr = $db{$table}{$i{id}}{sss_quote_nr} ; + + &db_switch_conn('sss'); + + my $reload_quote_id = $i{id} ; + + %i = () ; %ignore = () ; + + &db_min_ro('event_quotes','1,supplier_type_ids',"id='$sss_quote_nr'",'','') ; + + my $cnt = 0 ; + + $i{supplier_type_ids} = $sss{supplier_type_ids} ; + + foreach (sort split(/\;/,$db{event_quotes}{1}{supplier_type_ids})) { + if ($_ ne '4' && $_ ne '5' && $_ ne '6' && $_ ne '7' && $_ ne '8') { + $i{supplier_type_ids} .= ($i{supplier_type_ids}) ? qq~;$_~ : qq~$_~ ; + } + } + + # if ($sss{type} eq '10' && $db{event_quotes}{1}{supplier_type_ids} !~ /\b8\b/) { + # foreach (split(/\;/,$db{event_quotes}{1}{supplier_type_ids})) { + # $i{supplier_type_ids} .= qq~$_;~ if $_ ne '4' && $_ ne '5' && $_ ne '6' && $_ ne '7' && $_ ne '8' ; + # } + # $i{supplier_type_ids} .= qq~8~ ; + # } elsif ($sss{type} eq '13' && $db{event_quotes}{1}{supplier_type_ids} !~ /\b7\b/) { + # foreach (split(/\;/,$db{event_quotes}{1}{supplier_type_ids})) { + # $i{supplier_type_ids} .= qq~$_;~ if $_ ne '4' && $_ ne '5' && $_ ne '6' && $_ ne '7' && $_ ne '8' ; + # } + # $i{supplier_type_ids} .= qq~7~ ; + # } elsif ($sss{type} eq '3' && $db{event_quotes}{1}{supplier_type_ids} !~ /\b6\b/) { + # foreach (split(/\;/,$db{event_quotes}{1}{supplier_type_ids})) { + # $i{supplier_type_ids} .= qq~$_;~ if $_ ne '4' && $_ ne '5' && $_ ne '6' && $_ ne '7' && $_ ne '8' ; + # } + # $i{supplier_type_ids} .= qq~6~ ; + # } elsif ($sss{type} eq '2' && $db{event_quotes}{1}{supplier_type_ids} !~ /\b5\b/) { + # foreach (split(/\;/,$db{event_quotes}{1}{supplier_type_ids})) { + # $i{supplier_type_ids} .= qq~$_;~ if $_ ne '4' && $_ ne '5' && $_ ne '6' && $_ ne '7' && $_ ne '8' ; + # } + # $i{supplier_type_ids} .= qq~5~ ; + # } + + $i{datetime} = $sss{datetime} ; + $i{last_update} = $sss{last_update} ; + $i{quote_date} = $sss{quote_date} if $sss{quote_date} ; + $i{date_from} = $sss{date_from} if $sss{date_from} ; + $i{date_to} = $sss{date_to} if $sss{date_to} ; + $i{qty} = $sss{qty} || 1 ; + $i{times_from} = $sss{times_from} if $sss{times_from} ; + $i{times_to} = $sss{times_to} if $sss{times_to} ; + $i{days_active} = $sss{days_active} if $sss{days_active} ; + $i{event_length} = $sss{event_length} if $sss{event_length} ; + + $i{quote_pending} = $sss{quote_pending} ; + $i{quote_accepted} = $sss{quote_accepted} ; + $i{quote_cancelled} = $sss{quote_cancelled} ; + $i{quote_completed} = $sss{quote_completed} ; + $i{quote_rejected} = $sss{quote_rejected} ; + $i{ref} = $sss{ref} ; + $i{quote_to} = $sss{quote_to} ; + $i{notes} = $sss{notes} ; + $i{office_notes} = $sss{office_notes} ; + $i{poc_id} = $sss{poc_id} ; + # $i{poc_name} = $sss{poc_name} ; + # $i{poc_contact_nr} = $sss{poc_contact_nr} ; + # $i{festival_league_name} = $sss{festival_league_name} ; + $i{category_id_1} = $sss{category_id_1} ; + $i{category_id_2} = $sss{category_id_2} ; + my $category_details = ($sss{category_1_details} || $sss{category_2_details}) ? qq~$sss{category_1_details}|;|$sss{category_2_details}~ : qq~~ ; + $i{category_details} = $category_details ; + $i{recipient_id} = $sss{recipient_id} ; + # $i{recipient_name} = $sss{recipient_name} ; + # $i{recipient_nr} = $sss{recipient_nr} ; $ignore{recipient_nr} = 0 ; + $i{additional_notes} = $sss{additional_notes} ; + $i{linear_id} = $sss{linear_id} ; + $i{nr_of_units} = $sss{nr_of_systems} ; + $i{organisation_ids} = $sss{organisation_ids} ; + $i{city_ids} = $sss{city_id} ; $i{city_ids} =~ s/\,/\;/g ; $ignore{city_ids} = 0 ; + $i{region_id} = $sss{region_id} ; + $i{sport_type_ids} = $sss{sport_type_ids} ; $i{sport_type_ids} =~ s/\,/\;/g ; + + $i{upload_1} = $sss{upload_1} ; + $i{upload_2} = $sss{upload_2} ; + $i{upload_3} = $sss{upload_3} ; + + $ignore{upload_1} = (!$i{upload_1}) ? 1 : 0 ; + $ignore{upload_2} = (!$i{upload_2}) ? 1 : 0 ; + $ignore{upload_3} = (!$i{upload_3}) ? 1 : 0 ; + + $i{event_system_id_multiple} = $sss{event_system_id_multiple} ; + $i{club_ids} = $sss{club_ids} ; + + &db_min_upd($table,"id='$sss_quote_nr'") ; + + #______________ Copying Files to SSS + + $i{iattachupload_1} = $sss{iattachupload_1} ; + $i{iattachupload_2} = $sss{iattachupload_2} ; + $i{iattachupload_3} = $sss{iattachupload_3} ; + + my $to_dir = $htmlpath_sss . "/uploads/uploads/$sss_quote_nr" ; + + our $upload_files_to_sss = 1 ; + + my $from_dir = "$htmlpath/uploads/uploads/$reload_quote_id" ; + + $i{iattachupload_1} = &common_process_uploaded_file_names($i{iattachupload_1},"upload_1") if $i{iattachupload_1} ; + $i{iattachupload_2} = &common_process_uploaded_file_names($i{iattachupload_2},"upload_2") if $i{iattachupload_2} ; + $i{iattachupload_3} = &common_process_uploaded_file_names($i{iattachupload_3},"upload_3") if $i{iattachupload_3} ; + + &common_min_copy_files($from_dir,$to_dir,"$i{iattachupload_1}") if $i{iattachupload_1} ; + &common_min_copy_files($from_dir,$to_dir,"$i{iattachupload_2}") if $i{iattachupload_2} ; + &common_min_copy_files($from_dir,$to_dir,"$i{iattachupload_3}") if $i{iattachupload_3} ; + + $upload_files_to_sss = 0 ; + + #______________ Copying Files to SSS + + &db_switch_conn('aisa'); + + # foreach (keys %sss) { + # $i{$_} = $sss{$_} unless $ignore{$_} ; + # } + + $i{id} = $reload_quote_id ; + +} #------------------------------------------------------------------------------------------ + +sub log_changes { + + return unless $line ; + + chop $line ; + + &common_log_changes("events/changes.dat",$line) ; + + if ($db{$table}{$i{id}}{quote_accepted}) { # Can you change it that she only gets emails where an Accepted Event been edited by school manager and when they upload docs afterwards, She just need notification if there been changes to event she or anyone else already accepted it + # if (!$quote_accepted || $is_schools_manager || $glod_user_level < 4) { + if (!$quote_accepted || $is_schools_manager || $glod_user_level < 3) { + &send_email_to_manager($i{id},$status,$line) ; + } + } + +} #------------------------------------------------------------------------------------------ + +sub process_times_from { + + # for (1 .. 6) { + # $ignore{"time_from_$_"} = 1 ; + # $ignore{"time_to_$_"} = 1 ; + # $i{times_from} .= qq~$i{"time_from_$_"};~ if $_ > 1 ; + # $i{times_to} .= qq~$i{"time_to_$_"};~ if $_ < 6 ; + # } + # chop $i{times_from} if $i{times_from} ; + # chop $i{times_to} if $i{times_to} ; + +} #------------------------------------------------------------------------------------------ + +sub send_email_to_manager { + + my ($event_id,$status,$msg) = @_ ; + + return if $username eq 'marizen' ; # don't send to marizen if she did the change. + + my $usernametemp = (substr($username,0,4) eq 'rory') ? 'rory' : $username ; + + my $attachpath = "$pdfpath/event_details" ; $attachfile = "Event_Details-$event_id.pdf" ; + + my $subj = 'Event [' . $event_id . ']' ; + $subj .= " $status" if $status ; + $subj .= " by $username" if $username ; + $subj .= " : $i{ref}" if $i{ref} ; + + my $event_details_pdf = get("$useropts{domain}$useropts{'scripts'}/pdf/event_details_pdf.pl?$event_id&&") ; + my $to = ($useropts{it}{$usernametemp}) ? "$usernametemp\@kre8it.co.za" : $email_events{1} ; + $got_mail_add{$to} = 1 ; + my $cc = ($is_schools_manager) ? "$useremail" : (!$got_mail_add{$useremail}) ? "$useremail" : '' ; + # my $bcc = ($useropts{it}{$usernametemp}) ? '' : 'rory@kre8it.co.za' ; + my $bcc = '' ; + &common_send_smtp_mail('',$to,$cc,$bcc,"$subj","Click here to view event details

    $msg",'','html','',$attachpath,$attachfile,'',0,0) ; + +} #------------------------------------------------------------------------------------------ + +sub build_event_details_fields { + + my ($quote_accepted,$quote_rejected,$quote_cancelled) = @_ ; + + # $i{operator_ids} .= qq~;\~;~ ; + + our $cnt_last_system_row = 0 ; + + for (1 .. $nr_of_system_names_and_clubs) { + + $cnt_last_system_row = $_ if $i{"system_name_$_"} || $i{"club_name_$_"} ; + + my $system_name = "system_name_$_" ; + my $club_name = "club_name_$_" ; + my $op_name = "operator_id_calibration_$_" ; + # my $sss_fixed_systems = "sss_fixed_systems_$_" ; + $ignore{$system_name} = 1 ; + $ignore{$club_name} = 1 ; + $ignore{$op_name} = 1 ; + # $ignore{$sss_fixed_systems} = 1 ; + + } + + return if ($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3 ; + + unless ($cnt_last_system_row) { + $i{club_ids} = qq~~ ; + $i{event_system_id_multiple} = qq~~ ; + return ; + } + + # return if $is_schools_manager ; + # return if $glod_user_level < 4 ; + # return if $glod_user_level < 3 ; + + $i{operator_ids} = '' ; + + # our $cnt_rows = 0 ; + + my $sss_fixed_systems_exists = 0 ; + + my @saved_system_ids = split(/\;/,$db{$table}{$i{id}}{event_system_id_multiple}) ; + + my %sss_fixed_system = () ; + foreach (@saved_system_ids) { + my $system_id_ = $_ ; + $system_id_ =~ s/f-//g ; + $sss_fixed_system{$system_id_} = 1 if $_ =~ /f-/ ; + } + + for my $event_row (1 .. $nr_of_system_names_and_clubs) { + + my $op_name = "operator_id_calibration_$event_row" ; + $i{operator_ids} .= ($event_row <= $cnt_last_system_row || ($event_row > $cnt_last_system_row && $i{$op_name})) ? qq~$i{$op_name},~ : qq~~ ; + + next if $event_row > $cnt_last_system_row ; + + # my $sss_fixed_systems = "sss_fixed_systems_$event_row" ; + # $sss_fixed_systems_exists = 1 if $i{$sss_fixed_systems} ; + # next if $i{$sss_fixed_systems} ; + + my $system_name = "system_name_$event_row" ; + my $club_name = "club_name_$event_row" ; + + # next if !$i{$system_name} && !$i{$club_name} ; + + # $cnt_rows++ ; + + $i{club_ids} .= qq~$i{$club_name};~ ; + + # $i{event_system_id_multiple} .= ($i{$sss_fixed_systems}) ? qq~f-$i{$system_name};~ : qq~$i{$system_name};~ ; + + # my $saved_system_id = $saved_system_ids[$event_row-1] ; + # $saved_system_id =~ s/f-//g ; + + $i{event_system_id_multiple} .= ($i{$system_name} && $sss_fixed_system{$i{$system_name}}) ? qq~f-$i{$system_name};~ : (!$i{$system_name} && $saved_system_ids[$event_row - 1] =~ /f-/) ? qq~$saved_system_ids[$event_row - 1];~ : qq~$i{$system_name};~ ; + + # &process_system_club_operator($event_row) ; + + } + + # if ($sss_fixed_systems_exists) { + # for my $event_row (1 .. $nr_of_system_names_and_clubs) { + + # my $sss_fixed_systems = "sss_fixed_systems_$event_row" ; + # next if !$i{$sss_fixed_systems} ; + # process_system_club_operator($event_row) ; + + # } + # } + + $ignore{club_name} = 1 ; + + $i{club_ids} =~ s/;+$//; + $i{event_system_id_multiple} =~ s/;+$//; + + if ($i{event_system_id_multiple} =~ /f-/) { + + my @upd_systems = split(/\;/,$i{event_system_id_multiple}) ; + if ($upd_systems[-1] !~ /f-/) { + $i{event_system_id_multiple} =~ s/f-//g ; + } else { + my $cnt__ = 0 ; + foreach (@upd_systems) { + if ($upd_systems[$cnt__] =~ /f-/ && $upd_systems[$cnt__ + 1] && $upd_systems[$cnt__ + 1] !~ /f-/) { + $i{event_system_id_multiple} =~ s/f-//g ; + last ; + } + $cnt__++ ; + } + } + } + + # chop $i{club_ids} if $i{club_ids} ; + # chop $i{event_system_id_multiple} if $i{event_system_id_multiple} ; + + # chop $i{operator_ids} if $i{operator_ids} ; + +} #------------------------------------------------------------------------------------------ + +# sub process_system_club_operator { + + # my ($event_row) = @_ ; + + # my $system_name = "system_name_$event_row" ; + # my $club_name = "club_name_$event_row" ; + # my $op_name = "operator_id_calibration_$event_row" ; + + # return if !$i{$system_name} && !$i{$club_name} ; + + # $cnt_rows++ ; + + # $i{club_ids} .= qq~$i{$club_name};~ ; + # $i{event_system_id_multiple} .= ($i{$sss_fixed_systems}) ? qq~f-$i{$system_name};~ : qq~$i{$system_name};~ ; + # $i{operator_ids} .= qq~$i{$op_name},~ if $cnt_rows <= $cnt_last_row ; + +# } #------------------------------------------------------------------------------------------ + +sub process_daily_details_from_the_events_datails_tab { + + my ($id) = @_ ; + + use Time::Piece ; + + # my $final_day = 0 ; + # for (1 .. 20) { + # $final_day = $_ if $i{"day_$_"} ; + # } + + my $final_day = &common_min_calc_day_diff($i{date_to},$i{date_from}) ; + + for my $event_day (1 .. 20) { + + $ignore{"time_from_$event_day"} = 1 ; + $ignore{"time_to_$event_day"} = 1 ; + $ignore{"day_$event_day"} = 1 ; + $ignore{"event_length_$event_day"} = 1 ; + $ignore{"selected_$event_day\_event_length"} = 1; + + $i{times_from} .= qq~$i{"time_from_$event_day"};~ if $event_day > 1 && $i{"day_$event_day"} ; + $i{times_from} .= qq~;~ if $event_day > 1 && !$i{"day_$event_day"} ; + $i{times_to} .= qq~$i{"time_to_$event_day"};~ if $event_day < $final_day && $i{"day_$event_day"}; + $i{times_to} .= qq~;~ if $event_day < $final_day && !$i{"day_$event_day"}; + $i{days_active} .= qq~$i{"day_$event_day"};~ ; + $i{event_length} .= ($i{"day_$event_day"}) ? qq~$i{"event_length_$event_day"};~ : qq~;~ ; + + } + + # my $sss_fixed_systems_exists = 0 ; + + for my $event_row (1 .. $nr_of_system_names_and_clubs) { + + # my $sss_fixed_systems = "sss_fixed_systems_$event_row" ; + # $sss_fixed_systems_exists = 1 if $i{$sss_fixed_systems} ; + # next if $i{$sss_fixed_systems} ; + # &process_daily_operator_ids($event_row) ; + + $ignore{"clicked_button_$event_row"} = 1 ; + + my $system_name = "system_name_$event_row" ; + my $club_name = "club_name_$event_row" ; + + # if (!$i{$system_name} && !$i{$club_name}) { + + if ($cnt_last_system_row < $event_row) { + for my $event_day (1 .. 20) { + $ignore{"custom_operator_$event_row\_$event_day"} = 1 ; + } + next ; + } + + for my $event_day (1 .. 20) { + $ignore{"custom_operator_$event_row\_$event_day"} = 1 ; + if ($i{"clicked_button_$event_row"}) { + $i{"custom_operator_$event_row\_$event_day"} = "" unless $i{"day_$event_day"} ; + $i{daily_operator_ids} .= qq~$i{"custom_operator_$event_row\_$event_day"};~ ; + } + } + + # chop $i{daily_operator_ids} if $i{daily_operator_ids} && $i{"clicked_button_$event_row"} ; + $i{daily_operator_ids} =~ s/;+$//; + $i{daily_operator_ids} .= qq~|~ ; + + } + + # if ($sss_fixed_systems_exists) { + # for my $event_row (1 .. $nr_of_system_names_and_clubs) { + # my $sss_fixed_systems = "sss_fixed_systems_$event_row" ; + # next if !$i{$sss_fixed_systems} ; + # &process_daily_operator_ids($event_row) ; + # } + # } + + $i{daily_operator_ids} =~ s/\|+$//; + + # chop $i{daily_operator_ids} if $i{daily_operator_ids} ; + # chop $i{times_from} if $i{times_from} ; + # chop $i{times_to} if $i{times_to} ; + # chop $i{days_active} if $i{days_active} ; + # chop $i{event_length} if $i{event_length} ; + + $i{times_from} =~ s/([^;])(;+)\z/$1/; + $i{times_to} =~ s/([^;])(;+)\z/$1/; + $i{days_active} =~ s/([^;])(;+)\z/$1/; + $i{event_length} =~ s/([^;])(;+)\z/$1/; + + # $ignore{daily_operator_ids} = 1 if $i{daily_operator_ids} eq $db{$table}{$id}{daily_operator_ids} ; + # $ignore{times_from} = 1 if $i{times_from} eq $db{$table}{$id}{times_from} ; + # $ignore{times_to} = 1 if $i{times_to} eq $db{$table}{$id}{times_to} ; + # $ignore{days_active} = 1 if $i{days_active} eq $db{$table}{$id}{days_active} ; + # $ignore{event_length} = 1 if $i{event_length} eq $db{$table}{$id}{event_length} ; + +} #------------------------------------------------------------------------------------------ + +# sub process_daily_operator_ids { + + # my ($event_row) = @_ ; + + # $ignore{"clicked_button_$event_row"} = 1 ; + + # my $system_name = "system_name_$event_row" ; + # my $club_name = "club_name_$event_row" ; + + # if (!$i{$system_name} && !$i{$club_name}) { + # for my $event_day (1 .. 20) { + # $ignore{"custom_operator_$event_row\_$event_day"} = 1 ; + # } + # return ; + # } + + # for my $event_day (1 .. 20) { + # $ignore{"custom_operator_$event_row\_$event_day"} = 1 ; + # if ($i{"clicked_button_$event_row"}) { + # $i{"custom_operator_$event_row\_$event_day"} = "" unless $i{"day_$event_day"} ; + # $i{daily_operator_ids} .= qq~$i{"custom_operator_$event_row\_$event_day"};~ ; + # } + # } + + # chop $i{daily_operator_ids} if $i{daily_operator_ids} && $i{"clicked_button_$event_row"} ; + # $i{daily_operator_ids} .= qq~|~ ; + +# } #------------------------------------------------------------------------------------------ + +sub build_working_fields { + + my ($id,$quote_accepted,$quote_rejected,$quote_cancelled) = @_ ; + + if (($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) { + + ### ADD IGNORE WITH EVENT SYSTEM NAME TABLE + for my $col (1 .. 20) { + $ignore{"time_from_$col"} = 1 ; + $ignore{"time_to_$col"} = 1 ; + $ignore{"day_$col"} = 1 ; + for (1 .. 15) { + $ignore{"custom_operator_$_\_$col"} = 1 ; + } + } + $ignore{total_amount_workings_event} = 1 ; + $ignore{total_vat_amount_workings_event} = 1 ; + $ignore{total_grand_amount_workings_event} = 1 ; + + return ; + } + + # if ($glod_user_level < 3) { + # $ignore{daily_operator_ids} = 1 ; + # $ignore{event_length} = 1 ; + # $ignore{times_from} = 1 ; + # $ignore{times_to} = 1 ; + # $ignore{event_length} = 1 ; + # } + + &process_daily_details_from_the_events_datails_tab($id) ; + + my $diplayed_exp_tab = 0 ; my $hidden_exp_tab = 0 ; + if ($glod_user_level > 3) { + # if ($glod_user_level > 2) { + $diplayed_exp_tab = 1 ; + } elsif ($glod_user_level < 4) { + # } elsif ($glod_user_level < 3) { + $hidden_exp_tab = 1 ; + # $ignore{sub_total} = 1 ; + # $ignore{vat_total} = 1 ; + # $ignore{grand_total} = 1 ; + } + + # return if !$diplayed_exp_tab && !$hidden_exp_tab ; + + $i{sub_total} = $i{sub_total_costing_event} ; + $i{vat_total} = $i{vat_total_costing_event} ; + $i{grand_total} = $i{grand_total_costing_event} ; + # $i{profit_loss} =~ s/\,//g ; + # $i{sub_total} =~ s/\,//g ; + # $i{vat_total} =~ s/\,//g ; + # $i{grand_total} =~ s/\,//g ; + + $ignore{sub_total_workings_event} = 1 ; + $ignore{vat_total_workings_event} = 1 ; + $ignore{grand_total_workings_event} = 1 ; + $ignore{sub_total_costing_event} = 1 ; + $ignore{vat_total_costing_event} = 1 ; + $ignore{grand_total_costing_event} = 1 ; + $ignore{sub_total} = 1 if $i{sub_total} eq $db{$table}{$id}{sub_total} ; + $ignore{vat_total} = 1 if $i{vat_total} eq $db{$table}{$id}{vat_total} ; + $ignore{grand_total} = 1 if $i{grand_total} eq $db{$table}{$id}{grand_total} ; + + for (1 .. 50) { + + $y{1}{$_} = "excl_costing_event_$_" ; + $y{2}{$_} = "description_costing_event_$_" ; + $y{3}{$_} = "qty_costing_event_$_" ; + $y{4}{$_} = "amount_usd_costing_event_$_" ; + $y{5}{$_} = "amount_ttl_costing_event_$_" ; + $y{6}{$_} = "vat_costing_event_$_" ; + $y{7}{$_} = "excl_workings_event_$_" ; + $y{8}{$_} = "description_workings_event_$_" ; + $y{9}{$_} = "operator_workings_event_$_" ; + $y{10}{$_} = "remarks_workings_event_$_" ; + $y{11}{$_} = "supplier_workings_event_$_" ; + $y{12}{$_} = "ref_nr_workings_event_$_" ; + $y{13}{$_} = "qty_workings_event_$_" ; + $y{14}{$_} = "amount_usd_workings_event_$_" ; + $y{15}{$_} = "amount_ttl_workings_event_$_" ; + $y{16}{$_} = "vat_workings_event_$_" ; + # $y{17}{$_} = "curr_amnt_costing_event_$_" ; + + $hidden_expenses_amounts_exist = ($hidden_expenses_amounts_exist || ($glod_user_level < 4 && ($y{8}{$_} || $y{9}{$_} || $y{13}{$_} || $i{$y{14}{$_}} || $i{$y{15}{$_}}))) ? 1 : 0 ; + + foreach my $a (keys %y) { + foreach my $b (keys %{$y{$a}}) { + $ignore{$y{$a}{$b}} = 1 ; + $x{$a}{$b} = $i{$y{$a}{$b}} ; + } + } + } + + # return if $i{custom_set} ; + + if ($i{custom_set}) { + $i{total_amount_workings_event} = $i{sub_total_workings_event} ; + $i{total_vat_amount_workings_event} = $i{vat_total_workings_event} ; + $i{total_grand_amount_workings_event} = $i{grand_total_workings_event} ; + return ; + } + + $i{total_amount_workings_event} = 0 ; + $i{total_vat_amount_workings_event} = 0 ; + $i{total_grand_amount_workings_event} = 0 ; + + my %operator_day_count = () ; my %operator_row = () ; + my $operator_count = 0 ; + my %ii = () ; + + # $i{operator_ids} = $db{$table}{$id}{operator_ids} if $glod_user_level < 3 ; + + my @operator_ids = split(/\,/,$i{operator_ids}) ; + + &db_min_ro('event_systems','id,system_type','','','') ; + + for my $system_name_row_nr (1 .. $nr_of_system_names_and_clubs) { + + my $field4 = "system_name_$system_name_row_nr" ; + + # next if !$i{$field4} || $i{$field4} < 0 ; + + $i{$field4} = -1 if !$i{$field4} && $i{"clicked_button_$system_name_row_nr"} ; + + next unless $i{$field4} ; + + for my $days (1 .. 20) { + + my $day_field = "day_$days" ; + next unless $i{$day_field} ; + + my $field1 = "custom_operator_$system_name_row_nr\_$days" ; + my $field2 = "operator_id_calibration_$system_name_row_nr" ; + my $field3 = "event_length_$days" ; + + if ($i{$field1}) { + if ($i{$field4} eq '-1') { + $operator_day_count{blank_system}{$i{$field1}}++ ; + } elsif ($i{$field3} eq '1' && $db{event_systems}{$i{$field4}}{system_type} ne 'fixed') { #full day + $operator_day_count{afull_day_mobile}{$i{$field1}}++ ; + } elsif (($i{$field3} eq '1' && $db{event_systems}{$i{$field4}}{system_type} eq 'fixed') or ($i{$field3} eq '2' && $db{event_systems}{$i{$field4}}{system_type} ne 'fixed')) { #full day + $operator_day_count{bfull_day_fixed_half_day_mobile}{$i{$field1}}++ ; + } elsif ($i{$field3} eq '2' && $db{event_systems}{$i{$field4}}{system_type} eq 'fixed') { + $operator_day_count{chalf_day_fixed}{$i{$field1}}++ ; + } + } + } + } + + if ($i{operator_ids}) { + my $cnt = 0 ; + foreach my $op_id (@operator_ids) { + $cnt++ ; + next unless $op_id ; + my $field5 = "system_name_$cnt" ; + + $i{$field5} = -1 if !$i{$field5} && $i{"operator_id_calibration_$cnt"} ; + + # if ($i{$field5} && $i{$field5} > 0) { + + for my $days (1 .. 20) { + my $day_field = "day_$days" ; + next unless $i{$day_field} ; + my $field6 = "event_length_$days" ; + if ($i{$field5} eq '-1') { + $operator_day_count{blank_system}{$op_id}++ ; + } elsif ($i{$field6} eq '1' && $db{event_systems}{$i{$field5}}{system_type} && $db{event_systems}{$i{$field5}}{system_type} ne 'fixed') { #full day + $operator_day_count{afull_day_mobile}{$op_id}++ ; + } elsif (($i{$field6} eq '1' && $db{event_systems}{$i{$field5}}{system_type} eq 'fixed') or ($i{$field6} eq '2' && $db{event_systems}{$i{$field5}}{system_type} && $db{event_systems}{$i{$field5}}{system_type} ne 'fixed')) { #full day + $operator_day_count{bfull_day_fixed_half_day_mobile}{$op_id}++ ; + } elsif ($i{$field6} eq '2' && $db{event_systems}{$i{$field5}}{system_type} eq 'fixed') { + $operator_day_count{chalf_day_fixed}{$op_id}++ ; + } + } + + next if $i{$field5} eq '-1' || $db{event_systems}{$i{$field5}}{system_type} ; + + # } else { + for my $days (1 .. 20) { + my $day_field = "day_$days" ; + next unless $i{$day_field} ; + my $field6 = "event_length_$days" ; + if ($i{$field6} eq '1' && $i{type} ne '3') { #full day + $operator_day_count{afull_day_mobile}{$op_id}++ ; + } elsif (($i{$field6} eq '1' && $i{type} eq '3') or ($i{$field6} eq '2' && $i{type} ne '3')) { #full day + $operator_day_count{bfull_day_fixed_half_day_mobile}{$op_id}++ ; + } elsif ($i{$field6} eq '2' && $i{type} eq '3') { + $operator_day_count{chalf_day_fixed}{$op_id}++ ; + } + } + # } + } + } + + my %iii = %i ; + our %i2 = () ; + + for (1 .. 50) { + if ($i{"description_workings_event_$_"} eq '14' && $i{"operator_workings_event_$_"}) { + my $op = $i{"operator_workings_event_$_"} ; + my $day_len = ($i{"amount_usd_workings_event_$_"} eq '1000.00' || $db{event_quotes}{$id}{demo_id}) ? "afull_day_mobile" : ($i{"amount_usd_workings_event_$_"} eq '750.00') ? "bfull_day_fixed_half_day_mobile" : ($i{"amount_usd_workings_event_$_"} eq '500.00') ? "chalf_day_fixed" : "" ; + if ($day_len) { + $saved_values{$day_len}{$op}{saved_values} = 1 ; + $saved_values{$day_len}{$op}{supplier_workings_event} = $i{"supplier_workings_event_$_"} ; + $saved_values{$day_len}{$op}{ref_nr_workings_event} = $i{"ref_nr_workings_event_$_"} ; + $saved_values{$day_len}{$op}{remarks_workings_event} = $i{"remarks_workings_event_$_"} ; + $saved_values{$day_len}{$op}{vat_workings_event} = $i{"vat_workings_event_$_"} ; + $saved_values{$day_len}{$op}{excl_workings_event} = $i{"excl_workings_event_$_"} ; + # $saved_values{$day_len}{$op}{amount_usd_workings_event} = $i{"amount_usd_workings_event_$_"} if $day_len eq "other" ; + } + } + $i{"description_workings_event_$_"} = "" ; + $i{"operator_workings_event_$_"} = "" ; + $i{"qty_workings_event_$_"} = "" ; + $i{"amount_usd_workings_event_$_"} = "" ; + $i{"amount_ttl_workings_event_$_"} = "" ; + $i{"excl_workings_event_$_"} = "1"; + $i{"vat_workings_event_$_"} = "" ; + $i{"supplier_workings_event_$_"} = "" ; + $i{"ref_nr_workings_event_$_"} = "" ; + $i{"remarks_workings_event_$_"} = "" ; + + } + + my $row_cnt = 0 ; + + foreach my $len (sort keys %operator_day_count) { + + foreach $op_id (sort keys %{$operator_day_count{$len}}) { + + $row_cnt++ ; + $i2{description_workings_event} .= '14;' ; + $i2{operator_workings_event} .= "$op_id;" ; + $i2{qty_workings_event} .= "$operator_day_count{$len}{$op_id};" ; + + # my $custom_saved_amnt = $saved_values{"other"}{$op_id}{amount_usd_workings_event} ; + + $i2{amount_usd_workings_event} .= ($len eq 'blank_system') ? '0.00' : ($len eq "afull_day_mobile") ? '1000.00' : ($len eq "bfull_day_fixed_half_day_mobile") ? '750.00' : '500.00' ; + $i2{amount_usd_workings_event} .= qq~;~ ; + my $amnt = ($len eq 'blank_system') ? 0 : ($len eq "afull_day_mobile") ? 1000 * $operator_day_count{$len}{$op_id} * $i{roe} : ($len eq "bfull_day_fixed_half_day_mobile") ? 750 * $operator_day_count{$len}{$op_id} * $i{roe} : 500 * $operator_day_count{$len}{$op_id} * $i{roe} ; + $amnt = sprintf ("%0.2f",$amnt) ; + + $i2{amount_workings_event} .= "$amnt;" ; + $i{total_amount_workings_event} += $amnt if !$saved_values{$len}{$op_id}{excl_workings_event} ; + if ($saved_values{$len}{$op_id}{saved_values}) { + foreach (keys %{$saved_values{$len}{$op_id}}) { + $i2{$_} .= qq~$saved_values{$len}{$op_id}{$_};~ if $_ ne "saved_values" ; + $i{total_vat_amount_workings_event} += $amnt*0.15 if !$saved_values{$len}{$op_id}{excl_workings_event} && $saved_values{$len}{$op_id}{vat_workings_event} && $_ eq "vat_workings_event" ; + } + } else { + $i2{supplier_workings_event} .= ";" ; + $i2{ref_nr_workings_event} .= ";" ; + $i2{remarks_workings_event} .= ";" ; + $i2{vat_workings_event} .= "1;" ; + $i2{excl_workings_event} .= "0;" ; + $i{total_vat_amount_workings_event} += $amnt*0.15 ; + } + } + } + + for (1 .. 50) { + if ($iii{"description_workings_event_$_"} && $iii{"description_workings_event_$_"} ne '14') { + $row_cnt++ ; + $i2{"excl_workings_event"} .= qq~$iii{"excl_workings_event_$_"};~ ; + $i2{"description_workings_event"} .= qq~$iii{"description_workings_event_$_"};~ ; + $i2{"operator_workings_event"} .= qq~$iii{"operator_workings_event_$_"};~ ; + $i2{"remarks_workings_event"} .= qq~$iii{"remarks_workings_event_$_"};~ ; + $i2{"supplier_workings_event"} .= qq~$iii{"supplier_workings_event_$_"};~ ; + $i2{"ref_nr_workings_event"} .= qq~$iii{"ref_nr_workings_event_$_"};~ ; + $i2{"qty_workings_event"} .= qq~$iii{"qty_workings_event_$_"};~ ; + $i2{"amount_usd_workings_event"} .= qq~$iii{"amount_usd_workings_event_$_"};~ ; + $i2{"amount_workings_event"} .= qq~$iii{"amount_ttl_workings_event_$_"};~ ; + $i2{"vat_workings_event"} .= qq~$iii{"vat_workings_event_$_"};~ ; + $iii{"amount_ttl_workings_event_$_"} =~ s/\,//g ; + $i{total_amount_workings_event} += $iii{"amount_ttl_workings_event_$_"} if !$iii{"excl_workings_event_$_"} ; + $i{total_vat_amount_workings_event} += $iii{"amount_ttl_workings_event_$_"} * 0.15 if !$iii{"excl_workings_event_$_"} && $iii{"vat_workings_event_$_"} ; + + } + } + + unless ($row_cnt) { + $i2{excl_workings_event} = qq~~ ; + $i2{description_workings_event} = qq~~ ; + $i2{operator_workings_event} = qq~~ ; + $i2{remarks_workings_event} = qq~~ ; + $i2{supplier_workings_event} = qq~~ ; + $i2{ref_nr_workings_event} = qq~~ ; + $i2{qty_workings_event} = qq~~ ; + $i2{amount_usd_workings_event} = qq~~ ; + $i2{amount_workings_event} = qq~~ ; + $i2{vat_workings_event} = qq~~ ; + } + + $i{total_grand_amount_workings_event} = $i{total_vat_amount_workings_event} + $i{total_amount_workings_event} ; + + $i{profit_loss} = $db{$table}{$id}{grand_total} - $i{total_grand_amount_workings_event} ; + + $i{total_amount_workings_event} = sprintf("%0.2f",$i{total_amount_workings_event}) ; + $i{total_vat_amount_workings_event} = sprintf("%0.2f",$i{total_vat_amount_workings_event}) ; + $i{total_grand_amount_workings_event} = sprintf("%0.2f",$i{total_grand_amount_workings_event}) ; + $i{profit_loss} = sprintf("%0.2f",$i{profit_loss}) ; + + foreach (keys %i2) { + # chop $i2{$_} if $i2{$_} ; + # $i{$_} = $i2{$_} ; + } + +} #------------------------------------------------------------------------------------------ + +sub build_event_quotes_min_fields { + + my ($quote_accepted,$quote_rejected,$quote_cancelled) = @_ ; + + my $category_details = qq~$i{category_1_details}|;|$i{category_2_details}~ if $i{category_1_details} || $i{category_2_details} ; + $i{category_details} = $category_details ; + + $ignore{last_update} = 1 ; + $ignore{poc_contact_nr} = 1 ; + $ignore{poc_name} = 1 ; + $ignore{poc_id} = 1 ; + $ignore{format_of_title} = 1 ; + $ignore{additional_notes} = 1 ; + $ignore{upload_1} = 1 ; + $ignore{upload_2} = 1 ; + $ignore{upload_3} = 1 ; + $ignore{email} = 1 ; + $ignore{address} = 1 ; + $ignore{country_id} = 1 ; + $ignore{quote_date} = 1 ; + $ignore{contact_name} = 1 ; + $ignore{notes} = 1 ; + $ignore{tel} = 1 ; + $ignore{category_id_1} = 1 ; + $ignore{category_id_2} = 1 ; + $ignore{custom_set} = 1 ; + $ignore{quote_accepted} = 1 ; + $ignore{quote_cancelled} = 1 ; + $ignore{quote_rejected} = 1 ; + $ignore{quote_completed} = 1 ; + + return if ($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3 ; + + $iid = $i{id} ; + my $custom_set = $i{custom_set} ; + %i = %i2 ; + $i{custom_set} = $custom_set ; + if ($glod_user_level > 3) { + + for (1 .. 50) { + next unless $x{2}{$_} ; + $i{excl_costing_event} .= "$x{1}{$_};" ; + $i{item_costing_event} .= "$x{2}{$_};"; + $i{qty_costing_event} .= "$x{3}{$_};"; + $i{usd_amnt_costing_event} .= "$x{4}{$_};"; + $i{item_ttl_costing_event} .= "$x{5}{$_};"; + $i{vat_costing_event} .= "$x{6}{$_};"; + + # $i{curr_amnt_costing_event} .= "$x{17}{$_};"; + } + if ($i{custom_set}) { + for (1 .. 50) { + next unless $x{8}{$_} ; + $i{excl_workings_event} .= "$x{7}{$_};"; + $i{description_workings_event} .= "$x{8}{$_};"; + $i{operator_workings_event} .= "$x{9}{$_};"; + $i{remarks_workings_event} .= "$x{10}{$_};"; + $i{supplier_workings_event} .= "$x{11}{$_};"; + $i{ref_nr_workings_event} .= "$x{12}{$_};"; + $i{qty_workings_event} .= "$x{13}{$_};"; + $i{amount_usd_workings_event} .= "$x{14}{$_};"; + $i{amount_workings_event} .= "$x{15}{$_};"; + $i{vat_workings_event} .= "$x{16}{$_};"; + } + } + + $i{excl_costing_event} = "" unless $i{excl_costing_event} ; + $i{item_costing_event} = "" unless $i{item_costing_event} ; + $i{qty_costing_event} = "" unless $i{qty_costing_event} ; + $i{usd_amnt_costing_event} = "" unless $i{usd_amnt_costing_event} ; + $i{item_ttl_costing_event} = "" unless $i{item_ttl_costing_event} ; + $i{vat_costing_event} = "" unless $i{vat_costing_event} ; + + $i{excl_workings_event} = "" unless $i{excl_workings_event} ; + $i{description_workings_event} = "" unless $i{description_workings_event} ; + $i{operator_workings_event} = "" unless $i{operator_workings_event} ; + $i{remarks_workings_event} = "" unless $i{remarks_workings_event} ; + $i{supplier_workings_event} = "" unless $i{supplier_workings_event} ; + $i{ref_nr_workings_event} = "" unless $i{ref_nr_workings_event} ; + $i{qty_workings_event} = "" unless $i{qty_workings_event} ; + $i{amount_usd_workings_event} = "" unless $i{amount_usd_workings_event} ; + $i{amount_workings_event} = "" unless $i{amount_workings_event} ; + $i{vat_workings_event} = "" unless $i{vat_workings_event} ; + + } elsif ($glod_user_level < 4 && $hidden_expenses_amounts_exist) { + + for (1 .. 50) { + # $i{description_workings_event} .= "$x{8}{$_};"; + # $i{operator_workings_event} .= "$x{9}{$_};"; + # $i{qty_workings_event} .= "$x{13}{$_};"; + # $i{amount_usd_workings_event} .= "$x{14}{$_};"; + # $i{amount_workings_event} .= "$x{15}{$_};"; + # $i{vat_workings_event} .= "$x{16}{$_};"; + } + } + + foreach (keys %i) { chop $i{$_} ; } + + $i{category_details} = $category_details ; + $i{id} = $iid ; + +} #------------------------------------------------------------------------------------------ + +sub process_multi_select { + + my ($quote_accepted,$quote_rejected,$quote_cancelled) = @_ ; + + # $ignore{event_system_id} = 1 ; + + # if ($usertype ne 'schools_manager') { + # if ($glod_user_level > 3) { + + # return if ($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3 ; + + if (($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) { + $ignore{operatorids} = 1 ; + $ignore{typedetailsid} = 1 ; + $ignore{organisationids} = 1 ; + $ignore{sporttypeids} = 1 ; + $ignore{operator_ids} = 1 ; + } + + local @operatorids = split(/\,/,$i{operatorids}) ; + $i{nr_of_casuals} = scalar @operatorids || '0' ; $i{nr_of_casuals_2} = '0' ; + my $operatorids = join(",",@operatorids) ; + $operatorids =~ s/\s//g; # remove white space + $ignore{operatorids} = 1 ; + + $i{operator_ids} .= $operatorids ; + $i{operator_ids} = 0 unless $i{operator_ids} ; + chop $i{operator_ids} if substr($i{operator_ids},-1,1) eq ',' ; + + if ($glod_user_level > 2) { + + local @typedetailsid = split(/\,/,$i{typedetailsid}) ; + my $typedetailsid = join(",",@typedetailsid) ; + $typedetailsid =~ s/\s//g; # remove white space + $ignore{typedetailsid} = 1 ; + $i{type_details_id} = $typedetailsid ; + $i{type_details_id} = 0 unless $i{type_details_id} ; + + # @event_system_ids = split(/\,/,$i{event_system_ids}) ; + # my @db_event_system_ids = () ; foreach (@event_system_ids) { push @db_event_system_ids, $_ ; } + # my $db_event_system_ids = join(';',@db_event_system_ids) ; + # $ignore{event_system_ids} = 1 ; + # $i{event_system_id_multiple} = $db_event_system_ids ; + } + + $ignore{city_ids} = 1 ; + $i{city_id} = $i{city_ids} ; + + local @organisationids = split(/\,/,$i{organisationids}) ; + my $organisationids = join(",",@organisationids) ; + $organisationids =~ s/\s//g; # remove white space + $ignore{organisationids} = 1 ; + $i{organisation_ids} = $organisationids ; + $i{organisation_ids} = 0 unless $i{organisation_ids} ; + + local @sporttypeids = split(/\,/,$i{sporttypeids}) ; + my $sporttypeids = join(",",@sporttypeids) ; + $sporttypeids =~ s/\s//g; # remove white space + $ignore{sporttypeids} = 1 ; + $i{sport_type_ids} = $sporttypeids ; + $i{sport_type_ids} = 0 unless $i{sport_type_ids} ; + + local @suppliertypeids = split(/\,/,$i{suppliertypeids}) ; + my $suppliertypeids = join(";",@suppliertypeids) ; + $suppliertypeids =~ s/\s//g; # remove white space + $ignore{suppliertypeids} = 1 ; + $i{supplier_type_ids} = $suppliertypeids ; + $i{supplier_type_ids} = 0 unless $i{suppliertypeids} ; + $ignore{supplier_type_ids} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub duplicate { + + unless ($i{id}) { + $error = qq~NO ID~ ; + return ; + } + + my $orig_id = $i{id} ; + + &db_min_copy($table,$i{id}) ; + + my $copy_id = $i{id} ; + + &common_min_copy_files("$htmlpath/uploads/uploads/$orig_id","$htmlpath/uploads/uploads/$copy_id",'') ; + + &db_min_ro($table,'1,sss_quote_nr',"id='$copy_id'","","") ; + + my %ii = %i ; + + # if ($db{$table}{1}{sss_quote_nr} || $db{$table}{1}{event_system_calibration_ids} || $db{$table}{1}{set_up_groups_status_ids}) { + %i = () ; + my %ignore_for_now = %ignore ; + %ignore = () ; + $i{sss_quote_nr} = '0' ; + &common_shared_event_quotes_column_not_to_copy ; + $ignore{sss_quote_nr} = (!$db{$table}{1}{sss_quote_nr}) ? 1 : 0 ; + # $ignore{event_system_calibration_ids} = (!$db{$table}{1}{event_system_calibration_ids}) ? 1 : 0 ; + # $ignore{set_up_groups_status_ids} = (!$db{$table}{1}{set_up_groups_status_ids}) ? 1 : 0 ; + &db_min_upd($table,"id='$copy_id'") ; + %ignore = %ignore_for_now ; + # } + + %i = %ii ; + + &db_min_copy('event_quotes_min',$orig_id) ; + + %ii = %i ; + %i = () ; + $i{quote_nr} = $copy_id ; + $i{operator_dates_paid} = '' ; + $i{operator_dates_paid_min} = '' ; + $i{operator_amounts_paid} = '' ; + &db_min_upd('event_quotes_min',"id='$copy_id'") ; + %i = %ii ; + +} #------------------------------------------------------------------------------------------ + +# sub copy { + + # unless ($i{id}) { + # $error = qq~NO ID~ ; + # return ; + # } + + # my $id = $i{id} ; + + # &db_min_copy($table,$i{id}) ; + + # my $id2 = $i{id} ; + + # $i{id} = $id ; + + # &db_min_copy('event_quotes_min',$i{id}) ; + + # $i{id} = $id ; + + # # use File::Copy; + # # # use File::Path 'make_path'; + + + + # # my $src_dir = "$htmlpath/uploads/uploads/$id"; + # # my $dst_dir = "$htmlpath/uploads/uploads/$id2"; + + # # return unless -d $src_dir ; + + # # mkdir $dst_dir unless -d $dst_dir ; + + # # opendir(my $dh, $src_dir) or die "Can't open $src_dir: $!"; + # # my $file_counter = 0 ; + # # while (my $file = readdir($dh)) { + # # next if $file =~ /^\.\.?$/; # Skip '.' and '..' + # # last if !$file || $file_counter >= 3 ; + # # my $src_file = "$src_dir/$file"; + # # my $dst_file = "$dst_dir/$file"; + # # copy($src_dir, $dst_dir) or warn "Failed to copy $src_file to $dst_file: $!"; + # # $file_counter++ ; + # # } + + # # closedir($dh); + +# } #------------------------------------------------------------------------------------------ + + +sub delete { + + unless ($i{id}) { $error = uc "NO ID" ; return ; } + + &db_min_ro($table,'1,sss_quote_nr',"id = '$i{id}'",'','') ; + + my $sss_delete_id = $db{$table}{1}{sss_quote_nr} ; + + my $aisa_delete_id = $i{id} ; + + &db_min_delete('event_quotes',"`id`='$aisa_delete_id'") ; + &db_min_delete('event_quotes_min',"`id`='$aisa_delete_id'") ; + &common_min_delete_files("$htmlpath/uploads/uploads/$aisa_delete_id") ; + &common_min_delete_files("$htmlpath/pdf/event_details","Event_Details-$aisa_delete_id.pdf") ; + + if ($sss_delete_id) { + + &db_switch_conn('sss') ; + &db_min_ro($table,'1,id',"id = '$sss_delete_id' AND aisa_quote_nr = '$aisa_delete_id'",'','') ; + if ($db{$table}{1}{id}) { + &db_min_delete($table,"id = '$sss_delete_id'") ; + &common_min_delete_files("$htmlpath_sss/uploads/uploads/$sss_delete_id") ; + &common_min_delete_files("$htmlpath_sss/pdf/event_details","Event_Details-$sss_delete_id.pdf") ; + } + &db_switch_conn('aisa') ; + + } + +} #------------------------------------------------------------------------------------------ + +sub process_upload_ifields { + + foreach (keys %uploads_file) { $i{$_} = $uploads_file{$_} ; $ignore{$_} = '' ; } + +} #------------------------------------------------------------------------------------------ + +sub set_default_i_vals { + + my $srch_where_sql = "`id`='$i{id}'" ; + + $iaction eq 'save' ? &db_min_ro($table,'*','','id DESC',1) : &db_min_ro($table,'*',$srch_where_sql,'','') ; + + foreach (sort { $col_name{$a} cmp $col_name{$b} } keys %col_name) { + $col = $col_name{$_} ; + + # &common_min_debug("1. [$col] [$i{$col}]"); + + if (substr($col,0,4) eq 'vat_' or substr($col,0,5) eq 'excl_' or substr($col,0,4) eq 'qty_') { + $i{$col} = 0 unless $i{$col} ; + } # only create the column if it doesn't exist + + if (substr($col,0,5) eq 'date_') { + $i{$col} = 'NULL' unless $i{$col} ; + } # only create the column if it doesn't exist + + if (substr($col,0,11) eq 'amount_ttl_' or substr($col,0,9) eq 'usd_amnt_' or substr($col,0,10) eq 'curr_amnt_' or substr($col,0,9) eq 'item_ttl_' or substr($col,-6,6) eq '_total') { + $i{$col} = '0.00' unless $i{$col} ; + } + + if ((substr($col,6,9) eq '_costing_' and substr($col,0,5) eq 'item_' and $i{$col}) or ($col eq 'quote_to' and $i{$col})) { + my @valarr = split(/\:/,$i{$col}) ; + $i{$col} = $valarr[0] ; # set the value to only be the id + } + } + + $i{quote_completed} = 0 unless $i{quote_completed} ; + $i{quote_accepted} = 0 unless $i{quote_accepted} ; + $i{quote_pending} = 0 unless $i{quote_pending} ; + $i{quote_cancelled} = 0 unless $i{quote_cancelled} ; + $i{quote_rejected} = 0 unless $i{quote_rejected} ; + $i{annual_invoice} = 0 unless $i{annual_invoice} ; + $i{nr_of_casuals_2} = 0 unless $i{nr_of_casuals_2} ; + $i{linear_id} = 0 unless $i{linear_id} ; + $ignore{invoice_date} = 1 unless length($i{invoice_date}) == 10 ; + + # if ($i{quote_completed}) { + # $i{quote_accepted} = 1 ; + # $i{quote_cancelled} = 0 ; + # $i{quote_pending} = 0 ; + # $i{quote_rejected} = 0 ; + # } elsif ($i{quote_accepted}) { + # $i{quote_cancelled} = 0 ; + # $i{quote_completed} = 0 ; + # $i{quote_pending} = 0 ; + # $i{quote_rejected} = 0 ; + # } elsif ($i{quote_rejected}) { + # $i{quote_cancelled} = 0 ; + # $i{quote_completed} = 0 ; + # $i{quote_pending} = 0 ; + # $i{quote_accepted} = 0 ; + # } elsif ($i{quote_pending}) { + # $i{quote_cancelled} = 0 ; + # $i{quote_rejected} = 0 ; + # } + + $i{ligr} = ($i{ligr}) ? 'Yes' : 'No' ; + + $i{city_id} = 0 unless $i{city_id} ; + $i{region_id} = 0 unless $i{region_id} ; + $i{category_id_1} = 0 unless $i{category_id_1} ; + $i{category_id_2} = 0 unless $i{category_id_2} ; + $i{po_nr} = 0 unless $i{po_nr} ; + + # $i{grand_total} = '0.00' unless $i{grand_total} ; + $i{format_of_title} = uc $i{format_of_title} ; + $i{ref} = uc $i{ref} ; + $i{category_1_details} = uc $i{category_1_details} ; + $i{category_2_details} = uc $i{category_2_details} ; + + &common_shared_process_poc_recipients("poc") ; + &common_shared_process_poc_recipients("recipient") ; + +} #---------------------------------------------------------------------------------------- + +sub list_screen { + + # my $page2 = 'event-quotes' ; + + # if ($page2 && $ENV{SCRIPT_NAME} =~ /\_test/) { $page2 .= '-test' ; } + + # my $action_delete_2 = qq~delete-$page2~ ; + + # $print_footer_forms .= qq~ + #
    + # + # + # + # + # + # + # + # + # + # + # + # + # + # + # + # + # + # + # + # + #
    + # ~ ; + + $trigger_jquery_raw .= qq~ + function deleteMinItem_custom (name,id) { + BootstrapDialog.confirm({ + title: 'Confirm Delete', + message: 'Are you sure you want to delete '+name+'?', + type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + callback: function(result) { + if (result) { + let delete_url = "$useropts{scripts}/get/get_delete_event_quote.pl?"+id ; + \$.get(delete_url) ; + \$("#event_quote_row_"+id).html("") ; + } + } + }) ; + } + ~ ; + + &db_min_ro('event_type_details','id,name','','','') ; + &db_min_ro('event_quotes_categories','id,category','','','') ; + &db_min_ro('event_systems','id,name,description,system_type','','','') ; + &db_min_ro('clubs','id,name','','','') ; + &db_min_ro('cities','id,city,province','','','') ; + &db_min_ro('analytics_event_bookings','id,event_quote_id',"event_quote_id <> '0'",'','') ; + + our %analytics_events = () ; + foreach (keys %{$db{analytics_event_bookings}}) { + $analytics_events{$db{analytics_event_bookings}{$_}{event_quote_id}} .= qq~$_;~ ; + } + + &db_min_ro('users','id,username,name,email','','','') ; + foreach my $_id (keys %{$db{users}}) { + $username{$_id} = $db{users}{$_id}{username} ; + $name{$_id} = $db{users}{$_id}{name} ; + $email{$_id} = $db{users}{$_id}{email} ; + } + + &db_min_ro('sport_types','*','','','') ; + foreach my $_id (keys %{$db{sport_types}}) { $sort_type{$_id} = $db{sport_types}{$_id}{name} ; } + + &db_min_ro('organisations','id,name','','','') ; + foreach my $_id (keys %{$db{organisations}}) { $organisation{$_id} = $db{organisations}{$_id}{name} ; } + + if ($iaction eq 'completed' or $i{options} eq 'completed') { push @report_sql, "q.quote_completed='1'" ; } + if ($iaction eq 'accepted' or $i{options} eq 'accepted') { push @report_sql, "q.quote_accepted='1'" ; } + if ($iaction eq 'rejected' or $i{options} eq 'rejected') { push @report_sql, "q.quote_rejected='1'" ; } + if ($iaction eq 'closed' or $i{options} eq 'closed') { push @report_sql, "(q.quote_cancelled='1' OR (q.quote_expiry<'$now_year-$now_mm-$now_dd' AND q.quote_accepted<>'1'))" ; } + if ($iaction eq 'pending' or $i{options} eq 'pending') { push @report_sql, "q.quote_pending='1'" ; } + if ($iaction eq 'list' or $i{options} eq 'list') { push @report_sql, "q.quote_cancelled<>'1'" ; } + + my $t1 = 'event_quotes'; + my $t2 = 'countries' ; + my $t3 = 'cities' ; + my $t4 = 'customers' ; + my $t5 = 'event_types' ; + my $t6 = 'regions' ; + my $t7 = 'event_quotes_min' ; + our $tables = "$t1,$t2,$t3,$t4,$t5,$t6,$t7" ; + + if ($is_schools_manager || $is_operator) { + @report_sql_or = () ; + foreach $_reg_id (keys %{$glob_regids{$userid}}) { + push @report_sql_or, "q.region_id = '$_reg_id'" + } + my $sql_or = join(' OR ',@report_sql_or) ; + push @report_sql, "($sql_or)" if $sql_or ; + push @report_sql, "(q.quote_created='1')" if $is_schools_manager ; + # push @report_sql, "(q.user_id='$userid')" if $is_schools_manager ; + push @report_sql, "(q.quote_accepted='1')" if $is_operator && !$i{options} ; + } + + push @report_sql, "(q.quote_completed <> '1')" if $iaction eq 'list' ; + + my $srch_where_sql = join(' AND ', @report_sql) ; my $sql_where = ($srch_where_sql) ? "WHERE $srch_where_sql" : '' ; + + &db_min_raw("SELECT q.id AS 'quote_id', + q.quote_nr, + q.sport_type_ids, + q.city_id, + q.region_id, + q.organisation_ids, + q.date_from, + q.date_to, + q.grand_total, + q.ref, + q.qty, + q.quote_expiry, + q.quote_to, + q.invoice_nr, + q.quote_date, + q.type, + q.currency, + q.country_id, + q.quote_cancelled, + q.quote_accepted, + q.quote_completed, + q.quote_pending, + q.quote_created, + q.quote_rejected, + q.activetab, + q.user_id, + q.category_1, + q.category_id_1, + q.category_2, + q.category_id_2, + q.additional_notes, + q.poc_id, + q.type_details_id, + q.club_ids, + q.event_system_id_multiple, + q.operator_ids, + q.format_of_title, + q.emailed_op_ids, + q.fixed_system_overall_status, + q.daily_operator_ids, + q.sss_quote_nr, + q.demo_id, + c.name AS 'country', + t.name AS 'customer', + y.city, + y.province, + r.code AS 'reg_code', + r.name AS 'region', + e.name AS 'event_type', + emin.category_details + FROM $t1 q LEFT JOIN $t2 c ON q.country_id = c.id + LEFT JOIN $t3 y ON q.city_id = y.id + LEFT JOIN $t4 t ON q.quote_to = t.id + LEFT JOIN $t5 e ON q.type = e.id + LEFT JOIN $t6 r ON q.region_id = r.id + LEFT JOIN $t7 emin ON q.id = emin.quote_nr + $sql_where;"); + + foreach $row (@$rows_array_ref) { + for (0 .. $col_cnt){ + # &common_debug("[$_] $col_name{$_} -> @$row[$_]") ; + $db{$tables}{@$row[0]}{$col_name{$_}} = @$row[$_] ; + } + } + + + &tab_hash ; # load for PDF links + "e_list ; # load for PDF links + + if ($iaction eq 'update' or $iaction eq 'save'){ + &common_min_extra_crumb("list-$lcpage\s","List $ucfirstpage\s") ; + } + +} #------------------------------------------------------------------------------------------ + +sub quote_list { + + # our @sql_col_display = ("nr","date","customer","user","event","venue","location","sports_type","date_from","date_to","days","type") ; + # our @sql_col_display = ("nr","event_start","event_end","date_added","customer","user","event","venue","location","sports_type","days","type") ; + + our @sql_col_display = () ; + our @col_display_excel = () ; + + if ($usertype eq 'support') { + @sql_col_display = ("nr","event_start","days","event","location","sport","system_name","club_names","operators") ; + @col_display_excel = @sql_col_display ; + &report_xlsx_export_header("Events_Quotes",'events') ; + } else { + @col_display_excel = ("nr","event","event_start","event_end","days","type_of_system","system_details","system_name","sport_type","cities","region","venue","club_names","operators","client","poc_name","poc_contact_nr","category_1","category_1_details","category_2","category_2_details","format_of_title") ; + @sql_col_display = @col_display_excel ; + &report_xlsx_export_header("Events_Quotes",'events') ; + @sql_col_display = ("nr","event_start","event_end","days","date_added","customer","event","venue","location","sport","type","operators") ; + if ($userid eq '24') { + # if ($glod_user_level > 3) { + push @sql_col_display, "amount" ; + push @sql_col_display, "invoice_nr" ; + } + } + + push @sql_col_display, "" ; + + my @month_fullname = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") ; # if ($i{export_to_excel}) { &report_xls_export_header("Event Quotes",'event_quotes') ; } + my @day_of_week_text = ("", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") ; + + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) { + + next unless $id ; + + my $quote_expiry = $db{$tables}{$id}{quote_expiry} ; $quote_expiry =~ s/\-//iog ; + my $invoice_nr = $db{$tables}{$id}{invoice_nr} ; + my $quote_accepted = $db{$tables}{$id}{quote_accepted} ; + my $quote_pending = $db{$tables}{$id}{quote_pending} ; + my $quote_cancelled = $db{$tables}{$id}{quote_cancelled} ; + my $quote_completed = $db{$tables}{$id}{quote_completed} ; + my $quote_created = $db{$tables}{$id}{quote_created} ; + my $quote_rejected = $db{$tables}{$id}{quote_rejected} ; + my @cat_details = split('\|;\|',$db{$tables}{$id}{category_details}) ; + + if ($quote_completed) { + $sortprefix = 'd' ; + } elsif ($quote_accepted) { + $sortprefix = 'c' ; + } elsif ($quote_rejected) { + $sortprefix = 'x' ; + } elsif ($quote_cancelled) { + $sortprefix = 'z' ; + } elsif ($quote_created) { # create by schools_manager + $sortprefix = 'a' ; + } elsif ($quote_pending) { + $sortprefix = 'b' ; + } + + if ($usertype eq 'support') { + next unless $quote_accepted && !$quote_completed ; + } + + # if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all') { next ; } + + my $quote_date = $db{$tables}{$id}{quote_date} ; $quote_date =~ s/\-//iog ; + + $yr = substr($quote_date, 0, 4) ; + $mm = substr($quote_date, 4, 2) ; + $dd = substr($quote_date, 6, 2) ; + + my ($yr2,$mm2,$dd2) = Add_Delta_Days($yr,$mm,$dd,60); # + + $mm2 = sprintf("%02s", $mm2) ; + $dd2 = sprintf("%02s", $dd2) ; + + $quote_date = "$yr2$mm2$dd2" ; + + if ($quote_date && $quote_date < "$now_year$now_mm$now_dd" && $quote_accepted!=1 && + $iaction ne 'report' && $iaction ne 'accepted' && $iaction ne 'closed' && $iaction ne 'all' && + $i{options} ne 'accepted' && $i{options} ne 'closed' && $i{options} ne 'all') + { next ; } + + $print_tbody .= qq~~ ; + + $xlsxcol=0; + + my $quote_nr = $db{$tables}{$id}{quote_nr} ; + + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$tables}{$id}{$_} ; + my $align = qq~ class="dt-center"~ ; + my $nowrap = '' ; + + # if ($_ eq 'event_end') { $val = substr($db{$tables}{$id}{date_to},0,10) ; $align = qq~ class="dt-center" style="width:6.9%"~ ; } + # elsif ($_ eq 'event_start') { $val = substr($db{$tables}{$id}{date_from},0,10) ; $nowrap = 'nowrap' ; } + if ($_ eq 'event_end') { + + # my $sort_val = $db{$tables}{$id}{date_to} ; + # $sort_val =~ s/\-//g ; + # $sort_val =~ s/\://g ; + # $sort_val =~ s/ //g ; + my $sort_val = $db{$tables}{$id}{date_to} =~ s/[\-:\s]//gr; + $val = qq~$sort_val~ . &common_min_date_as_string(substr($db{$tables}{$id}{date_to},0,16)) ; $align = qq~ class="dt-center"~ ; $nowrap = 'nowrap' ; + } elsif ($_ eq 'event_start') { + my $sort_val = $db{$tables}{$id}{date_from} =~ s/[\-:\s]//gr; + $val = qq~$sort_val~ . &common_min_date_as_string(substr($db{$tables}{$id}{date_from},0,16)) ; + # my ($dy,$dm,$dd,$th,$tm,$ts) = &common_min_split_sql_date_time($db{$tables}{$id}{date_from}) ; my $sccyymmddhrmnsc = $dy . $dm . $dd . $th . $tm . $ts ; $val = "$sortprefix$sccyymmddhrmnsc" . substr($db{$tables}{$id}{date_from},0,16) ; + $nowrap = 'nowrap' ; + } elsif ($_ eq 'event') { + $val = $db{$tables}{$id}{ref} ; + $nowrap = '' ; + } elsif ($_ eq 'customer') { + $nowrap = 'nowrap' ; + } elsif ($_ eq 'date_added') { + my $sort_val = $db{$tables}{$id}{quote_date} =~ s/[\-:\s]//gr; + $val = qq~$sort_val~ . &common_min_date_as_string($db{$tables}{$id}{quote_date}) ; + $val = qq~$val~ ; + $nowrap = 'nowrap' ; + } elsif ($_ eq 'curr') { + $val = $db{$tables}{$id}{currency} ; + } elsif ($_ eq 'location') { + $val = ($db{$tables}{$id}{city} & $db{$tables}{$id}{reg_code}) ? "$db{$tables}{$id}{city}, $db{$tables}{$id}{reg_code}" : ($db{$tables}{$id}{city}) ? $db{$tables}{$id}{city} : $db{$tables}{$id}{reg_code} ; + $nowrap = 'nowrap' ; + } elsif ($_ eq 'country_id') { + $val = $db{$tables}{$id}{country} ; + } elsif ($_ eq 'days') { + $val = $db{$tables}{$id}{qty} ; + } elsif ($_ eq 'type') { + my $txt = uc substr($db{$tables}{$id}{event_type},0,1) ; + $val = qq~$txt~; + $nowrap = 'nowrap' ; + } elsif ($_ eq 'amount') { + my $ttl = sprintf("%0.2f",($db{$tables}{$id}{grand_total})) ; + $val = &common_commify($ttl) ; + } elsif ($_ eq 'system_name') { + # $val = '' ; + # foreach my $event_id (split(";",$db{$tables}{$id}{event_system_id_multiple})) { + # $val .= qq~$db{event_systems}{$event_id}{name} [$db{event_systems}{$event_id}{description}], ~ ; + # } + # chop $val if $val ; chop $val if $val ; + + $val = join("
    ", map { "$db{event_systems}{$_}{name} [$db{event_systems}{$_}{description}]" } split(/\;/,$db{$tables}{$id}{event_system_id_multiple})) ; + + } elsif ($_ eq 'club_names') { + # $val = '' ; + # foreach my $club_id (split(/\;/,$db{$tables}{$id}{club_ids})) { + # $val .= qq~$db{clubs}{$club_id}{name}, ~ ; + # } + # chop $val if $val ; chop $val if $val ; + $val = join("
    ",map { "$db{clubs}{$_}{name}" } split(/\;/,$db{$tables}{$id}{club_ids})) ; + + } elsif ($_ eq 'operators') { + $val = '' ; $op_cnt = 0 ; + my %seen_op_id = () ; + my @op_ids = split(/\,/,$db{$tables}{$id}{operator_ids}) ; + for my $op_id (@op_ids) { + next if $seen_op_id{$op_id} || !$op_id ; + $seen_op_id{$op_id} = 1 ; $op_cnt++; + $val .= qq~$name{$op_id}
    ~ ; + } + foreach my $op_ids (split(/\|/,$db{$tables}{$id}{daily_operator_ids})) { + foreach my $opid (split(/\;/,$op_ids)) { + next if $seen_op_id{$opid} || !$opid ; + $seen_op_id{$opid} = 1 ; $op_cnt++; + $val .= qq~$name{$opid}
    ~ ; + } + } + $val = substr($val,0,-4) if $val ; + # $val = qq~~ if $val ; + $glyph_icon = ($op_cnt > 1) ? qq~~ : qq~~ ; + $val = qq~$glyph_icon~ if $val ; + + } elsif ($_ eq 'venue') { + # my @oids = split(/\,/,$db{$tables}{$id}{organisation_ids}) ; + # my @venues = map { $organisation{$_} } @oids; + # $val = join(" & ",@venues) ; + $nowrap = '' ; + $val = join("
    ", map { $organisation{$_} } split(/\,/,$db{$tables}{$id}{organisation_ids})) ; + # foreach $_oid (@oids) { + # $val .= $organisation{$_oid} . ',' ; + # } + # chop $val ; + } elsif ($_ eq 'sport') { + # my @sptyps = split(/\,/,$db{$tables}{$id}{sport_type_ids}) ; + # my @sports = map { $sort_type{$_} } split(/\,/,$db{$tables}{$id}{sport_type_ids}) ; + # $val = join(", ",@sports) ; # foreach $_sp (@sptyps) { $val .= $sort_type{$_sp} . ', ' ; } + $val = join("
    ", map { $sort_type{$_} } split(/\,/,$db{$tables}{$id}{sport_type_ids})) ; # foreach $_sp (@sptyps) { $val .= $sort_type{$_sp} . ', ' ; } + # chop $val if $val ; + } elsif ($_ eq 'nr') { + + $nowrap = 'nowrap' ; + + $sort_val = sprintf("%06d",$id) ; + $sort_val = ($quote_accepted) ? qq~5~ . $sort_val : ($quote_completed) ? qq~4~ . $sort_val : ($quote_pending) ? qq~3~ . $sort_val : ($quote_rejected) ? qq~2~ . $sort_val : ($quote_cancelled) ? qq~1~ . $sort_val : qq~0~ . $sort_val ; + + # my $event_id = $db{$tables}{$id}{id} ; + # $db{$tables}{$id}{id} = $db{$tables}{$id}{quote_id} ; + + $val = qq~$sort_val~ . &common_min_get_event_quote_button($id,$tables,"event-quotes") ; + $val .= qq~~ if $db{$tables}{$id}{sss_quote_nr} ; + + # $db{$tables}{$id}{id} = $event_id ; + + if ($analytics_events{$id}) { + chop $analytics_events{$id} ; + foreach (sort {$a <=> $b} split(/\;/,$analytics_events{$id})) { + $val .= qq~~ ; + } + } + + if ($db{$tables}{$id}{demo_id}) { + + my $glod_user_level_eff = ($glod_user_level == 2 && $is_operator) ? 3 : $glod_user_level ; + + # $val .= ($glod_user_level_eff < 3 || $db{$table}{$event_id}{quote_cancelled}) ? + $val .= ($glod_user_level_eff < 3 || $db{$tables}{$id}{quote_cancelled}) ? + qq~~ : + qq~~ ; + } + + # my $class = 'info' ; my $style = '' ; + # if ($quote_completed) { + # $class = 'success' ; # green + # $tt_txt = 'Completed' ; + # } elsif ($quote_accepted) { + # $class = 'info' ; # blue + # $tt_txt = 'Accepted' ; + # my @fixed_system_overall_statuses = split(/\;/,$db{$tables}{$id}{fixed_system_overall_status}) ; + # my @event_system_ids = split(/\;/,$db{$tables}{$id}{event_system_id_multiple}) ; + # my $event_sys_cnt = 0 ; my $event_sys_test_status = 0 ; my $got_some_fixed = 0 ; my $fixed_status_color = '164473' ; # Dark Blue + # foreach my $event_id (@event_system_ids) { + # if ($db{event_systems}{$event_id}{system_type} eq 'fixed') { + # $tt_txt = 'Accepted and tests show All Clear for the Fixed Systems' if $tt_txt eq 'Accepted' ; + # $got_some_fixed = 1 ; + # if ($fixed_system_overall_statuses[$event_sys_cnt] == 3) { # Not Clear + # $fixed_status_color = '5d09d3' ; # Dark Purple + # $tt_txt = 'Accepted but Not Clear on some Fixed Systems' ; + # } elsif ($fixed_system_overall_statuses[$event_sys_cnt] == 2) { # Sound Issue + # $fixed_status_color = '5d092c' ; + # $tt_txt = 'Accepted but Sound Issue found on some Fixed Systems' ; + # } + # } + # $event_sys_cnt++; + # } + # if ($got_some_fixed) { $style = "style='background-color:#$fixed_status_color;border-color:#$fixed_status_color'"; } + # } elsif ($quote_rejected) { + # $style = 'style="background-color:#ca0ad3;border-color:#ca0ad3"'; # purple + # $tt_txt = 'Rejected' ; + # } elsif ($quote_cancelled) { + # $class = 'danger' ; # red + # $tt_txt = 'Cancelled' ; + # } elsif ($quote_created) { # create by schools_manager + # $style = 'style="background-color:#f6e305;border-color:#f6e305"'; # yellow + # $tt_txt = 'Pending, created by School Manager' ; + # } elsif ($quote_pending) { + # $class = 'warning' ; # orange + # $tt_txt = 'Pending' ; + # } + + # my $tt = qq~data-toggle="tooltip" data-placement="right" data-title="$tt_txt"~; + + # # &common_debug("$quote_nr quote_created [$quote_created] $style") if $quote_created ; + + # # $val = ($is_schools_manager) ? qq~$quote_nr~ : qq~$quote_nr~ ; + # # $val = ($glod_user_level < 4 || $quote_cancelled) ? qq~$quote_nr~ : qq~$quote_nr~ ; + # $val = ($glod_user_level < 3 || $quote_cancelled) ? qq~$quote_nr~ : qq~$quote_nr~ ; + } elsif ($col_name eq 'poc_name') { + $val = $db{event_quotes_poc}{$db{$tables}{$id}{poc_id}}{name} ; + } elsif ($col_name eq 'poc_contact_nr') { + $val = $db{event_quotes_poc}{$db{$tables}{$id}{poc_id}}{contact_nr} ; + } + # elsif ($_ eq 'user') { + # $val = '' ; + # # $val = $db{users}{$db{$tables}{$id}{user_id}}{username} if $db{$tables}{$id}{user_id} ; + # $val = $username{$db{$tables}{$id}{user_id}} ; + # } + + $print_tbody .= qq~$val~ ; + } + + my $start_date = substr($db{$tables}{$id}{date_from},0,10); + my $end_date = substr($db{$tables}{$id}{date_to},0,10); + # my @event_dates = () ; + + my $year = substr($db{$tables}{$id}{date_from}, 0, 4) ; + my $month = substr($db{$tables}{$id}{date_from}, 5, 2) ; + my $day = substr($db{$tables}{$id}{date_from}, 8, 2) ; + + my $year_end = substr($db{$tables}{$id}{date_to}, 0, 4 ) ; + my $month_end = substr($db{$tables}{$id}{date_to}, 5, 2 ) ; + my $day_end = substr($db{$tables}{$id}{date_to}, 8, 2 ) ; + + # push @event_dates, $year . '-' . $month . '-' . $day ; + + # my $Dd = Delta_Days($year,$month,$day, $year_end,$month_end,$day_end); + + my $row_count = 0; + # for my $event_date (sort @event_dates) { + $xlsxcol = 0 ; + $row_count++ ; + + if (($quote_created and not $quote_accepted and not $quote_completed) or ($quote_completed and not $quote_created and not $quote_accepted and not $quote_completed)) { + $xlsxrow-- ; + } + + my @event_sys = split(/;/,$db{$tables}{$id}{event_system_id_multiple}) ; + my $cnt_event_sys = 0 ; + foreach (split(/;/,$db{$tables}{$id}{event_system_id_multiple})) { + $cnt_event_sys++ ; + } + $cnt_event_sys = 1 unless $cnt_event_sys ; + + foreach my $col_name (@col_display_excel) { + + next if ($quote_created and not $quote_accepted and not $quote_completed) or ($quote_completed and not $quote_created and not $quote_accepted and not $quote_completed) ; + + $val = $db{$tables}{$id}{$col_name} ; + + # $xlsxrow-- if $col_name ne 'event_start' ; + + if ($col_name eq 'event_end') { $val = substr($db{$tables}{$id}{date_to},0,16) ; } + elsif ($col_name eq 'event_start') { $val = substr($db{$tables}{$id}{date_from},0,16) ; } + elsif ($col_name eq 'nr') { + $val = $id ; + if ($db{$table}{$id}{demo_id}) { + for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format108) ; $xlsxrow++; } # green + $xlsxrow = $xlsxrow - $cnt_event_sys ; + } elsif ($analytics_events{$id}) { + for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format107) ; $xlsxrow++; } # green + $xlsxrow = $xlsxrow - $cnt_event_sys ; + } elsif ($quote_completed) { + for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format80) ; $xlsxrow++; } # green + $xlsxrow = $xlsxrow - $cnt_event_sys ; + } elsif ($quote_accepted) { + my $accp_format = $format77 ; + my @fixed_system_overall_statuses = split(/\;/,$db{$tables}{$id}{fixed_system_overall_status}) ; + my @event_system_ids = split(/\;/,$db{$tables}{$id}{event_system_id_multiple}) ; + my $event_sys_cnt = 0 ; my $event_sys_test_status = 0 ; my $got_some_fixed = 0 ; my $possible_format = $format103 ; # '164473' ; # Dark Blue $format103 + foreach my $event_id (@event_system_ids) { + if ($db{event_systems}{$event_id}{system_type} eq 'fixed') { + $tt_txt = 'Accepted and tests show All Clear for the Fixed Systems' if $tt_txt eq 'Accepted' ; + $got_some_fixed = 1 ; + if ($fixed_system_overall_statuses[$event_sys_cnt] == 3) { # Not Clear + # $fixed_status_color = '5d09d3' ; # Dark Purple $format105 + $possible_format = $format105 ; + $tt_txt = 'Accepted but Not Clear on some Fixed Systems' ; + } elsif ($fixed_system_overall_statuses[$event_sys_cnt] == 2) { # Sound Issue + # $fixed_status_color = '5d092c' ; # $format106 + $possible_format = $format106 ; + $tt_txt = 'Accepted but Sound Issue found on some Fixed Systems' ; + } + } + $event_sys_cnt++ ; + } + if ($got_some_fixed) { $accp_format = $possible_format ; } + for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$accp_format) ; $xlsxrow++; } # blue + $xlsxrow = $xlsxrow - $cnt_event_sys ; + } elsif ($quote_pending) { + for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format79) ; $xlsxrow++; } # blue + $xlsxrow = $xlsxrow - $cnt_event_sys ; + # next ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format79) ; # orange + } elsif ($quote_cancelled) { + for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format81) ; $xlsxrow++; } # red + $xlsxrow = $xlsxrow - $cnt_event_sys ; + } elsif ($quote_rejected ) { + for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format104) ; $xlsxrow++; } # red + $xlsxrow = $xlsxrow - $cnt_event_sys ; + } elsif ($quote_created) { # create by schools_manager + # next ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format78) ; # yellow + } + $xlsxcol++ ; + next ; + } elsif ($col_name eq 'event') { + $val = $db{$tables}{$id}{ref} ; + for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format82) ; $xlsxrow++; } + $xlsxrow = $xlsxrow - $cnt_event_sys ; + $xlsxcol++; + next ; + } elsif ($col_name eq 'date') { + $val = substr($event_date, 5, 2 ) ; + $val = substr($event_date, 8, 2 ) . ' ' . $month_fullname[$val - 1] . ' ' . substr($event_date, 0, 4 ) ; + } elsif ($col_name eq 'days') { + $val = $db{$tables}{$id}{qty} ; + } elsif ($col_name eq 'type_of_system') { + $val = $db{$tables}{$id}{event_type} ; + } elsif ($col_name eq 'system_details') { + # $val = '' ; + # foreach my $type_id (split(",",$db{$tables}{$id}{type_details_id})) { + # $val .= qq~$db{event_type_details}{$type_id}{name}, ~; + # } + # chop $val if $val ; chop $val if $val ; + $val = join (", ", map{ "$db{event_type_details}{$_}{name}" } split(",",$db{$tables}{$id}{type_details_id})) ; + } elsif ($col_name eq 'system_name') { + + for (0 .. $cnt_event_sys-1) { + $val = qq~$db{event_systems}{$event_sys[$_]}{name}~ unless $db{event_systems}{$event_sys[$_]}{description} ; + $val = qq~$db{event_systems}{$event_sys[$_]}{name} [$db{event_systems}{$event_sys[$_]}{description}]~ if $db{event_systems}{$event_sys[$_]}{description} ; + if ($event_date ne $end_date){ + &report_write_events($val, 0) ; + } else { + &report_write_events($val, 1) ; + } + $xlsxrow++; + } + $xlsxrow = $xlsxrow - $cnt_event_sys ; + + } elsif ($col_name eq 'sport_type') { + my @sptyps2 = split(/\,/,$db{$tables}{$id}{sport_type_ids}) ; + $val = '' ; + foreach $_sp (@sptyps2) { + $val .= qq~$sort_type{$_sp} & ~ ; + } + chop $val if $val ; chop $val if $val ; + # } elsif ($_ eq 'cities' && $row_count == 1) { + } elsif ($col_name eq 'cities') { + $val = qq~$db{$tables}{$id}{city}~ ; + if ($db{$tables}{$id}{city_id} =~ /,/) { + $val = '' ; + foreach my $c_id (split(",",$db{$tables}{$id}{city_id})) { + $val .= qq~$db{cities}{$c_id}{city}, ~ ; + } + chop $val if $val ; chop $val if $val ; + } + } elsif ($col_name eq 'region') { + $val = qq~$db{$tables}{$id}{region}~ ; + } elsif ($col_name eq 'venue') { + $val = '' ; + foreach my $venue_id (split(",",$db{$tables}{$id}{organisation_ids})) { + $val .= qq~$organisation{$venue_id} & ~ ; + } + chop $val if $val ; chop $val if $val ; chop $val if $val ; + } elsif ($col_name eq 'club_names') { + $val = '' ; + foreach my $club_id (split(";",$db{$tables}{$id}{club_ids})) { + $val .= qq~$db{clubs}{$club_id}{name}, ~ ; + } + chop $val if $val ; chop $val if $val ; + } + + elsif ($col_name eq 'operators') { + $val = '' ; + # my @op_split3 = split(/;~;/,$db{$table}{$id}{operator_ids}) ; + # foreach my $op_id (split(/\,/,$op_split3[0])) { + foreach my $op_id (split(/\,/,$db{$tables}{$id}{operator_ids})) { + $val .= qq~$name{$op_id} [$email{$op_id}], ~ ; + } + chop $val if $val ; chop $val if $val ; + } + elsif ($col_name eq 'client') { + $val = $db{$tables}{$id}{customer} ; + } elsif ($col_name eq 'poc_name') { + $val = $db{event_quotes_poc}{$db{$tables}{$id}{poc_id}}{name} ; + } elsif ($col_name eq 'poc_contact_nr') { + $val = $db{event_quotes_poc}{$db{$tables}{$id}{poc_id}}{contact_nr} ; + } elsif ($col_name eq 'category_1') { + $val = $db{event_quotes_categories}{$db{$tables}{$id}{category_id_1}}{category} ; + } elsif ($col_name eq 'category_1_details') { + $val = $cat_details[0] ; + } elsif ($col_name eq 'category_2') { + $val = $db{event_quotes_categories}{$db{$tables}{$id}{category_id_2}}{category} ; + } elsif ($col_name eq 'category_2_details') { + $val = $cat_details[1] ; + } elsif ($row_count != 1) { + # $val = '' ; + } + + if ($col_name ne 'system_name') { + + for (1 .. $cnt_event_sys) { + if ($event_date ne $end_date){ + &report_write_events($val, 0) ; + } else { + &report_write_events($val, 1) ; + } + $xlsxrow++; + } + $xlsxrow = $xlsxrow - $cnt_event_sys ; + } + + # } + # ------------------------------------------------------------------------- HTML AFTER + $xlsxcol++; + } + + $xlsxrow = $cnt_event_sys + $xlsxrow ; + + my $quote_nr = $quote_nr ; $quote_nr =~ s/'//iog; unless ($quote_nr) { $quote_nr = $id ; } + + # if ($useropts{boss}{$username} or $useropts{super}{$username}) { } + + # my $view_butt = qq~~ ; + my $edit_butt = qq~~ ; + # my $delete_butt = ($glod_user_level < 4 || $quote_accepted || $quote_completed || $quote_rejected || $quote_pending) ? '' : qq~~ ; + my $delete_butt = ($glod_user_level < 3 || $quote_accepted || $quote_completed || $quote_rejected || $quote_pending) ? '' + : ($db{$table}{$id}{demo_id}) ? qq~~ + : ($analytics_events{$id}) ? qq~~ + : qq~~ ; + + my $copy_butt = qq~~ ; + + # my $copy_butt = qq~~; + # my $pdf_butt = qq~~; + my $pdf_butt .= qq~~; + + $email_butt = qq~~; + + my %emailed_op_ids = () ; my $all_op_ids = 1 ; my $cnt_op_ids = 0 ; + foreach my $op_id (split(/\;/,$db{$tables}{$id}{emailed_op_ids})) { + $emailed_op_ids{$op_id} = 1 ; + } + + foreach my $op_id2 (split(/\,/,$db{$tables}{$id}{operator_ids})) { + $all_op_ids = 0 if $op_id2 and not $emailed_op_ids{$op_id2} ; + $cnt_op_ids++ if $op_id2 ; + } + + if ($all_op_ids and $cnt_op_ids) { + $trigger_jquery_raw .= qq~ + \$("#email_$id").css({ + "background-color": "lightgrey", + "border-color": "lightgrey" + }); + ~ ; + } + + if ($glod_user_level < 3) { + $delete_butt = '' ; + if ($quote_completed || $quote_cancelled || $quote_rejected) { + $edit_butt = '' ; + } + } + + # $edit_butt = '' if $usertype eq 'support' ; + # $edit_butt = '' if $quote_cancelled && !$useropts{it}{$username}; + + $edit_butt = qq~$edit_butt ~ if $edit_butt ; + $copy_butt = qq~$copy_butt ~ if $copy_butt ; + $delete_butt = qq~$delete_butt ~ if $delete_butt ; + $pdf_butt = qq~$pdf_butt ~ if $pdf_butt ; + $email_butt = qq~$email_butt ~ if $email_butt ; + + if ($quote_created and not $quote_completed and not $quote_accepted) { + $pdf_butt = qq~~ ; $email_butt = qq~~ ; + } + + # $email_butt = qq~ ~ unless $email_butt ; + # $pdf_butt = qq~ ~ unless $pdf_butt ; + + $print_tbody .= qq~ $edit_butt$copy_butt$delete_butt$pdf_butt$email_butt~ ; + } + + $worksheet{$ws}->set_column(0,0,10) ; + $worksheet{$ws}->set_column(1,1,50) ; + $worksheet{$ws}->set_column(2,3,20) ; + $worksheet{$ws}->set_column(4,4,10) ; + $worksheet{$ws}->set_column(5,10,30) ; + $worksheet{$ws}->set_column(11,11,75) ; + $worksheet{$ws}->set_column(12,21,30) ; + + &report_xlsx_export_footer('L',15,'events') ; + + if ($usertype eq 'support') { + $fnsortcol = 1 ; # start date + $fnsortorder = 'asc' ; + } + + # &common_min_extra_crumb("search-$lcpage\s","Search Screen") if $glod_user_level > 3 ; + &common_min_extra_crumb("filter-$lcpage\s","Search Screen") if $glod_user_level > 3 ; + +} #------------------------------------------------------------------------------- + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub add_db_fields { + + &hidden_fields ; + $hidden{id} = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &hidden_fields ; + $hidden{id} = 1 ; + # $readonly{ref} = 'READONLY' ; + +} #------------------------------------------------------------------------------------------ + +sub view_db_fields { + + &hidden_fields ; + $hidden{id} = 1 ; + $label{ref} = 1 ; + $label{qty} = 1 ; + $label{date_from} = 1 ; + $label{date_to} = 1 ; + $label{sport_type_ids} = 1 ; + $label{region_id} = 1 ; + $label{city_id} = 1 ; + $label{organisation_ids} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub hidden_fields { + + # if ($glod_user_level < 4) { + if ($glod_user_level < 3) { + + $ignore{type_of_system} = 1 ; + $ignore{system_details} = 1 ; + $ignore{system_name} = 1 ; + $ignore{operators} = 1 ; + # $ignore{operator_ids} = 1 ; + } + + if ($glod_user_level < 4) { + # if ($glod_user_level < 3) { + $ignore{po_nr} = 1 ; + $ignore{income} = 1 ; + $ignore{sub_total} = 1 ; + $ignore{vat_total} = 1 ; + $ignore{grand_total} = 1 ; + $ignore{custom_set} = 1 ; + + } + + # $ignore{custom_set} = 1 ; + + $ignore{event_system_calibration_ids} = 1 ; + $ignore{event_system_calibration_status} = 1 ; + + $ignore{category_1_details} = 1 ; + $ignore{category_2_details} = 1 ; + + $ignore{iattachslip} = 1 ; + $ignore{iattachupload_1} = 1 ; + $ignore{iattachupload_2} = 1 ; + $ignore{iattachupload_3} = 1 ; + + $ignore{iattachupload_1} = 1 ; + $ignore{iattachupload_2} = 1 ; + $ignore{iattachupload_3} = 1 ; + + $ignore{sport_type_ids_readonly} = 1 ; + $ignore{region_id_readonly} = 1 ; + $ignore{city_id_readonly} = 1 ; + $ignore{organisation_ids_readonly} = 1 ; + $ignore{linear_id_readonly} = 1 ; + $ignore{custom_selected_region} = 1 ; + $ignore{custom_selected_country} = 1 ; + # $ignore{date_to} = 1 ; + # $ignore{date_from} = 1 ; + $ignore{iaction} = 1 ; + $required{qty} = 4 ; # number + $required{quote_nr} = 1 ; + $readonly{quote_nr} = 'READONLY' ; + $required{quote_to} = 1 ; + $required{currency} = 1 ; + $required{roe} = 1 ; + $required{ref} = 1 ; + $required{region_id} = 1 ; + $required{country_id} = '' ; + $required{city_id} = 1 ; + + $required{poc_name} = 1 ; + $required{poc_contact_nr} = 1 ; + $required{category_id_1} = 1 ; + $required{category_1_details} = 1 ; + $required{category_id_2} = 1 ; + $required{category_2_details} = 1 ; + + $hidden{quote_date} = 2 ; + $hidden{last_update} = 2 ; + $hidden{user_id} = 2 ; + $hidden{datetime} = 2 ; + $ignore{saveandexit} = 1 ; + $ignore{income} = 1 ; + $ignore{expenses} = 1 ; + $trigger_jquery_raw .= qq~var curr_changed=0;~; + $trigger_jquery_raw .= qq~var curr_changedW=0;~; + $trigger_jquery_raw .= qq~\$.validate();~; + $extra_js .= qq~~; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + + $selected{max_cams}{10} = 'SELECTED'; + &select_opts('') ; + %col_name = () ; + &db_min_ro($table,'*',"id > 1 AND id < 10",'','') ; + + $page_title = substr($page_title,0,-1) ; + $db{$table}{''}{quote_nr} = &db_min_get_max($table,'quote_nr') ; + $db{$table}{''}{qty} = 1 ; + + # if ($username eq 'rory') { $db{$table}{''}{quote_nr} = 1000 ; } + + &add_db_fields ; + + &build_boxes('','save') ; + + local $all_select_ids_string = join(",",@all_select_ids) ; + $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true,search_contains: true });~ ; + +} #------------------------------------------------------------------------------------------ + +sub view_screen { + + &edit_screen ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + unless ($i{id}) { $warning = qq(NO ID) ; return ; } + + # my $users_cols = "id,name,user_type" ; $users_cols = "id,name,user_type,region_ids" if $glod_user_level < 4 ; + my $users_cols = "id,name,user_type" ; $users_cols = "id,name,user_type,region_ids" if $glod_user_level < 3 ; + + &db_min_ro('users',$users_cols,"`user_type` LIKE 'casual%' OR `user_type` = 'schools_manager'",'','') ; + foreach (keys %{$db{users}}) { + next if $db{users}{$_}{user_type} eq 'schools_manager' ; + $casual_name{$_} = $db{users}{$_}{name} ; + $casual_type{$_} = uc substr($db{users}{$_}{user_type},-1,1) ; + $casuals{$_} = 1 if substr($db{users}{$_}{user_type},0,6) eq 'casual' ; + } + + # unless ($iaction eq 'save' or $iaction eq 'update') { + &db_min_ro($table,'*',"id='$i{id}'",'','') ; + # } + + # if ($glod_user_level < 4) { + + # my @abcdef = split(/ /,$db{$table}{$i{id}}{date_from}) ; + + # my ($year1,$month1,$day1) = split(/-/,$abcdef[0]) ; + + # my ($hour1,$min1,$sec1) = split(/:/,$abcdef[1]) ; + + # $trigger_jquery .= qq~ + + # const date1 = new Date("$year1-$month1-$day1T$hour1:$min1:$sec1"); + # const date2 = new Date("$now_year-$now_mm-$now_ddT$now_hour:$now_min:$now_sec"); + + # let timeDiffMillis = Math.abs(date1 - date2); + # let timeDiffHours = timeDiffMillis / (1000 * 60 * 60); + + # if (date1 >= date2 && timeDiffHours <= 18) { + # \$("#cancelbutt").removeClass('btn btn-danger').addClass('btn btn-void'); + # } + + # ~ ; + # } + + my @system_name_ids = split(";",$db{$table}{$i{id}}{event_system_id_multiple}) ; + my @club_ids = split(";",$db{$table}{$i{id}}{club_ids}) ; + my @op_ids = ($db{$table}{$i{id}}{operator_ids} =~ /,/) ? split(",",$db{$table}{$i{id}}{operator_ids}) : ($db{$table}{$i{id}}{operator_ids} =~ /;/) ? split(";",$db{$table}{$i{id}}{operator_ids}) : $db{$table}{$i{id}}{operator_ids} ; + + my $cnt_rows = 0 ; + for (1 .. $nr_of_system_names_and_clubs) { + $cnt_rows = $_ if $system_name_ids[$_ - 1] or $club_ids[$_ - 1] ; + } + + our @table_op_ids = () ; + our @multi_select_op_ids = () ; + + for (1 .. $cnt_rows) { + push @table_op_ids,$op_ids[$_ - 1] if $op_ids[$_ - 1] ; + push @table_op_ids,0 unless $op_ids[$_ - 1] ; + } + for ($cnt_rows+1 .. $nr_of_system_names_and_clubs) { + push @multi_select_op_ids,$op_ids[$_ - 1] if $op_ids[$_ - 1] ; + } + + our $quote_completed = $db{$table}{$i{id}}{quote_completed} ; + our $quote_accepted = $db{$table}{$i{id}}{quote_accepted} ; + our $quote_pending = $db{$table}{$i{id}}{quote_pending} ; + our $quote_cancelled = $db{$table}{$i{id}}{quote_cancelled} ; + our $quote_rejected = $db{$table}{$i{id}}{quote_rejected} ; + + # our $cancel_butt = ($d_check[2] > $now_ccyymmddhrmnsc && $iaction eq 'edit' && ($quote_completed || $quote_accepted || $quote_pending) && ($glod_user_level > 2 || $is_schools_manager)) ? 1 : 0 ; + our $cancel_butt = ($iaction eq 'edit' && ($quote_completed || $quote_accepted || $quote_pending) && ($glod_user_level > 2 || $is_schools_manager)) ? 1 : 0 ; + our $invoice_exists = 1 if $db{$table}{$i{id}}{invoice_nr} ; + + # if ($is_schools_manager) { + if ($is_schools_manager || $glod_user_level < 4) { + my @ed_from = &common_split_sql_time($db{$table}{$i{id}}{date_from}) ; + my @d_check = &common_add_delta_dhms($ed_from[0],$ed_from[1],$ed_from[2],$ed_from[3],$ed_from[4],$ed_from[5],0,-18,0,0) ; # go 18 hours back from event start + + if ($d_check[2] < $now_ccyymmddhrmnsc) { + $cancel_butt = 0 ; + } + } + + # &common_debug("cancel_butt=$cancel_butt [$i{id}] [$db{$table}{$i{id}}{date_from}] [($d_check[2] > $now_ccyymmddhrmnsc && iaction=$iaction eq 'edit' && (quote_completed=$quote_completed || quote_accepted=$quote_accepted || quote_pending=$quote_pending) && (glod_user_level=$glod_user_level > 2 || is_schools_manager=$is_schools_manager))]"); + + &db_min_ro('events','id,event_quote_nr,category,user_id,startdate,enddate',"event_quote_nr='$db{$table}{$i{id}}{quote_nr}'",'','') ; + + $max_cams = $db{$table}{$i{id}}{max_cams} if $db{$table}{$i{id}}{max_cams} ; + + $page_title = substr($page_title,0,-1) ; + $page_title .= " : $i{id}" ; + + $custom_back_button = qq~ ~ ; + # $custom_back_button = qq~$val~ ; + + # our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + &common_min_footer('id',"$lcpage\s"); + + &edit_db_fields ; + + $selected{max_cams}{$db{$table}{$i{id}}{max_cams}} = 'SELECTED'; + $selected{casual_worker}{$db{$table}{$i{id}}{casual_worker}} = 'SELECTED'; + $selected{casual_worker_2}{$db{$table}{$i{id}}{casual_worker_2}} = 'SELECTED'; + + # my @assigned_users_a = split(/\:/,$db{$table}{$i{id}}{operator_names_type_a}) ; + # my @assigned_users_b = split(/\:/,$db{$table}{$i{id}}{operator_names_type_b}) ; + + # for (@assigned_users_a){ $selected{operator_names_type_a}{$_} = 'SELECTED'; } + # for (@assigned_users_b){ $selected{operator_names_type_b}{$_} = 'SELECTED'; } + + # $selected{operator_names_type_b}{$db{$table}{$i{id}}{operator_names_type_b}} = 'SELECTED'; + + &select_opts($i{id}) ; + + our $saveandexit = 1 ; + + &build_boxes($i{id},'update') ; + + &common_min_extra_crumb("filter-$lcpage\s","Search $ucfirstpage\s") if $glod_user_level > 3 ; + + local $all_select_ids_string = join(",",@all_select_ids) ; + $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true,search_contains: true });~ ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes { + + my ($id,$action) = @_ ; + + our @jquery_trigger_fields = () ; + our @jquery_custom_vat_ids = () ; + our @jquery_duty_ids = () ; + our @jquery_workings_trigger_fields = () ; + + push @jquery_trigger_fields, 'inputRoe' ; + push @jquery_workings_trigger_fields, 'inputRoe' ; + + for (1 .. 15) { + push @jquery_workings_trigger_fields, "checkboxVat_workings_event_$_" ; + push @jquery_workings_trigger_fields, "checkboxExcl_workings_event_$_" ; + # push @jquery_workings_trigger_fields, "checkboxVat_$_\_workings_casual_users" ; + # push @jquery_workings_trigger_fields, "checkboxExcl_$_\_workings_casual_users" ; + } + &tab_curr_symbols; + + foreach $col(keys %required) { + &common_min_forms_required ; + } + + our $tab_cnt = 0 ; + + &tab_load_vars; + + $print_box_content_rows .= &common_min_forms_start($table) ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq~ +
    +
    ~ ; + &build_boxes_top($id); + $print_box_content_rows .= qq~ +
    +
    + ~ ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq~
    ~ ; + + &tab_cnt; + + $print_box_content_rows .= qq(
    + +
    ); + + our %tab_sections = () ; + + foreach (keys %cntxt) { + + my $tab_name = &tab_names($_) ; my $active = '' ; + + # # if ($is_schools_manager) { + # if ($glod_user_level < 4) { + # $active = ($_==2) ? 'active' : '' ; + # } else { + # $active = (($_==1 && $db{$table}{$id}{activetab} eq '') || ($db{$table}{$id}{activetab} eq $tab_name)) ? 'active' : '' ; + # } + + $active = ($_==2) ? 'active' : '' ; + + # if (($_==1) and ($db{$table}{$id}{activetab} eq '')) { + # $active = 'active' ; + # } + # elsif ($db{$table}{$id}{activetab} eq $tab_name) { + # $active = 'active' ; + # } + + my $colsleft = 12 ; my $showright = '' ; + + if ($cntxt{$_} eq 'one' or $cntxt{$_} eq 'seven') { + $colsleft = 6 ; + $showright = 1 ; + } + + $print_box_content_rows .= qq~
    ~; + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_left($id,$_); + $print_box_content_rows .= qq~
    ~ ; + + if ($showright) { + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_right($id,$_); + $print_box_content_rows .= qq~
    ~ ; + } + + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~
    ~ ; + + if ($id) { + $print_box_content_rows .= qq~ +
    +
    ~ ; + $print_box_content_rows .= ($tab_name eq 'Quote') ? qq~~ : qq~~ ; + $print_box_content_rows .= &common_min_box_foot; + } + + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~
    ~ ; + } + + $print_box_content_rows .= qq~ +
    +
    + ~ ; + + $print_box_content_rows .= qq~
    ~ ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_bottom($id); + $print_box_content_rows .= qq~
    ~ ; + + #-------------------------------------------------------------------------- + + our $skip_save_btn = ($quote_completed && $glod_user_level <= 3) ? 1 : 0 ; + + $print_box_content_rows .= &common_min_forms_end($id,$table,$action,$skip) ; + + my $jquery_trigger_ids = '#' . join(",#",@jquery_trigger_fields) ; + my $jquery_workings_trigger_ids = '#' . join(",#",@jquery_workings_trigger_fields) ; + + my $jq_tab_var = '' ; + my $jq_tab = '' ; + my $inp_tab_val = '' ; + foreach (keys %cntxt) { + $jq_tab_var .= qq(var totalTab_$_=0 ; ) ; + $jq_tab .= qq(totalTab_$_=0 ; ) ; + } # $inp_tab_val .= qq(\$("#inputTotal_tab_$_").val(totalTab_$_.toFixed(2)) ;) ; + + # $trigger_jquery_raw .= qq~ + # \$("#selectCurrency").change(function() { + # curr_changed=1; + # curr_changedW=1; + # console.log("1. curr_changed: "+curr_changed) ; + # calcCurr(); + # }); + + # \$('#event_quotes-form:checkbox').change(function() { + # calcAll(); + # }); + + # function calcCosting(excl,item,qty,usd,conv,vat,ttl) + # { + # var itval = item.val(); + # var uval = usd.val(); + # var cval = conv.val(); // currency amount + # var qval = qty.val(); + # var vval = vat.val(); + # // var tval = ttl.val(); + + # if (excl.val() != 0){ + + # var xval = 1; + + # } + + # else if (excl.val() == 0){ + + # var xval = 0; + + # } + # //var xval = excl.val(); + # var dis = \$("#selectDiscount").val(); + # var roe = \$("#inputRoe").val(); // getNum() + + # if (!itval) { + # calcAll(); + # return ; + # } + + # var arrP = itval.split(":"); // 3:0.00:100.00:200.00:223.00:223.00:250.00:250.00:200.00 // id:freight:nett:main_price:gross_10_1_50:gross_10_51_plus:gross_20_1_50:gross_20_51_plus:gross_50 // + # var list = { freight:arrP[1], nett:arrP[2], main_price:arrP[3], source_admin:arrP[4], perc3:arrP[5], perc5:arrP[6], perc6:arrP[6], perc8:arrP[7], perc10:arrP[8], perc15:arrP[9], perc20:arrP[10] }; + + # if (!qval) { + # qval=1; + # qty.val(qval); + # } // set quantity if blank + + # if (!uval) // set USD amount if no amount + # { + # var uval = list.main_price; + # if (dis==3 && qval>0) + # { + # uval=list.perc3; + # } + # else if (dis==5 && qval>0) + # { + # uval=list.perc5; + # } + # else if (dis==6 && qval>0) + # { + # uval=list.perc6; + # } + # else if (dis==8 && qval>0) + # { + # uval=list.perc8; + # } + # else if (dis==10 && qval>0) + # { + # uval=list.perc10; + # } + # else if (dis==15 && qval>0) + # { + # uval=list.perc15; + # } + # else if (dis==20 && qval>0) + # { + # uval=list.perc20; + # } + # } + + # var usdAmnt = uval * 1 ; + # // var currAmnt = usdAmnt / roe ; + # var currAmnt = usdAmnt * roe ; + # var ttlAmnt = currAmnt * qval ; + + # usd.val(usdAmnt.toFixed(2)) ; // set USD currency amount + # conv.val(currAmnt.toFixed(2)) ; // set foreign currency amount + # ttl.val(ttlAmnt.toFixed(2)) ; // set total amount + + # calcAll(); // recalculate the entire sheet + + # console.log("COSTINGS CALCCOSTINGS build boxes : USD AMOUNT="+usdAmnt + "CURR AMOUNT="+currAmnt + "TOTAL AMOUNT="+ttlAmnt) ; + + # // alert(usdAmnt+'(inputAmount_usd_$field):'+usd+':'+qty+'(inputQty_$field)') ; // 0.00:100.00:200.00:223.00:223.00:250.00:250.00:200.00 // + # } + + # function calcCostingWorkings(excl,item,qty,usd,conv,vat) + # { + # var itvalW = item.val(); + # var uvalW = usd.val(); + # var cvalW = conv.val(); // currency amount + # var qvalW = qty.val(); + # var vvalW = vat.val(); + # var xvalW = excl.val(); + + # if (excl.val() != 0){ + # var xvalW = 1 ; + # } + # else if (excl.val() == 0){ + # var xvalW = 0 ; + # } + + # // var disW = \$("#selectDiscount").val(); + # var roeW = \$("#inputRoe").val(); // getNum() + + # if (!itvalW) { + # calcAllWorkings(); + # return ; + # } + + # if (!qvalW) { + # qvalW = 1 ; + # qtyW.val(qvalW) ; + # } // set quantity if blank + + # var usdAmntW = uvalW * 1 ; + # var currAmntW = usdAmntW * roeW ; + # var ttlAmntW = currAmntW * qvalW ; + + # usd.val(usdAmntW.toFixed(2)) ; // set USD currency amount + # // conv.val(currAmntW.toFixed(2)) ; // set foreign currency amount + # conv.val(ttlAmntW.toFixed(2)) ; // set foreign currency amount + # // ttl.val(ttlAmntW.toFixed(2)) ; // set total amount + + # calcAllWorkings(); // recalculate the entire sheet + + # // console.log("WORKINGS CALCCOSTINGSWORKINGS build boxes : USD AMOUNT="+usdAmntW + "CURR AMOUNT="+currAmntW + "TOTAL AMOUNT="+ttlAmntW) ; + + # console.log("calcCostingWorkings tabs: EXCL="+xvalW+", DESCRIPTION="+item+", AMOUNT USD="+uvalW+", QTY="+qvalW+", AMOUNT="+ttlAmntW+", VAT="+vvalW) ; + + # } + + # function calcCurr() + # { + # var roe = \$("#inputRoe") ; + # // roe.val(1); // default currency to 1 + # // var curr = \$("#selectCurrency").val() ; + # // var url = "$useropts{scripts}/get/get_roe.pl?" + curr ; + # // \$.get(url, function(json) { + # // \$.each(json, function(key, data) { + # // roe.val(data.sell_rate); + # // }); + # // calcAll(); + # // }, + # // 'json'); + # } + # ~; + + # $trigger_jquery_raw .= qq~ + # var currArr = {}; // var vat_total = {} ; var total_total = {} ; var subtotal = {} ; var fs_total = {} ; + # var currArrW = {}; + + # $js_curr_arr + + # var currVal = \$("#selectCurrency").val() ; + # var prevRoe = '' ; + # var curRoe = '' ; + + # var currValW = \$("#selectCurrency").val() ; + # var prevRoeW = '' ; + # var curRoeW = '' ; + + # var grandTtl = 0 ; + # var grandSub = 0 ; + # var grandVat = 0 ; + + # var grandTtlW = 0 ; + # var grandSubW = 0 ; + # var grandVatW = 0 ; + + # $jq_tab_var + # \$("$jquery_trigger_ids").change(function() { + # // calcAll(); + # }); + + # function calcAll() + # { + # if (!\$("#selectCurrency\_chosen").val()) { + # \$("#selectCurrency\_chosen").val('ZAR'); + # \$("#selectCurrency\_chosen").trigger("chosen:updated"); + # } + + # if (!\$("#inputRoe").val() || \$("#inputRoe").val() <= 0) { \$("#inputRoe").val(1) ; } + + # grandTtl= 0 ; + # grandSub = 0 ; + # grandVat = 0 ; + + # $jq_tab + # $re_calc_jquery + + # \$("#inputSub_total").val(grandSub.toFixed(2)) ; + # \$("#inputVat_total").val(grandVat.toFixed(2)) ; + # \$("#inputGrand_total").val(grandTtl.toFixed(2)) ; + # \$("#inputIncome").val(grandTtl.toFixed(2)) ; + + # calcProfitLoss() ; + + # console.log("COSTINGS CALC_ALL: SUB TOTAL="+grandSub + "VAT TOTAL="+grandVat + "GRAND TOTAL="+grandTtl ) ; + + # curr_changed=0; + # // console.log("2. curr_changed: "+curr_changed) ; + # } + + # // \$("$jquery_workings_trigger_ids").change(function() { + # ///calcAllWorkings(); + # // }); + + # function calcAllWorkings() + # { + # if (!\$("#selectCurrency\_chosen").val()) { + # \$("#selectCurrency\_chosen").val('ZAR'); + # \$("#selectCurrency\_chosen").trigger("chosen:updated"); + # } + + # if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) ; } + + # grandTtlW = 0 ; + # grandSubW = 0 ; + # grandVatW = 0 ; + + # $re_calc_jqueryW + + # \$("#inputTotal_amount_workings_event").val(grandSubW.toFixed(2)) ; + # \$("#inputTotal_vat_amount_workings_event").val(grandVatW.toFixed(2)) ; + # \$("#inputTotal_grand_amount_workings_event").val(grandTtlW.toFixed(2)) ; + # \$("#inputExpenses").val(grandTtlW.toFixed(2)) ; // Profit loss calculation + + # calcProfitLoss() ; + + # console.log("WORKINGS CALC_ALLWORKINGS: SUB TOTAL="+grandSubW + "VAT TOTAL="+grandVatW + "GRAND TOTAL="+grandTtlW ) ; + + # curr_changedW=0; + + # } + + # function calcProfitLoss() + # { + + # let inc = \$("#inputIncome").val() ; + # let exp = \$("#inputExpenses").val() ; + + # let pl = inc - exp ; + + # \$("#inputProfit_loss").val(pl.toFixed(2)) ; + # } + # ~ ; + + # $onload .= qq(onload="calcAll();"); + if ($iaction eq 'add'){ $onload .= qq~onload="calcCurr();"~ ; } + # $onload .= qq~onload="calcCurr();"~ ; + + &build_workings_costings_forms_jquery if $glod_user_level > 4 ; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_top { + + my ($id) = @_ ; + + &event_tabs_build_boxes_top($id) ; + + $trigger_jquery .= qq~ + + let qu_to = \$("select[name='quote_to']").val() ; + var colonIndex = qu_to.indexOf(":") ; var extractedNumber ; + if (colonIndex !== -1) { + extractedNumber = qu_to.substring(0, colonIndex); + } else { + extractedNumber = qu_to ; + } + if (extractedNumber != 5) { + \$("#inputPoc_name").removeAttr("data-validation") ; + \$("#inputPoc_contact_nr").removeAttr("data-validation") ; + \$("#selectCategory_id_1").removeAttr("data-validation") ; + \$("#textareaCategory_1_details").removeAttr("data-validation") ; + \$("#selectCategory_id_2").removeAttr("data-validation") ; + \$("#textareaCategory_2_details").removeAttr("data-validation") ; + + \$("label[for='inputPoc_name'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='inputPoc_contact_nr'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='selectCategory_id_1'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='textareaCategory_1_details'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='selectCategory_id_2'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='textareaCategory_2_details'] i.glyphicon-asterisk.yellow").remove(); + } + ~ ; + + $trigger_jquery_raw .= qq~ + + \$("select[name='quote_to']").change(function() { + + let qu_to = \$("select[name='quote_to']").val() ; + var colonIndex = qu_to.indexOf(":") ; var extractedNumber ; + if (colonIndex !== -1) { + extractedNumber = qu_to.substring(0, colonIndex); + } else { + extractedNumber = qu_to ; + } + + if (extractedNumber != 5) { + \$("#inputPoc_name").removeAttr("data-validation") ; + \$("#inputPoc_contact_nr").removeAttr("data-validation") ; + \$("#selectCategory_id_1").removeAttr("data-validation") ; + \$("#textareaCategory_1_details").removeAttr("data-validation") ; + \$("#selectCategory_id_2").removeAttr("data-validation") ; + \$("#textareaCategory_2_details").removeAttr("data-validation") ; + + \$("label[for='inputPoc_name'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='inputPoc_contact_nr'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='selectCategory_id_1'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='textareaCategory_1_details'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='selectCategory_id_2'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='textareaCategory_2_details'] i.glyphicon-asterisk.yellow").remove(); + } else if (extractedNumber == 5 && \$("label[for='inputPoc_name']").find("i.glyphicon.glyphicon-asterisk.yellow").length === 0) { + + \$("label[for='inputPoc_name']").append('') ; + \$("label[for='inputPoc_contact_nr']").append('') ; + \$("label[for='selectCategory_id_1']").append('') ; + \$("label[for='textareaCategory_1_details']").append('') ; + \$("label[for='selectCategory_id_2']").append('') ; + \$("label[for='textareaCategory_2_details']").append('') ; + + \$("#inputPoc_name").attr("data-validation", "required"); + \$("#inputPoc_contact_nr").attr("data-validation", "required"); + \$("#selectCategory_id_1").attr("data-validation", "required"); + \$("#textareaCategory_1_details").attr("data-validation", "required"); + \$("#selectCategory_id_2").attr("data-validation", "required"); + \$("#textareaCategory_2_details").attr("data-validation", "required"); + + } + }); + ~ ; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_left { + + my ($id,$tab) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(3,6) ; + + &event_tabs_build_qt_left($id,$tab); + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_right { + + my ($id,$tab) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(3,6) ; + + &tab_build_qt_right($id,$tab); + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_bottom { + + my ($id) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(2,2) ; + + $add_form_fields = '' ; + + # --------------- START GRAND TOTAL ---------------------------------------------------------------------------------------------------------------------- + + $print_box_content_rows .= &common_min_form_input('activetab',$db{$table}{$id}{activetab},'hidden') ; + + # --------------- END RAND TOTAL ------------------------------------------------------------------------------------------------------------------------ + +} #---------------------------------------------------------------------------------------- + +sub build_extra_name_row_1 { + + my ($row_cnt,$display) = @_ ; + my $count_dates_in_first_extra_row = 0 ; + $display = ($display) ? "style='display:none;'" : "" ; + my $extra_row_hearders_1 = qq~
    ~ ; + for (1 .. 20) { + $count_dates_in_first_extra_row++ if $days_active_arr[$_ - 1] ; + $date_is_displayed_in_first_extra_row{$_} = 1 if $days_active_arr[$_ - 1] && $count_dates_in_first_extra_row <= 10 ; + $extra_row_hearders_1 .= ($days_active_arr[$_ - 1] && $count_dates_in_first_extra_row <= 10 && $some_row_has_daily_op_1) ? qq~
    ~ : qq~~ ; + } + $extra_row_hearders_1 .= qq~
    ~ ; + return $extra_row_hearders_1 ; + +} #---------------------------------------------------------------------------------------- + +sub build_extra_name_row_2 { + + my ($row_cnt,$display) = @_ ; + $display = ($display) ? "style='display:none;'" : "" ; + my $extra_row_hearders_2 = qq~
    ~ ; + for (11 .. 20) { + $extra_row_hearders_2 .= ($some_row_has_daily_op_2 && $days_active_arr[$_ - 1] && !$date_is_displayed_in_first_extra_row{$_}) ? qq~
    ~ : qq~~ ; + } + $extra_row_hearders_2 .= qq~
    ~ ; + return $extra_row_hearders_2; + +} #---------------------------------------------------------------------------------------- + +sub build_system_name_form { + + my ($system_ids,$club_ids,$quote_accepted,$quote_rejected,$quote_cancelled,$daily_operator_ids,$days_active,$quote_completed) = @_ ; + + my @system_name_ids = split(";",$system_ids) ; + + # if ($system_ids =~ /f-/ && ($db{$table}{$i{id}}{supplier_ids} !~ /\b62\b/ || $db{$table}{$i{id}}{supplier_type_ids} !~ /\b6\b/)) { + + # $system_ids = "" ; + # foreach (@system_name_ids) { + # $system_ids = "$_;" if $_ !~ /f-/ ; + # } + # $system_ids =~ s/;+$// ; + # @system_name_ids = split(";",$system_ids) ; + + # } + + my @club_ids = split(";",$club_ids) ; + our @days_active_arr = split(/\;/,$days_active) ; + my @daily_op_ids = () ; + + # # my @arr_fixed_system_online_status = split(/\;/,$db{$table}{$i{id}}{fixed_system_online_status}) ; + # # my @arr_fixed_system_network_test = split(/\;/,$db{$table}{$i{id}}{fixed_system_network_test}) ; + # # my @arr_fixed_system_system_test = split(/\;/,$db{$table}{$i{id}}{fixed_system_system_test}) ; + # # my @arr_fixed_system_test_event = split(/\;/,$db{$table}{$i{id}}{fixed_system_test_event}) ; + # # my @arr_fixed_system_sound_test = split(/\;/,$db{$table}{$i{id}}{fixed_system_sound_test}) ; + # # my @arr_fixed_system_overall_status = split(/\;/,$db{$table}{$i{id}}{fixed_system_overall_status}) ; + # # my @arr_fixed_system_additional_comments = split(/\;/,$db{$table}{$i{id}}{fixed_system_additional_comments}) ; + + # # my @arr_calibrator_amounts_paid = split(/\;/,$db{$table}{$i{id}}{calibrator_amounts_paid}) ; + # # my @arr_calibrator_dates_paid = split(/\;/,$db{$table}{$i{id}}{calibrator_dates_paid}) ; + # # my @arr_event_system_calibration_ids = split(/\;/,$db{$table}{$i{id}}{event_system_calibration_ids}) ; + # # my @arr_event_system_calibration_status = split(/\;/,$db{$table}{$i{id}}{event_system_calibration_status}) ; + + # # my @arr_set_up_groups_head_operator_ids = split(/\;/,$db{$table}{$i{id}}{set_up_groups_head_operator_ids}) ; + # # my @arr_set_up_groups_status_ids = split(/\;/,$db{$table}{$i{id}}{set_up_groups_status_ids}) ; + + # # for (0 .. $nr_of_system_names_and_clubs - 1) { + + # # my $row_cnt = $_ + 1 ; + + # # $arr_fixed_system_online_status[$_] = "" if $arr_fixed_system_online_status[$_] !~ /(\d+)/g && $arr_fixed_system_online_status[$_] !~ /none/ ; + # # $arr_fixed_system_network_test[$_] = "" if $arr_fixed_system_network_test[$_] !~ /(\d+)/g && $arr_fixed_system_network_test[$_] !~ /none/ ; + # # $arr_fixed_system_system_test[$_] = "" if $arr_fixed_system_system_test[$_] !~ /(\d+)/g && $arr_fixed_system_system_test[$_] !~ /none/ ; + # # $arr_fixed_system_test_event[$_] = "" if $arr_fixed_system_test_event[$_] !~ /(\d+)/g && $arr_fixed_system_test_event[$_] !~ /none/ ; + # # $arr_fixed_system_sound_test[$_] = "" if $arr_fixed_system_sound_test[$_] !~ /(\d+)/g && $arr_fixed_system_sound_test[$_] !~ /none/ ; + # # $arr_fixed_system_overall_status[$_] = "" if $arr_fixed_system_overall_status[$_] !~ /(\d+)/g && $arr_fixed_system_overall_status[$_] !~ /none/ ; + # # $arr_fixed_system_additional_comments[$_] = "" if $arr_fixed_system_additional_comments[$_] !~ /(\d+)/g && $arr_fixed_system_additional_comments[$_] !~ /none/ ; + + # # $arr_calibrator_amounts_paid[$_] = "" if $arr_calibrator_amounts_paid[$_] !~ /(\d+)/g && $arr_calibrator_amounts_paid[$_] !~ /none/ ; + # # $arr_calibrator_dates_paid[$_] = "" if $arr_calibrator_dates_paid[$_] !~ /(\d+)/g && $arr_calibrator_dates_paid[$_] !~ /none/ ; + # # $arr_event_system_calibration_ids[$_] = "" if $arr_event_system_calibration_ids[$_] !~ /(\d+)/g && $arr_event_system_calibration_ids[$_] !~ /none/ ; + # # $arr_event_system_calibration_status[$_] = "" if $arr_event_system_calibration_status[$_] !~ /(\d+)/g && $arr_event_system_calibration_status[$_] !~ /none/ ; + + # # $arr_set_up_groups_head_operator_ids[$_] = "" if $arr_set_up_groups_head_operator_ids[$_] !~ /(\d+)/g && $arr_set_up_groups_head_operator_ids[$_] !~ /none/ ; + # # $arr_set_up_groups_status_ids[$_] = "" if $arr_set_up_groups_status_ids[$_] !~ /(\d+)/g && $arr_set_up_groups_status_ids[$_] !~ /none/ ; + + # # $system_used{fixed_report}{$row_cnt} = ($arr_fixed_system_online_status[$_] || $arr_fixed_system_network_test[$_] || $arr_fixed_system_system_test[$_] || $arr_fixed_system_test_event[$_] || $arr_fixed_system_sound_test[$_] || $arr_fixed_system_overall_status[$_] || $arr_fixed_system_additional_comments[$_]) ? 1 : 0 ; + # # $system_used{calibration_report}{$row_cnt} = ($arr_calibrator_amounts_paid[$_] || $arr_calibrator_dates_paid[$_] || $arr_event_system_calibration_ids[$_] || $arr_event_system_calibration_status[$_]) ? 1 : 0 ; + # # $system_used{set_up_report}{$row_cnt} = ($arr_set_up_groups_head_operator_ids[$_] || $arr_set_up_groups_status_ids[$_]) ? 1 : 0 ; + + # # } + + # event_system_head_operator_ids + + local $system_count = 0 ; local $system_day_cnt = 0 ; my %row_has_daily_op = () ; my $some_row_has_daily_op = 0 ; our $some_row_has_daily_op_1 = 0 ; our $some_row_has_daily_op_2 = 0 ; my $active_days_count = 0 ; + + foreach my $row (split(/\|/,$daily_operator_ids)) { + $system_count++ ; + + next unless $row ; + $system_day_cnt = 0 ; $active_days_count = 0 ; + foreach my $default_op (split(/\;/,$row)) { + $system_day_cnt++ ; + next if !$days_active_arr[$system_day_cnt-1] ; + $active_days_count++ ; + $default_op_ids{$system_count}{$system_day_cnt} = $default_op if $default_op ; + $row_has_daily_op{$system_count} = 1 if $default_op ; + $row_has_daily_op_1{$system_count} = 1 if $default_op && $active_days_count <= 10 ; + $row_has_daily_op_2{$system_count} = 1 if $default_op && $active_days_count > 10 ; + $some_row_has_daily_op = 1 if $default_op ; + $some_row_has_daily_op_1 = 1 if $default_op && $active_days_count <= 10 ; + $some_row_has_daily_op_2 = 1 if $default_op && $active_days_count > 10 ; + + } + } + + $active_days_count = 0 ; my $total_days = 0 ; + + foreach (@days_active_arr) { + $active_days_count++ if $_ ; + $total_days++ ; + } + + $some_row_has_daily_op = 0 if $active_days_count > 6 ; + + $fcol = 2 ; $lcol = 2 ; + + # $dlg_add_club = ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) ? '
    ' : qq~
    ~ ; + $dlg_add_club = ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) ? '
    ' : qq~
    ~ ; + + my $dlg_operator_ids = '' ; + + # if ($glod_user_level > 2 || ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled))) { + $add_form_fields .= qq~ +
    +
    + +
    +
    +
    +
    + +
    +
    + +
    + $dlg_add_club +
    + +
    + $dlg_operator_ids +
    +
    + ~ ; + + our %date_is_displayed_in_first_extra_row = () ; + + if ($active_days_count <= 6) { + + for (1 .. 20) { + $add_form_fields .= ($some_row_has_daily_op && $days_active_arr[$_ - 1]) ? qq~
    ~ : ($some_row_has_daily_op && !$days_active_arr[$_ - 1] && $final_day >= $_) ? qq~~ : + qq~~ ; + } + $add_form_fields .= qq~
    ~ ; + + } else { + + for (1 .. 20) { + $add_form_fields .= qq~~ ; + } + $add_form_fields .= qq~
    ~ ; + + } + + my $note_display_butt = qq~~ ; + + my $system_name_id = "" ; my $club_name_id = "" ; + + my @plus_button_ids = () ; my @event_system_ids = () ; my @event_club_ids = () ; my @event_operator_ids = () ; my @overall_op_ids = () ; + + my @table_system_name_ids = () ; my @table_club_name_ids = () ; my @table_operator_calibration_ids = () ; + + my $old_op_opts = $opts{operator_ids} ; + $opts{operator_ids} =~ s/\SELECTED//g ; + + for my $row_cnt (1 .. $nr_of_system_names_and_clubs) { + + if ($system_name_ids[$row_cnt - 1] =~ /f-/ && ($db{$table}{$i{id}}{supplier_ids} !~ /\b62\b/ || $db{$table}{$i{id}}{supplier_type_ids} !~ /\b6\b/)) { + $system_name_ids[$row_cnt - 1] = "" ; + $system_name_ids[$row_cnt] = "" if $system_name_ids[$row_cnt] =~ /f-/ ; + $club_ids[$row_cnt - 1] = "" ; + } + + my $select_sys_name = 0 ; my $select_club_name = 0 ; + + $add_form_fields .= ($active_days_count > 6 && $some_row_has_daily_op_1 && $row_cnt > 1 && ($row_has_daily_op{$row_cnt} || $system_name_ids[$row_cnt - 1] || $club_ids[$row_cnt - 1] || $table_op_ids[$row_cnt - 1])) ? qq~
    ~ : qq~~ ; + + $add_form_fields .= qq~~ if $row_cnt > 1 && !$system_name_ids[$row_cnt - 1] && !$club_ids[$row_cnt - 1] && !$row_has_daily_op{$row_cnt} && !$table_op_ids[$row_cnt - 1] ; + $add_form_fields .= qq~
    ~ if $row_cnt == 1 || $system_name_ids[$row_cnt - 1] || $club_ids[$row_cnt - 1] || $row_has_daily_op{$row_cnt} || $table_op_ids[$row_cnt - 1] ; + + push @plus_button_ids,"#btn_system_name_$row_cnt" ; + + my $input_fields_dates_1 = qq~~ ; + my $input_fields_1 = qq~~ ; + my $input_fields_dates_2 = qq~~ ; + my $input_fields_2 = qq~~ ; + + # if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + # $add_form_fields .= qq~
    ~ if $row_cnt > 1 and not $system_name_ids[$row_cnt - 1] and not $club_ids[$row_cnt - 1] ; + # } + + if ($row_cnt == 1 || $row_has_daily_op{$row_cnt} || $system_name_ids[$row_cnt - 1] || $club_ids[$row_cnt - 1] || $table_op_ids[$row_cnt - 1]) { + + # if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { + + $system_name_id = "inputSystem_name_" ; $club_name_id = "inputClub_name_" ; + $readonly{"system_name_$row_cnt"} = "READONLY" ; $readonly{"club_name_$row_cnt"} = "READONLY" ; $readonly{"operator_id_calibration_$row_cnt"} = "READONLY" ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $fcol = 4 ; + + my $system_id = $system_name_ids[$row_cnt - 1] ; + $system_id =~ s/f-//g ; + + $add_form_fields .= &common_min_form_input_col("system_name_$row_cnt",$db{event_systems}{$system_id}{name}) ; + $add_form_fields .= &common_min_form_input_col("club_name_$row_cnt",$db{clubs}{$club_ids[$row_cnt - 1]}{name}) ; + $add_form_fields .= &common_min_form_input_col("operator_id_calibration_$row_cnt",$db{users}{$table_op_ids[$row_cnt - 1]}{name}) ; + $add_form_fields .= qq~
    ~ ; + $fcol = 1 ; + if ($row_has_daily_op{$row_cnt} && $some_row_has_daily_op) { + for (1 .. 20) { + $readonly{"custom_operator_$row_cnt\_$_"} = "READONLY" ; + $add_form_fields .= ($days_active_arr[$_ - 1]) ? &common_min_form_input_col("custom_operator_$row_cnt\_$_",$db{users}{$default_op_ids{$row_cnt}{$_}}{name}) : "" ; + } + + } elsif ($row_has_daily_op{$row_cnt} && $some_row_has_daily_op_1) { + + my $displayed_dates = 0 ; + # $add_form_fields .= qq~
    ~ ; + + $input_fields_dates_1 = qq~
    ~ ; + $input_fields_1 = qq~
    ~ ; + $input_fields_dates_2 = qq~~ ; + $input_fields_2 = qq~~ ; + + my %date_used = () ; + + for (1 .. 20) { + if ($days_active_arr[$_ - 1] && $displayed_dates < 10) { + $input_fields_dates_1 .= qq~
    ~ ; + $readonly{"custom_operator_$row_cnt\_$_"} = "READONLY" ; + $input_fields_1 .= &common_min_form_input_col("custom_operator_$row_cnt\_$_",$db{users}{$default_op_ids{$row_cnt}{$_}}{name}) ; + $displayed_dates++ ; + $date_used{$_} = 1 ; + } + } + + for (11 .. 20) { + + if ($days_active_arr[$_ - 1] && !$date_used{$_}) { + $input_fields_2 = qq~
    ~ unless $input_fields_2 ; + $input_fields_dates_2 = qq~
    ~ unless $input_fields_dates_2 ; + $input_fields_dates_2 .= qq~
    ~ ; + $readonly{"custom_operator_$row_cnt\_$_"} = "READONLY" ; + $input_fields_2 .= &common_min_form_input_col("custom_operator_$row_cnt\_$_",$db{users}{$default_op_ids{$row_cnt}{$_}}{name}) ; + } + } + + $input_fields_1 .= qq~
    ~ ; + $input_fields_dates_1 .= qq~
    ~ ; + $input_fields_2 .= qq~
    ~ if $input_fields_2 ; + $input_fields_dates_2 .= qq~
    ~ if $input_fields_dates_2 ; + + } + + + $fcol = 4 ; + + } else { + + $system_name_id = "selectSystem_name_" ; $club_name_id = "selectClub_name_" ; $op_name_id = "selectOperator_id_calibration_" ; + + push @event_system_ids,"#$system_name_id$row_cnt\_chosen" ; + push @event_club_ids,"#$club_name_id$row_cnt\_chosen" ; + push @event_operator_ids,"#$op_name_id$row_cnt\_chosen" ; + push @overall_op_ids,"#selectOperator_id_calibration_$row_cnt" ; + + # $opts{fixed_event_system_id} .= qq~~ if $db{event_systems}{$_}{system_type} eq 'fixed' ; + # $opts{mobile_event_system_id} .= qq~~ if $db{event_systems}{$_}{system_type} eq 'mobile' ; + # $opts{mobile_or_solo_event_system_id} + + # $opts{"system_name_$row_cnt"} = (($system_used{fixed_report}{$row_cnt} && $system_used{set_up_report}{$row_cnt}) || ($system_used{fixed_report}{$row_cnt} && $system_used{calibration_report}{$row_cnt})) ? $opts{event_system_id} : ($system_used{fixed_report}{$row_cnt} || $system_name_ids[$row_cnt - 1] =~ /f-/) ? $opts{fixed_event_system_id} : ($system_used{set_up_report}{$row_cnt}) ? $opts{mobile_or_solo_event_system_id} : ($system_used{calibration_report}{$row_cnt}) ? $opts{mobile_event_system_id} : $opts{event_system_id} ; + $opts{"system_name_$row_cnt"} = (($system_used{fixed_report}{$row_cnt} && $system_used{set_up_report}{$row_cnt}) || ($system_used{fixed_report}{$row_cnt} && $system_used{calibration_report}{$row_cnt})) ? $opts{event_system_id} : ($system_used{fixed_report}{$row_cnt} || $system_name_ids[$row_cnt - 1] =~ /f-/) ? $opts{fixed_event_system_id} : ($system_used{set_up_report}{$row_cnt}) ? $opts{mobile_or_solo_event_system_id} : ($system_used{calibration_report}{$row_cnt}) ? $opts{mobile_event_system_id} : $opts{event_system_id} ; + + # $opts{"system_name_$row_cnt"} = $opts{event_system_id} ; + $opts{"club_name_$row_cnt"} = $opts{club_ids} ; + $opts{"operator_id_calibration_$row_cnt"} = $opts{operator_ids} ; + + $allow_deselect{"system_name_$row_cnt"} = ($system_used{fixed_report}{$row_cnt} || $system_used{set_up_report}{$row_cnt} || $system_used{calibration_report}{$row_cnt}) ? 0 : 1 ; + $allow_deselect{"club_name_$row_cnt"} = 1 ; $allow_deselect{"operator_id_calibration_$row_cnt"} = 1 ; + + my $sys_name_id = $system_name_ids[$row_cnt - 1] ; + $sys_name_id =~ s/f-//g ; + + # my $fixed_system_indication = ($system_name_ids[$row_cnt - 1] =~ /f-/) ? qq~~ : qq~~ ; + # my $aisa_system_indication = ($system_name_ids[$row_cnt - 1] !~ /f-/) ? qq~~ : qq~~ ; + + if ($sys_name_id) { + $trigger_jquery_raw .= qq~ + \$("#selectSystem_name_$row_cnt").val('$sys_name_id').trigger("chosen:updated") ; + orig_selected_system_names["$row_cnt"] = "$sys_name_id" ; + if (default_cost_item_rates[get_event_cost_id["$sys_name_id"]]) { + system_with_cost_item_rates_selected = 1 ; + } + ~ ; + } else { + push @table_system_name_ids,"#selectSystem_name_$row_cnt" ; + } + + my $club_id = $club_ids[$row_cnt - 1] ; + if ($club_id) { + $trigger_jquery_raw .= qq~\$("#selectClub_name_$row_cnt").val('$club_id').trigger("chosen:updated") ; ~ ; + } else { + push @table_club_name_ids,"#selectClub_name_$row_cnt" ; + } + + my $op_id = $table_op_ids[$row_cnt - 1] ; + + $preferred_title{"operator_id_calibration_$row_cnt"} = "Operator $row_cnt" ; + + $fcol = 4 ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= &common_min_form_select_col("system_name_$row_cnt",$sys_name_id) if $row_cnt == 1 ; + $add_form_fields .= &common_min_form_select_col("system_name_$row_cnt",'') if $row_cnt > 1 ; + $add_form_fields .= &common_min_form_select_col("club_name_$row_cnt",$club_ids[$row_cnt - 1]) if $row_cnt == 1 ; + $add_form_fields .= &common_min_form_select_col("club_name_$row_cnt",'') if $row_cnt > 1 ; + $add_form_fields .= &common_min_form_select_col("operator_id_calibration_$row_cnt",'') ; + + $add_form_fields .= qq~
    ~ ; + + $fcol = 2 ; + + my $clicked_op_butt = ($row_has_daily_op{$row_cnt}) ? qq~value="1"~ : qq~~ ; + + # if ($glod_user_level > 2) { + my $clicked_any_button = ($row_cnt == 1) ? "" : "" ; + $add_form_fields .= qq~~ ; + push @table_plus_button_ids,"#add_daily_operators_$row_cnt" ; # my $daily_op_exists = 0 ; + # } + + if (!$row_has_daily_op{$row_cnt} && $op_id) { + $trigger_jquery_raw .= qq~\$("#selectOperator_id_calibration_$row_cnt").val('$op_id') ; \$("#selectOperator_id_calibration_$row_cnt").trigger("chosen:updated") ; ~ ; + } + else { + push @table_operator_calibration_ids,"#selectOperator_id_calibration_$row_cnt" ; + } + + for (1 .. 20) { + push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ; + } + + if ($active_days_count <= 6) { + + for (1 .. 20) { + + # push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ; + + my $style_disp = ($row_has_daily_op{$row_cnt} && $days_active_arr[$_ - 1]) ? "" : "style='display:none;'" ; + + if (!$row_has_daily_op{$row_cnt} || ($style_disp && $row_has_daily_op{$row_cnt} && $final_day < $_)) { + $add_form_fields .= qq~
    ~ ; + } else { + # $style_disp = ($row_has_daily_op{$row_cnt} && $days_active_arr[$_ - 1]) ? "" : "style='display:none;'" ; + $style_disp = (!$days_active_arr[$_ - 1]) ? "style='display:none;'" : "" ; + my $class = ($style_disp) ? 0 : 1 ; + push @all_select_ids,"#selectCustom_operator_$row_cnt\_$_" ; #####CHECK!!!!!!!!!!!!!!!!!!!!!!!!!! + # push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ; + $add_form_fields .= qq~
    ~ ; + + $trigger_jquery_raw .= qq~ + \$("#selectCustom_operator_$row_cnt\_$_").val("$default_op_ids{$row_cnt}{$_}") ; \$("#selectCustom_operator_$row_cnt\_$_").trigger("chosen:updated") ; + + if (!\$("#clicked_any_button").text()) { + \$("#clicked_any_button").text("1") ; + } + if (!\$("input[name='clicked_button_$row_cnt']").val()){ + \$("input[name='clicked_button_$row_cnt']").val("1") ; + } + ~ if $default_op_ids{$row_cnt}{$_} ; + } + } + + my $extra_row_hearders_1 = &build_extra_name_row_1($row_cnt,1) ; + + $add_form_fields .= qq~
    $extra_row_hearders_1$extra_row_hearders_2$extra_row_hearders_1
    ~ ; + + my $final_day_in_extra_row_1 = 0 ; + foreach (sort {$a <=> $b} keys %date_is_displayed_in_first_extra_row) { + $final_day_in_extra_row_1 = $_ ; + } + + for (1 .. 20) { + + # push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ; + + if ($_ <= $final_day_in_extra_row_1) { + + my $style_disp = ($days_active_arr[$_ - 1]) ? "" : "style='display:none;'" ; + my $class = ($style_disp) ? 0 : 1 ; + + push @all_select_ids,"#selectCustom_operator_$row_cnt\_$_" ; #####CHECK!!!!!!!!!!!!!!!!!!!!!!!!!! + # push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ; + $add_form_fields .= qq~
    ~ ; + + $trigger_jquery_raw .= qq~ + \$("#selectCustom_operator_$row_cnt\_$_").val("$default_op_ids{$row_cnt}{$_}") ; \$("#selectCustom_operator_$row_cnt\_$_").trigger("chosen:updated") ; + + if (!\$("#clicked_any_button").text()) { + \$("#clicked_any_button").text("1") ; + } + if (!\$("input[name='clicked_button_$row_cnt']").val()){ + \$("input[name='clicked_button_$row_cnt']").val("1") ; + } + ~ if $default_op_ids{$row_cnt}{$_} ; + + } else { + $add_form_fields .= qq~~ ; + } + } + + # $style_disp = ($active_days_count >= 10) ? "" : "style='display:none;'" ; + $style_disp = ($row_has_daily_op_2{$row_cnt}) ? "" : "style='display:none;'" ; + # $style_disp = ($some_row_has_daily_op_2) ? "" : "style='display:none;'" ; + + my $extra_row_hearders_2 = ($row_has_daily_op_2{$row_cnt}) ? &build_extra_name_row_2($row_cnt,0) : &build_extra_name_row_2($row_cnt,1) ; + $add_form_fields .= qq~
    $extra_row_hearders_2
    ~ ; + + for (11 .. 20) { + + if (!$date_is_displayed_in_first_extra_row{$_} && $days_active_arr[$_ - 1] && $_ <= $final_day) { + + push @all_select_ids,"#selectCustom_operator_$row_cnt\_$_" ; #####CHECK!!!!!!!!!!!!!!!!!!!!!!!!!! + # push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ; + $add_form_fields .= qq~
    ~ ; + $trigger_jquery_raw .= qq~ + \$("#selectCustom_operator_$row_cnt\_$_").val("$default_op_ids{$row_cnt}{$_}") ; \$("#selectCustom_operator_$row_cnt\_$_").trigger("chosen:updated") ; + + if (!\$("#clicked_any_button").text()) { + \$("#clicked_any_button").text("1") ; + } + if (!\$("input[name='clicked_button_$row_cnt']").val()){ + \$("input[name='clicked_button_$row_cnt']").val("1") ; + } + ~ if $default_op_ids{$row_cnt}{$_} ; + } else { + $add_form_fields .= qq~~ ; + } + } + } + $select_sys_name = $system_name_ids[$row_cnt] ; + $select_sys_name = '' unless $select_sys_name ; + } + + $add_form_fields .= qq~
    $input_fields_dates_1$input_fields_1$input_fields_dates_2$input_fields_2~ ; + + } + + # $add_form_fields .= ($active_days_count > 6 && $some_row_has_daily_op_1 && ($row_cnt == 1 || $row_has_daily_op{$row_cnt} || $system_name_ids[$row_cnt - 1] || $club_ids[$row_cnt - 1] || $table_op_ids[$row_cnt - 1])) ? qq~
     
    ~ : qq~~ ; + + $note_display_butt = '' ; + + # if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { + $note_display_butt = qq~display:none;~ ; + } else { + if ($row_cnt > 1 && !$system_name_ids[$row_cnt-1] && !$club_ids[$row_cnt-1] && !$row_has_daily_op{$row_cnt} && !$table_op_ids[$row_cnt - 1]) { + $note_display_butt = qq~display:none;~ ; + } + if ($system_name_ids[$row_cnt] || $club_ids[$row_cnt] || $row_has_daily_op{$row_cnt + 1} || $table_op_ids[$row_cnt]) { + $note_display_butt = qq~display:none;~ ; + } + + $add_form_fields .= qq~ +
    +
    +
    + + + +
    +
    + ~ ; + } + + # $trigger_jquery_raw .= qq~ + # \$("#btn_system_name_$row_cnt").click(function () { + # var v = $row_cnt + 1 ; var v2 = $row_cnt + 2 ; + # \$("#btn_row_$row_cnt").hide(); + # if (v < 15 && \$('#system_name_row_'+v2).is(':hidden')) { + # \$("#btn_row_"+v).show(); + # } + # \$("#system_name_row_"+v).show(); + # }); + # ~ ; + + # $trigger_jquery .= qq~\$("#$system_name_id$row_cnt\_chosen").css("width","100%");~ ; + # $trigger_jquery .= qq~\$("#$club_name_id$row_cnt\_chosen").css("width","100%");~ ; + # $trigger_jquery .= qq~\$("#$op_name_id$row_cnt\_chosen").css("width","90%");~ ; + + } + + $opts{operator_ids} = $old_op_opts ; + + my $table_system_name_ids_string = join(",",@table_system_name_ids) ; + my $table_club_name_ids_string = join(",",@table_club_name_ids) ; + my $table_operator_calibration_ids_string = join(",",@table_operator_calibration_ids) ; + + my @all_table_ids = () ; + push @all_table_ids,$table_system_name_ids_string if $table_system_name_ids_string ; + push @all_table_ids,$table_club_name_ids_string if $table_club_name_ids_string ; + push @all_table_ids,$table_operator_calibration_ids_string if $table_operator_calibration_ids_string ; + + my $all_table_ids_string = join(",",@all_table_ids) ; + + $trigger_jquery_raw .= qq~ + \$("$all_table_ids_string").val('') ; \$("$all_table_ids_string").trigger("chosen:updated") ; + ~ if $all_table_ids_string ; + + my $plus_button_ids_string = join(",",@plus_button_ids) ; + + # if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + if ((($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) || ($quote_completed && $glod_user_level <= 3)) { + + } else { + + my $system_name_options = &fix_options_for_javascript($opts{"system_name_1"}) ; + my $club_name_options = &fix_options_for_javascript($opts{"club_name_1"}) ; + our $operator_options = &fix_options_for_javascript($opts{"operator_id_calibration_1"}) ; + my $event_system_ids_string = join(",",@event_system_ids) ; + my $event_club_ids_string = join(",",@event_club_ids) ; + my $event_operator_ids_string = join(",",@event_operator_ids) ; + my $daily_op_ids_string = join(",",@daily_op_ids) ; + my $overall_op_ids_string = join(",",@overall_op_ids) ; + $trigger_jquery .= qq~\$("$event_system_ids_string").css("width","100%");~ ; + $trigger_jquery .= qq~\$("$event_club_ids_string").css("width","100%");~ ; + $trigger_jquery .= qq~\$("$event_operator_ids_string").css("width","90%");~ ; + + my $table_plus_button_ids_string = join (",",@table_plus_button_ids) ; + # $table_plus_button_ids_string = "#selectCustom_operator_1_1,#selectCustom_operator_1_3,#selectCustom_operator_1_2" ; + # $table_plus_button_ids_string = "#selectCustom_operator_1_1,#selectCustom_operator_1_3,#selectCustom_operator_1_2" ; + + $trigger_jquery_raw .= qq~ + + function get_row_nr (id) { + let lastIndex = id.lastIndexOf('_'); + lastIndex = parseInt(lastIndex) ; + let row_nr = id.substring(1+lastIndex); + row_nr = parseInt(row_nr) ; + return row_nr ; + } + + function add_checkbox (row_nr,field_name,field_id,tindex,fcol) { + let checkbox = "
    " ; + return checkbox ; + } + + function add_input (row_nr,field_name,field_id,placeholder,tindex,readonly,fcol) { + let input = "
    " ; + return input ; + } + + function add_select (row_nr,field_name,field_id,placeholder,options,tindex,fcol,width,div_id,hide_div) { + let select = "
    " ; + select = select + add_select_raw(row_nr,field_name,field_id,placeholder,options,tindex,width) ; + select = select + "
    " ; + return select ; + } + + function add_select_raw (row_nr,field_name,field_id,placeholder,options,tindex,width) { + let select_raw = "
    " ; + return select_raw ; + } + + function add_event_system_extra_row (row_cnt,nr_of_active_days) { + + } + + function add_event_system_row (row_cnt,nr_of_active_days) { + + let new_row = "
    " ; + + new_row = new_row + add_select (row_cnt,"system_name_"+row_cnt,"selectSystem_name_"+row_cnt,"Select System Name "+row_cnt,"$system_name_options",-1,4,100,'','') ; + new_row = new_row + add_select (row_cnt,"club_name_"+row_cnt,"selectClub_name_"+row_cnt,"Select Club Name "+row_cnt,"$club_name_options",-1,4,100,'','') ; + new_row = new_row + add_select (row_cnt,"operator_id_calibration_"+row_cnt,"selectOperator_id_calibration_"+row_cnt,"Select Operator "+row_cnt,"$operator_options",-1,4,90,'','') ; + + // let glod_user_level = parseInt("$glod_user_level") ; + + // if (glod_user_level < 3) { return new_row ; } + + new_row = new_row +"
    " ; + + let extra_row_1,extra_row_2,extra_name_row_1,extra_name_row_2 ; + + // if (nr_of_active_days <= 6) { + + for (let col=1; col<=20; col++) { + // if (\$("#day_"+col).val()) { + // new_row = new_row + add_select (row_cnt,"custom_operator_"+row_cnt+"_"+col,"selectCustom_operator_"+row_cnt+"_"+col,"Select an Option","$operator_options",-1,1,100,"id='day_"+row_cnt+"_"+col+"'","style='display:none;'") ; + // } else { + new_row = new_row + "" ; + // } + } + + new_row = new_row+"
    " ; + extra_row_1 = " + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use db ; +use db_min ; +use dialog ; +use today ; +use common ; +use pdf ; +use tabs ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/pdf/event_quote_pdf.pl b/scripts/_FromProd/v1.0/pdf/event_quote_pdf.pl new file mode 100644 index 0000000..39fdb49 --- /dev/null +++ b/scripts/_FromProd/v1.0/pdf/event_quote_pdf.pl @@ -0,0 +1,1032 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +# unless ($username eq 'handre') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +use DBI; +use CGI::Carp qw(fatalsToBrowser); +use Date::Manip; +use Date::Calc qw(:all); + +use PDF::API2::Lite; +use constant mm => 25.4/72; +use constant in => 1/72; +use constant pt => 1; + +#------------------------------------------------------------------------------------------ + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); + +our $qt_id = $ARGV[0] ; +our $tab_no = $ARGV[1] ; +our $tab_secs = $ARGV[2] ; + +# my @sections = split(/\|/,$tab_secs); + +my @prefix_arr = qw( cost_desc_ curr_amnt_ qty_cost_ zar_amnt_ ); + +# our $debug = 1 ; +our $label = 1 ; # used in pdf_check_value_of_up + +#------------------------------------------------------------------------------------------ + +print "Content-type: text/html\n\n"; + +&today ; +&pdf_curr_symbols ; + +my $table = 'event_quotes' ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &prep_pdf ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +&exclusions ; +&start_pdf ; +&build_pdf ; +&finish_pdf ; +&screen2 ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub prep_pdf { + + my @cols = () ; + + &tab_hash ; + + &db_min_ro('event_quotes',"*","`id`='$qt_id'",'','') ; + + our $countryid = $db{$table}{$qt_id}{country_id} ; + our $custid = $db{$table}{$qt_id}{quote_to} ; + our $date_from_for_pdf = $db{$table}{$qt_id}{date_from} ; + our $type_id = $db{$table}{$qt_id}{type} ; + + my @month_array = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ) ; + my $year = substr($date_from_for_pdf, 0, 4) ; + my $month = substr($date_from_for_pdf, 5, 2) ; + $month = int($month); + $month = $month_array[$month - 1] ; + my $day = substr($date_from_for_pdf, 8, 2) ; + $date_from_for_pdf = "$day-" ; + $date_from_for_pdf .= "$month-" ; + $date_from_for_pdf .= "$year" ; + + our %country = () ; + # print "COUNTty ID: $countryid, $custid \n" ; + + &db_min_ro('customers','id,name,physical_address,contact_email,phone,contact_name,vat_nr',"`id`='$custid'",'','') ; + $customer_name{$custid} = $db{customers}{$custid}{name} ; + $customer_address{$custid} = $db{customers}{$custid}{physical_address} ; + $customer_email{$custid} = $db{customers}{$custid}{contact_email} ; + $customer_phone{$custid} = $db{customers}{$custid}{phone} ; + $customer_contact_name{$custid} = $db{customers}{$custid}{contact_name} ; + $customer_vat_nr{$custid} = $db{customers}{$custid}{vat_nr} ; + + &db_min_ro('event_cost_items','id,name','','','') ; + foreach my $id (keys %{$db{event_cost_items}}) { $price_list{$id} = $db{event_cost_items}{$id}{name} ; } + + &db_min_ro('event_quotes_poc','id,name,contact_nr','','','') ; + + &db_min_ro('countries','*',"`id`='$countryid'",'','') ; + $country{$countryid} = $db{countries}{$countryid}{name} ; + # print "Country : $country{$countryid}" ; + $country{$countryid} = "Unknown" if not $country{$countryid} ; + + our $camera_system_id = $db{$table}{$qt_id}{camera_system_id} ; + &db_min_ro('camera_systems','*',"`id`='$camera_system_id'",'','') ; + $camera_system{$camera_system_id} = $db{camera_systems}{$camera_system_id}{name} ; + + our %event_type_for_pdf = () ; + &db_min_ro('event_types','id, name',"`id`='$type_id'",'','') ; + $event_type_for_pdf{$type_id} = $db{event_types}{$type_id}{name} ; + + &db_min_ro('event_quotes_min','id, excl_costing_event, item_costing_event, qty_costing_event , usd_amnt_costing_event , item_ttl_costing_event , vat_costing_event, curr_amnt_costing_event ',"id = $qt_id",, '', '' ); + +} #------------------------------------------------------------------------------------------ + +sub exclusions { + + our $exclude_rate = 0 ; + our $exclude_vat = 0 ; + + if ($db{$table}{$qt_id}{currency} ne 'ZAR') { + $exclude_vat = 1 ; + } + +} #------------------------------------------------------------------------------------------ + +sub start_pdf { + + my $qtpdfpath = "$pdfpath/event_quotes_added_by_handre" ; + our $pdfname = "EQT-$qt_id-" . $now_ccyymmdd . '.pdf' ; + + &pdf_delete_previous_pdf($qtpdfpath) ; + &pdf_initialise($qtpdfpath,$pdfname,'ITV Event Quote') ; + +} #------------------------------------------------------------------------------------------ + +sub build_pdf { + + &tab_curr_symbols; + &pdf_initialise_page ; + + $up = 292 ; + # "e_pdf_page_header ; + + &pdf_box_block_top(5,205,'#009bc8') ; + + $up = 260 ; + $across = 1 ; + $blue_box = 1 ; + + &pdf_page_header ; + "e_pdf_vars ; + "e_out_to_pdf ; + # "e_pdf_footer ; + + $up = 5 ; + &pdf_box_block_bottom(5,205,'#009bc8') ; + +} #------------------------------------------------------------------------------------------ + +# sub quote_pdf_page_header { + +# $page_num++ ; + +# my $image1 = $page->gfx(1) ; +# my $image1_thumb = "$htmlpath/img/pdf_logo.png"; +# $pdf_image1_file = $pdf->image_png($image1_thumb); +# $image1->image($pdf_image1_file, 7/mm, $up/mm, 90/mm, 29/mm); + +# $up+=18 ; + +# &pdf_nl_gap_3 ; +# &pdf_xx_large_bold_text (156,$up,"QUOTE") ; +# &pdf_nl_gap_1 ; + +# } #------------------------------------------------------------------------------- + + +# sub pdf_small_white_text_bold { + + # my ($along, $up, $text) = @_ ; $small_bold_text_white->translate( $along/mm, $up/mm ); $small_bold_text_white->text( $text ); +# } + +# sub pdf_medium_white_text_bold { + + # my ($along, $up, $text) = @_ ; $medium_bold_text_white->translate( $along/mm, $up/mm ); $medium_bold_text_white->text( $text ); +# } + +# sub pdf_large_white_text_bold { + + # my ($along, $up, $text) = @_ ; $large_bold_text_white->translate( $along/mm, $up/mm ); $large_bold_text_white->text( $text ); +# } + +# sub pdf_grey_text_above_right { + + # my ($along, $up, $text) = @_ ; $grey_text_above_right->translate( $along/mm, $up/mm ); $grey_text_above_right->text( $text ); +# } + +# sub pdf_small_white_text_bold_right { + + # my ($along, $up, $text) = @_ ; $grey_text_above_right->translate( $along/mm, $up/mm ); $grey_text_above_right->text_right( $text ); +# } + +# sub pdf_medium_white_text_bold_right { + + # my ($along, $up, $text) = @_ ; $medium_bold_text_white->translate( $along/mm, $up/mm ); $medium_bold_text_white->text_right( $text ); +# } + +# sub pdf_large_white_text_bold_right { + + # my ($along, $up, $text) = @_ ; $large_bold_text_white->translate( $along/mm, $up/mm ); $large_bold_text_white->text_right( $text ); +# } + +sub quote_out_to_pdf { + + &pdf_nl_t; + # unless ($db{$table}{$qt_id}{currency} eq 'ZAR') { &pdf_medium_red_bold_text (70, $up, "$db{$table}{$qt_id}{currency} ROE : $db{$table}{$qt_id}{roe}") ; } # hidden for client + # &pdf_medium_bold_text (157, $up, "Nr. :") ; + + &pdf_small_bold_text(150, $up, "Date") ; + my $dttxt = &custom_date_txt($db{$table}{$qt_id}{quote_date}); + &pdf_small_bold_text_right (198, $up, $dttxt) ; + + &pdf_nl; + + # &pdf_small_bold_text(150, $up, "Quote Nr") ; + &pdf_small_bold_text(150, $up, "Event Nr") ; + # &pdf_small_text_right (198, $up, $qt_id) ; + &pdf_small_bold_text_right (198, $up, $db{$table}{$qt_id}{quote_nr}) ; + + # &pdf_large_bold_text (10, $up, $db{$table}{$qt_id}{ref}) if $db{$table}{$qt_id}{ref} ; + + # &pdf_nl_gap_1; + &pdf_nl; + + &pdf_nl_t; + &pdf_bar(10,$up,200,$up,'#009bc8','QUOTE',20,98) ; + $up = $up - 5; + + &pdf_box_block_top(10,200,'#009bc8') ; # start block ------------------------------------- + + if ($custid) { + + # # my ($quote_year,$quote_month,$quote_day) = split(/\-/,$db{$table}{$qt_id}{quote_date}); + # # my ($expiry_year,$expiry_month,$expiry_day) = Add_Delta_Days($quote_year,$quote_month,$quote_day,14); # Add 7 days to quote date + # # $expiry_month = sprintf("%02s", $expiry_month) ; + # # $expiry_day = sprintf("%02s", $expiry_day) ; + # my ($expiry_year,$expiry_month,$expiry_day) = split(/\-/,$db{$table}{$qt_id}{quote_expiry}); + # my $expiry_date = &custom_date_txt("$expiry_year-$expiry_month-$expiry_day"); + # # my $expiry_date = "$expiry_year-$expiry_month-$expiry_day"; + + &pdf_nl; + &pdf_thin_box_block_top(15,100,'#009bc8'); + # &pdf_thin_box_block_top(110,195,'#009bc8'); + + $top = $up; + my $pos = 37; + my $pos2 = $pos + 1; + my $pos3 = 132; + my $pos4 = $pos3 + 1; + + $up = $up - 5.5 ; + # $up = $up + 1.75; + + # $up = $up - 1.75; + &pdf_small_bold_text (16, $up, "Customer") ; + &pdf_small_text ($pos2, $up, $customer_name{$custid}) ; + + $up = $up + 5.5 ; + $up = $up - 3.25; + # &pdf_small_bold_text (111, $up, "Event Start") ; + # my $start_date = &custom_date_txt(substr($db{$table}{$qt_id}{date_from}, 0, 10)); + # $start_date .= substr($db{$table}{$qt_id}{date_from}, 10); + # &pdf_small_text ($pos4, $up, $start_date) ; + $up = $up -1.25; + # &pdf_extra_thin_black_line (110,$up, 195 ,$up,'#009bc8') ; + $up = $up - 3.25; + # &pdf_small_bold_text (111, $up, "Event End") ; + # my $end_date = &custom_date_txt(substr($db{$table}{$qt_id}{date_to}, 0, 10)); + # $end_date .= substr($db{$table}{$qt_id}{date_to}, 10); + # &pdf_small_text ($pos4, $up, $end_date) ; + $up = $up -1.25; + # &pdf_extra_thin_black_line ($pos3,$top, $pos3 ,$up,'#009bc8') ; + + &pdf_extra_thin_black_line ($pos,$top, $pos ,$up,'#009bc8') ; + &pdf_thin_box_block_bottom(15,100,'#009bc8'); + # &pdf_thin_box_block_bottom(110,195,'#009bc8'); + &pdf_thin_box_block_top(15,100,'#009bc8'); + &pdf_thin_box_block_top(110,195,'#009bc8'); + + $top = $up; + $up = $up - 3.25; + + &pdf_small_bold_text (111, $up, "Country") ; + &pdf_small_text ($pos4, $up, $country{$countryid}) ; + $up = $up -1.25; + &pdf_thin_box_block_bottom(110,195,'#009bc8'); + &pdf_small_bold_text (16, $up, "Address") ; + my @waypoint = split(/\, / , $customer_address{$custid}); + my $top2 = $up; + my $count = 0; + for my $py (@waypoint){ + &pdf_small_text ($pos2, $up, $waypoint[$count]) ; + $count++; + $up = $up - 4; + } + $up = $top2; + &pdf_thin_box_block_top(110,195,'#009bc8'); + $up = $up - 3.25; + &pdf_small_bold_text (111, $up, "Tax/VAT Nr") ; + &pdf_small_text ($pos4, $up, $customer_vat_nr{$custid}) ; + $up = $up - 1.25; + &pdf_thin_box_block_bottom(110,195,'#009bc8'); + &pdf_extra_thin_black_line ($pos3,$top, $pos3 ,$up,'#009bc8') ; + $up = $up - 4.5; + &pdf_extra_thin_black_line ($pos,$top, $pos ,$up,'#009bc8') ; + $top = $up; + &pdf_thin_box_block_top(110,195,'#009bc8'); + $up = $up - 3.25; + # &pdf_small_bold_text (111, $up, "Quote Expiry") ; + # &pdf_small_text ($pos4, $up, $expiry_date) ; + $up = $up - 1.25; + &pdf_thin_box_block_bottom(110,195,'#009bc8'); + &pdf_thin_box_block_bottom(15,100,'#009bc8'); + &pdf_extra_thin_black_line ($pos,$top, $pos ,$up,'#009bc8') ; + &pdf_extra_thin_black_line ($pos3,$top, $pos3 ,$up,'#009bc8') ; + $up = $up - 4.5; + &pdf_thin_box_block_top(15,100,'#009bc8'); + $top = $up; + &pdf_thin_box_block_top(110,195,'#009bc8'); + $up = $up - 3.25; + &pdf_small_bold_text (16, $up, "Contact") ; + &pdf_small_text ($pos2, $up, $customer_contact_name{$custid}) ; + &pdf_small_bold_text (111, $up, "Reference") ; + &pdf_small_text ($pos4, $up, $db{$table}{$qt_id}{ref}) ; + $up = $up -1.25; + &pdf_thin_box_block_bottom(15,100,'#009bc8'); + &pdf_thin_box_block_bottom(110,195,'#009bc8'); + &pdf_thin_box_block_top(110,195,'#009bc8'); + &pdf_thin_box_block_top(15,100,'#009bc8'); + $up = $up - 3.25; + &pdf_small_bold_text (16, $up, "Phone Nr") ; + &pdf_small_text ($pos2, $up, $customer_phone{$custid}) ; + &pdf_small_bold_text (111, $up, "Date") ; + &pdf_small_text ($pos4, $up, $date_from_for_pdf) ; + # &pdf_small_text ($pos4, $up, $db{$table}{$qt_id}{po_nr}) ; + $up = $up - 1.25; + &pdf_thin_box_block_bottom(110,195,'#009bc8'); + &pdf_thin_box_block_bottom(15,100,'#009bc8'); + &pdf_extra_thin_black_line ($pos3,$top, $pos3 ,$up,'#009bc8') ; + &pdf_thin_box_block_top(15,100,'#009bc8'); + $up = $up - 3.25; + &pdf_small_bold_text (16, $up, "Email") ; + &pdf_small_text ($pos2, $up, $customer_email{$custid}) ; + $up = $up - 1.25; + &pdf_extra_thin_black_line ($pos,$top, $pos ,$up,'#009bc8') ; + &pdf_thin_box_block_bottom(15,100,'#009bc8'); + &pdf_nl; + &pdf_thin_box_block_top(15,100,'#009bc8'); + &pdf_thin_box_block_top(110,195,'#009bc8'); + $top = $up; + $up = $up - 3.25; + &pdf_small_bold_text (16, $up, "Notes") ; + &pdf_small_bold_text (111, $up, "Type") ; + $up = $up - 1.25; + &pdf_extra_thin_black_line ($pos3,$top, $pos3 ,$up,'#009bc8') ; + &pdf_thin_box_block_bottom(110,195,'#009bc8'); + $up = $up + 1.25; + # &pdf_small_text ($pos4, $up, $camera_system{$camera_system_id}) ; + &pdf_small_text ($pos4, $up, $event_type_for_pdf{$type_id}) ; + # &pdf_small_text (29, $up, $db{$table}{$qt_id}{notes}) ; + &pdf_text_block ($pos2 ,$db{$table}{$qt_id}{notes},60,5) ; + $up = $up - 9; + &pdf_thin_box_block_bottom(15,100,'#009bc8'); + &pdf_extra_thin_black_line ($pos,$top, $pos ,$up,'#009bc8') ; + $up = $up - 4.5; + } + + &pdf_box_block_bottom(10,200,'#009bc8') ; # end block ------------------------------------- + + $up = $up - 6; + #&pdf_nl_gap_1; + &pdf_bar(9.75,$up,200.25,$up,'#009bc8','Item List',20,97) ; + + $top=$up; + + #&pdf_check_value_of_up(20); + $up = $up - 3; + &pdf_box_block_top($blocks[1],200,'#009bc8') ; # start block ------------------------------------- + + $up = $up - 6; + &pdf_small_bold_text ($boxtxt[1]+5,$up,'Item') ; + $up += 2; + &pdf_small_bold_text (87,$up,'Per Day') ; + $up -= 4; + &pdf_small_bold_text (87,$up,'/Venue') ; + $up += 2; + &pdf_small_bold_text ($boxtxt[2]+2,$up,'Qty') ; + &pdf_small_bold_text ($boxtxt[3]+2.5,$up,'Per x Day Qty') ; + &pdf_small_bold_text ($boxtxt[4]+7.5,$up,'VAT') ; + &pdf_small_bold_text ($boxtxt[5]+7.5,$up,'Total') ; + $up = $up - 4; + &pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + + &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up,'#009bc8') ; + &pdf_thin_black_line (80,$top,80,$up,'#009bc8') ; + &pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[5],$top,$blocks[5],$up,'#009bc8') ; + $top = $up; + &pdf_nl_gap_1; + my $price_times_qty = 0 ; + $inner_blue_box = 1 ; + my %sec_cnt2 = ('a_costing_event' => "30-Event Costings"); + + foreach (sort keys %sec_cnt2) { + + if ($up>280){ $up=280; } + $_k = substr($_,1) ; + my @parts = split(/\-/,$sec_cnt2{$_}) ; + + # my $sec = '_costing' ; + # my $suffix = "$sec$_k" ; + + my $sec = '_costing_event' ; + my $suffix = "$sec" ; + my $vat_amnt = 0 ; + # unless ($db{$table}{$qt_id}{"item_1$suffix"}) { next ; } + + &pdf_small_bold_text ($boxtxt[1]+5,$up,$parts[1]) ; + # &build_cost_form($id,$tab,$parts[0],"$sec$_k"); + &pdf_nl; + + my @excl_cost = split(";", $db{event_quotes_min}{$qt_id}{excl_costing_event}); + my @qty_cost = split(";", $db{event_quotes_min}{$qt_id}{qty_costing_event}); + my @usd_amnt_cost = split(";", $db{event_quotes_min}{$qt_id}{usd_amnt_costing_event}); + my @item_ttl_cost = split(";", $db{event_quotes_min}{$qt_id}{item_ttl_costing_event}); + my @vat_cost = split(";", $db{event_quotes_min}{$qt_id}{vat_costing_event}); + my @item_cost = split(";", $db{event_quotes_min}{$qt_id}{item_costing_event}); + my @curr_amnt_cost = split(";", $db{event_quotes_min}{$qt_id}{curr_amnt_costing_event}); + + my $event_costings_cnt = 0 ; + + for (1 .. $parts[0]) { + + # &pdf_check_value_of_up(60) if $_ == 25 ; + # next if $db{$table}{$qt_id}{"excl_$_$suffix"}; + next if $excl_cost[$_ - 1] or (not $qty_cost[$_ - 1] and not $curr_amnt_cost[$_ - 1]) ; + + $event_costings_cnt++ ; + + if ($up < 10){ + &pdf_thin_black_line (80,$top,80,10,'#009bc8') ; + &pdf_check_value_of_up(10) if $_ > 15; + $new_page = 1 ; + } + + if ($up>280){ $up=280; } + # my $disp_item = $price_list{$db{$table}{$qt_id}{"item_$_$suffix"}} ? $price_list{$db{$table}{$qt_id}{"item_$_$suffix"}} : $db{$table}{$qt_id}{"item_$_$suffix"} ; + my $disp_item = $price_list{$item_cost[$_ - 1]} ? $price_list{$item_cost[$_ - 1]} : $item_cost[$_ - 1] ; + + &pdf_small_text($boxtxt[1]+5,$up,$disp_item) ; + # &pdf_small_text($boxtxt[2]+4.4,$up,$db{$table}{$qt_id}{"qty_$_$suffix"}) ; + &pdf_small_text($boxtxt[2]+4.4,$up,$qty_cost[$_ - 1]) ; + # &pdf_small_text ($boxtxt[3]+2,$up,&common_commify($db{$table}{$qt_id}{"curr_amnt_$_$suffix"})) ; + &pdf_small_text($boxtxt[3],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right(102,$up,&common_commify($db{$table}{$qt_id}{"curr_amnt_$_$suffix"})) ; + # &pdf_small_text_right(102,$up,&common_commify($db{$table}{$qt_id}{"curr_amnt_$_$suffix"})) ; + &pdf_small_text_right(102,$up,&common_commify($curr_amnt_cost[$_ - 1])) ; + &pdf_small_text_right(84,$up,"R") ; + # $price_times_qty = $db{$table}{$qt_id}{"curr_amnt_$_$suffix"} * $db{$table}{$qt_id}{"qty_$_$suffix"} ; + $price_times_qty = $curr_amnt_cost[$_ - 1] * $qty_cost[$_ - 1] ; + $price_times_qty = sprintf("%.2f", $price_times_qty) ; + $price_times_qty = &common_commify($price_times_qty) ; + &pdf_small_text_right($rboxtxt[3],$up,$price_times_qty); + + # if ($db{$table}{$qt_id}{"vat_$_$suffix"}) { + if ($vat_cost[$_ - 1]) { + # $vat_amnt = sprintf("%0.2f",$db{$table}{$qt_id}{"curr_amnt_$_$suffix"} * $db{$table}{$qt_id}{"qty_$_$suffix"} * 0.15) ; + $vat_amnt = sprintf("%0.2f",$curr_amnt_cost[$_ - 1] * $qty_cost[$_ - 1] * 0.15) ; + # &pdf_small_text ($boxtxt[4]+2,$up,&common_commify($vat_amnt)) ; + &pdf_small_text($boxtxt[4],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($rboxtxt[4],$up,&common_commify($vat_amnt)) ; + } + + # &pdf_small_text ($boxtxt[5]+2,$up,&common_commify($db{$table}{$qt_id}{"curr_amnt_$_$suffix"}+$vat_amnt)) ; + &pdf_small_text($boxtxt[5],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # my $ttl_amnt = sprintf("%0.2f",$db{$table}{$qt_id}{"curr_amnt_$_$suffix"}*$db{$table}{$qt_id}{"qty_$_$suffix"}+$vat_amnt) ; + my $ttl_amnt = sprintf("%0.2f",$curr_amnt_cost[$_ - 1]*$qty_cost[$_ - 1]+$vat_amnt) ; + &pdf_small_text_right($rboxtxt[5],$up,&common_commify($ttl_amnt)) ; + &pdf_nl; + } + + unless ($event_costings_cnt) { + &pdf_small_text($boxtxt[1]+5,$up,"None") ; + } + + if (not $new_page and $up < 65){ + &pdf_check_value_of_up(65) ; + $new_page = 1 ; + } + + if ($_k eq '_systems' and $db{$table}{$qt_id}{systems_included}) { + my @para = split /^/m, $db{$table}{$qt_id}{systems_included} ; + foreach (@para) { + &pdf_small_text($boxtxt[1]+5,$up,$_) ; + &pdf_nl_s; + } + # &pdf_text_block ($boxtxt[1]+2,$db{$table}{$qt_id}{systems_included},50,5) ; + } + + if ($_k eq '_rental' and $db{$table}{$qt_id}{rental_included}) { + my @para = split /^/m, $db{$table}{$qt_id}{rental_included} ; + foreach (@para) { + &pdf_small_text($boxtxt[1]+5,$up,$_) ; + &pdf_nl_s; + } + } + &pdf_nl; + } + #$up=80; + #&pdf_box_block_bottom($blocks[1],200,'#009bc8') ; # end block ------------------------------------- + + $inner_blue_box = 0 ; + + # ------------- totals ------------------------------------------------------------------ + + + #$top=$up; + + #&pdf_box_block_top($blocks[1],200,'#009bc8') ; # start block ------------------------------------- + + # &pdf_nl_gap_1;#&pdf_nl_t; + # &pdf_small_bold_text ($boxtxt[1]+2,$up,'') ; + # &pdf_small_bold_text ($boxtxt[2],$up,'') ; + # &pdf_small_bold_text ($boxtxt[3],$up,'Sub Total') ; + # &pdf_small_bold_text ($boxtxt[4],$up,'Vat Total') ; + # &pdf_small_bold_text ($boxtxt[5],$up,'Grand Total') ; + # &pdf_nl_t; + + #$top = $up; + my $a = 0; + my $b = 0; + my $c = 0; + + if ($up < 65){ + &pdf_check_value_of_up(65); + $new_page = 1 ; + } + + $up = 55; + + # if ($db{$table}{$qt_id}{subtotal_one_time_fee} ne '0.00' or $db{$table}{$qt_id}{vat_one_time_fee} ne '0.00' or $db{$table}{$qt_id}{total_one_time_fee} ne '0.00'){ + $a = 1; + $up = $up + 8; + # } + # if ($db{$table}{$qt_id}{subtotal_monthly_recurring_fee} ne '0.00' or $db{$table}{$qt_id}{vat_monthly_recurring_fee} ne '0.00' or $db{$table}{$qt_id}{total_monthly_recurring_fee} ne '0.00' ){$b = 1;$up = $up + 8;} + # if ($db{$table}{$qt_id}{subtotal_annual_fee} ne '0.00' or $db{$table}{$qt_id}{vat_annual_fee} ne '0.00' or $db{$table}{$qt_id}{total_annual_fee} ne '0.00'){$c = 1;$up = $up + 8;} + + unless ($new_page){ + &pdf_thin_black_line (80,$top,80,$up,'#009bc8') ; + &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up,'#009bc8') ; + &pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up-8,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up-8,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[5],$top,$blocks[5],$up-8,'#009bc8') ; + } + + $top = $up ; + + $top = 287 if $new_page; + &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up,'#009bc8') ; + &pdf_thin_black_line (80,$top,80,$up,'#009bc8') ; + + if ($a == 1) { + &pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + $up = $up - 5; + $inner_blue_box = 1 ; + &pdf_small_bold_text ($boxtxt[1]+2,$up,'Total') ; + &pdf_small_text($boxtxt[3],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($rboxtxt[3],$up,&common_commify($db{$table}{$qt_id}{sub_total})) ; + &pdf_small_text($boxtxt[4],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($rboxtxt[4],$up,&common_commify($db{$table}{$qt_id}{vat_total})) ; + &pdf_small_text($boxtxt[5],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($rboxtxt[5],$up,&common_commify($db{$table}{$qt_id}{grand_total})) ; + $up = $up - 3; + } + + # if ($b == 1) { + # &pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + # $up = $up - 5; + # &pdf_small_bold_text ($boxtxt[1]+2,$up,'Monthly Recurring Fee') ; + # &pdf_small_text($boxtxt[3],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right($rboxtxt[3],$up,&common_commify($db{$table}{$qt_id}{subtotal_monthly_recurring_fee})) ; + # &pdf_small_text($boxtxt[4],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right($rboxtxt[4],$up,&common_commify($db{$table}{$qt_id}{vat_monthly_recurring_fee})) ; + # &pdf_small_text($boxtxt[5],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right($rboxtxt[5],$up,&common_commify($db{$table}{$qt_id}{total_monthly_recurring_fee})) ; + # $up = $up - 3; + # } + + # if ($c == 1) { + # &pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + # $up = $up - 5; + # &pdf_small_bold_text ($boxtxt[1]+2,$up,'Annual Fee') ; + # &pdf_small_text($boxtxt[3],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right($rboxtxt[3],$up,&common_commify($db{$table}{$qt_id}{subtotal_annual_fee})) ; + # &pdf_small_text($boxtxt[4],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right($rboxtxt[4],$up,&common_commify($db{$table}{$qt_id}{vat_annual_fee})) ; + # &pdf_small_text($boxtxt[5],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right($rboxtxt[5],$up,&common_commify($db{$table}{$qt_id}{total_annual_fee})) ; + # $up = $up - 3; + # } + # &pdf_extra_thin_black_line ($blocks[2],$top,$blocks[2],$up,'#009bc8') ; + # + if ($new_page){ + &pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[5],$top,$blocks[5],$up,'#009bc8') ; + } + &pdf_thin_black_line (10,$up,200,$up,'#009bc8') ; + #&vertical_lines_inner_box; + $up -= 5; + + # &pdf_thin_black_line ($tblocks[3],$top,$tblocks[3],$up,'#009bc8') ; # vertical + # &pdf_thin_black_line ($tblocks[4],$top,$tblocks[4],$up,'#009bc8') ; # vertical + # &pdf_thin_black_line ($tblocks[5],$top,$tblocks[5],$up,'#009bc8') ; + + &pdf_box_block_bottom($blocks[1],200,'#009bc8') ; # end block ------------------------------------- + + $inner_blue_box = 0 ; + + # ------------- totals ------------------------------------------------------------------ + + # ------------- purchase summary ------------------------------------------------------------------ + + # # &pdf_check_value_of_up(200); + + unless ($db{$table}{$qt_id}{excl_purchase_summary}) { + + # &pdf_box_block_top($tblocks[1],200,'#009bc8') ; # start block --------- + # $up = $up - 3.5; + + + # &pdf_bar(10,$up,200,$up,'#009bc8','Purchase Summary',20,90, 'med') ; + + # $up = $up - 10; + # $top = $up ; + # &pdf_bar(10,$up,200,$up,'#009bc8','Description',20, 14, 'med'); + # &pdf_bar (10,$up,200,$up,'#009bc8','Year 1', 20, 90, 'med') ; + # &pdf_bar (10,$up,200,$up,'#009bc8','Year 2', 20, 120, 'med') ; + # &pdf_bar (10,$up,200,$up,'#009bc8','Year 3', 20, 150, 'med') ; + # &pdf_bar (10,$up,200,$up,'#009bc8','TOTAL', 20, 180, 'med') ; + # $up = $up - 8; + # # $top=$up; + + # # &pdf_check_value_of_up(20); + + # # # ---------------------------- + + # # &pdf_nl_gap_1;&pdf_nl_t; + # # &pdf_small_bold_text ($tboxtxt[1]+2,$up,'Description') ; + # # &pdf_small_bold_text ($tboxtxt[2],$up,'Year 1') ; + # # &pdf_small_bold_text ($tboxtxt[3],$up,'Year 2') ; + # # &pdf_small_bold_text ($tboxtxt[4],$up,'Year 3') ; + # # &pdf_small_bold_text ($tboxtxt[5],$up,'Total') ; + # # &pdf_nl_t; + # # &pdf_thin_black_line ($tblocks[1],$up,200,$up,'#009bc8') ; + # # &pdf_nl_gap_1; + + # $inner_blue_box = 1 ; + + # my $suffix = "_purchase_summary" ; + + # foreach (1 .. 3) { + # &pdf_check_value_of_up(15); if ($up>280){ $up=280; } + + # if ($db{$table}{$qt_id}{"excl_$_$suffix"}) { next ; } + + # &pdf_small_bold_text ($tboxtxt[1]+2,$up,$db{$table}{$qt_id}{"item_$_$suffix"}) ; + # $box=1; + # for my $y_ (1 .. 3) { + # $box++; + # $ttl{$y_} += $db{$table}{$qt_id}{"year_$y_\_$_$suffix"} ; + # # &pdf_small_text ($tboxtxt[$box],$up,&common_commify($db{$table}{$qt_id}{"year_$y_\_$_$suffix"})) ; + # &pdf_small_bold_text($tboxtxt[$box],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_bold_text_right($tboxrtxt[$box],$up,&common_commify($db{$table}{$qt_id}{"year_$y_\_$_$suffix"})) ; + # } + # $box++; + # $ttl += $db{$table}{$qt_id}{"total_$_$suffix"} ; + # # &pdf_small_text ($tboxtxt[$box],$up,&common_commify($db{$table}{$qt_id}{"total_$_$suffix"})) ; + # &pdf_small_bold_text($tboxtxt[$box],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_bold_text_right($tboxrtxt[$box],$up,&common_commify($db{$table}{$qt_id}{"total_$_$suffix"})) ; + # $up = $up - 6; + # } + + # #$up = $up - 4; + # #&pdf_thin_black_line ($tblocks[1],$up,200,$up,'#009bc8') ; + + # &pdf_bar (10,$up,200,$up,'#009bc8','Total', 20, 14, 'med') ; + # #&pdf_large_bold_text(22, $up, 'Total'); + # #&pdf_large_white_text_bold(12, $up, 'Total'); + + # # our @tboxrtxt = (0,77,107,137,167,197) ; + # #our @tboxtxt = (0,12,82,112,142,172) ; + # # &pdf_small_bold_text ($tboxtxt[2],$up,&common_commify($ttl{1})) ; + # # &pdf_small_bold_text ($tboxtxt[3],$up,&common_commify($ttl{2})) ; + # # &pdf_small_bold_text ($tboxtxt[4],$up,&common_commify($ttl{3})) ; + # # &pdf_small_bold_text ($tboxtxt[5],$up,&common_commify($ttl)) ; + # # &pdf_small_bold_text($tboxtxt[2],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # # &pdf_small_bold_text_right($tboxrtxt[2],$up,&common_commify(sprintf("%0.2f",$ttl{1}))) ; + # # &pdf_small_bold_text($tboxtxt[3],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # # &pdf_small_bold_text_right($tboxrtxt[3],$up,&common_commify(sprintf("%0.2f",$ttl{2}))) ; + # # &pdf_small_bold_text($tboxtxt[4],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # # &pdf_small_bold_text_right($tboxrtxt[4],$up,&common_commify(sprintf("%0.2f",$ttl{3}))) ; + # # &pdf_small_bold_text($tboxtxt[5],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # # &pdf_small_bold_text_right($tboxrtxt[5],$up,&common_commify(sprintf("%0.2f",$ttl))) ; + + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt[2], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl{1})), 20, $tboxrtxt[2], 'small_right') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt[3], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl{2})), 20, $tboxrtxt[3], 'small_right') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt[4], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl{3})), 20, $tboxrtxt[4], 'small_right') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt[5], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl)), 20, $tboxrtxt[5], 'small_right') ; + + # #&pdf_nl_t; + + # #&vertical_lines_inner_box_t; + # &pdf_thin_black_line ($tblocks[2],$top,$tblocks[2],$up,'#009bc8') ; # vertical + # &pdf_thin_black_line ($tblocks[3],$top,$tblocks[3],$up,'#009bc8') ; # vertical + # &pdf_thin_black_line ($tblocks[4],$top,$tblocks[4],$up,'#009bc8') ; # vertical + # &pdf_thin_black_line ($tblocks[5],$top,$tblocks[5],$up,'#009bc8') ; # vertical + + # &pdf_box_block_bottom($tblocks[1],200,'#009bc8') ; # end block ------------------------------------- + + # $inner_blue_box = 0 ; +} + +# ------------- purchase summary ------------------------------------------------------------------ + + #&pdf_nl_gap_1; + #&pdf_nl_gap_3; + # $up = $up - 15; + #$&pdf_check_value_of_up(50); + + for (1 .. 20) { + next if $db{$table}{$qt_id}{"excl_$_\_notes"} || $db{$table}{$qt_id}{"note_$_"} eq ''; + $notes_exist = 1 ; + } + $up -= 8; + if ($notes_exist) { + &pdf_medium_bold_text ($blocks[1],$up,'Notes:') ; + $up = $up - 1; + for (1 .. 20) { + unless ($db{$table}{$qt_id}{"excl_$_\_notes"}) { + my $note = $db{$table}{$qt_id}{"note_$_"}; + if ($note) { + &pdf_nl; $up = $up - 1; + &pdf_medium_text ($blocks[1],$up,"$note") ; + + } + } + } + } + + for (1 .. 20) { + next if $db{$table}{$qt_id}{"excl_$_\_payment_terms"} || $db{$table}{$qt_id}{"payment_term_$_"} eq ''; + $payment_terms_exists = 1 ; + } + + if ($payment_terms_exists) { + &pdf_nl_gap_3 ; + # &pdf_check_value_of_up(50); + &pdf_medium_bold_text ($blocks[1],$up,'Payment Terms:') ; + $up = $up - 1 ; + for (1 .. 20) { + unless ($db{$table}{$qt_id}{"excl_$_\_payment_terms"}) { + my $payment_term = $db{$table}{$qt_id}{"payment_term_$_"}; + if (length($payment_term) > 2) { + $up = $up - 6 ; + &pdf_medium_text ($blocks[1],$up,"$payment_term") ; + } + } + } + } + + # for (1 .. 20) { + # next if $db{$table}{$qt_id}{"excl_$_\_roes"} || $db{$table}{$qt_id}{"roe_$_"} eq ''; + # $roe_exists = 1 ; + # } + + # if ($roe_exists) { + # &pdf_nl_gap_3; + # &pdf_check_value_of_up(50); + # &pdf_medium_bold_text ($blocks[1],$up,'ROE:') ; + # $up = $up - 1; + # for (1 .. 20) { + # unless ($db{$table}{$qt_id}{"excl_$_\_roes"}) { + # my $roe = $db{$table}{$qt_id}{"roe_$_"}; + # if ($roe) { + # &pdf_nl; + # $up = $up - 1; + # &pdf_medium_text ($blocks[1],$up,"- $roe") ; + # } + # } + # } + # } + + # for (1 .. 20) { + # next if $db{$table}{$qt_id}{"excl_$_\_delivery_times"} || $db{$table}{$qt_id}{"delivery_time_$_"} eq ''; + # $delivery_time_exists = 1 ; + # } + + # if ($delivery_time_exists) { + # &pdf_nl_gap_3; + # &pdf_check_value_of_up(50); + # &pdf_medium_bold_text ($blocks[1],$up,'Manufacturing time:') ; + # $up = $up - 1; + + # for (1 .. 20) { + # unless ($db{$table}{$qt_id}{"excl_$_\_delivery_times"}) { + # my $delivery_time = $db{$table}{$qt_id}{"delivery_time_$_"}; + # if ($delivery_time) { + # &pdf_nl; $up = $up - 1; + # &pdf_medium_text ($blocks[1],$up,"- $delivery_time") ; + # } + # } + # } + # } +} #------------------------------------------------------------------------------------------ + +sub vertical_lines_inner_box { + + &pdf_thin_black_line ($blocks[1],$top,$blocks[1],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[5],$top,$blocks[5],$up,'#009bc8') ; # vertical + +} #---------------------------------------------------------------------------------------------------- + +sub vertical_lines_inner_box_t { + + &pdf_thin_black_line ($tblocks[1],$top,$tblocks[1],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[2],$top,$tblocks[2],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[3],$top,$tblocks[3],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[4],$top,$tblocks[4],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[5],$top,$tblocks[5],$up,'#009bc8') ; # vertical + +} #---------------------------------------------------------------------------------------------------- + +sub quote_pdf_footer { + + &pdf_check_value_of_up(60); + $up = 90; + my $txt = qq~The parties hereby accept and agree to this quote, which incorporates by reference all the terms and conditions set forth in the Interactive Television Africa's Terms and Conditions document, attached hereto as Annexure A and the Service Level Agreement attached hereto as Annexure B (all, collectively with this quote, the "Agreement") effective as of the later of the signature dates below.~; + &pdf_text_block (10,$txt,120,3) ; + $up = $up - 10; + &pdf_medium_bold_text (10, $up, "Name:") ; &pdf_thin_black_line (30,$up,100,$up,'#009bc8') ; #&pdf_tiny_text (25, $up, "________________________________________________") ; + &pdf_medium_bold_text (110, $up, "Date:") ; &pdf_thin_black_line (130,$up,200,$up,'#009bc8') ; + $up = $up - 5; + &pdf_small_text (10, $up, "(Duly Authorised)") ; + $up = $up - 10; + &pdf_medium_bold_text (10, $up, "Company:") ; &pdf_thin_black_line (30,$up,100,$up,'#009bc8') ; + &pdf_medium_bold_text (110, $up, "Signature:") ; &pdf_thin_black_line (130,$up,200,$up,'#009bc8') ; + $up = $up - 15; + &pdf_medium_bold_text (10, $up, "Name:") ; &pdf_thin_black_line (30,$up,100,$up,'#009bc8') ; + &pdf_medium_bold_text (110, $up, "Date:") ; &pdf_thin_black_line (130,$up,200,$up,'#009bc8') ; + $up = $up - 5; + &pdf_small_text (10, $up, "(Duly Authorised on behalf of Interactive Television Africa)") ; + $up = $up - 10; + &pdf_medium_bold_text (110, $up, "Signature:") ; + &pdf_thin_black_line (130,$up,200,$up,'#009bc8') ; + +} #------------------------------------------------------------------------------------------ + +sub quote_pdf_vars { + + # our @htxt = (0,0,115,0,146,172,0) ; + # our @boxtxt = (0,12,102,117,142,167) ; + # our @blocks = (0,10,100,115,140,165) ; + + # our @rboxtxt = (0,97,122,147,172,197) ; + # our @boxtxt = (0,12,102,127,152,177) ; + # our @blocks = (0,10,100,125,150,175) ; + + our @rboxtxt = (0,103,116,143,170,197) ; + our @boxtxt = (0,12,106,120,147,174) ; + our @blocks = (0,10,104,118,145,172) ; + + our @tboxrtxt = (0,77,107,137,167,197) ; + our @tboxtxt = (0,12,82,112,142,172) ; + our @tblocks = (0,10,80,110,140,170) ; + +} #------------------------------------------------------------------------------- + +sub custom_date_txt { + + my ($date) = @_ ; + + return('') unless $date; + + my $dt_txt = Date_to_Text(substr($date,0,4),substr($date,5,2),substr($date,8,2)); + + $dt_txt = substr($dt_txt,4) ; + + return ($dt_txt) ; + +} #------------------------------------------------------------------------------------------ + +sub check_space_on_page_custom { + + my ($value) = @_ ; + + if ($up < $value) { + &pdf_thin_black_line (10,$top,10,$up) ; + &vertical_lines_table ; # draw vertical_lines on prematurely ended table + &pdf_initialise_page ; + $up = 282 ; + $top = $up ; + &pdf_thin_black_line(10,$up,200,$up) ; + $across = 1 ; + } + +} #---------------------------------------------------------------------------------------------------- + +sub get_val { + + my ($val,$cur) = @_ ; + + my $disp_val = $val ; + + if ($val eq '0.00') { + $disp_val = '' ; + + } elsif ($val) { + $disp_val = $cur . ' ' . $val ; + } + # &common_min_debug($val); + + return($disp_val) ; + +} #------------------------------------------------------------------------------------------ + +sub vertical_lines_table { + + unless ($exclude_rate) { + &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up) ; # vertical + &pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up) ; # vertical + } + + unless ($exclude_vat) { + &pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up) ; # vertical + } + + &pdf_thin_black_line ($blocks[5],$top,$blocks[5],$up) ; # vertical + &pdf_thin_black_line ($blocks[6],$top,$blocks[6],$up) ; # vertical + +} #------------------------------------------------------------------------------------------ + +# sub pdf_extra_thin_black_line { + +# my ($x1,$y1,$x2,$y2,$color) = @_ ; + +# $color = 'black' if not $color ; # $color = '#009bc8' ; + +# unless ($x1) { $x1 = 10 ; } +# unless ($y1) { $y1 = $up ; } +# unless ($x2) { $x2 = 200 ; } +# unless ($y2) { $y2 = $up ; } + +# my $pdf_black_line = $page->gfx(1); +# $pdf_black_line->strokecolor($color); +# $pdf_black_line->linewidth( '0.5' ); +# $pdf_black_line->linedash(); +# $pdf_black_line->move($x1/mm,$y1/mm); +# $pdf_black_line->line($x2/mm,$y2/mm); +# $pdf_black_line->stroke; + +# } #------------------------------------------------------------------------------- + +# sub pdf_thin_box_block_top { + +# my ($st,$en,$color) = @_ ; unless ($color) { $color = 'black' ; } # $color = '#009bc8' ; + +# $box_start{$st} = $up ; + +# &pdf_extra_thin_black_line($st,$up,$en,$up,$color) ; # horizontal + +# } #------------------------------------------------------------------------------- + +# sub pdf_thin_box_block_bottom { + +# my ($st,$en,$color) = @_ ; unless ($color) { $color = 'black' ; } # $color = '#009bc8' ; + +# &pdf_extra_thin_black_line($st,$up,$en,$up,$color) ; # horizontal + +# &pdf_extra_thin_black_line ($st,$box_start{$st},$st,$up,$color) ; # vertical +# &pdf_extra_thin_black_line ($en,$box_start{$st},$en,$up,$color) ; # vertical + +# } #------------------------------------------------------------------------------- + +sub screen2 { + + print < +
    + + + + +
    + +
    + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use db ; +use db_min ; +use dialog ; +use today ; +use common ; +use pdf ; +use tabs ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/pdf/event_quote_pdf_test.pl b/scripts/_FromProd/v1.0/pdf/event_quote_pdf_test.pl new file mode 100644 index 0000000..226df3d --- /dev/null +++ b/scripts/_FromProd/v1.0/pdf/event_quote_pdf_test.pl @@ -0,0 +1,1016 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +# unless ($username eq 'handre') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +use DBI; +use CGI::Carp qw(fatalsToBrowser); +use Date::Manip; +use Date::Calc qw(:all); + +use PDF::API2::Lite; +use constant mm => 25.4/72; +use constant in => 1/72; +use constant pt => 1; + +#------------------------------------------------------------------------------------------ + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); + +our $qt_id = $ARGV[0] ; +our $tab_no = $ARGV[1] ; +our $tab_secs = $ARGV[2] ; + +# my @sections = split(/\|/,$tab_secs); + +my @prefix_arr = qw( cost_desc_ curr_amnt_ qty_cost_ zar_amnt_ ); + +# our $debug = 1 ; +our $label = 1 ; # used in pdf_check_value_of_up + +#------------------------------------------------------------------------------------------ + +print "Content-type: text/html\n\n"; + +&today ; +&pdf_curr_symbols ; + +my $table = 'event_quotes' ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &prep_pdf ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +&exclusions ; +&start_pdf ; +&build_pdf ; +&finish_pdf ; +&screen2 ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub prep_pdf { + + my @cols = () ; + + &tab_hash ; + + &db_min_ro('event_quotes',"*","`id`='$qt_id'",'','') ; + + our $countryid = $db{$table}{$qt_id}{country_id} ; + our $custid = $db{$table}{$qt_id}{quote_to} ; + our $date_from_for_pdf = $db{$table}{$qt_id}{date_from} ; + our $type_id = $db{$table}{$qt_id}{type} ; + + my @month_array = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ) ; + my $year = substr($date_from_for_pdf, 0, 4) ; + my $month = substr($date_from_for_pdf, 5, 2) ; + $month = int($month); + $month = $month_array[$month - 1] ; + my $day = substr($date_from_for_pdf, 8, 2) ; + $date_from_for_pdf = "$day-" ; + $date_from_for_pdf .= "$month-" ; + $date_from_for_pdf .= "$year" ; + + our %country = () ; + # print "COUNTty ID: $countryid, $custid \n" ; + + &db_min_ro('customers','id,name,physical_address,contact_email,phone,contact_name,vat_nr',"`id`='$custid'",'','') ; + $customer_name{$custid} = $db{customers}{$custid}{name} ; + $customer_address{$custid} = $db{customers}{$custid}{physical_address} ; + $customer_email{$custid} = $db{customers}{$custid}{contact_email} ; + $customer_phone{$custid} = $db{customers}{$custid}{phone} ; + $customer_contact_name{$custid} = $db{customers}{$custid}{contact_name} ; + $customer_vat_nr{$custid} = $db{customers}{$custid}{vat_nr} ; + + &db_min_ro('event_cost_items','id,name','','','') ; + foreach my $id (keys %{$db{event_cost_items}}) { $price_list{$id} = $db{event_cost_items}{$id}{name} ; } + + + &db_min_ro('countries','*',"`id`='$countryid'",'','') ; + $country{$countryid} = $db{countries}{$countryid}{name} ; + # print "Country : $country{$countryid}" ; + $country{$countryid} = "Unknown" if not $country{$countryid} ; + + our $camera_system_id = $db{$table}{$qt_id}{camera_system_id} ; + &db_min_ro('camera_systems','*',"`id`='$camera_system_id'",'','') ; + $camera_system{$camera_system_id} = $db{camera_systems}{$camera_system_id}{name} ; + + our %event_type_for_pdf = () ; + &db_min_ro('event_types','id, name',"`id`='$type_id'",'','') ; + $event_type_for_pdf{$type_id} = $db{event_types}{$type_id}{name} ; + + &db_min_ro('event_quotes_min','id, excl_costing_event, item_costing_event, qty_costing_event , usd_amnt_costing_event , item_ttl_costing_event , vat_costing_event, curr_amnt_costing_event ',"id = $qt_id",, '', '' ); + +} #------------------------------------------------------------------------------------------ + +sub exclusions { + + our $exclude_rate = 0 ; + our $exclude_vat = 0 ; + + if ($db{$table}{$qt_id}{currency} ne 'ZAR') { + $exclude_vat = 1 ; + } + +} #------------------------------------------------------------------------------------------ + +sub start_pdf { + + my $qtpdfpath = "$pdfpath/event_quotes_added_by_handre" ; + our $pdfname = "EQT-$qt_id-" . $now_ccyymmdd . '.pdf' ; + + &pdf_delete_previous_pdf($qtpdfpath) ; + &pdf_initialise($qtpdfpath,$pdfname,'ITV Event Quote') ; + +} #------------------------------------------------------------------------------------------ + +sub build_pdf { + + &tab_curr_symbols; + &pdf_initialise_page ; + + $up = 292 ; + # "e_pdf_page_header ; + + &pdf_box_block_top(5,205,'#009bc8') ; + + $up = 260 ; + $across = 1 ; + $blue_box = 1 ; + + &pdf_page_header ; + "e_pdf_vars ; + "e_out_to_pdf ; + # "e_pdf_footer ; + + $up = 5 ; + &pdf_box_block_bottom(5,205,'#009bc8') ; + +} #------------------------------------------------------------------------------------------ + +# sub quote_pdf_page_header { + +# $page_num++ ; + +# my $image1 = $page->gfx(1) ; +# my $image1_thumb = "$htmlpath/img/pdf_logo.png"; +# $pdf_image1_file = $pdf->image_png($image1_thumb); +# $image1->image($pdf_image1_file, 7/mm, $up/mm, 90/mm, 29/mm); + +# $up+=18 ; + +# &pdf_nl_gap_3 ; +# &pdf_xx_large_bold_text (156,$up,"QUOTE") ; +# &pdf_nl_gap_1 ; + +# } #------------------------------------------------------------------------------- + + +# sub pdf_small_white_text_bold { + + # my ($along, $up, $text) = @_ ; $small_bold_text_white->translate( $along/mm, $up/mm ); $small_bold_text_white->text( $text ); +# } + +# sub pdf_medium_white_text_bold { + + # my ($along, $up, $text) = @_ ; $medium_bold_text_white->translate( $along/mm, $up/mm ); $medium_bold_text_white->text( $text ); +# } + +# sub pdf_large_white_text_bold { + + # my ($along, $up, $text) = @_ ; $large_bold_text_white->translate( $along/mm, $up/mm ); $large_bold_text_white->text( $text ); +# } + +# sub pdf_grey_text_above_right { + + # my ($along, $up, $text) = @_ ; $grey_text_above_right->translate( $along/mm, $up/mm ); $grey_text_above_right->text( $text ); +# } + +# sub pdf_small_white_text_bold_right { + + # my ($along, $up, $text) = @_ ; $grey_text_above_right->translate( $along/mm, $up/mm ); $grey_text_above_right->text_right( $text ); +# } + +# sub pdf_medium_white_text_bold_right { + + # my ($along, $up, $text) = @_ ; $medium_bold_text_white->translate( $along/mm, $up/mm ); $medium_bold_text_white->text_right( $text ); +# } + +# sub pdf_large_white_text_bold_right { + + # my ($along, $up, $text) = @_ ; $large_bold_text_white->translate( $along/mm, $up/mm ); $large_bold_text_white->text_right( $text ); +# } + +sub quote_out_to_pdf { + + &pdf_nl_t; + # unless ($db{$table}{$qt_id}{currency} eq 'ZAR') { &pdf_medium_red_bold_text (70, $up, "$db{$table}{$qt_id}{currency} ROE : $db{$table}{$qt_id}{roe}") ; } # hidden for client + # &pdf_medium_bold_text (157, $up, "Nr. :") ; + + &pdf_small_bold_text(150, $up, "Date") ; + my $dttxt = &custom_date_txt($db{$table}{$qt_id}{quote_date}); + &pdf_small_bold_text_right (198, $up, $dttxt) ; + + &pdf_nl; + + &pdf_small_bold_text(150, $up, "Quote Nr") ; + # &pdf_small_text_right (198, $up, $qt_id) ; + &pdf_small_bold_text_right (198, $up, $db{$table}{$qt_id}{quote_nr}) ; + + # &pdf_large_bold_text (10, $up, $db{$table}{$qt_id}{ref}) if $db{$table}{$qt_id}{ref} ; + + # &pdf_nl_gap_1; + &pdf_nl; + + &pdf_nl_t; + &pdf_bar(10,$up,200,$up,'#009bc8','QUOTE',20,98) ; + $up = $up - 5; + + &pdf_box_block_top(10,200,'#009bc8') ; # start block ------------------------------------- + + if ($custid) { + + # my ($quote_year,$quote_month,$quote_day) = split(/\-/,$db{$table}{$qt_id}{quote_date}); + # my ($expiry_year,$expiry_month,$expiry_day) = Add_Delta_Days($quote_year,$quote_month,$quote_day,14); # Add 7 days to quote date + # $expiry_month = sprintf("%02s", $expiry_month) ; + # $expiry_day = sprintf("%02s", $expiry_day) ; + my ($expiry_year,$expiry_month,$expiry_day) = split(/\-/,$db{$table}{$qt_id}{quote_expiry}); + my $expiry_date = &custom_date_txt("$expiry_year-$expiry_month-$expiry_day"); + # my $expiry_date = "$expiry_year-$expiry_month-$expiry_day"; + + &pdf_nl; + &pdf_thin_box_block_top(15,100,'#009bc8'); + # &pdf_thin_box_block_top(110,195,'#009bc8'); + + $top = $up; + my $pos = 37; + my $pos2 = $pos + 1; + my $pos3 = 132; + my $pos4 = $pos3 + 1; + + $up = $up - 5.5 ; + # $up = $up + 1.75; + + # $up = $up - 1.75; + &pdf_small_bold_text (16, $up, "Customer") ; + &pdf_small_text ($pos2, $up, $customer_name{$custid}) ; + + $up = $up + 5.5 ; + $up = $up - 3.25; + # &pdf_small_bold_text (111, $up, "Event Start") ; + # my $start_date = &custom_date_txt(substr($db{$table}{$qt_id}{date_from}, 0, 10)); + # $start_date .= substr($db{$table}{$qt_id}{date_from}, 10); + # &pdf_small_text ($pos4, $up, $start_date) ; + $up = $up -1.25; + # &pdf_extra_thin_black_line (110,$up, 195 ,$up,'#009bc8') ; + $up = $up - 3.25; + # &pdf_small_bold_text (111, $up, "Event End") ; + # my $end_date = &custom_date_txt(substr($db{$table}{$qt_id}{date_to}, 0, 10)); + # $end_date .= substr($db{$table}{$qt_id}{date_to}, 10); + # &pdf_small_text ($pos4, $up, $end_date) ; + $up = $up -1.25; + # &pdf_extra_thin_black_line ($pos3,$top, $pos3 ,$up,'#009bc8') ; + + &pdf_extra_thin_black_line ($pos,$top, $pos ,$up,'#009bc8') ; + &pdf_thin_box_block_bottom(15,100,'#009bc8'); + # &pdf_thin_box_block_bottom(110,195,'#009bc8'); + &pdf_thin_box_block_top(15,100,'#009bc8'); + &pdf_thin_box_block_top(110,195,'#009bc8'); + + $top = $up; + $up = $up - 3.25; + + &pdf_small_bold_text (111, $up, "Country") ; + &pdf_small_text ($pos4, $up, $country{$countryid}) ; + $up = $up -1.25; + &pdf_thin_box_block_bottom(110,195,'#009bc8'); + &pdf_small_bold_text (16, $up, "Address") ; + my @waypoint = split(/\, / , $customer_address{$custid}); + my $top2 = $up; + my $count = 0; + for my $py (@waypoint){ + &pdf_small_text ($pos2, $up, $waypoint[$count]) ; + $count++; + $up = $up - 4; + } + $up = $top2; + &pdf_thin_box_block_top(110,195,'#009bc8'); + $up = $up - 3.25; + &pdf_small_bold_text (111, $up, "Tax/VAT Nr") ; + &pdf_small_text ($pos4, $up, $customer_vat_nr{$custid}) ; + $up = $up - 1.25; + &pdf_thin_box_block_bottom(110,195,'#009bc8'); + &pdf_extra_thin_black_line ($pos3,$top, $pos3 ,$up,'#009bc8') ; + $up = $up - 4.5; + &pdf_extra_thin_black_line ($pos,$top, $pos ,$up,'#009bc8') ; + $top = $up; + &pdf_thin_box_block_top(110,195,'#009bc8'); + $up = $up - 3.25; + &pdf_small_bold_text (111, $up, "Quote Expiry") ; + &pdf_small_text ($pos4, $up, $expiry_date) ; + $up = $up - 1.25; + &pdf_thin_box_block_bottom(110,195,'#009bc8'); + &pdf_thin_box_block_bottom(15,100,'#009bc8'); + &pdf_extra_thin_black_line ($pos,$top, $pos ,$up,'#009bc8') ; + &pdf_extra_thin_black_line ($pos3,$top, $pos3 ,$up,'#009bc8') ; + $up = $up - 4.5; + &pdf_thin_box_block_top(15,100,'#009bc8'); + $top = $up; + &pdf_thin_box_block_top(110,195,'#009bc8'); + $up = $up - 3.25; + &pdf_small_bold_text (16, $up, "Contact") ; + &pdf_small_text ($pos2, $up, $customer_contact_name{$custid}) ; + &pdf_small_bold_text (111, $up, "Reference") ; + &pdf_small_text ($pos4, $up, $db{$table}{$qt_id}{ref}) ; + $up = $up -1.25; + &pdf_thin_box_block_bottom(15,100,'#009bc8'); + &pdf_thin_box_block_bottom(110,195,'#009bc8'); + &pdf_thin_box_block_top(110,195,'#009bc8'); + &pdf_thin_box_block_top(15,100,'#009bc8'); + $up = $up - 3.25; + &pdf_small_bold_text (16, $up, "Phone Nr") ; + &pdf_small_text ($pos2, $up, $customer_phone{$custid}) ; + &pdf_small_bold_text (111, $up, "Date") ; + &pdf_small_text ($pos4, $up, $date_from_for_pdf) ; + # &pdf_small_text ($pos4, $up, $db{$table}{$qt_id}{po_nr}) ; + $up = $up - 1.25; + &pdf_thin_box_block_bottom(110,195,'#009bc8'); + &pdf_thin_box_block_bottom(15,100,'#009bc8'); + &pdf_extra_thin_black_line ($pos3,$top, $pos3 ,$up,'#009bc8') ; + &pdf_thin_box_block_top(15,100,'#009bc8'); + $up = $up - 3.25; + &pdf_small_bold_text (16, $up, "Email") ; + &pdf_small_text ($pos2, $up, $customer_email{$custid}) ; + $up = $up - 1.25; + &pdf_extra_thin_black_line ($pos,$top, $pos ,$up,'#009bc8') ; + &pdf_thin_box_block_bottom(15,100,'#009bc8'); + &pdf_nl; + &pdf_thin_box_block_top(15,100,'#009bc8'); + &pdf_thin_box_block_top(110,195,'#009bc8'); + $top = $up; + $up = $up - 3.25; + &pdf_small_bold_text (16, $up, "Notes") ; + &pdf_small_bold_text (111, $up, "Type") ; + $up = $up - 1.25; + &pdf_extra_thin_black_line ($pos3,$top, $pos3 ,$up,'#009bc8') ; + &pdf_thin_box_block_bottom(110,195,'#009bc8'); + $up = $up + 1.25; + # &pdf_small_text ($pos4, $up, $camera_system{$camera_system_id}) ; + &pdf_small_text ($pos4, $up, $event_type_for_pdf{$type_id}) ; + # &pdf_small_text (29, $up, $db{$table}{$qt_id}{notes}) ; + &pdf_text_block ($pos2 ,$db{$table}{$qt_id}{notes},60,5) ; + $up = $up - 9; + &pdf_thin_box_block_bottom(15,100,'#009bc8'); + &pdf_extra_thin_black_line ($pos,$top, $pos ,$up,'#009bc8') ; + $up = $up - 4.5; + } + + &pdf_box_block_bottom(10,200,'#009bc8') ; # end block ------------------------------------- + + $up = $up - 6; + #&pdf_nl_gap_1; + &pdf_bar(9.75,$up,200.25,$up,'#009bc8','Item List',20,97) ; + + $top=$up; + + #&pdf_check_value_of_up(20); + $up = $up - 3; + &pdf_box_block_top($blocks[1],200,'#009bc8') ; # start block ------------------------------------- + + $up = $up - 6; + &pdf_small_bold_text ($boxtxt[1]+5,$up,'Item') ; + $up += 2; + &pdf_small_bold_text (87,$up,'Per Day') ; + $up -= 4; + &pdf_small_bold_text (87,$up,'/Venue') ; + $up += 2; + &pdf_small_bold_text ($boxtxt[2]+2,$up,'Qty') ; + &pdf_small_bold_text ($boxtxt[3]+2.5,$up,'Per x Day Qty') ; + &pdf_small_bold_text ($boxtxt[4]+7.5,$up,'VAT') ; + &pdf_small_bold_text ($boxtxt[5]+7.5,$up,'Total') ; + $up = $up - 4; + &pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + + &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up,'#009bc8') ; + &pdf_thin_black_line (80,$top,80,$up,'#009bc8') ; + &pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[5],$top,$blocks[5],$up,'#009bc8') ; + $top = $up; + &pdf_nl_gap_1; + my $price_times_qty = 0 ; + $inner_blue_box = 1 ; + my %sec_cnt2 = ('a_costing_event' => "30-Event Costings"); + + foreach (sort keys %sec_cnt2) { + + if ($up>280){ $up=280; } + $_k = substr($_,1) ; + my @parts = split(/\-/,$sec_cnt2{$_}) ; + + # my $sec = '_costing' ; + # my $suffix = "$sec$_k" ; + + my $sec = '_costing_event' ; + my $suffix = "$sec" ; + my $vat_amnt = 0 ; + # unless ($db{$table}{$qt_id}{"item_1$suffix"}) { next ; } + + &pdf_small_bold_text ($boxtxt[1]+5,$up,$parts[1]) ; + # &build_cost_form($id,$tab,$parts[0],"$sec$_k"); + &pdf_nl; + + my @excl_cost = split(";", $db{event_quotes_min}{$qt_id}{excl_costing_event}); + my @qty_cost = split(";", $db{event_quotes_min}{$qt_id}{qty_costing_event}); + my @usd_amnt_cost = split(";", $db{event_quotes_min}{$qt_id}{usd_amnt_costing_event}); + my @item_ttl_cost = split(";", $db{event_quotes_min}{$qt_id}{item_ttl_costing_event}); + my @vat_cost = split(";", $db{event_quotes_min}{$qt_id}{vat_costing_event}); + my @item_cost = split(";", $db{event_quotes_min}{$qt_id}{item_costing_event}); + my @curr_amnt_cost = split(";", $db{event_quotes_min}{$qt_id}{curr_amnt_costing_event}); + + for (1 .. $parts[0]) { + + # &pdf_check_value_of_up(60) if $_ == 25 ; + # next if $db{$table}{$qt_id}{"excl_$_$suffix"}; + next if $excl_cost[$_ - 1]; + + next if not $qty_cost[$_ - 1] and not $curr_amnt_cost[$_ - 1] ; + + if ($up < 10){ + &pdf_thin_black_line (80,$top,80,10,'#009bc8') ; + &pdf_check_value_of_up(10) if $_ > 15; + $new_page = 1 ; + } + + if ($up>280){ $up=280; } + # my $disp_item = $price_list{$db{$table}{$qt_id}{"item_$_$suffix"}} ? $price_list{$db{$table}{$qt_id}{"item_$_$suffix"}} : $db{$table}{$qt_id}{"item_$_$suffix"} ; + my $disp_item = $price_list{$item_cost[$_ - 1]} ? $price_list{$item_cost[$_ - 1]} : $item_cost[$_ - 1] ; + + &pdf_small_text($boxtxt[1]+5,$up,"$disp_item") ; + # &pdf_small_text($boxtxt[2]+4.4,$up,$db{$table}{$qt_id}{"qty_$_$suffix"}) ; + &pdf_small_text($boxtxt[2]+4.4,$up,$qty_cost[$_ - 1]) ; + # &pdf_small_text ($boxtxt[3]+2,$up,&common_commify($db{$table}{$qt_id}{"curr_amnt_$_$suffix"})) ; + &pdf_small_text($boxtxt[3],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right(102,$up,&common_commify($db{$table}{$qt_id}{"curr_amnt_$_$suffix"})) ; + # &pdf_small_text_right(102,$up,&common_commify($db{$table}{$qt_id}{"curr_amnt_$_$suffix"})) ; + &pdf_small_text_right(102,$up,&common_commify($curr_amnt_cost[$_ - 1])) ; + &pdf_small_text_right(84,$up,"R") ; + # $price_times_qty = $db{$table}{$qt_id}{"curr_amnt_$_$suffix"} * $db{$table}{$qt_id}{"qty_$_$suffix"} ; + $price_times_qty = $curr_amnt_cost[$_ - 1] * $qty_cost[$_ - 1] ; + $price_times_qty = sprintf("%.2f", $price_times_qty) ; + $price_times_qty = &common_commify($price_times_qty) ; + &pdf_small_text_right($rboxtxt[3],$up,$price_times_qty); + + # if ($db{$table}{$qt_id}{"vat_$_$suffix"}) { + if ($vat_cost[$_ - 1]) { + # $vat_amnt = sprintf("%0.2f",$db{$table}{$qt_id}{"curr_amnt_$_$suffix"} * $db{$table}{$qt_id}{"qty_$_$suffix"} * 0.15) ; + $vat_amnt = sprintf("%0.2f",$curr_amnt_cost[$_ - 1] * $qty_cost[$_ - 1] * 0.15) ; + # &pdf_small_text ($boxtxt[4]+2,$up,&common_commify($vat_amnt)) ; + &pdf_small_text($boxtxt[4],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($rboxtxt[4],$up,&common_commify($vat_amnt)) ; + } + + # &pdf_small_text ($boxtxt[5]+2,$up,&common_commify($db{$table}{$qt_id}{"curr_amnt_$_$suffix"}+$vat_amnt)) ; + &pdf_small_text($boxtxt[5],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # my $ttl_amnt = sprintf("%0.2f",$db{$table}{$qt_id}{"curr_amnt_$_$suffix"}*$db{$table}{$qt_id}{"qty_$_$suffix"}+$vat_amnt) ; + my $ttl_amnt = sprintf("%0.2f",$curr_amnt_cost[$_ - 1]*$qty_cost[$_ - 1]+$vat_amnt) ; + &pdf_small_text_right($rboxtxt[5],$up,&common_commify($ttl_amnt)) ; + &pdf_nl; + } + + if (not $new_page and $up < 65){ + &pdf_check_value_of_up(65) ; + $new_page = 1 ; + } + + if ($_k eq '_systems' and $db{$table}{$qt_id}{systems_included}) { + my @para = split /^/m, $db{$table}{$qt_id}{systems_included} ; + foreach (@para) { + &pdf_small_text($boxtxt[1]+5,$up,$_) ; + &pdf_nl_s; + } + # &pdf_text_block ($boxtxt[1]+2,$db{$table}{$qt_id}{systems_included},50,5) ; + } + + if ($_k eq '_rental' and $db{$table}{$qt_id}{rental_included}) { + my @para = split /^/m, $db{$table}{$qt_id}{rental_included} ; + foreach (@para) { + &pdf_small_text($boxtxt[1]+5,$up,$_) ; + &pdf_nl_s; + } + } + &pdf_nl; + } + #$up=80; + #&pdf_box_block_bottom($blocks[1],200,'#009bc8') ; # end block ------------------------------------- + + $inner_blue_box = 0 ; + + # ------------- totals ------------------------------------------------------------------ + + + #$top=$up; + + #&pdf_box_block_top($blocks[1],200,'#009bc8') ; # start block ------------------------------------- + + # &pdf_nl_gap_1;#&pdf_nl_t; + # &pdf_small_bold_text ($boxtxt[1]+2,$up,'') ; + # &pdf_small_bold_text ($boxtxt[2],$up,'') ; + # &pdf_small_bold_text ($boxtxt[3],$up,'Sub Total') ; + # &pdf_small_bold_text ($boxtxt[4],$up,'Vat Total') ; + # &pdf_small_bold_text ($boxtxt[5],$up,'Grand Total') ; + # &pdf_nl_t; + + #$top = $up; + my $a = 0; + my $b = 0; + my $c = 0; + + if ($up < 65){ + &pdf_check_value_of_up(65); + $new_page = 1 ; + } + + $up = 55; + + # if ($db{$table}{$qt_id}{subtotal_one_time_fee} ne '0.00' or $db{$table}{$qt_id}{vat_one_time_fee} ne '0.00' or $db{$table}{$qt_id}{total_one_time_fee} ne '0.00'){ + $a = 1; + $up = $up + 8; + # } + # if ($db{$table}{$qt_id}{subtotal_monthly_recurring_fee} ne '0.00' or $db{$table}{$qt_id}{vat_monthly_recurring_fee} ne '0.00' or $db{$table}{$qt_id}{total_monthly_recurring_fee} ne '0.00' ){$b = 1;$up = $up + 8;} + # if ($db{$table}{$qt_id}{subtotal_annual_fee} ne '0.00' or $db{$table}{$qt_id}{vat_annual_fee} ne '0.00' or $db{$table}{$qt_id}{total_annual_fee} ne '0.00'){$c = 1;$up = $up + 8;} + + unless ($new_page){ + &pdf_thin_black_line (80,$top,80,$up,'#009bc8') ; + &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up,'#009bc8') ; + &pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up-8,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up-8,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[5],$top,$blocks[5],$up-8,'#009bc8') ; + } + + $top = $up ; + + $top = 287 if $new_page; + &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up,'#009bc8') ; + &pdf_thin_black_line (80,$top,80,$up,'#009bc8') ; + + if ($a == 1) { + &pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + $up = $up - 5; + $inner_blue_box = 1 ; + &pdf_small_bold_text ($boxtxt[1]+2,$up,'Total') ; + &pdf_small_text($boxtxt[3],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($rboxtxt[3],$up,&common_commify($db{$table}{$qt_id}{sub_total})) ; + &pdf_small_text($boxtxt[4],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($rboxtxt[4],$up,&common_commify($db{$table}{$qt_id}{vat_total})) ; + &pdf_small_text($boxtxt[5],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($rboxtxt[5],$up,&common_commify($db{$table}{$qt_id}{grand_total})) ; + $up = $up - 3; + } + + # if ($b == 1) { + # &pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + # $up = $up - 5; + # &pdf_small_bold_text ($boxtxt[1]+2,$up,'Monthly Recurring Fee') ; + # &pdf_small_text($boxtxt[3],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right($rboxtxt[3],$up,&common_commify($db{$table}{$qt_id}{subtotal_monthly_recurring_fee})) ; + # &pdf_small_text($boxtxt[4],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right($rboxtxt[4],$up,&common_commify($db{$table}{$qt_id}{vat_monthly_recurring_fee})) ; + # &pdf_small_text($boxtxt[5],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right($rboxtxt[5],$up,&common_commify($db{$table}{$qt_id}{total_monthly_recurring_fee})) ; + # $up = $up - 3; + # } + + # if ($c == 1) { + # &pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + # $up = $up - 5; + # &pdf_small_bold_text ($boxtxt[1]+2,$up,'Annual Fee') ; + # &pdf_small_text($boxtxt[3],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right($rboxtxt[3],$up,&common_commify($db{$table}{$qt_id}{subtotal_annual_fee})) ; + # &pdf_small_text($boxtxt[4],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right($rboxtxt[4],$up,&common_commify($db{$table}{$qt_id}{vat_annual_fee})) ; + # &pdf_small_text($boxtxt[5],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right($rboxtxt[5],$up,&common_commify($db{$table}{$qt_id}{total_annual_fee})) ; + # $up = $up - 3; + # } + # &pdf_extra_thin_black_line ($blocks[2],$top,$blocks[2],$up,'#009bc8') ; + # + if ($new_page){ + &pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[5],$top,$blocks[5],$up,'#009bc8') ; + } + &pdf_thin_black_line (10,$up,200,$up,'#009bc8') ; + #&vertical_lines_inner_box; + $up -= 5; + + # &pdf_thin_black_line ($tblocks[3],$top,$tblocks[3],$up,'#009bc8') ; # vertical + # &pdf_thin_black_line ($tblocks[4],$top,$tblocks[4],$up,'#009bc8') ; # vertical + # &pdf_thin_black_line ($tblocks[5],$top,$tblocks[5],$up,'#009bc8') ; + + &pdf_box_block_bottom($blocks[1],200,'#009bc8') ; # end block ------------------------------------- + + $inner_blue_box = 0 ; + + # ------------- totals ------------------------------------------------------------------ + + # ------------- purchase summary ------------------------------------------------------------------ + + # # &pdf_check_value_of_up(200); + + unless ($db{$table}{$qt_id}{excl_purchase_summary}) { + + # &pdf_box_block_top($tblocks[1],200,'#009bc8') ; # start block --------- + # $up = $up - 3.5; + + + # &pdf_bar(10,$up,200,$up,'#009bc8','Purchase Summary',20,90, 'med') ; + + # $up = $up - 10; + # $top = $up ; + # &pdf_bar(10,$up,200,$up,'#009bc8','Description',20, 14, 'med'); + # &pdf_bar (10,$up,200,$up,'#009bc8','Year 1', 20, 90, 'med') ; + # &pdf_bar (10,$up,200,$up,'#009bc8','Year 2', 20, 120, 'med') ; + # &pdf_bar (10,$up,200,$up,'#009bc8','Year 3', 20, 150, 'med') ; + # &pdf_bar (10,$up,200,$up,'#009bc8','TOTAL', 20, 180, 'med') ; + # $up = $up - 8; + # # $top=$up; + + # # &pdf_check_value_of_up(20); + + # # # ---------------------------- + + # # &pdf_nl_gap_1;&pdf_nl_t; + # # &pdf_small_bold_text ($tboxtxt[1]+2,$up,'Description') ; + # # &pdf_small_bold_text ($tboxtxt[2],$up,'Year 1') ; + # # &pdf_small_bold_text ($tboxtxt[3],$up,'Year 2') ; + # # &pdf_small_bold_text ($tboxtxt[4],$up,'Year 3') ; + # # &pdf_small_bold_text ($tboxtxt[5],$up,'Total') ; + # # &pdf_nl_t; + # # &pdf_thin_black_line ($tblocks[1],$up,200,$up,'#009bc8') ; + # # &pdf_nl_gap_1; + + # $inner_blue_box = 1 ; + + # my $suffix = "_purchase_summary" ; + + # foreach (1 .. 3) { + # &pdf_check_value_of_up(15); if ($up>280){ $up=280; } + + # if ($db{$table}{$qt_id}{"excl_$_$suffix"}) { next ; } + + # &pdf_small_bold_text ($tboxtxt[1]+2,$up,$db{$table}{$qt_id}{"item_$_$suffix"}) ; + # $box=1; + # for my $y_ (1 .. 3) { + # $box++; + # $ttl{$y_} += $db{$table}{$qt_id}{"year_$y_\_$_$suffix"} ; + # # &pdf_small_text ($tboxtxt[$box],$up,&common_commify($db{$table}{$qt_id}{"year_$y_\_$_$suffix"})) ; + # &pdf_small_bold_text($tboxtxt[$box],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_bold_text_right($tboxrtxt[$box],$up,&common_commify($db{$table}{$qt_id}{"year_$y_\_$_$suffix"})) ; + # } + # $box++; + # $ttl += $db{$table}{$qt_id}{"total_$_$suffix"} ; + # # &pdf_small_text ($tboxtxt[$box],$up,&common_commify($db{$table}{$qt_id}{"total_$_$suffix"})) ; + # &pdf_small_bold_text($tboxtxt[$box],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_bold_text_right($tboxrtxt[$box],$up,&common_commify($db{$table}{$qt_id}{"total_$_$suffix"})) ; + # $up = $up - 6; + # } + + # #$up = $up - 4; + # #&pdf_thin_black_line ($tblocks[1],$up,200,$up,'#009bc8') ; + + # &pdf_bar (10,$up,200,$up,'#009bc8','Total', 20, 14, 'med') ; + # #&pdf_large_bold_text(22, $up, 'Total'); + # #&pdf_large_white_text_bold(12, $up, 'Total'); + + # # our @tboxrtxt = (0,77,107,137,167,197) ; + # #our @tboxtxt = (0,12,82,112,142,172) ; + # # &pdf_small_bold_text ($tboxtxt[2],$up,&common_commify($ttl{1})) ; + # # &pdf_small_bold_text ($tboxtxt[3],$up,&common_commify($ttl{2})) ; + # # &pdf_small_bold_text ($tboxtxt[4],$up,&common_commify($ttl{3})) ; + # # &pdf_small_bold_text ($tboxtxt[5],$up,&common_commify($ttl)) ; + # # &pdf_small_bold_text($tboxtxt[2],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # # &pdf_small_bold_text_right($tboxrtxt[2],$up,&common_commify(sprintf("%0.2f",$ttl{1}))) ; + # # &pdf_small_bold_text($tboxtxt[3],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # # &pdf_small_bold_text_right($tboxrtxt[3],$up,&common_commify(sprintf("%0.2f",$ttl{2}))) ; + # # &pdf_small_bold_text($tboxtxt[4],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # # &pdf_small_bold_text_right($tboxrtxt[4],$up,&common_commify(sprintf("%0.2f",$ttl{3}))) ; + # # &pdf_small_bold_text($tboxtxt[5],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # # &pdf_small_bold_text_right($tboxrtxt[5],$up,&common_commify(sprintf("%0.2f",$ttl))) ; + + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt[2], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl{1})), 20, $tboxrtxt[2], 'small_right') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt[3], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl{2})), 20, $tboxrtxt[3], 'small_right') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt[4], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl{3})), 20, $tboxrtxt[4], 'small_right') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt[5], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl)), 20, $tboxrtxt[5], 'small_right') ; + + # #&pdf_nl_t; + + # #&vertical_lines_inner_box_t; + # &pdf_thin_black_line ($tblocks[2],$top,$tblocks[2],$up,'#009bc8') ; # vertical + # &pdf_thin_black_line ($tblocks[3],$top,$tblocks[3],$up,'#009bc8') ; # vertical + # &pdf_thin_black_line ($tblocks[4],$top,$tblocks[4],$up,'#009bc8') ; # vertical + # &pdf_thin_black_line ($tblocks[5],$top,$tblocks[5],$up,'#009bc8') ; # vertical + + # &pdf_box_block_bottom($tblocks[1],200,'#009bc8') ; # end block ------------------------------------- + + # $inner_blue_box = 0 ; +} + +# ------------- purchase summary ------------------------------------------------------------------ + + #&pdf_nl_gap_1; + #&pdf_nl_gap_3; + # $up = $up - 15; + #$&pdf_check_value_of_up(50); + + for (1 .. 20) { + next if $db{$table}{$qt_id}{"excl_$_\_notes"} || $db{$table}{$qt_id}{"note_$_"} eq ''; + $notes_exist = 1 ; + } + $up -= 8; + if ($notes_exist) { + &pdf_medium_bold_text ($blocks[1],$up,'Notes:') ; + $up = $up - 1; + for (1 .. 20) { + unless ($db{$table}{$qt_id}{"excl_$_\_notes"}) { + my $note = $db{$table}{$qt_id}{"note_$_"}; + if ($note) { + &pdf_nl; $up = $up - 1; + &pdf_medium_text ($blocks[1],$up,"$note") ; + + } + } + } + } + + for (1 .. 20) { + next if $db{$table}{$qt_id}{"excl_$_\_payment_terms"} || $db{$table}{$qt_id}{"payment_term_$_"} eq ''; + $payment_terms_exists = 1 ; + } + + if ($payment_terms_exists) { + &pdf_nl_gap_3; + # &pdf_check_value_of_up(50); + &pdf_medium_bold_text ($blocks[1],$up,'Payment Terms:') ; + $up = $up - 1; + for (1 .. 20) { + unless ($db{$table}{$qt_id}{"excl_$_\_payment_terms"}) { + my $payment_term = $db{$table}{$qt_id}{"payment_term_$_"}; + if (length($payment_term)>2) { + $up = $up - 6; + &pdf_medium_text ($blocks[1],$up,"$payment_term") ; + } + } + } + } + + # for (1 .. 20) { + # next if $db{$table}{$qt_id}{"excl_$_\_roes"} || $db{$table}{$qt_id}{"roe_$_"} eq ''; + # $roe_exists = 1 ; + # } + + # if ($roe_exists) { + # &pdf_nl_gap_3; + # &pdf_check_value_of_up(50); + # &pdf_medium_bold_text ($blocks[1],$up,'ROE:') ; + # $up = $up - 1; + # for (1 .. 20) { + # unless ($db{$table}{$qt_id}{"excl_$_\_roes"}) { + # my $roe = $db{$table}{$qt_id}{"roe_$_"}; + # if ($roe) { + # &pdf_nl; + # $up = $up - 1; + # &pdf_medium_text ($blocks[1],$up,"- $roe") ; + # } + # } + # } + # } + + # for (1 .. 20) { + # next if $db{$table}{$qt_id}{"excl_$_\_delivery_times"} || $db{$table}{$qt_id}{"delivery_time_$_"} eq ''; + # $delivery_time_exists = 1 ; + # } + + # if ($delivery_time_exists) { + # &pdf_nl_gap_3; + # &pdf_check_value_of_up(50); + # &pdf_medium_bold_text ($blocks[1],$up,'Manufacturing time:') ; + # $up = $up - 1; + + # for (1 .. 20) { + # unless ($db{$table}{$qt_id}{"excl_$_\_delivery_times"}) { + # my $delivery_time = $db{$table}{$qt_id}{"delivery_time_$_"}; + # if ($delivery_time) { + # &pdf_nl; $up = $up - 1; + # &pdf_medium_text ($blocks[1],$up,"- $delivery_time") ; + # } + # } + # } + # } +} #------------------------------------------------------------------------------------------ + +sub vertical_lines_inner_box { + + &pdf_thin_black_line ($blocks[1],$top,$blocks[1],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[5],$top,$blocks[5],$up,'#009bc8') ; # vertical +} #---------------------------------------------------------------------------------------------------- + +sub vertical_lines_inner_box_t { + &pdf_thin_black_line ($tblocks[1],$top,$tblocks[1],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[2],$top,$tblocks[2],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[3],$top,$tblocks[3],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[4],$top,$tblocks[4],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[5],$top,$tblocks[5],$up,'#009bc8') ; # vertical +} #---------------------------------------------------------------------------------------------------- + +sub quote_pdf_footer { + + &pdf_check_value_of_up(60); + $up = 90; + my $txt = qq~The parties hereby accept and agree to this quote, which incorporates by reference all the terms and conditions set forth in the Interactive Television Africa's Terms and Conditions document, attached hereto as Annexure A and the Service Level Agreement attached hereto as Annexure B (all, collectively with this quote, the "Agreement") effective as of the later of the signature dates below.~; + &pdf_text_block (10,$txt,120,3) ; + $up = $up - 10; + &pdf_medium_bold_text (10, $up, "Name:") ; &pdf_thin_black_line (30,$up,100,$up,'#009bc8') ; #&pdf_tiny_text (25, $up, "________________________________________________") ; + &pdf_medium_bold_text (110, $up, "Date:") ; &pdf_thin_black_line (130,$up,200,$up,'#009bc8') ; + $up = $up - 5; + &pdf_small_text (10, $up, "(Duly Authorised)") ; + $up = $up - 10; + &pdf_medium_bold_text (10, $up, "Company:") ; &pdf_thin_black_line (30,$up,100,$up,'#009bc8') ; + &pdf_medium_bold_text (110, $up, "Signature:") ; &pdf_thin_black_line (130,$up,200,$up,'#009bc8') ; + $up = $up - 15; + &pdf_medium_bold_text (10, $up, "Name:") ; &pdf_thin_black_line (30,$up,100,$up,'#009bc8') ; + &pdf_medium_bold_text (110, $up, "Date:") ; &pdf_thin_black_line (130,$up,200,$up,'#009bc8') ; + $up = $up - 5; + &pdf_small_text (10, $up, "(Duly Authorised on behalf of Interactive Television Africa)") ; + $up = $up - 10; + &pdf_medium_bold_text (110, $up, "Signature:") ; + &pdf_thin_black_line (130,$up,200,$up,'#009bc8') ; +} #------------------------------------------------------------------------------------------ + +sub quote_pdf_vars { + + # our @htxt = (0,0,115,0,146,172,0) ; + # our @boxtxt = (0,12,102,117,142,167) ; + # our @blocks = (0,10,100,115,140,165) ; + + # our @rboxtxt = (0,97,122,147,172,197) ; + # our @boxtxt = (0,12,102,127,152,177) ; + # our @blocks = (0,10,100,125,150,175) ; + + our @rboxtxt = (0,103,116,143,170,197) ; + our @boxtxt = (0,12,106,120,147,174) ; + our @blocks = (0,10,104,118,145,172) ; + + our @tboxrtxt = (0,77,107,137,167,197) ; + our @tboxtxt = (0,12,82,112,142,172) ; + our @tblocks = (0,10,80,110,140,170) ; +} #------------------------------------------------------------------------------- + +sub custom_date_txt { + + my ($date) = @_ ; + + return "Unknown" if not $date; + + my $dt_txt = Date_to_Text(substr($date,0,4),substr($date,5,2),substr($date,8,2)); + + $dt_txt = substr($dt_txt,4) ; + + return ($dt_txt) ; +} #------------------------------------------------------------------------------------------ + +sub check_space_on_page_custom { + + my ($value) = @_ ; + + if ($up < $value) { + &pdf_thin_black_line (10,$top,10,$up) ; + &vertical_lines_table; # draw vertical_lines on prematurely ended table + &pdf_initialise_page ; + $up=282 ; + $top=$up; + &pdf_thin_black_line(10,$up,200,$up) ; + $across = 1 ; + } +} #---------------------------------------------------------------------------------------------------- + +sub get_val { + + my ($val,$cur) = @_ ; + + my $disp_val = $val ; + + if ($val eq '0.00') { + $disp_val = '' ; + + } elsif ($val) { + $disp_val = $cur . ' ' . $val ; + } + # &common_min_debug($val); + + return($disp_val); +} #------------------------------------------------------------------------------------------ + +sub vertical_lines_table { + + unless ($exclude_rate) { + &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up) ; # vertical + &pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up) ; # vertical + } + + unless ($exclude_vat) { + &pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up) ; # vertical + } + + &pdf_thin_black_line ($blocks[5],$top,$blocks[5],$up) ; # vertical + &pdf_thin_black_line ($blocks[6],$top,$blocks[6],$up) ; # vertical + +} #------------------------------------------------------------------------------------------ + +# sub pdf_extra_thin_black_line { + +# my ($x1,$y1,$x2,$y2,$color) = @_ ; + +# $color = 'black' if not $color ; # $color = '#009bc8' ; + +# unless ($x1) { $x1 = 10 ; } +# unless ($y1) { $y1 = $up ; } +# unless ($x2) { $x2 = 200 ; } +# unless ($y2) { $y2 = $up ; } + +# my $pdf_black_line = $page->gfx(1); +# $pdf_black_line->strokecolor($color); +# $pdf_black_line->linewidth( '0.5' ); +# $pdf_black_line->linedash(); +# $pdf_black_line->move($x1/mm,$y1/mm); +# $pdf_black_line->line($x2/mm,$y2/mm); +# $pdf_black_line->stroke; + +# } #------------------------------------------------------------------------------- + +# sub pdf_thin_box_block_top { + +# my ($st,$en,$color) = @_ ; unless ($color) { $color = 'black' ; } # $color = '#009bc8' ; + +# $box_start{$st} = $up ; + +# &pdf_extra_thin_black_line($st,$up,$en,$up,$color) ; # horizontal + +# } #------------------------------------------------------------------------------- + +# sub pdf_thin_box_block_bottom { + +# my ($st,$en,$color) = @_ ; unless ($color) { $color = 'black' ; } # $color = '#009bc8' ; + +# &pdf_extra_thin_black_line($st,$up,$en,$up,$color) ; # horizontal + +# &pdf_extra_thin_black_line ($st,$box_start{$st},$st,$up,$color) ; # vertical +# &pdf_extra_thin_black_line ($en,$box_start{$st},$en,$up,$color) ; # vertical + +# } #------------------------------------------------------------------------------- + +sub screen2 { + + print < +
    + + + + +
    + +
    + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use db ; +use db_min ; +use dialog ; +use today ; +use common ; +use pdf ; +use tabs ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/pdf/inv_pdf.pl b/scripts/_FromProd/v1.0/pdf/inv_pdf.pl new file mode 100644 index 0000000..f222150 --- /dev/null +++ b/scripts/_FromProd/v1.0/pdf/inv_pdf.pl @@ -0,0 +1,356 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); + +require cfg ; + +print header; + +use Date::Calc qw(:all); +use POSIX; + +use PDF::API2::Lite; +use constant mm => 25.4/72; +use constant in => 1/72; +use constant pt => 1; + +#------------------------------------------------------------------------------------------ + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); + +my $cl_id = $ARGV[0] ; +my $wb_list = $ARGV[1] ; + +my @waybills = split(/\|/,$wb_list); + +#------------------------------------------------------------------------------------------ + +unless ($wb_list) { print "ERROR" ; exit ; } + +&today ; + +&db_load_airports ; + +&start_pdf ; + +foreach my $wb_no (@waybills) { + &db_load_waybill($wb_no) ; + @parcels = () ; + &db_load_parcels($wb_no) ; + &build_pdf($wb_no) ; + } + +&finish_pdf ; + +&screen2 ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub start_pdf { + +my $invpdfpath = "$pdfpath/invoice" ; +our $pdfname = "INV-$cl_id-" . $now_ccyymmdd . '.pdf' ; + +&pdf_delete_previous_pdf($invpdfpath) ; +&pdf_initialise($invpdfpath,$pdfname,'Film Freight Waybill') ; ; + +} #------------------------------------------------------------------------------------------ + +sub build_pdf { + +my ($wb_no) = @_ ; + +&pdf_initialise_page ; + +$up = 285 ; + +&invoice_header($wb_no) ; +&invoice_out_to_pdf($wb_no) ; + +} #------------------------------------------------------------------------------------------ + +sub invoice_header { + +my ($wb_no) = @_ ; + +if (($coldatedd ne '00') and ($coldatedd ne '')) { + $invoive_date = "$coldatedd-$coldatemm-$coldateccyy"; + } +else + { + $invoive_date = "$now_dd-$now_mm-$now_year"; + } + +&pdf_nl_gap_2 ; +&pdf_xx_large_bold_text (77, $up, 'Commercial Invoice') ; +&pdf_nl_gap_2 ; +&pdf_nl ; +&pdf_medium_bold_text (10, $up, "Invoice # : ") ; +&pdf_large_text (28, $up, $wb_no) ; # Invoice Number +&pdf_medium_bold_text (170, $up, "Date : ") ; +&pdf_medium_text (182, $up, $invoive_date) ; +&pdf_nl_t ; +&pdf_black_line(10,$up,200,$up) ; # horizontal +&pdf_nl_t ; + +} #------------------------------------------------------------------------------- + +sub invoice_out_to_pdf { + +my ($wb_no) = @_ ; + +&pdf_check_value_of_up(40) ; + +&pdf_nl; +$top=$up; +&pdf_black_line(10,$up,200,$up) ; # horizontal +&pdf_nl_s; + +our @colstart = (10,106,200) ; +our @txtstart_1 = (12,108) ; +our @txtstart_2 = (12,197) ; # include align right values + +&pdf_nl_tt ; +&pdf_small_bold_text ($txtstart_1[0], $up, "From :") ; +&pdf_text_block ($txtstart_1[0]+12,$wb{sender},50,4) ; $up = $up + 4 ; +&pdf_small_bold_text ($txtstart_1[1], $up, "To :") ; +&pdf_text_block ($txtstart_1[1]+8,$wb{receiver},50,4) ; + +$get_inline_address = 1 ; +&common_get_addresses ; + +$senderup = $up ; $receiverup = $up ; + +@senderaddresses = split(/
    /,$address_for_email{sender}) ; +foreach (@senderaddresses) { + &pdf_small_text ($txtstart_1[0]+12,$senderup,$_) ; + $senderup-=3; + } + +@receiveraddresses = split(/
    /,$address_for_email{receiver}) ; +foreach (@receiveraddresses) { + &pdf_small_text ($txtstart_1[1]+8,$receiverup,$_) ; + $receiverup-=3; + } + +if ($receiverup < $senderup) { $up = $receiverup ; } else { $up = $senderup ; } + +&pdf_nl_tt; + +unless ($wb{sencontact}) { $wb{sencontact} = $contact{sender} ; } +unless ($wb{senphone}) { $wb{senphone} = $phoneno{sender} ; } +unless ($wb{sencellno}) { $wb{sencellno} = $cellno{sender} ; } + +&pdf_nl_t; +&pdf_small_text ($txtstart_1[0], $up, "Contact : $wb{sencontact}") ; +&pdf_small_text ($txtstart_1[1], $up, "Contact : $wb{reccontact}") ; +&pdf_nl_t; +&pdf_small_text ($txtstart_1[0], $up, "Phone : $wb{senphone} $wb{sencellno}") ; +&pdf_small_text ($txtstart_1[1], $up, "Phone : $wb{recphone} $wb{reccellno}") ; +&pdf_nl; + +if ($airport_code{$wb{originid}}){ $print_originopshub = qq($airport_code{$wb{originid}} - ) ; } +if ($airport_code{$wb{destid}}) { $print_destopshub = qq($airport_code{$wb{destid}} - ) ; } + +&pdf_small_bold_text ($txtstart_1[0], $up, "Origin :") ; +&pdf_medium_bold_text ($txtstart_1[0]+11, $up, "$print_originopshub$wb{'origin'}") ; +&pdf_small_bold_text ($txtstart_1[1], $up, "Destination :") ; +&pdf_medium_bold_text ($txtstart_1[1]+18, $up, "$print_destopshub$wb{'dest'}") ; + +&pdf_nl_s; + +&pdf_black_line(10,$up,200,$up) ; # horizontal + +&vertical_lines_table ; + +$top=$up; + +&pdf_nl_gap_3 ; +&pdf_nl_gap_3 ; +# &pdf_nl_gap_3 ; +# &pdf_nl_gap_3 ; + +&pdf_black_line(10,$up,200,$up) ; # horizontal + +&pdf_black_line ($colstart[0],$top,$colstart[0],$up) ; # vertical +&pdf_black_line ($colstart[2],$top,$colstart[2],$up) ; # vertical + +$top=$up; + +&pdf_nl_gap_1; + +# &pdf_small_bold_text ($txtstart_1[0], $up, "Contents :") ; +&pdf_small_bold_text ($txtstart_1[0], $up, "CONTENTS") ; +&pdf_small_bold_text_right ($txtstart_2[1], $up, "VALUE FOR CUSTOMS") ; + +&pdf_nl_s; +&pdf_black_line(10,$up,200,$up) ; # horizontal +&pdf_nl_gap_1; +&pdf_nl_gap_1; + +foreach (@parcels) { + my ($pcs,$desc,$actkgs,$volkgs) = split(/\|/) ; + # &pdf_small_text ($txtstart_1[0]+15, $up, "$pcs x $desc") ; + &pdf_small_text ($txtstart_1[0], $up, "$desc") ; + last; + } + +$disp_cust_val = sprintf("%.2f",$wb{customsvalue}) ; + +if ($wb{custvalcurr}) { + # &pdf_medium_bold_text (170, $up, "$wb{custvalcurr} $disp_cust_val") ; + &pdf_small_bold_text_right ($txtstart_2[1], $up, "$wb{custvalcurr} $disp_cust_val") ; + } + +&pdf_nl_gap_3 ; +&pdf_nl_gap_3 ; + +&pdf_nl_s; + +&pdf_black_line(10,$up,200,$up) ; # horizontal + +&vertical_lines_table ; + +$top=$up; + +&pdf_nl_gap_3 ; +&pdf_nl_s ; + +&pdf_small_text (86, $up, 'No Financial Transaction Involved') ; +&pdf_nl; +&pdf_small_text (86, $up, 'Value for Customs Purposes Only') ; +&pdf_nl; +&pdf_small_text (86, $up, 'Item Strictly not for resale') ; +&pdf_nl; +&pdf_nl; + +&pdf_black_line(10,$up,200,$up) ; # horizontal + +&pdf_black_line ($colstart[0],$top,$colstart[0],$up) ; # vertical +&pdf_black_line ($colstart[2],$top,$colstart[2],$up) ; # vertical + +$top=$up; + +&pdf_nl_gap_1; + +&pdf_small_bold_text ($txtstart_1[0], $up, "Origin : South Africa") ; + +&pdf_nl_s; + +&pdf_black_line(10,$up,200,$up) ; # horizontal + +&vertical_lines_table ; + + + +} #------------------------------------------------------------------------------------------ + +sub text_block { + +my ($along,$text_block,$tlock_length,$grid,$align_right) = @_ ; + +my $lines = 1; + +my @words_array = split (/ /, $text_block) ; +my $wrapped_line = '' ; +my $block_start_up = $up ; + +foreach my $word(@words_array) { + my $word_length = length($word) ; + my $wrapped_line_length = length($wrapped_line) ; + + if ( ($wrapped_line_length + $word_length) > $tlock_length ) { + &text_block_line($along,$grid,$wrapped_line,$align_right) ; + &pdf_nl_s; + $lines++; + $wrapped_line = '' ; + } + + $wrapped_line .= $word . ' ' ; + } + +&text_block_line($along,$grid,$wrapped_line,$align_right) ; + +&pdf_nl_s; + +return ($lines) ; + +} #---------------------------------------------------------------------------------------------------- + +sub text_block_line { + +my ($along,$grid,$wrapped_line,$align_right) = @_ ; + +if ($align_right) { + &pdf_tiny_text_right ($along,$up,$wrapped_line) ; + } +else + { + &pdf_tiny_text ($along,$up,$wrapped_line) ; + } + +# &pdf_small_text ($along,$up,$wrapped_line) ; + +&check_value_of_up(20,1) ; + +} #------------------------------------------------------------------------------- + +sub vertical_lines_table { + +&pdf_black_line ($colstart[0],$top,$colstart[0],$up) ; # vertical +&pdf_black_line ($colstart[1],$top,$colstart[1],$up) ; # vertical +&pdf_black_line ($colstart[2],$top,$colstart[2],$up) ; # vertical + +} #------------------------------------------------------------------------------------------ + +sub check_value_of_up { + +my ($value,$intxtblock) = @_ ; + +if ($up < $value) { + if ($intxtblock) { &pdf_nl; &pdf_black_line(10,$up,200,$up) ; } + &vertical_lines_table ; + &pdf_initialise_page ; + $up = 290 ; + $across = 1 ; + $top = $up; $lowest_up = $up ; + &pdf_black_line(10,$up,200,$up) ; # horizontal + if ($intxtblock) { &pdf_nl; $start_up = $up ; } + } + +} #---------------------------------------------------------------------------------------------------- + +sub screen2 { + +print < +
    + + + + +
    + +
    + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use dialog ; +use today ; +use common ; +use common_min ; +use db_min ; +use pdf ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/pdf/label_pdf.pl b/scripts/_FromProd/v1.0/pdf/label_pdf.pl new file mode 100644 index 0000000..5ccf67f --- /dev/null +++ b/scripts/_FromProd/v1.0/pdf/label_pdf.pl @@ -0,0 +1,220 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use DBI; +use CGI::Carp qw(fatalsToBrowser); +# use Date::Calc qw(:all); +use POSIX; + +use PDF::API2::Lite; +use constant mm => 25.4/72; +use constant in => 1/72; +use constant pt => 1; + +# use GD::Barcode::UPCE; +# use GD::Barcode::Image; + +#------------------------------------------------------------------------------------------ + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); + +my $waybillno = $ARGV[0] ; + +#------------------------------------------------------------------------------------------ + +print "Content-type: text/html\n\n"; + +&today ; + +&db_load_airports ; +&db_load_waybill($waybillno) ; +&db_load_parcels($waybillno) ; +&build_pdf ; +&screen2 ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub build_pdf { + +my $wbpdfpath = "$pdfpath/label" ; +our $pdfname = 'WB-LABEL-' . $waybillno . '-' . $now_ccyymmdd . '.pdf' ; + +$layout = 'label' ; + +&pdf_delete_previous_pdf($wbpdfpath) ; +&pdf_initialise($wbpdfpath,$pdfname,'Film Freight Waybill Label') ; ; +&waybill_out_to_label_pdf ; +&finish_pdf ; + +} #------------------------------------------------------------------------------------------ + +sub label_line { + +&pdf_black_line (5,$up,95,$up) ; +&pdf_nl_gap_2 ; + +} #------------------------------------------------------------------------------------------ + +sub label_header { + +$top = 5 ; + +# end 107.5mm (label 100mm x 100mm) +&pdf_xx_large_text (5,$up,"Film Freight CC") ; + +# binmode(STDOUT); +# print "Content-Type: image/png\n\n"; +# my $barcode_png = GD::Barcode->new('EAN13', '123456789012')->plot->png; + +# my $image1 = $page->gfx(1) ; +# my $image1_thumb = $barcode_png ; +# $pdf_image1_file = $pdf->image_jpeg($image1_thumb); +# $image1->image($pdf_image1_file, 50/mm, $up/mm, 20/mm, 5/mm); + +&pdf_medium_text (67,$up,"Wb No. : $wb{'waybillno'}") ; +&pdf_nl_gap_2 ; + +} #------------------------------------------------------------------------------- + +sub label_row_2 { + +my $print_sender = uc $wb{'sender'} ; + +# if ($wb{'originopshub'}){ $block_length = 28 ; } else { $block_length = 50 ; } +if ($airport_code{$wb{originid}}){ $block_length = 26 ; } else { $block_length = 34 ; } + +&pdf_xx_large_bold_text (82,$up,$airport_code{$wb{originid}}) ; +&pdf_medium_text (5,$up,"From :") ; +&pdf_text_block (16,$print_sender,$block_length,3) ; + +} #------------------------------------------------------------------------------- + +sub label_row_3 { + +my $print_receiver = uc $wb{'receiver'} ; + +&pdf_medium_text (5,$up,"To :") ; +# &pdf_medium_text (12,$up,$print_receiver) ; +&pdf_text_block (12,$print_receiver,38,3) ; + +$get_inline_address = 1 ; +&common_get_addresses ; +# &pdf_nl ; + +@receiveraddresses = split(/
    /,$address_for_email{'receiver'}) ; +foreach (@receiveraddresses) { + &pdf_medium_text (12,$up,$_) ; + &pdf_nl; + } + +my $print_receiver_contact = '' ; +my $print_receiver_cellno = '' ; +my $print_receiver_cellno_2 = '' ; + +if ($wb{'reccellno'}) { $print_receiver_cellno = ' or ' . $wb{'reccellno'} ; } +if ($wb{'reccellno'}) { $print_receiver_cellno_2 = ' : ' . $wb{'reccellno'} ; } + +if (($wb{'reccontact'}) and ($wb{'recphone'})) { + $print_receiver_contact = $wb{'reccontact'} . " : " . $wb{'recphone'} . $print_receiver_cellno ; + } +elsif ($wb{'recphone'}) { + $print_receiver_contact = $wb{'recphone'} . $print_receiver_cellno ; + } +elsif ($wb{'reccontact'}) { + $print_receiver_contact = $wb{'reccontact'} . $print_receiver_cellno_2 ; + } + +if ($print_receiver_contact) { + &pdf_medium_text (12,$up,$print_receiver_contact) ; + &pdf_nl ; + } + +$up=$up+4 ; +&pdf_xx_large_bold_text (82,$up,$airport_code{$wb{destid}}) ; +&pdf_nl ; + +} #------------------------------------------------------------------------------- + +sub label_row_4 { + +my ($colccyy,$colmm,$coldd) = split(/\-/,$wb{'coldate'}) ; + +$date_to_text = "$coldd-$colmm-$colccyy"; +# $date_to_text = Date_to_Text($colccyy,$colmm,$coldd); +# $date_to_text =~ s/\-/ /g ; +# $date_to_text = substr($date_to_text,4) ; + +&pdf_medium_text (5,$up,"Date : $date_to_text") ; +&pdf_medium_text (70,$up,"Pcs :") ; +&pdf_xx_large_bold_text (80,$up,"$pccnt - $wb{'pcs'}") ; +&pdf_nl ; +&pdf_medium_text (5,$up,"Service : $wb{'service'}") ; +&pdf_nl_gap_2 ; +&pdf_medium_text (5,$up,"Wb No. :") ; +&pdf_xx_large_bold_text (20,$up,$wb{'waybillno'}) ; +&pdf_medium_text (70,$up,"Kgs :") ; +# &pdf_xx_large_bold_text (80,$up,$kgs) ; + +if ($wb{volmass} > $wb{actmass}) { $chgmass = ceil($wb{volmass}); } else { $chgmass = ceil($wb{actmass}); } + +# my $chgmass = sprintf("%.0f",($wb{chgmass})) ; +&pdf_xx_large_bold_text (80,$up,$chgmass) ; + +} #------------------------------------------------------------------------------- + +sub waybill_out_to_label_pdf { + +$label = 1 ; + +foreach (@parcels) { + ($pcs,$desc,$kgs) = split(/\|/) ; + for (1 .. $pcs) { + $pccnt++ ; + $up = 90 ; + &pdf_initialise_page ; + &label_header ; + &label_line ; + &label_row_2 ; + &label_line ; + &label_row_3 ; + &label_line ; + &label_row_4 ; + &pdf_nl_gap_1 ; + } + } + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + +print < +
    + + + + +
    + +
    + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use db ; +use dialog ; +use today ; +use common ; +use pdf ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/pdf/mail_attach.pl b/scripts/_FromProd/v1.0/pdf/mail_attach.pl new file mode 100644 index 0000000..3d603df --- /dev/null +++ b/scripts/_FromProd/v1.0/pdf/mail_attach.pl @@ -0,0 +1,72 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser); + +# https://itvadmin.co.za/cgi-bin/scripts/pdf/mail_attach.pl?1182677259885215755/QT-308-20230424.pdf + +#------------------------------------------------------------------------------------------ + +my @ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +my $file = $ARGV[0] ; +my $attachpath = $mailpath . '/tickets/' . $file ; + +#------------------------------------------------------------------------------------------ + +if (substr($file,-3,3) eq 'pdf') { + print "Content-Type: application/pdf\n\n"; +} elsif (substr($file,-3,3) eq 'doc') { + print "Content-Type: application/msword\n\n"; +} elsif (substr($file,-3,3) eq 'xls') { + print "Content-Type: application/vnd.ms-excel\n\n"; +} elsif (substr($file,-4,4) eq 'docx') { + print "Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document\n\n"; +} elsif (substr($file,-4,4) eq 'xlsx') { + print "Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\n\n"; +} elsif (substr($file,-3,3) eq 'gif') { + print "Content-Type: image/gif\n\n"; +} elsif (substr($file,-3,3) eq 'csv') { + print "Content-Type: text/csv\n\n"; +} elsif (substr($file,-3,3) eq 'txt') { + print "Content-Type: text/plain\n\n"; +} elsif (substr($file,-3,3) eq 'jpg' || substr($file,-4,4) eq 'jpeg') { + print "Content-Type: image/jpeg\n\n"; +} else { + print "Content-type: text/html\n\n"; +} + +open(FILE,"$attachpath") or die("$attachpath : $!"); +binmode(FILE); +while (sysread(FILE,$buffer,1024)) { + print STDOUT $buffer; +} + +# if (substr($file,-3,3) eq 'pdf') { + # print "Content-Type: application/pdf\n\n"; +# } elsif (substr($file,-3,3) eq 'xls' || substr($file,-4,4) eq 'xlsx') { + # print "Content-type: text/html\n\n"; + # use CGI::Application::Plugin::Stream (qw/stream_file/); + # $self->stream_file($attachpath) or $self->error_mode() ; + # exit; +# } else { + # print "Content-type: text/html\n\n"; +# } + +# open(FILE,"$attachpath") or die("$attachpath : $!"); +# binmode(FILE); +# while (sysread(FILE,$buffer,1024)) { + # print STDOUT $buffer; +# } + +# exit ; + +exit ; + +#------------------------------------------------------------------------------------------ + +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/pdf/operators_invoice_pdf.pl b/scripts/_FromProd/v1.0/pdf/operators_invoice_pdf.pl new file mode 100644 index 0000000..d8b7abb --- /dev/null +++ b/scripts/_FromProd/v1.0/pdf/operators_invoice_pdf.pl @@ -0,0 +1,732 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use DBI; +use CGI::Carp qw(fatalsToBrowser); +use Date::Manip; +use Date::Calc qw(:all); + +use PDF::API2::Lite; +use constant mm => 25.4/72; +use constant in => 1/72; +use constant pt => 1; + +#------------------------------------------------------------------------------------------ + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); + +our $start_date = $ARGV[0] ; +our $end_date = $ARGV[1] ; +our $operator_id = $ARGV[2] ; +our $event_id = $ARGV[3] ; + +$operator_id = "" unless $operator_id ; + +exit if not $start_date or not $end_date ; + +#------------------------------------------------------------------------------------------ + +print "Content-type: text/html\n\n"; + +&today ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &prep_pdf ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +&start_pdf ; +&build_pdf ; +&finish_pdf ; +&screen2 ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub prep_pdf { + + &db_min_ro('event_quotes_min','*',"`operator_workings_event` LIKE '%;$operator_id;%'") ; + + foreach (keys %{$db{event_quotes_min}}) { + + # push @abc,"`quote_nr`='$db{event_quotes_min}{$_}{quote_nr}'" ; + push @abc,"`id`='$_'" ; + + } + + my $event_ids = qq~~ ; $event_ids = join(" OR ",@abc) ; $event_ids = qq~($event_ids)~ ; + my $start_sql = qq~~ ; my $end_sql = qq~~ ; my $event_id2 = qq~~ ; + + if ($start_date) { + $start_sql .= qq~ AND ~ if $event_ids ; + $start_sql .= qq~`quote_date`>='$start_date'~ ; + } + + if ($end_date) { + $end_sql .= qq~ AND ~ if $start_sql or $event_ids ; + $end_sql .= qq~`quote_date`<='$end_date'~ ; + } + if ($event_id) { + $event_id .= qq~ AND ~ if $event_ids or $start_sql or $end_sql ; + # $event_id2 .= qq~`quote_nr`='$event_id'~ ; + $event_id2 .= qq~`id`='$event_id'~ ; + } + + &db_min_ro('event_quotes','id,ref,date_to,date_from',"$event_ids$start_sql$end_sql$event_id",'','') ; + + my $payments_exist = 0 ; + + foreach (keys %{$db{event_quotes}}) { + $payments_exist++ ; + } + + unless ($payments_exist) { + print "No Payments have been made!!!" ; + exit ; + } + + &db_min_ro('event_cost_items','*','','','') ; + +} #------------------------------------------------------------------------------------------ + +sub exclusions { + + + +} #------------------------------------------------------------------------------------------ + +sub start_pdf { + + my $qtpdfpath = "$pdfpath/operators_invoices" ; + our $pdfname = "Operators_Invoice-$start_date-$end_date-$operator_id" . '.pdf' ; + + &pdf_delete_previous_pdf($qtpdfpath) ; + &pdf_initialise($qtpdfpath,$pdfname,'ITV Operators Invoice') ; + +} #------------------------------------------------------------------------------------------ + +sub build_pdf { + + &tab_curr_symbols; + &pdf_initialise_page ; + + $up = 292 ; + # "e_pdf_page_header ; + + &pdf_box_block_top(5,205,'#009bc8') ; + + $up = 260 ; + $across = 1 ; + $blue_box = 1 ; + + &pdf_page_header ; + "e_pdf_vars ; + "e_out_to_pdf ; + # "e_pdf_footer ; + + $up = 5 ; + &pdf_box_block_bottom(5,205,'#009bc8') ; + +} #------------------------------------------------------------------------------------------ + +# sub quote_pdf_page_header { + +# $page_num++ ; + +# my $image1 = $page->gfx(1) ; +# my $image1_thumb = "$htmlpath/img/pdf_logo.png"; +# $pdf_image1_file = $pdf->image_png($image1_thumb); +# $image1->image($pdf_image1_file, 7/mm, $up/mm, 90/mm, 29/mm); + +# $up+=18 ; + +# &pdf_nl_gap_3 ; +# &pdf_xx_large_bold_text (156,$up,"QUOTE") ; +# &pdf_nl_gap_1 ; + +# } #------------------------------------------------------------------------------- + + +# sub pdf_small_white_text_bold { + + # my ($along, $up, $text) = @_ ; $small_bold_text_white->translate( $along/mm, $up/mm ); $small_bold_text_white->text( $text ); +# } + +# sub pdf_medium_white_text_bold { + + # my ($along, $up, $text) = @_ ; $medium_bold_text_white->translate( $along/mm, $up/mm ); $medium_bold_text_white->text( $text ); +# } + +# sub pdf_large_white_text_bold { + + # my ($along, $up, $text) = @_ ; $large_bold_text_white->translate( $along/mm, $up/mm ); $large_bold_text_white->text( $text ); +# } + +# sub pdf_grey_text_above_right { + + # my ($along, $up, $text) = @_ ; $grey_text_above_right->translate( $along/mm, $up/mm ); $grey_text_above_right->text( $text ); +# } + +# sub pdf_small_white_text_bold_right { + + # my ($along, $up, $text) = @_ ; $grey_text_above_right->translate( $along/mm, $up/mm ); $grey_text_above_right->text_right( $text ); +# } + +# sub pdf_medium_white_text_bold_right { + + # my ($along, $up, $text) = @_ ; $medium_bold_text_white->translate( $along/mm, $up/mm ); $medium_bold_text_white->text_right( $text ); +# } + +# sub pdf_large_white_text_bold_right { + + # my ($along, $up, $text) = @_ ; $large_bold_text_white->translate( $along/mm, $up/mm ); $large_bold_text_white->text_right( $text ); +# } + +sub quote_out_to_pdf { + + our @cell_width = (15,70,110,132.5,155,177.5,200) ; + + &db_min_ro('users','*',"`id`='$operator_id'",'','') ; + + &pdf_nl_t; + # unless ($db{$table}{$qt_id}{currency} eq 'ZAR') { &pdf_medium_red_bold_text (70, $up, "$db{$table}{$qt_id}{currency} ROE : $db{$table}{$qt_id}{roe}") ; } # hidden for client + # &pdf_medium_bold_text (157, $up, "Nr. :") ; + + &pdf_small_bold_text(172.5, $up, "Date :") ; + my $dttxt = &custom_date_txt("$now_year-$now_mm-$now_dd"); + &pdf_small_bold_text_right (198, $up, $dttxt) ; + + # &pdf_nl; + + # &pdf_small_bold_text(150, $up, "Quote Nr") ; + # &pdf_small_text_right (198, $up, $qt_id) ; + # &pdf_small_bold_text_right (198, $up, $db{$table}{$qt_id}{quote_nr}) ; + + # &pdf_large_bold_text (10, $up, $db{$table}{$qt_id}{ref}) if $db{$table}{$qt_id}{ref} ; + + # &pdf_nl_gap_1; + + &pdf_nl; + + &pdf_nl_t; + &pdf_bar(10,$up,200,$up,'#009bc8','OPERATOR DETAILS',20,80) ; + $up = $up - 5 ; + + &pdf_box_block_top(10,200,'#009bc8') ; # + $up = $up - 5 ; + $top = $up ; + &pdf_thin_box_block_top(15,100,'#009bc8') ; + $top3 = $up ; + $up = $up - 5 ; + &pdf_small_bold_text (16, $up, "Name") ; + my $pos2 = 38 ; + &pdf_small_text ($pos2, $up, "$db{users}{$operator_id}{name}") ; + $up = $up - 3 ; + &pdf_thin_box_block_bottom(15,100,'#009bc8') ; + &pdf_extra_thin_black_line ($pos2-1,$top,$pos2-1,$up,'#009bc8') ; + $up = $up - 5 ; + + &pdf_thin_box_block_top(15,100,'#009bc8') ; + $top = $up ; + $up = $up - 3.25 ; + &pdf_small_bold_text (16, $up, "Username") ; &pdf_small_text ($pos2,$up,"$db{users}{$operator_id}{username}") ; + $up = $up - 1.25 ; + &pdf_extra_thin_black_line (15,$up,100,$up,'#009bc8') ; + $up = $up - 3.25 ; + my $tpe = $db{users}{$operator_id}{user_type} ; my $tpe2 = qq~~ ; + foreach (split("_",$tpe)) { + $tpe2 .= ucfirst $_ ; + $tpe2 .= " " ; + } + &pdf_small_bold_text (16, $up, "User Type") ; &pdf_small_text ($pos2, $up, "$tpe2") ; + $up = $up - 1.25 ; + &pdf_extra_thin_black_line (15,$up,100,$up,'#009bc8') ; + $up = $up - 3.25 ; + + # my $cty = $db{users}{$operator_id}{based_in} ; + # $cty = "Cape Town" if $db{users}{$operator_id}{based_in} eq 'CPT' ; + # $cty = "Johannesburg" if $db{users}{$operator_id}{based_in} eq 'JNB' ; + + # $selected{based_in}{$db{users}{$operator_id}{based_in}} = 'SELECTED' ; + + &db_min_ro('regions','code,name','','','') ; + + # &pdf_small_bold_text (16, $up, "Based In") ; &pdf_small_text ($pos2, $up, "$cty") ; + &pdf_small_bold_text (16, $up, "Based In") ; &pdf_small_text ($pos2, $up, "$db{regions}{$db{users}{$operator_id}{based_in}}{name}") ; + $up = $up - 1.25 ; + &pdf_extra_thin_black_line (15,$up,100,$up,'#009bc8') ; + $up = $up - 3.25 ; + my $act = "Yes" ; + $act = "No" if $db{users}{$operator_id}{inactive} ; + &pdf_small_bold_text (16, $up, "Active") ; &pdf_small_text ($pos2,$up,"$act") ; + $up = $up - 1.25 ; + + &pdf_extra_thin_black_line ($pos2-1,$top,$pos2-1,$up,'#009bc8') ; + &pdf_thin_box_block_bottom(15,100,'#009bc8') ; + $top4 = $up ; + + + $up = $up - 5 ; + $up = $top3 ; + $pos2 = 133 ; + + + &pdf_thin_box_block_top(110,195,'#009bc8') ; + $top = $up ; + $up = $up - 3.25 ; + &pdf_small_bold_text (111, $up, "Phone Nr") ; &pdf_small_text ($pos2, $up, "$db{users}{$operator_id}{phone}") ; + $up = $up - 1.25 ; + &pdf_extra_thin_black_line (110,$up,195,$up,'#009bc8') ; + $up = $up - 3.25 ; + &pdf_small_bold_text (111, $up, "Email") ; &pdf_small_text ($pos2, $up, "$db{users}{$operator_id}{email}") ; + $up = $up - 1.25 ; + &pdf_extra_thin_black_line ($pos2-1,$top,$pos2-1,$up,'#009bc8') ; + &pdf_thin_box_block_bottom(110,195,'#009bc8') ; + $up = $up - 5 ; + # &pdf_thin_box_block_bottom(10,200,'#009bc8') ; + # $up = $up - 5 ; + &pdf_thin_box_block_top(110,195,'#009bc8') ; + $top = $up ; + $up = $up - 3.25 ; + &pdf_small_bold_text (111, $up, "Bank Details") ; &pdf_small_text ($pos2, $up, "$db{users}{$operator_id}{bank}") ; + $up = $up - 1.25 ; + $up = $up - 3.25 ; + &pdf_small_text ($pos2, $up, "$db{users}{$operator_id}{bank_acc_no}") ; + $up = $up - 1.25 ; + &pdf_extra_thin_black_line ($pos2-1,$top,$pos2-1,$up,'#009bc8') ; + &pdf_thin_box_block_bottom(110,195,'#009bc8') ; + + $up = $top4 if $top4 < $up ; + $up -= 5 ; + &pdf_box_block_bottom(10,200,'#009bc8') ; + + $up -= 5 ; + + my @abc = () ; + + &pdf_bar(10,$up,200,$up,'#009bc8','PAYMENTS',20,90) ; + $up = $up - 5 ; + + &pdf_box_block_top(10,200,'#009bc8') ; # + + $top = $up ; + + $up = $up - 5 ; + + &pdf_small_bold_text ($cell_width[0],$up,"Event") ; + &pdf_small_bold_text (0.5*($cell_width[2]+$cell_width[1])-8,$up,"Description") ; + &pdf_small_bold_text (0.5*($cell_width[3]+$cell_width[2])-6,$up,"Amount") ; + &pdf_small_bold_text (0.5*($cell_width[4]+$cell_width[3])-7,$up,"Dates Paid") ; + &pdf_small_bold_text (0.5*($cell_width[5]+$cell_width[4])-9,$up,"Amount Paid") ; + &pdf_small_bold_text (0.5*(200+$cell_width[5])-9,$up,"Outstanding") ; + + # &pdf_small_bold_text ($cell_width[1]+1,$up,"Description") ; + # &pdf_small_bold_text ($cell_width[2]+1,$up,"Amount") ; + # &pdf_small_bold_text ($cell_width[3]+1,$up,"Date Paid") ; + # &pdf_small_bold_text ($cell_width[4]+1,$up,"Amount Paid") ; + # &pdf_small_bold_text ($cell_width[5]+1,$up,"Outstanding") ; + + $up = $up - 3 ; + + &pdf_thin_black_line (10,$up,200,$up,'#009bc8') ; + + my $tot_all_amnts = 0 ; my $tot_all_amnts_paid = 0 ; my $tot_all_oust = 0 ; + + # $up = 48 ; + + foreach my $id (sort keys %{$db{event_quotes}}) { + + next unless $db{event_quotes_min}{$id}{operator_dates_paid} ; + + $up = $up - 5 ; + + &next_page(15) if length($db{event_quotes}{$id}{ref}) <= 37 ; + &next_page(19.5) if length($db{event_quotes}{$id}{ref}) > 37 ; + + # &pdf_small_bold_text ($cell_width[0],$up,"$db{event_quotes}{$db{event_quotes_min}{$id}{quote_nr}}{ref}") ; + + &pdf_small_bold_text ($cell_width[0],$up,"$db{event_quotes}{$id}{ref}") if length($db{event_quotes}{$id}{ref}) <= 37 ; + if (length($db{event_quotes}{$id}{ref}) > 37) { + + my @a = split(" ",$db{event_quotes}{$id}{ref}) ; + my $line2 = qq~~ ; my $line1 = qq~~ ; + foreach (@a) { + $line1 = $line2 ; $line2 .= qq~$_ ~ ; + if (length($line2) > 38 and length($line1) <= 38) { + chop $line1 ; + &pdf_small_bold_text ($cell_width[0],$up,"$line1") ; + $line1 = qq~~ ; $line2 = qq~$_ ~ ; + $up -= 4.5 ; + } + } + + &pdf_small_bold_text ($cell_width[0],$up,"$line2") ; + $up += 4.5 ; + + } + &pdf_small_bold_text ($cell_width[1]+2.5,$up,"Total") ; + + my @a = split(";",$db{event_quotes_min}{$id}{operator_amounts_paid}) ; + my @b = split(";",$db{event_quotes_min}{$id}{amount_workings_event}) ; + my @c = split(";",$db{event_quotes_min}{$id}{operator_workings_event}) ; + my @d = split(";",$db{event_quotes_min}{$id}{description_workings_event}) ; + my @e = split(";",$db{event_quotes_min}{$id}{operator_dates_paid}) ; + + my $cnt = 0 ; my $tot_amnt = 0 ; my %des_tot = () ; my $paid = 0 ; my %amnt_date = () ; my $out_stand = 0 ; + + foreach (@b) { + if ($operator_id eq $c[$cnt]) { + $tot_amnt += $_ ; + $des_tot{$d[$cnt]} += $_ ; + } + $cnt++ ; + } + local $tot_amnt_old = $tot_amnt ; + $tot_all_amnts += $tot_amnt ; + $tot_amnt = &common_commify(sprintf("%.2f",$tot_amnt)) ; + &pdf_small_bold_text_right ($cell_width[3]-2.5,$up,$tot_amnt) ; + + # $top2 = $up ; + $cnt = 0 ; + foreach (@a) { + my @f = split(":",$_) ; + $paid += $f[1] if $f[0] eq $operator_id ; + $amnt_date{$e[$cnt]}{$cnt}{$f[1]} = 1 if $f[0] eq $operator_id ; + $cnt++ ; + } + $out_stand = $tot_amnt_old - $paid ; + + $paid = &common_commify(sprintf("%.2f",$paid)) ; + &pdf_small_bold_text_right ($cell_width[5]-2.5,$up,$paid) ; + $out_stand = &common_commify(sprintf("%.2f",$out_stand)) ; + &pdf_small_bold_text_right ($cell_width[6]-2.5,$up,$out_stand) ; + + $up = $up - 1.5 ; my $cnr_des = 0 ; my $new_date1 = qq~~ ; my $new_date2 = qq~~ ; + + $up -= 5 if length($db{event_quotes}{$id}{ref}) > 37 ; + + foreach (sort {$db{event_cost_items}{$a}{name} cmp $db{event_cost_items}{$b}{name}} keys %des_tot) { + + $up = $up - 3.25 ; + &next_page(15) if $up < 15 ; + unless ($cnr_des) { + $new_date1 = &custom_date_txt(substr($db{event_quotes}{$id}{date_from},0,10)) ; + $new_date2 = &custom_date_txt(substr($db{event_quotes}{$id}{date_to},0,10)) ; + + my $dates = qq~~ ; + + if ($new_date1 eq $new_date2) { + $dates = qq~$new_date2~ ; + } elsif (substr($db{event_quotes}{$id}{date_from},0,4) eq substr($db{event_quotes}{$id}{date_to},0,4) and substr($db{event_quotes}{$id}{date_from},5,2) eq substr($db{event_quotes}{$id}{date_to},5,2)) { + $new_date1 = substr($new_date1,0,2) ; + $dates = qq~$new_date1 to $new_date2~ ; + } elsif (substr($db{event_quotes}{$id}{date_from},0,4) eq substr($db{event_quotes}{$id}{date_to},0,4)) { + $new_date1 = substr($new_date1,0,6) ; + $dates = qq~$new_date1 to $new_date2~ ; + } else { + $dates = qq~$new_date1 to $new_date2~ ; + } + + &pdf_small_text ($cell_width[0],$up,"($dates)") ; + } + $cnr_des++ ; + &pdf_small_text ($cell_width[1]+5,$up,$db{event_cost_items}{$_}{name}) if length($db{event_cost_items}{$_}{name}) <= 20 ; + + if (length($db{event_cost_items}{$_}{name}) > 24) { + + my @b = split(" ",$db{event_cost_items}{$_}{name}) ; + my $lines1 = qq~~ ; my $lines2 = qq~~ ; + foreach (@b) { + $lines1 = $lines2 ; $lines2 .= qq~$_ ~ ; + if (length($lines2) > 26 and length($lines1) <= 26) { + chop $lines1 ; + &pdf_small_text ($cell_width[1]+5,$up,"$lines1") ; + $up -= 4.5 ; + $lines1 = qq~~ ; $lines2 = qq~$_ ~ ; + } + } + &pdf_small_text ($cell_width[1]+5,$up,"$lines2") ; + $up += 4.5 ; + + } + + $des_tot{$_} = &common_commify(sprintf("%.2f",$des_tot{$_})) ; + &pdf_small_text_right ($cell_width[3]-2.5,$up,$des_tot{$_}) ; + $up = $up - 1.25 ; + $up -= 5 if length($db{event_cost_items}{$_}{name}) > 20 ; + } + $out_stand = $tot_amnt_old ; + + foreach my $date (sort keys %amnt_date) { + foreach my $ct (keys %{$amnt_date{$date}}) { + foreach my $amnt (keys %{$amnt_date{$date}{$ct}}) { + $up = $up - 3.25 ; + &next_page(15) if $up < 15 ; + my $date_name = &custom_date_txt($date) ; + &pdf_small_text (0.5*($cell_width[3]+$cell_width[4])-7,$up,$date_name) ; + $tot_all_amnts_paid += $amnt ; + $out_stand -= $amnt ; + $amnt = &common_commify(sprintf("%.2f",$amnt)) ; + &pdf_small_text_right ($cell_width[5]-2.5,$up,$amnt) ; + # $paid += $amnt ; + $out_stand = &common_commify(sprintf("%.2f",$out_stand)) ; + &pdf_small_text_right ($cell_width[6]-2.5,$up,$out_stand) ; + $up = $up - 1.25 ; + + } + } + } + # $up = $up - 3 ; + } + $up -= 1.75 ; + # $top = $up ; + &pdf_thin_black_line (10,$up,200,$up,'#009bc8') ; + + &pdf_extra_thin_black_line ($cell_width[1],$top,$cell_width[1],$up,'#009bc8') ; + &pdf_extra_thin_black_line ($cell_width[2],$top,$cell_width[2],$up,'#009bc8') ; + &pdf_extra_thin_black_line ($cell_width[3],$top,$cell_width[3],$up,'#009bc8') ; + &pdf_extra_thin_black_line ($cell_width[4],$top,$cell_width[4],$up,'#009bc8') ; + &pdf_extra_thin_black_line ($cell_width[5],$top,$cell_width[5],$up,'#009bc8') ; + + &next_page(18) if $up < 18 ; + + $top = $up ; + $up -= 5 ; + $tot_all_oust = $tot_all_amnts - $tot_all_amnts_paid ; + $tot_all_amnts = &common_commify(sprintf("%.2f",$tot_all_amnts)) ; + $tot_all_amnts_paid = &common_commify(sprintf("%.2f",$tot_all_amnts_paid)) ; + $tot_all_oust = &common_commify(sprintf("%.2f",$tot_all_oust)) ; + + &pdf_small_bold_text_right ($cell_width[2]-2.5,$up,"Total") ; + &pdf_small_bold_text_right ($cell_width[3]-2.5,$up,"$tot_all_amnts ") ; + &pdf_small_bold_text_right ($cell_width[5]-2.5,$up,"$tot_all_amnts_paid") ; + &pdf_small_bold_text_right ($cell_width[6]-2.5,$up,"$tot_all_oust") ; + + $up -= 3 ; + + &pdf_thin_black_line (10,$up,200,$up,'#009bc8') ; + + # &pdf_extra_thin_black_line ($cell_width[1],$top,$cell_width[1],$up,'#009bc8') ; + &pdf_extra_thin_black_line ($cell_width[2],$top,$cell_width[2],$up,'#009bc8') ; + &pdf_extra_thin_black_line ($cell_width[3],$top,$cell_width[3],$up,'#009bc8') ; + &pdf_extra_thin_black_line ($cell_width[4],$top,$cell_width[4],$up,'#009bc8') ; + &pdf_extra_thin_black_line ($cell_width[5],$top,$cell_width[5],$up,'#009bc8') ; + + &pdf_box_block_bottom(10,200,'#009bc8') ; # + +} #------------------------------------------------------------------------------------------ + +sub vertical_lines_inner_box { + + &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[5],$top,$blocks[5],$up,'#009bc8') ; # vertical +} #---------------------------------------------------------------------------------------------------- + +sub vertical_lines_inner_box_t { + + &pdf_thin_black_line ($tblocks[2],$top,$tblocks[2],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[3],$top,$tblocks[3],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[4],$top,$tblocks[4],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[5],$top,$tblocks[5],$up,'#009bc8') ; # vertical +} #---------------------------------------------------------------------------------------------------- + +sub quote_pdf_footer { + + +} #------------------------------------------------------------------------------------------ + +sub quote_pdf_vars { + + # our @htxt = (0,0,115,0,146,172,0) ; + # our @boxtxt = (0,12,102,117,142,167) ; + # our @blocks = (0,10,100,115,140,165) ; + + # our @rboxtxt = (0,97,122,147,172,197) ; + # our @boxtxt = (0,12,102,127,152,177) ; + # our @blocks = (0,10,100,125,150,175) ; + + our @rboxtxt = (0,103,116,143,170,197) ; + our @boxtxt = (0,12,106,120,147,174) ; + our @blocks = (0,10,104,118,145,172) ; + + our @tboxrtxt = (0,77,107,137,167,197) ; + our @tboxtxt = (0,12,82,112,142,172) ; + our @tblocks = (0,10,80,110,140,170) ; +} #------------------------------------------------------------------------------- + +sub custom_date_txt { + + my ($date) = @_ ; + + return "Unknown" if not $date; + + my $dt_txt = Date_to_Text(substr($date,0,4),substr($date,5,2),substr($date,8,2)); + + $dt_txt = substr($dt_txt,4) ; + + if (substr($dt_txt,1,1) eq '-') { + local $day = int(substr($dt_txt,0,1)) ; + $dt_txt = substr($dt_txt,1) ; + $day = sprintf("%02d",$day) ; + $dt_txt = qq~$day$dt_txt~ ; + } + + return ($dt_txt) ; + +} #------------------------------------------------------------------------------------------ + +sub check_space_on_page_custom { + + my ($value) = @_ ; + + if ($up < $value) { + &pdf_thin_black_line (10,$top,10,$up) ; + &vertical_lines_table; # draw vertical_lines on prematurely ended table + &pdf_initialise_page ; + $up=282 ; + $top=$up; + &pdf_thin_black_line(10,$up,200,$up) ; + $across = 1 ; + } +} #---------------------------------------------------------------------------------------------------- + +sub get_val { + + my ($val,$cur) = @_ ; + + my $disp_val = $val ; + + if ($val eq '0.00') { + $disp_val = '' ; + + } elsif ($val) { + $disp_val = $cur . ' ' . $val ; + } + # &common_min_debug($val); + + return($disp_val); +} #------------------------------------------------------------------------------------------ + +sub vertical_lines_table { + + unless ($exclude_rate) { + &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up) ; # vertical + &pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up) ; # vertical + } + + unless ($exclude_vat) { + &pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up) ; # vertical + } + + &pdf_thin_black_line ($blocks[5],$top,$blocks[5],$up) ; # vertical + &pdf_thin_black_line ($blocks[6],$top,$blocks[6],$up) ; # vertical + +} #------------------------------------------------------------------------------------------ + +sub next_page { + + my ($up2) = @_ ; + + if ($up < $up2) { + $up = 10 ; + &pdf_extra_thin_black_line ($cell_width[1],$top,$cell_width[1],$up,'#009bc8') ; + &pdf_extra_thin_black_line ($cell_width[2],$top,$cell_width[2],$up,'#009bc8') ; + &pdf_extra_thin_black_line ($cell_width[3],$top,$cell_width[3],$up,'#009bc8') ; + &pdf_extra_thin_black_line ($cell_width[4],$top,$cell_width[4],$up,'#009bc8') ; + &pdf_extra_thin_black_line ($cell_width[5],$top,$cell_width[5],$up,'#009bc8') ; + + &pdf_box_block_bottom(10,200,'#009bc8') ; + $up-=5 ; + &pdf_box_block_bottom(5,205,'#009bc8') ; + &pdf_initialise_page ; + $up = 292 ; + + &pdf_box_block_top(5,205,'#009bc8') ; + $up -= 5 ; + &pdf_box_block_top(10,200,'#009bc8') ; + $top = $up ; + $up -= 5 ; + + } + +} #------------------------------------------------------------------------------------------ + +# sub pdf_extra_thin_black_line { + +# my ($x1,$y1,$x2,$y2,$color) = @_ ; + +# $color = 'black' if not $color ; # $color = '#009bc8' ; + +# unless ($x1) { $x1 = 10 ; } +# unless ($y1) { $y1 = $up ; } +# unless ($x2) { $x2 = 200 ; } +# unless ($y2) { $y2 = $up ; } + +# my $pdf_black_line = $page->gfx(1); +# $pdf_black_line->strokecolor($color); +# $pdf_black_line->linewidth( '0.5' ); +# $pdf_black_line->linedash(); +# $pdf_black_line->move($x1/mm,$y1/mm); +# $pdf_black_line->line($x2/mm,$y2/mm); +# $pdf_black_line->stroke; + +# } #------------------------------------------------------------------------------- + +# sub pdf_thin_box_block_top { + +# my ($st,$en,$color) = @_ ; unless ($color) { $color = 'black' ; } # $color = '#009bc8' ; + +# $box_start{$st} = $up ; + +# &pdf_extra_thin_black_line($st,$up,$en,$up,$color) ; # horizontal + +# } #------------------------------------------------------------------------------- + +# sub pdf_thin_box_block_bottom { + +# my ($st,$en,$color) = @_ ; unless ($color) { $color = 'black' ; } # $color = '#009bc8' ; + +# &pdf_extra_thin_black_line($st,$up,$en,$up,$color) ; # horizontal + +# &pdf_extra_thin_black_line ($st,$box_start{$st},$st,$up,$color) ; # vertical +# &pdf_extra_thin_black_line ($en,$box_start{$st},$en,$up,$color) ; # vertical + +# } #------------------------------------------------------------------------------- + +sub screen2 { + + print < +
    + + + + +
    + +
    + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use db ; +use db_min ; +use dialog ; +use today ; +use common ; +use pdf ; +use tabs ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/pdf/quote_pdf.pl b/scripts/_FromProd/v1.0/pdf/quote_pdf.pl new file mode 100644 index 0000000..7eae15b --- /dev/null +++ b/scripts/_FromProd/v1.0/pdf/quote_pdf.pl @@ -0,0 +1,1289 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use DBI; +use CGI::Carp qw(fatalsToBrowser); +use Date::Manip; +use Date::Calc qw(:all); + +use PDF::API2::Lite; +use constant mm => 25.4/72; +use constant in => 1/72; +use constant pt => 1; + +#------------------------------------------------------------------------------------------ + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); + +my $qt_id = $ARGV[0] ; +my $tab_no = $ARGV[1] ; +my $tab_secs = $ARGV[2] ; + +# my @sections = split(/\|/,$tab_secs); + +my @prefix_arr = qw( cost_desc_ curr_amnt_ qty_cost_ zar_amnt_ ); + +# our $debug = 1 ; +our $label = 1 ; # used in pdf_check_value_of_up + +#------------------------------------------------------------------------------------------ + +print "Content-type: text/html\n\n"; + +&today ; +&pdf_curr_symbols ; + +my $table = 'quotes' ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &prep_pdf ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +&exclusions ; +&start_pdf ; +&build_pdf ; +&finish_pdf ; +&screen2 ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub prep_pdf { + +my @cols = () ; + +&tab_hash ; + +&db_min_ro('quotes_min',"*","`id`='$qt_id'",'','') ; + +&db_min_ro('quote_notes',"*","`id`='2'",'','') ; + +&db_min_ro('quotes_pdf_titles',"*","`quote_id`='$qt_id'",'','') ; + +&db_min_ro($table,"*","`id`='$qt_id'",'','') ; + +my @total_names = ("subtotal_one_time_fee","vat_one_time_fee","total_one_time_fee","subtotal_monthly_recurring_fee","vat_monthly_recurring_fee","total_monthly_recurring_fee","subtotal_annual_fee","vat_annual_fee","total_annual_fee") ; + +foreach (@total_names) { + my @abc = split(/\;/,$db{$table}{$qt_id}{$_}) ; + $db{$table}{$qt_id}{$_} = sprintf("%0.2f",$abc[0]+$abc[1]) ; +} + +our $custid = $db{$table}{$qt_id}{quote_to} ; +&db_min_ro('customers','id,name,physical_address,contact_email,phone,contact_name,vat_nr',"`id`='$custid'",'','') ; +$customer_name{$custid} = $db{customers}{$custid}{name} ; +$customer_address{$custid} = $db{customers}{$custid}{physical_address} ; +$customer_email{$custid} = $db{customers}{$custid}{contact_email} ; +$customer_phone{$custid} = $db{customers}{$custid}{phone} ; +$customer_contact_name{$custid} = $db{customers}{$custid}{contact_name} ; +$customer_vat_nr{$custid} = $db{customers}{$custid}{vat_nr} ; + +&db_min_ro('price_list','id,description','','','') ; +foreach my $id (keys %{$db{price_list}}) { $price_list{$id} = $db{price_list}{$id}{description} ; } + +our $countryid = $db{$table}{$qt_id}{country_shipped} ; +&db_min_ro('countries','*',"`id`='$countryid'",'','') ; +$country{$countryid} = $db{countries}{$countryid}{name} ; + +our $camera_system_id = $db{$table}{$qt_id}{camera_system_id} ; +&db_min_ro('camera_systems','*',"`id`='$camera_system_id'",'','') ; +$camera_system{$camera_system_id} = $db{camera_systems}{$camera_system_id}{name} ; + +# our %terms_and_con = () ; +# &db_min_ro('quote_notes','id, terms_1, terms_2, terms_3, terms_4, terms_5',"",'','') ; +# foreach my $id (keys %{$db{quote_notes}}){ + # for (1 .. 5){ + # $terms_and_con{$_} = $db{quote_notes}{$id}{"terms\_$_"} ; + # } +# } + +} #------------------------------------------------------------------------------------------ + +sub exclusions { + +our $exclude_rate = 0 ; +our $exclude_vat = 0 ; + +if ($db{$table}{$qt_id}{currency} ne 'ZAR') { + $exclude_vat = 1 ; +} + +} #------------------------------------------------------------------------------------------ + +sub start_pdf { + +my $qtpdfpath = "$pdfpath/quotes" ; +our $pdfname = "QT-$qt_id-" . $now_ccyymmdd . '.pdf' ; + +&pdf_delete_previous_pdf($qtpdfpath) ; +&pdf_initialise($qtpdfpath,$pdfname,'ITV Quote') ; + +} #------------------------------------------------------------------------------------------ + +sub build_pdf { + +&tab_curr_symbols; + +&pdf_initialise_page ; + + +$up = 292 ; +# "e_pdf_page_header ; + +&pdf_box_block_top(5,205,'#009bc8') ; + + $up = 260 ; + $across = 1 ; + $blue_box = 1 ; + + &pdf_page_header ; + + "e_pdf_vars ; + + "e_out_to_pdf ; + "e_pdf_footer ; + +$up = 5 ; +&pdf_box_block_bottom(5,205,'#009bc8') ; + +} #------------------------------------------------------------------------------------------ + +sub quote_out_to_pdf { + +my $qty_with_extra = 5.5 ; +my $pos = 37; +my $pos2 = $pos + 1; +my $pos3 = 132; +my $pos4 = $pos3 + 1; + +&pdf_nl_t; +# unless ($db{$table}{$qt_id}{currency} eq 'ZAR') { &pdf_medium_red_bold_text (70, $up, "$db{$table}{$qt_id}{currency} ROE : $db{$table}{$qt_id}{roe}") ; } # hidden for client +# &pdf_medium_bold_text (157, $up, "Nr. :") ; + +&pdf_small_bold_text($table_cols[3], $up, "Date") ; +my $dttxt = &custom_date_txt($db{$table}{$qt_id}{quote_date}); +&pdf_small_bold_text_right ($table_cols[-1]-6, $up, $dttxt) ; + +&pdf_nl; + +&pdf_small_bold_text($table_cols[3], $up, "Quote Nr") ; +# &pdf_small_text_right (198, $up, $qt_id) ; +&pdf_small_bold_text_right ($table_cols[-1]-6, $up, $db{$table}{$qt_id}{quote_nr}) ; + +&pdf_large_bold_text ($table_cols[0],$up,$db{$table}{$qt_id}{ref}) if $db{$table}{$qt_id}{ref} ; + +# &pdf_nl_gap_1; +&pdf_nl; + +&pdf_nl_t; +&pdf_bar($table_cols[0],$up,$table_cols[-1],$up,'#009bc8','QUOTE',20,98) ; +&pdf_nl_gap_1; + +# &pdf_box_block_top($table_cols[0],$up,$table_cols[-1],'#009bc8') ; # start block ------------------------------------- + +&pdf_thin_black_line($table_cols[0],$up,$table_cols[-1],$up,'#009bc8') ; +$box_start{$table_cols[0]} = $up ; + + if ($custid) { + + # my ($quote_year,$quote_month,$quote_day) = split(/\-/,$db{$table}{$qt_id}{quote_date}); + # my ($expiry_year,$expiry_month,$expiry_day) = Add_Delta_Days($quote_year,$quote_month,$quote_day,14); # Add 7 days to quote date + # $expiry_month = sprintf("%02s", $expiry_month) ; + # $expiry_day = sprintf("%02s", $expiry_day) ; + my ($expiry_year,$expiry_month,$expiry_day) = split(/\-/,$db{$table}{$qt_id}{quote_expiry}); + my $expiry_date = &custom_date_txt("$expiry_year-$expiry_month-$expiry_day"); + # my $expiry_date = "$expiry_year-$expiry_month-$expiry_day"; + + &pdf_nl; + &pdf_thin_box_block_top($table_cols[0]+5,$table_cols[1],'#009bc8'); + $top = $up; + &pdf_nl; + &pdf_small_bold_text ($table_cols[0]+6, $up, "Customer") ; + &pdf_small_text ($pos2, $up, $customer_name{$custid}) ; + $up = $up - 3.25; + &pdf_extra_thin_black_line($table_cols[0]+5,$top, $table_cols[0]+5 ,$up,'#009bc8') ; + &pdf_extra_thin_black_line($pos,$top,$pos,$up,'#009bc8') ; + &pdf_extra_thin_black_line($table_cols[1],$top,$table_cols[1] ,$up,'#009bc8') ; + # &pdf_box_block_bottom($table_cols[0],$table_cols[1],'#009bc8',1); + + &pdf_thin_box_block_top($table_cols[2],$table_cols[-1]-5,'#009bc8'); + $top = $up; + $up = $up - 3.25; + &pdf_small_bold_text ($table_cols[2]+1,$up,"Country") ; + &pdf_small_text ($pos4,$up,$country{$countryid}) ; + $up = $up -1.25; + &pdf_thin_box_block_bottom($table_cols[2],$table_cols[-1]-5,'#009bc8'); + + $box_start{$table_cols[2]} = $up ; + + $up -= 3.25; + &pdf_small_bold_text ($table_cols[2]+1,$up,"Tax/VAT Nr") ; + &pdf_small_text ($pos4, $up, $customer_vat_nr{$custid}) ; + $up -= 1.25; + &pdf_thin_box_block_bottom($table_cols[2],$table_cols[-1]-5,'#009bc8'); + &pdf_extra_thin_black_line ($pos3,$top, $pos3 ,$up,'#009bc8') ; + $up -= 4.5; + # &pdf_extra_thin_black_line ($pos,$top, $pos ,$up,'#009bc8') ; + $top = $up; + &pdf_thin_box_block_top($table_cols[2],$table_cols[-1]-5,'#009bc8'); + $up -= 3.25; + &pdf_small_bold_text ($table_cols[2]+1, $up, "Quote Expiry") ; + &pdf_small_text ($pos4, $up, $expiry_date) ; + $up -= 1.25; + &pdf_thin_box_block_bottom($table_cols[2],$table_cols[-1]-5,'#009bc8'); + &pdf_extra_thin_black_line ($pos3,$top, $pos3 ,$up,'#009bc8') ; + + + $bottom = $up ; + + # $up+=1.25 ; + + $up += 18 ; + $top = $up ; + &pdf_thin_box_block_top($table_cols[0]+5,$table_cols[1],'#009bc8'); + $up -= 3.25; + &pdf_small_bold_text ($table_cols[0]+6,$up,"Address") ; + # $customer_address{$custid} = "123" ; + my @waypoint = split(/\,/,$customer_address{$custid}); + # my $top2 = $up; + # my $count = 0; + for my $py (@waypoint){ + $py =~ s/^\s+//g; + &pdf_small_text ($pos2,$up,$py) ; + # $count++; + # &pdf_nl_s; + $up -= 4.5 ; + } + $up += 3.25 if $customer_address{$custid} ; + $up -= 1.25 if !$customer_address{$custid} ; + + # $up = $top2; + # $up-=1.25 ; + # &pdf_thin_box_block_top($table_cols[2],$table_cols[-1]-5,'#009bc8'); + + + &pdf_thin_box_block_bottom($table_cols[0]+5,$table_cols[1],'#009bc8'); + &pdf_extra_thin_black_line ($pos,$top, $pos ,$up,'#009bc8') ; + # &pdf_extra_thin_black_line ($pos3,$top, $pos3 ,$up,'#009bc8') ; + # $up = $up - 4.5; + $up = $bottom - 4.5 ; + &pdf_thin_box_block_top($table_cols[0]+5,$table_cols[1],'#009bc8'); + $top = $up; + &pdf_thin_box_block_top($table_cols[2],$table_cols[-1]-5,'#009bc8'); + $up = $up - 3.25; + # &pdf_small_bold_text (16, $up, "Contact") ; + # &pdf_small_text ($pos2, $up, $customer_contact_name{$custid}) ; + # &pdf_small_bold_text (111, $up, "Reference") ; + # &pdf_small_text ($pos4, $up, $db{$table}{$qt_id}{ref}) ; + # $up = $up -1.25; + # &pdf_box_block_bottom(15,100,'#009bc8'); + # &pdf_box_block_bottom(110,195,'#009bc8'); + # &pdf_box_block_top(110,195,'#009bc8'); + # &pdf_box_block_top(15,100,'#009bc8'); + # $up = $up - 3.25; + # &pdf_small_bold_text (16, $up, "Phone Nr") ; + # &pdf_small_text ($pos2, $up, $customer_phone{$custid}) ; + # &pdf_small_bold_text (111, $up, "PO Nr") ; + # &pdf_small_text ($pos4, $up, $db{$table}{$qt_id}{po_nr}) ; + # $up = $up - 1.25; + # &pdf_box_block_bottom(110,195,'#009bc8'); + # &pdf_box_block_bottom(15,100,'#009bc8'); + # &pdf_thin_black_line ($pos3,$top, $pos3 ,$up,'#009bc8') ; + # &pdf_box_block_top(15,100,'#009bc8'); + # $up = $up - 3.25; + # &pdf_small_bold_text (16, $up, "Email") ; + # &pdf_small_text ($pos2, $up, $customer_email{$custid}) ; + # $up = $up - 1.25; + # &pdf_thin_black_line ($pos,$top, $pos ,$up,'#009bc8') ; + # &pdf_box_block_bottom(15,100,'#009bc8'); + # &pdf_nl; + # &pdf_box_block_top(15,100,'#009bc8'); + # &pdf_box_block_top(110,195,'#009bc8'); + # $top = $up; + # $up = $up - 3.25; + &pdf_small_bold_text ($table_cols[0]+6, $up, "Notes") ; + &pdf_small_bold_text ($table_cols[2]+1, $up, "System") ; + &pdf_small_text ($pos4,$up,$camera_system{$camera_system_id}) ; + $up = $up - 1.25; + &pdf_extra_thin_black_line ($pos3,$top, $pos3 ,$up,'#009bc8') ; + &pdf_thin_box_block_bottom($table_cols[2],$table_cols[-1]-5,'#009bc8'); + $up = $up + 1.25; + + # &pdf_small_text (29, $up, $db{$table}{$qt_id}{notes}) ; + + + if ($db{$table}{$qt_id}{notes}) { + &pdf_text_block ($pos2,$db{$table}{$qt_id}{notes},60,5) ; + } else { + $up -= 1.25; + $up -= 4.5; + } + + # $up = $up - 9; + &pdf_thin_box_block_bottom($table_cols[0]+5,$table_cols[1],'#009bc8'); + &pdf_extra_thin_black_line ($pos,$top, $pos ,$up,'#009bc8') ; + $up = $up - 4.5; + + } + +# $top = $top2; + +&pdf_box_block_bottom($table_cols[0],$table_cols[-1],'#009bc8') ; # end block ------------------------------------- + + + +# &pdf_nl_gap_1 ; +#&pdf_nl_gap_1; + +# $up+=3.25 ; + +$up-= 8 ; +$up+=3.25 ; +&pdf_box_block_top($table_cols[0],$table_cols[-1],'#009bc8') ; # start block ------------------------------------- +$up-=3.25 ; +&pdf_bar($table_cols[0],$up,$table_cols[-1],$up,'#009bc8','Item List',20,97) ; +$up-=3.25 ; + +$top = $up ; + +#&pdf_check_value_of_up(20); +# &pdf_nl_t; + + # &pdf_nl_s; + + $up-=5; + + &pdf_small_bold_text ($table_cols[0]+5,$up,'Description') ; + &pdf_small_bold_text ($table_cols[1]+7.5,$up,'Qty') ; + &pdf_small_bold_text ($table_cols[2]+11,$up,'Amount') ; + &pdf_small_bold_text ($table_cols[3]+11,$up,'VAT') ; + &pdf_small_bold_text ($table_cols[4]+12.5,$up,'Total') ; + + $up -= 3 ; + + $up = $up ; + + &pdf_thin_black_line ($table_cols[0],$up,$table_cols[-1],$up,'#009bc8') ; + # &pdf_nl_gap_1; + $up = $up - 4.5 ; + + $inner_blue_box = 1 ; + + my @prefexes = ("excl","item","qty","usd_amnt","curr_amnt","item_ttl","vat") ; + + foreach (%{$db{quotes_pdf_titles}}){ + $get_pdf_name{$db{quotes_pdf_titles}{$_}{old_name}}{$db{quotes_pdf_titles}{$_}{quote_id}} = $db{quotes_pdf_titles}{$_}{new_name} ; + } + + $up_test = 12 ; my $a = 0 ; my $b = 0 ; my $c = 0 ; + + if ($db{$table}{$qt_id}{subtotal_one_time_fee} ne '0.00' or $db{$table}{$qt_id}{vat_one_time_fee} ne '0.00' or $db{$table}{$qt_id}{total_one_time_fee} ne '0.00'){$a = 1; $up_test += 8 ; } + if ($db{$table}{$qt_id}{subtotal_monthly_recurring_fee} ne '0.00' or $db{$table}{$qt_id}{vat_monthly_recurring_fee} ne '0.00' or $db{$table}{$qt_id}{total_monthly_recurring_fee} ne '0.00' ){$b = 1; $up_test += 8 ; } + if ($db{$table}{$qt_id}{subtotal_annual_fee} ne '0.00' or $db{$table}{$qt_id}{vat_annual_fee} ne '0.00' or $db{$table}{$qt_id}{total_annual_fee} ne '0.00'){$c = 1; $up_test += 8 ; } + if ($a or $b or $c) { $up_test += 8 ; } + + # $blue_box = 0 ; $inner_blue_box = 0 ; + + + foreach (sort keys %sec_cnt) { + # &pdf_check_value_of_up(45); + + if ($up > 280){ $up = 280 ; } + $_k = substr($_,1) ; + my @parts = split(/\-/,$sec_cnt{$_}) ; + + my $sec = '_costing' ; + + my $suffix = "$sec$_k" ; + + foreach my $prefex (@prefexes){ + $col_name = "$prefex" . "$suffix" ; + $cnt = 0 ; + if ($db{quotes_min}{$qt_id}{$col_name}) { + foreach my $col_input (split(/\;/,$db{quotes_min}{$qt_id}{$col_name})){ + $cnt++ ; + $saved_field{$prefex}{$suffix}{$cnt} = $col_input ; + # &common_debug("$aa/$suffix : $cc") ; + } + } + } + + # my $item = $db{$table}{$qt_id}{"item_1$suffix"} ; + my $item = $saved_field{"item"}{$suffix}{1} ; + + next unless $item ; + next if $item eq '0.00' ; + if ($get_pdf_name{$parts[1]}{$qt_id}) { + # &pdf_small_bold_text ($table_cols[0]+5,$up,$get_pdf_name{$parts[1]}{$qt_id}) ; + } else { + # &pdf_small_bold_text ($table_cols[0]+5,$up,$parts[1]) ; + } + + # if ($up < 15) { + # &pdf_check_value_of_up(15) ; + # $new_page = 1 ; + # } + + # &build_cost_form($id,$tab,$parts[0],"$sec$_k"); + # &pdf_nl; + + for (1 .. $parts[0]) { + # if ($db{$table}{$qt_id}{"excl_$_$suffix"}) { next ; } + if ($saved_field{"excl"}{$suffix}{$_}) { next ; } + + if ($up < 12){ + &pdf_check_value_of_up(12) ; + $new_page = 1 ; + $up-=4.5 ; + } + + # if ($up>280){ $up=280; } + # my $price_list_val = $price_list{$db{$table}{$qt_id}{"item_$_$suffix"}} ; + my $disp_item = ($price_list_val) ? $price_list_val : $saved_field{"item"}{$suffix}{$_} ; + @a = split(":", $disp_item) ; + $disp_item = $a[0] ; + # my $price_list_val = $price_list{$saved_field{"item"}{$suffix}{$_}} ; + my $price_list_val = $price_list{$disp_item} ; + $disp_item = $price_list{$disp_item} if $price_list{$disp_item} ; + # my $disp_item = ($price_list_val) ? $price_list_val : $db{$table}{$qt_id}{"item_$_$suffix"} ; + + &pdf_small_bold_text($table_cols[0]+5,$up,"$disp_item") ; + # &pdf_small_text($boxtxt[2]+4.4,$up,$db{$table}{$qt_id}{"qty_$_$suffix"}) ; + + # &pdf_small_text($boxtxt[2],$up,$saved_field{"qty"}{$suffix}{$_}) ; + + &pdf_small_text($table_cols[1]+$qty_with_extra+3.75,$up,$saved_field{"qty"}{$suffix}{$_}) if $saved_field{"qty"}{$suffix}{$_} < 10 and $saved_field{"qty"}{$suffix}{$_} >= 0 ; + &pdf_small_text($table_cols[1]+$qty_with_extra+3.00,$up,$saved_field{"qty"}{$suffix}{$_}) if $saved_field{"qty"}{$suffix}{$_} < 100 and $saved_field{"qty"}{$suffix}{$_} >= 10 ; + &pdf_small_text($table_cols[1]+$qty_with_extra+2.25,$up,$saved_field{"qty"}{$suffix}{$_}) if $saved_field{"qty"}{$suffix}{$_} < 1000 and $saved_field{"qty"}{$suffix}{$_} >= 100 ; + &pdf_small_text($table_cols[1]+$qty_with_extra+1.50,$up,$saved_field{"qty"}{$suffix}{$_}) if $saved_field{"qty"}{$suffix}{$_} < 10000 and $saved_field{"qty"}{$suffix}{$_} >= 1000 ; + &pdf_small_text($table_cols[1]+$qty_with_extra+0.75,$up,$saved_field{"qty"}{$suffix}{$_}) if $saved_field{"qty"}{$suffix}{$_} < 100000 and $saved_field{"qty"}{$suffix}{$_} >= 10000 ; + &pdf_small_text($table_cols[1]+$qty_with_extra+0.00,$up,$saved_field{"qty"}{$suffix}{$_}) if $saved_field{"qty"}{$suffix}{$_} < 1000000 and $saved_field{"qty"}{$suffix}{$_} >= 100000 ; + + # &pdf_small_text ($boxtxt[3]+2,$up,&common_commify($db{$table}{$qt_id}{"curr_amnt_$_$suffix"})) ; + &pdf_small_text($table_cols[2]+2,$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text($table_cols[3]+2,$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text($table_cols[4]+2,$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right($rboxtxt[3],$up,&common_commify($db{$table}{$qt_id}{"curr_amnt_$_$suffix"})) ; + &pdf_small_text_right($table_cols[3]-2,$up,&common_commify(sprintf("%0.2f",$saved_field{"curr_amnt"}{$suffix}{$_}))) ; + + my $vat_amnt = 0 ; + + # if ($db{$table}{$qt_id}{"vat_$_$suffix"}) { + if ($saved_field{"vat"}{$suffix}{$_}) { + # $vat_amnt = sprintf("%0.2f",$db{$table}{$qt_id}{"curr_amnt_$_$suffix"}*0.15) ; + $vat_amnt = &common_commify(sprintf("%0.2f",$saved_field{"curr_amnt"}{$suffix}{$_}*0.15)) ; + # &pdf_small_text ($boxtxt[4]+2,$up,&common_commify($vat_amnt)) ; + # &pdf_small_text($boxtxt[5],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # &pdf_small_text_right($rboxtxt[5],$up,&common_commify($vat_amnt)) ; + # &pdf_small_text_right($rboxtxt[5],$up,"S") ; + &pdf_small_text_right($table_cols[4]-2,$up,$vat_amnt) ; + } else { + &pdf_small_text_right($table_cols[4]-2,$up,"0.00") ; + # &pdf_small_text_right($rboxtxt[5],$up,"Z") ; + # &pdf_small_text_right($rboxtxt[5],$up,"Z") ; + } + + # &pdf_small_text ($boxtxt[5]+2,$up,&common_commify($db{$table}{$qt_id}{"curr_amnt_$_$suffix"}+$vat_amnt)) ; + # &pdf_small_text($boxtxt[4],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + # my $ttl_amnt = sprintf("%0.2f",$db{$table}{$qt_id}{"curr_amnt_$_$suffix"}+$vat_amnt) ; + + $vat_amnt =~ s/\,//g ; + my $ttl_amnt = sprintf("%0.2f",$saved_field{"curr_amnt"}{$suffix}{$_}+$vat_amnt) ; + # $ttl_amnt = $ttl_amnt * $saved_field{"qty"}{$suffix}{$_} ; + $ttl_amnt = &common_commify(sprintf("%0.2f",$ttl_amnt)) ; + &pdf_small_text_right($table_cols[5]-2,$up,&common_commify($ttl_amnt)) ; + $up-=4.5 ; + + } + + # $check_up = 40 ; + # if ($db{$table}{$qt_id}{subtotal_one_time_fee} + # $db{$table}{$qt_id}{subtotal_monthly_recurring_fee} + + # &pdf_check_value_of_up($up_test-5) unless $new_page ; + + # # # # # # # # # # # # # # if ($_k eq '_systems' and $db{$table}{$qt_id}{systems_included}) { + # # # # # # # # # # # # # # my @para = split /^/m, $db{$table}{$qt_id}{systems_included} ; + # # # # # # # # # # # # # # foreach (@para) { + # # # # # # # # # # # # # # &pdf_small_text($boxtxt[1]+5,$up,$_) ; + # # # # # # # # # # # # # # &pdf_nl_s; + # # # # # # # # # # # # # # } + # # # # # # # # # # # # # # # &pdf_text_block ($boxtxt[1]+2,$db{$table}{$qt_id}{systems_included},50,5) ; + # # # # # # # # # # # # # # } + + # # # # # # # # # # # # # # if ($_k eq '_rental' and $db{$table}{$qt_id}{rental_included}) { + # # # # # # # # # # # # # # my @para = split /^/m, $db{$table}{$qt_id}{rental_included} ; + # # # # # # # # # # # # # # foreach (@para) { + # # # # # # # # # # # # # # &pdf_small_text($boxtxt[1]+5,$up,$_) ; + # # # # # # # # # # # # # # &pdf_nl_s; + # # # # # # # # # # # # # # } + # # # # # # # # # # # # # # } + + # # # # # # # # # # # # # # if ($_k eq '_other' and $db{$table}{$qt_id}{other_included}) { + # # # # # # # # # # # # # # my @para = split /^/m, $db{$table}{$qt_id}{other_included} ; + # # # # # # # # # # # # # # foreach (@para) { + # # # # # # # # # # # # # # &pdf_small_text($boxtxt[1]+5,$up,$_) ; + # # # # # # # # # # # # # # &pdf_nl_s; + # # # # # # # # # # # # # # } + # # # # # # # # # # # # # # } + + # &pdf_nl; + # $up-=2 ; + } + $up+=2; + &pdf_thin_black_line ($table_cols[1],$top,$table_cols[1],$up,'#009bc8') ; + &pdf_box_block_bottom($table_cols[0],$table_cols[-1],'#009bc8') ; + + #$up=80; + +#&pdf_box_block_bottom($blocks[1],200,'#009bc8') ; # end block ------------------------------------- + +$inner_blue_box = 0 ; + +# ------------- totals ------------------------------------------------------------------ + +#$top=$up; + +#&pdf_box_block_top($blocks[1],200,'#009bc8') ; # start block ------------------------------------- + + # &pdf_nl_gap_1 ; #&pdf_nl_t; + # # &pdf_small_bold_text ($boxtxt[1]+2,$up,'') ; + # # &pdf_small_bold_text ($boxtxt[2],$up,'') ; + # # &pdf_small_bold_text ($boxtxt[3],$up,'Sub Total') ; + # # &pdf_small_bold_text ($boxtxt[4],$up,'Vat Total') ; + # # &pdf_small_bold_text ($boxtxt[5],$up,'Grand Total') ; + # &pdf_nl_t ; + + #$top = $up; + + # # $up -= 10 ; + # $up -= 10 ; + # $up -= 10 ; + + # Includes: (per each system) +# Air NXT Camera +# 12 months license fee +# Pixellot Analytics +# Live Sreamimg +# 24/7 Live Support +# Dedicated Project Manager +# B2B Fleet Management Platform +# Shipping + + if ($up < 57.5) { + &pdf_check_value_of_up(57.5) ; + &pdf_box_block_top($table_cols[0],$table_cols[-1],'#009bc8') ; + } + + $up -= 4.5 ; &pdf_small_bold_text ($table_cols[0]+05,$up,'Includes: (per each system)') ; + $up -= 4.5 ; &pdf_small_text ($table_cols[0]+6,$up,"Air NXT Camera") ; + $up -= 4.5 ; &pdf_small_text ($table_cols[0]+6,$up,"12 months license fee") ; + $up -= 4.5 ; &pdf_small_text ($table_cols[0]+6,$up,"Pixellot Analytics") ; + $up -= 4.5 ; &pdf_small_text ($table_cols[0]+6,$up,"Live Sreamimg") ; + $up -= 4.5 ; &pdf_small_text ($table_cols[0]+6,$up,"24/7 Live Support") ; + $up -= 4.5 ; &pdf_small_text ($table_cols[0]+6,$up,"Dedicated Project Manager") ; + $up -= 4.5 ; &pdf_small_text ($table_cols[0]+6,$up,"B2B Fleet Management Platform") ; + $up -= 4.5 ; &pdf_small_text ($table_cols[0]+6,$up,"Shipping") ; + $up -= 2 ; + + # if ($a == 1) { $up = $up - 8 ; } + # if ($b == 1) { $up = $up - 8 ; } + # if ($c == 1) { $up = $up - 8 ; } + + # $up -= 8 if $a || $b || $c ; + + &pdf_thin_black_line ($table_cols[2],$top,$table_cols[2],$up,'#009bc8') ; # vertical + &pdf_extra_thin_black_line ($table_cols[3],$top,$table_cols[3],$up,'#009bc8') ; # vertical + &pdf_extra_thin_black_line ($table_cols[4],$top,$table_cols[4],$up,'#009bc8') ; + + $top = $up ; + + if ($a || $b || $c) { + + my $up_min = ($a + $b + $c)*8 + 8 + 10 ; + + if ($up < $up_min) { + &pdf_box_block_bottom($table_cols[0],$table_cols[-1],'#009bc8') ; + &pdf_check_value_of_up($up_min) ; + &pdf_box_block_top($table_cols[0],$table_cols[-1],'#009bc8') ; + $top = $up ; + } else { + &pdf_thin_black_line ($table_cols[0],$up,$table_cols[-1],$up,'#009bc8') ; + } + + $up -= 5 ; + &pdf_small_bold_text ($table_cols[0]+05,$up,'Total Summary') ; + &pdf_small_bold_text ($table_cols[2]+10,$up,'Sub Total') ; + &pdf_small_bold_text ($table_cols[3]+10,$up,'VAT') ; + &pdf_small_bold_text ($table_cols[4]+10,$up,'Total') ; + $up -= 3 ; + } + + if ($a == 1) { + + &pdf_thin_black_line ($table_cols[0],$up,$table_cols[-1],$up,'#009bc8') ; + $up-=5; + # $inner_blue_box = 1 ; + + if ($get_pdf_name{"Hardware"}{$qt_id} and $get_pdf_name{"Hardware"}{$qt_id} ne "Hardware"){ + &pdf_small_text ($table_cols[0]+5,$up,$get_pdf_name{"Hardware"}{$qt_id}) ; + } else { + &pdf_small_text ($table_cols[0]+5,$up,"Hardware and/or other once-off costs") ; + } + + &pdf_small_text($table_cols[2]+2,$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($table_cols[-3]-2,$up,&common_commify($db{$table}{$qt_id}{subtotal_one_time_fee})) ; + + &pdf_small_text($table_cols[3]+2,$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($table_cols[-2]-2,$up,&common_commify($db{$table}{$qt_id}{vat_one_time_fee})) ; + + &pdf_small_text($table_cols[4]+2,$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($table_cols[-1]-2,$up,&common_commify($db{$table}{$qt_id}{total_one_time_fee})) ; + $up-=3; + + } + + if ($b == 1) { + + &pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + $up-=5; + &pdf_small_text ($table_cols[0]+5,$up,'Monthly Recurring Fee for contract period') ; + + &pdf_small_text($table_cols[2]+2,$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($table_cols[-3]-2,$up,&common_commify($db{$table}{$qt_id}{subtotal_monthly_recurring_fee})) ; + + &pdf_small_text($table_cols[3]+2,$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($table_cols[-2]-2,$up,&common_commify($db{$table}{$qt_id}{vat_monthly_recurring_fee})) ; + + &pdf_small_text($table_cols[4]+2,$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($table_cols[-1]-2,$up,&common_commify($db{$table}{$qt_id}{total_monthly_recurring_fee})) ; + $up-=3; + + } + + if ($c == 1) { + + &pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + $up-=5; + &pdf_small_text ($table_cols[0]+5,$up,'Annual Fee') ; + + &pdf_small_text($table_cols[2]+2,$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($table_cols[-3]-2,$up,&common_commify($db{$table}{$qt_id}{subtotal_annual_fee})) ; + + &pdf_small_text($table_cols[3]+2,$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($table_cols[-2]-2,$up,&common_commify($db{$table}{$qt_id}{vat_annual_fee})) ; + + &pdf_small_text($table_cols[4]+2,$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($table_cols[-1]-2,$up,&common_commify($db{$table}{$qt_id}{total_annual_fee})) ; + $up-=3; + + } + + &pdf_thin_black_line ($table_cols[2],$top,$table_cols[2],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($table_cols[3],$top,$table_cols[3],$up,'#009bc8') ; # vertical + &pdf_extra_thin_black_line ($table_cols[4],$top,$table_cols[4],$up,'#009bc8') ; # vertical + + + # our @blocks = (0,10,104,112,152,192) ; + # &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up,'#009bc8') ; + # &pdf_thin_black_line (136,$top,136,$up,'#009bc8') ; + # &pdf_thin_black_line (168,$top,168,$up,'#009bc8') ; # vertical + + #&vertical_lines_inner_box; + + # &pdf_thin_black_line ($tblocks[3],$top,$tblocks[3],$up,'#009bc8') ; # vertical + # &pdf_thin_black_line ($tblocks[4],$top,$tblocks[4],$up,'#009bc8') ; # vertical + # &pdf_thin_black_line ($tblocks[5],$top,$tblocks[5],$up,'#009bc8') ; + + + +&pdf_box_block_bottom($table_cols[0],$table_cols[-1],'#009bc8') ; # end block ------------------------------------- + +$inner_blue_box = 0 ; + + # $up -= 5 ; + + # &pdf_medium_bold_text ($table_cols[0]+5,$up,'Notes:') ; + # $up = $up - 1.5; + # my $counter = 1 ; + # for (1 .. 20) { + # my $note = $db{quote_notes}{2}{"note_$_"}; + # if ($note) { + # if ($counter == 1) { + # $up = $up - 3 ; + # } else { + $up = $up - 1 ; + # } + # $counter++ ; + # &pdf_medium_text ($table_cols[0]+6,$up,"-") ; + # &pdf_text_block ($table_cols[0]+8,"$note",130) ; + # } + # } + +# ------------- totals ------------------------------------------------------------------ + +# ------------- purchase summary ------------------------------------------------------------------ + + + +unless ($db{$table}{$qt_id}{excl_purchase_summary}) { + + &build_purchase_summary_table ; + +} + +# ------------- purchase summary ------------------------------------------------------------------ + + #&pdf_nl_gap_1; + + #&pdf_nl_gap_3; + # $up = $up - 15; + #$&pdf_check_value_of_up(50); + # my $txt = qq~The parties hereby accept and agree to this quote, which incorporates by reference all the terms and conditions set forth in the Interactive Television Africa's Terms and Conditions document, attached hereto as Annexure A and the Service Level Agreement attached hereto as Annexure B (all, collectively with this quote, the "Agreement") effective as of the later of the signature dates below.~; + # # my @excl_notes_qm = split(";", $db{quotes_min}{$qt_id}{"excl_notes"}) ; + # # our $paragraph_incl = 0 ; + # # for (1 .. 20) { + # # # next if $db{$table}{$qt_id}{"excl_$_\_notes"} || $db{$table}{$qt_id}{"note_$_"} eq ''; + # # next if $excl_notes_qm[$_ - 1] || $db{$table}{$qt_id}{"note_$_"} eq ''; + # # $notes_exist = 1 ; + # # } + # my $counter = 1 ; + # # if ($notes_exist) { + # &pdf_medium_bold_text ($blocks[1],$up,'Notes:') ; + # $up = $up - 1; + # for (1 .. 20) { + # # unless ($db{$table}{$qt_id}{"excl_$_\_notes"}) { + # unless ($excl_notes_qm[$_ - 1]) { + # # my $note = $db{$table}{$qt_id}{"note_$_"}; + # my $note = $db{quote_notes}{2}{"note_$_"}; + # if ($note) { + # if ($counter == 1) { + # &pdf_nl; $up = $up - 1 + # } else { + # $up = $up - 2 ; + # } + # $counter++ ; + # # if ($_ == 7) { + # &pdf_medium_text ($blocks[1],$up,"-") ; + # &pdf_text_block (12,"$note",130,3) ; + # # $paragraph_incl = 1 if $txt eq $db{$table}{$qt_id}{"excl_$_\_notes"} ; + # # } else { + # # &pdf_medium_text ($blocks[1],$up,"- $note") ; + # # } + # } + # } + # } + # $up = $up + 4 ; + # # } + + # # my @excl_payment_terms_qm = split(";", $db{quotes_min}{$qt_id}{"excl_payment_terms"}) ; + + # # for (1 .. 20) { + # # # next if $db{$table}{$qt_id}{"excl_$_\_payment_terms"} || $db{$table}{$qt_id}{"payment_term_$_"} eq ''; + # # next if $excl_payment_terms_qm[$_ - 1] || $db{$table}{$qt_id}{"payment_term_$_"} eq ''; + # # $payment_terms_exists = 1 ; + # # } + + # # if ($payment_terms_exists) { + # # &pdf_nl_gap_3; + # # &pdf_check_value_of_up(50); + # # &pdf_medium_bold_text ($blocks[1],$up,'Payment Terms:') ; + # # $up = $up - 1; + # # for (1 .. 20) { + # # # unless ($db{$table}{$qt_id}{"excl_$_\_payment_terms"}) { + # # unless ($excl_payment_terms_qm[$_ - 1]) { + # # my $payment_term = $db{$table}{$qt_id}{"payment_term_$_"}; + # # if (length($payment_term) > 2) { + # # &pdf_nl_gap_1 ; + # # &pdf_medium_text ($blocks[1],$up,"- $payment_term") ; + # # } + # # } + # # } + # # } + + # # my @excl_roes_qm = split(";", $db{quotes_min}{$qt_id}{"excl_roes"}) ; + + # # for (1 .. 20) { + # # # next if $db{$table}{$qt_id}{"excl_$_\_roes"} || $db{$table}{$qt_id}{"roe_$_"} eq ''; + # # next if $excl_roes_qm[$_ - 1] || $db{$table}{$qt_id}{"roe_$_"} eq ''; + # # $roe_exists = 1 ; + # # } + + # # if ($roe_exists) { + # # &pdf_nl_gap_3; + # # &pdf_check_value_of_up(50); + # # &pdf_medium_bold_text ($blocks[1],$up,'ROE:') ; + # # $up = $up - 1; + # # for (1 .. 20) { + # # # unless ($db{$table}{$qt_id}{"excl_$_\_roes"}) { + # # unless ($excl_roes_qm[$_ - 1]) { + # # my $roe = $db{$table}{$qt_id}{"roe_$_"}; + # # if ($roe) { + # # &pdf_nl; + # # $up = $up - 1; + # # &pdf_medium_text ($blocks[1],$up,"- $roe") ; + # # } + # # } + # # } + # # } + + # # my @excl_delivery_times_qm = split(";", $db{quotes_min}{$qt_id}{"excl_delivery_times"}) ; + + # # for (1 .. 20) { + # # # next if $db{$table}{$qt_id}{"excl_$_\_delivery_times"} || $db{$table}{$qt_id}{"delivery_time_$_"} eq ''; + # # next if $excl_delivery_times_qm[$_ - 1] || $db{$table}{$qt_id}{"delivery_time_$_"} eq ''; + # # $delivery_time_exists = 1 ; + # # } + + # # if ($delivery_time_exists) { + # # &pdf_nl_gap_3; + # # &pdf_check_value_of_up(50); + # # &pdf_medium_bold_text ($blocks[1],$up,'Delivery time:') ; + # # $up = $up - 1; + + # # for (1 .. 20) { + # # # unless ($db{$table}{$qt_id}{"excl_$_\_delivery_times"}) { + # # unless ($excl_delivery_times_qm[$_ - 1]) { + # # my $delivery_time = $db{$table}{$qt_id}{"delivery_time_$_"}; + # # if ($delivery_time) { + # # &pdf_nl; $up = $up - 1; + # # &pdf_medium_text ($blocks[1],$up,"- $delivery_time") ; + # # } + # # } + # # } + # # } + + # if ($db{$table}{$qt_id}{"terms"}){ + # &pdf_nl_gap_3; + # &pdf_check_value_of_up(50); + # &pdf_medium_bold_text ($blocks[1],$up,'Terms and Conditions:') ; + # $up = $up - 1; + # &pdf_nl_gap_1; + # &pdf_medium_text ($blocks[1],$up,"-") ; + # my $para = $terms_and_con{$db{$table}{$qt_id}{"terms"}} ; + # &pdf_text_block (12,"$para",130,3) ; + + + # } + +} #------------------------------------------------------------------------------------------ + +sub build_purchase_summary_table { + + if ($up<50) { + &pdf_check_value_of_up(50); + } else { + $up -= 5; + } + + $up = $up - 3.25; + + &pdf_bar(10,$up,200,$up,'#009bc8','Purchase Summary (Incl VAT)',20,90, 'med') ; + $up = $up - 3.25; + + &pdf_box_block_top($tblocks[1],200,'#009bc8') ; # start block --------- + $top = $up ; + + $up = $up - 5 ; + + # &pdf_small_bold_text ($table_cols[0]+5,$up,'Description') ; + # &pdf_small_bold_text ($table_cols[1]+7.5,$up,'Qty') ; + # &pdf_small_bold_text ($table_cols[2]+11,$up,'Amount') ; + # &pdf_small_bold_text ($table_cols[3]+11,$up,'VAT') ; + # &pdf_small_bold_text ($table_cols[4]+12.5,$up,'Total') ; + + # pdf_small_bold_text + # &pdf_bar(10,$up,200,$up,'#009bc8','Description',20, 14, 'med'); + # if ($db{$table}{$qt_id}{period} == 36) { + # &pdf_bar (10,$up,200,$up,'#009bc8','Year 1', 20, 90, 'med') ; + # &pdf_bar (10,$up,200,$up,'#009bc8','Year 2', 20, 120, 'med') ; + # &pdf_bar (10,$up,200,$up,'#009bc8','Year 3', 20, 150, 'med') ; + # &pdf_bar (10,$up,200,$up,'#009bc8','TOTAL', 20, 180, 'med') ; + # } + # elsif ($db{$table}{$qt_id}{period} == 60) { + # &pdf_bar (10,$up,200,$up,'#009bc8','Year 1', 20, 55, 'med') ; + # &pdf_bar (10,$up,200,$up,'#009bc8','Year 2', 20, 80, 'med') ; + # &pdf_bar (10,$up,200,$up,'#009bc8','Year 3', 20, 105, 'med') ; + # &pdf_bar (10,$up,200,$up,'#009bc8','Year 4', 20, 130, 'med') ; + # &pdf_bar (10,$up,200,$up,'#009bc8','Year 5', 20, 155, 'med') ; + # &pdf_bar (10,$up,200,$up,'#009bc8','TOTAL', 20, 180, 'med') ; + # } &pdf_bar(10,$up,200,$up,'#009bc8','Description',20, 14, 'med'); + + &pdf_small_bold_text($table_cols[0]+4,$up,'Description') ; + + if ($db{$table}{$qt_id}{period} == 36) { + + &pdf_small_bold_text(90,$up,'Year 1') ; + &pdf_small_bold_text(120,$up,'Year 2') ; + &pdf_small_bold_text(150,$up,'Year 3') ; + + } elsif ($db{$table}{$qt_id}{period} == 60) { + + &pdf_small_bold_text(55,$up,'Year 1') ; + &pdf_small_bold_text(80,$up,'Year 2') ; + &pdf_small_bold_text(105,$up,'Year 3') ; + &pdf_small_bold_text(130,$up,'Year 4') ; + &pdf_small_bold_text(155,$up,'Year 5') ; + + } + + &pdf_small_bold_text(180,$up,'TOTAL') ; + + # $up = $up - 8; + $up = $up - 3 ; + + &pdf_thin_black_line ($table_cols[0],$up,$table_cols[-1],$up,'#009bc8') ; + + $up-=4.5 ; + + $inner_blue_box = 1 ; + + my $suffix = "_purchase_summary" ; + my @prefexes = ("excl", "item") ; + foreach my $prefix (@prefexes) { + $col_name = "$prefix" . "$suffix" ; + $cnt = 0 ; + if($db{quotes_min}{$qt_id}{$col_name}){ + foreach my $col_input (split(";", $db{quotes_min}{$qt_id}{$col_name})){ + $cnt++ ; + $saved_field{$prefix}{$suffix}{$cnt} = $col_input ; + # &common_debug("$aa/$suffix : $cc") ; + } + } + } + + if ($db{$table}{$qt_id}{period} == 36) { + + foreach (1 .. 3) { + + &pdf_check_value_of_up(15); if ($up>280){ $up=280; } + + if ($saved_field{"excl"}{$suffix}{$_}) { next ; } + + &pdf_small_bold_text ($tboxtxt[1]+2,$up,$saved_field{"item"}{$suffix}{$_}) ; + $box=1; + for my $y_ (1 .. 3) { + $box++; + $ttl{$y_} += $db{$table}{$qt_id}{"year_$y_\_$_$suffix"} ; + &pdf_small_text($tboxtxt[$box],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($tboxrtxt[$box],$up,&common_commify($db{$table}{$qt_id}{"year_$y_\_$_$suffix"})) ; + } + $box++; + $ttl += $db{$table}{$qt_id}{"total_$_$suffix"} ; + &pdf_small_text($tboxtxt[$box],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($tboxrtxt[$box],$up,&common_commify($db{$table}{$qt_id}{"total_$_$suffix"})) ; + # &pdf_nl_gap_1; + $up-=4.5; + + } + + $up+=3; + + &pdf_thin_black_line ($table_cols[0],$up,$table_cols[-1],$up,'#009bc8') ; + + $up-=5; + + &pdf_small_bold_text($tboxtxt[1]+2,$up,'Total') ; + + &pdf_small_bold_text($tboxtxt[2],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_bold_text($tboxtxt[3],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_bold_text($tboxtxt[4],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_bold_text($tboxtxt[5],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + + &pdf_small_bold_text_right($tboxrtxt[2],$up,&common_commify(sprintf("%0.2f",$ttl{1}))) ; + &pdf_small_bold_text_right($tboxrtxt[3],$up,&common_commify(sprintf("%0.2f",$ttl{2}))) ; + &pdf_small_bold_text_right($tboxrtxt[4],$up,&common_commify(sprintf("%0.2f",$ttl{3}))) ; + &pdf_small_bold_text_right($tboxrtxt[5],$up,&common_commify(sprintf("%0.2f",$ttl))) ; + + $up-=3; + + # &pdf_bar (10,$up,200,$up,'#009bc8','Total', 20, 14, 'med') ; + + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt[2], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl{1})), 20, $tboxrtxt[2], 'small_right') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt[3], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl{2})), 20, $tboxrtxt[3], 'small_right') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt[4], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl{3})), 20, $tboxrtxt[4], 'small_right') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt[5], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl)), 20, $tboxrtxt[5], 'small_right') ; + + &pdf_thin_black_line ($tblocks[2],$top,$tblocks[2],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[3],$top,$tblocks[3],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[4],$top,$tblocks[4],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[5],$top,$tblocks[5],$up,'#009bc8') ; # vertical + + } elsif ($db{$table}{$qt_id}{period} == 60) { + + foreach (1 .. 3) { + &pdf_check_value_of_up(15); if ($up>280){ $up=280; } + + if ($saved_field{"excl"}{$suffix}{$_}) { next ; } + + &pdf_small_bold_text ($tboxtxt2[1]+2,$up,$saved_field{"item"}{$suffix}{$_}) ; + $box=1; + for my $y_ (1 .. 5) { + $box++; + $ttl{$y_} += $db{$table}{$qt_id}{"year_$y_\_$_$suffix"} ; + &pdf_small_text($tboxtxt2[$box],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($tboxrtxt2[$box],$up,&common_commify($db{$table}{$qt_id}{"year_$y_\_$_$suffix"})) ; + } + $box++; + $ttl += $db{$table}{$qt_id}{"total_$_$suffix"} ; + &pdf_small_text($tboxtxt2[$box],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_text_right($tboxrtxt2[$box],$up,&common_commify($db{$table}{$qt_id}{"total_$_$suffix"})) ; + # &pdf_nl_gap_1; + $up-=4.5; + } + + $up+=4.5; + + &pdf_thin_black_line ($table_cols[0],$up,$table_cols[-1],$up,'#009bc8') ; + + $up-=5; + + &pdf_small_bold_text($tboxtxt2[1]+2,$up,'Total') ; + + &pdf_small_bold_text($tboxtxt2[2],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_bold_text($tboxtxt2[3],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_bold_text($tboxtxt2[4],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_bold_text($tboxtxt2[5],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_bold_text($tboxtxt2[6],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + &pdf_small_bold_text($tboxtxt2[7],$up,$curr_symb{$db{$table}{$qt_id}{currency}}) ; + + &pdf_small_bold_text_right($tboxrtxt2[2],$up,&common_commify(sprintf("%0.2f",$ttl{1}))) ; + &pdf_small_bold_text_right($tboxrtxt2[3],$up,&common_commify(sprintf("%0.2f",$ttl{2}))) ; + &pdf_small_bold_text_right($tboxrtxt2[4],$up,&common_commify(sprintf("%0.2f",$ttl{3}))) ; + &pdf_small_bold_text_right($tboxrtxt2[5],$up,&common_commify(sprintf("%0.2f",$ttl{4}))) ; + &pdf_small_bold_text_right($tboxrtxt2[6],$up,&common_commify(sprintf("%0.2f",$ttl{5}))) ; + &pdf_small_bold_text_right($tboxrtxt2[7],$up,&common_commify(sprintf("%0.2f",$ttl))) ; + + $up-=3; + + # &pdf_bar (10,$up,200,$up,'#009bc8','Total', 20, 14, 'med') ; + + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt2[2], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl{1})), 20, $tboxrtxt2[2], 'small_right') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt2[3], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl{2})), 20, $tboxrtxt2[3], 'small_right') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt2[4], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl{3})), 20, $tboxrtxt2[4], 'small_right') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt2[5], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl{4})), 20, $tboxrtxt2[5], 'small_right') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt2[6], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl{5})), 20, $tboxrtxt2[6], 'small_right') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', $curr_symb{$db{$table}{$qt_id}{currency}}, 20, $tboxtxt2[7], 'small') ; + # &pdf_bar( 10, $up, 200, $up, '#009bc8', &common_commify(sprintf("%0.2f",$ttl)), 20, $tboxrtxt2[7], 'small_right') ; + + &pdf_thin_black_line ($tblocks2[2],$top,$tblocks2[2],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks2[3],$top,$tblocks2[3],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks2[4],$top,$tblocks2[4],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks2[5],$top,$tblocks2[5],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks2[6],$top,$tblocks2[6],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks2[7],$top,$tblocks2[7],$up,'#009bc8') ; # vertical + } + + &pdf_box_block_bottom($tblocks[1],200,'#009bc8') ; # end block ------------------------------------- + + # $up-=4; + + $inner_blue_box = 0 ; + +} #---------------------------------------------------------------------------------------------------- + +sub vertical_lines_inner_box { + + &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($blocks[5],$top,$blocks[5],$up,'#009bc8') ; # vertical + +} #---------------------------------------------------------------------------------------------------- + +sub vertical_lines_inner_box_t { + + &pdf_thin_black_line ($tblocks[2],$top,$tblocks[2],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[3],$top,$tblocks[3],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[4],$top,$tblocks[4],$up,'#009bc8') ; # vertical + &pdf_thin_black_line ($tblocks[5],$top,$tblocks[5],$up,'#009bc8') ; # vertical + +} #---------------------------------------------------------------------------------------------------- + +sub quote_pdf_footer { + + # &pdf_check_value_of_up(60); + + if ($up < 89) { + &pdf_check_value_of_up(89); + $up = 89 ; + } + + $up -= 4.5 ; + + &pdf_medium_bold_text ($table_cols[0],$up,'Notes:') ; + + $up = $up - 1.5; + + $up -= 3 ; &pdf_small_text ($table_cols[0]+2,$up,"- Payment due on date of order") ; + $up -= 4 ; &pdf_small_text ($table_cols[0]+2,$up,"- Minimum 36x month Contract") ; + $up -= 4 ; &pdf_small_text ($table_cols[0]+2,$up,"- Annual Fees for Year 2 & 3 = R 36,000.00 (Exl VAT) per system per year") ; + $up -= 4 ; &pdf_small_text ($table_cols[0]+2,$up,"- Annual fees due annually in advance") ; + $up -= 4 ; &pdf_small_text ($table_cols[0]+2,$up,"- Annual fees to be reviewed if renewed after 36 months") ; + + $up -= 5 ; + + &pdf_text_block (10,"The parties hereby accept and agree to this quote, which incorporates by reference all the terms and conditions set forth in the AI Sport Africa's Terms and Conditions document.",120) ; + + $up = $up - 6; + + &pdf_medium_bold_text (10, $up, "Name:") ; &pdf_thin_black_line (30,$up,100,$up,'#009bc8') ; #&pdf_tiny_text (25, $up, "________________________________________________") ; + &pdf_medium_bold_text (110, $up, "Date:") ; &pdf_thin_black_line (130,$up,200,$up,'#009bc8') ; + $up = $up - 5; + &pdf_small_text (10, $up, "(Duly Authorised)") ; + $up = $up - 5; + # &pdf_medium_bold_text (10, $up, "Company:") ; &pdf_thin_black_line (30,$up,100,$up,'#009bc8') ; + &pdf_medium_bold_text (110, $up, "Signature:") ; &pdf_thin_black_line (130,$up,200,$up,'#009bc8') ; + $up = $up - 10 ; + &pdf_medium_bold_text (10, $up, "Name:") ; &pdf_thin_black_line (30,$up,100,$up,'#009bc8') ; + &pdf_medium_bold_text (110, $up, "Date:") ; &pdf_thin_black_line (130,$up,200,$up,'#009bc8') ; + $up = $up - 5; + &pdf_small_text (10, $up, "(Duly Authorised on behalf of AI Sport Africa)") ; + + $up = $up - 5; + &pdf_medium_bold_text (110, $up, "Signature:") ; + + &pdf_thin_black_line (130,$up,200,$up,'#009bc8') ; + +} #------------------------------------------------------------------------------------------ + +sub quote_pdf_vars { + + our @table_cols = (10,80,100,135,165,200) ; + + # our @htxt = (0,0,115,0,146,172,0) ; + # our @boxtxt = (0,12,102,117,142,167) ; + # our @blocks = (0,10,100,115,140,165) ; + + # our @rboxtxt = (0,97,122,147,172,197) ; + # our @boxtxt = (0,12,102,127,152,177) ; + # our @blocks = (0,10,100,125,150,175) ; + + + # our @rboxtxt = (0,93,106,148,190,197) ; + # our @boxtxt = (0,12,106,114,154,194) ; + # our @blocks = (0,10,104,112,152,192) ; + + # our @rboxtxt = (0,93,106,151,190,197) ; + # our @boxtxt = (0,12,106,120,157,194) ; + + # our @blocks = (0,10,104,118,155,192) ; + our @blocks = (0,$table_cols[0],$table_cols[1],$table_cols[2],$table_cols[3],$table_cols[4]) ; + + our @tboxrtxt = (0,77,107,137,167,197) ; + our @tboxtxt = (0,12,82,112,142,172) ; + our @tblocks = (0,10,80,110,140,170) ; + + our @tboxrtxt2 = (0,42,67,92,117,142,167,197) ; + our @tboxtxt2 = (0,12,47,72,97,122,147,172) ; + our @tblocks2 = (0,10,45,70,95,120,145,170) ; + +} #------------------------------------------------------------------------------- + +sub custom_date_txt { + + my ($date) = @_ ; + + my $dt_txt = Date_to_Text(substr($date,0,4),substr($date,5,2),substr($date,8,2)); + + $dt_txt = substr($dt_txt,4) ; + + return ($dt_txt) ; + +} #------------------------------------------------------------------------------------------ + +sub check_space_on_page_custom { + + my ($value) = @_ ; + + if ($up < $value) { + &pdf_thin_black_line (10,$top,10,$up) ; + &vertical_lines_table; # draw vertical_lines on prematurely ended table + &pdf_initialise_page ; + $up=282 ; + $top=$up; + &pdf_thin_black_line(10,$up,200,$up) ; + $across = 1 ; + } + +} #---------------------------------------------------------------------------------------------------- + +sub get_val { + + my ($val,$cur) = @_ ; + + my $disp_val = $val ; + + if ($val eq '0.00') { + $disp_val = '' ; + } elsif ($val) { + $disp_val = $cur . ' ' . $val ; + } + + # &common_min_debug($val); + + return($disp_val); + +} #------------------------------------------------------------------------------------------ + +sub vertical_lines_table { + + unless ($exclude_rate) { + &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up) ; # vertical + &pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up) ; # vertical + } + + unless ($exclude_vat) { + &pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up) ; # vertical + } + + &pdf_thin_black_line ($blocks[5],$top,$blocks[5],$up) ; # vertical + &pdf_thin_black_line ($blocks[6],$top,$blocks[6],$up) ; # vertical + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + +print < +
    + + + + +
    + +
    + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use db ; +use db_min ; +use dialog ; +use today ; +use common ; +use pdf ; +use tabs ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/pdf/vat_recon_pdf.pl b/scripts/_FromProd/v1.0/pdf/vat_recon_pdf.pl new file mode 100644 index 0000000..c548324 --- /dev/null +++ b/scripts/_FromProd/v1.0/pdf/vat_recon_pdf.pl @@ -0,0 +1,121 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use DBI; +use CGI::Carp qw(fatalsToBrowser); +# use Date::Calc qw(:all); +use POSIX; + +use PDF::API2::Lite; +use constant mm => 25.4/72; +use constant in => 1/72; +use constant pt => 1; + +print "Content-type: text/html\n\n"; + +&today ; + +#------------------------------------------------------------------------------------------ + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); + +#------------------------------------------------------------------------------------------ + +&build_pdf ; +&screen2 ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub build_pdf { + +my $wbpdfpath = "$pdfpath/recon" ; +our $pdfname = 'VAT-RECON-' . '-' . $now_ccyymmdd . '.pdf' ; + +&pdf_delete_previous_pdf($wbpdfpath) ; +&pdf_initialise($wbpdfpath,$pdfname,'Film Freight Waybill VAT Recon') ; ; +&pdf_initialise_page ; + +$up = 275 ; +$across = 1 ; +&pdf_page_header ; + +&pdf_nl; +&pdf_black_line; +&pdf_nl; + +&waybill_out_to_vat_recon_pdf ; + +&pdf_footer ; + +&finish_pdf ; + +} #------------------------------------------------------------------------------------------ + + +sub waybill_out_to_vat_recon_pdf { + +&pdf_small_bold_text (10, $up, 'Date') ; +&pdf_small_bold_text (30, $up, 'HAWB') ; +&pdf_small_bold_text (45, $up, 'Client') ; +&pdf_small_bold_text (100, $up, 'Customs VAT') ; +&pdf_small_bold_text (130, $up, 'Customs Duty') ; +&pdf_small_bold_text (160, $up, 'Invoice No') ; +&pdf_small_bold_text (185, $up, 'Paid') ; +&pdf_nl_t; +&pdf_dashed_line; + +foreach (@ARGV) { + # print "
    " . $_ ; + &pdf_check_value_of_up(30) ; + &db_load_waybill($_) ; + &pdf_nl; + + my $invno = sprintf("%.0f",($wb{invno})) ; + my $invvalue = &common_commify(sprintf("%.2f",($wb{invvalue}))) ; + my $customsvat = &common_commify(sprintf("%.2f",($wb{customsvat}))) ; + my $customsduty = &common_commify(sprintf("%.2f",($wb{customsduty}))) ; + + &pdf_small_text (10, $up, $wb{capturedate}) ; + &pdf_small_text (30, $up, $wb{waybillno}) ; + &pdf_small_text (45, $up, $wb{client}) ; + &pdf_small_text (100, $up, $customsvat) ; + &pdf_small_text (130, $up, $customsduty) ; + &pdf_small_text (160, $up, $invno) ; + &pdf_small_text (185, $up, $invvalue) ; + } + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + +print < +
    + + + + +
    + +
    + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use db ; +use dialog ; +use today ; +use common ; +use pdf ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/pdf/warranty_pdf.pl b/scripts/_FromProd/v1.0/pdf/warranty_pdf.pl new file mode 100644 index 0000000..d21b58f --- /dev/null +++ b/scripts/_FromProd/v1.0/pdf/warranty_pdf.pl @@ -0,0 +1,599 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use DBI; +use CGI::Carp qw(fatalsToBrowser); +use Date::Manip; +use Date::Calc qw(:all); + +use PDF::API2::Lite; +use constant mm => 25.4/72; +use constant in => 1/72; +use constant pt => 1; + +#------------------------------------------------------------------------------------------ + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); + +my $qt_id = $ARGV[0] ; +my $cam_id = $ARGV[1] ; + +# our $debug = 1 ; +our $label = 1 ; # used in pdf_check_value_of_up + +#------------------------------------------------------------------------------------------ + +print "Content-type: text/html\n\n"; + +&today ; +&pdf_curr_symbols; + +my $table = 'quotes' ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &prep_pdf ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +&exclusions ; +&start_pdf ; +&build_pdf ; +&finish_pdf ; +&screen2 ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub prep_pdf { + +my @cols = () ; + +&tab_hash ; + +&db_min_ro($table,"*","`id`='$qt_id'",'','') ; + +our $custid = $db{$table}{$qt_id}{quote_to} ; +our $quote_nr = $db{$table}{$qt_id}{quote_nr} ; + +&db_min_ro('customers','id,name,physical_address,contact_email,phone,contact_name,vat_nr',"`id`='$custid'",'','') ; +$customer_name{$custid} = $db{customers}{$custid}{name} ; +$customer_address{$custid} = $db{customers}{$custid}{physical_address} ; +$customer_email{$custid} = $db{customers}{$custid}{contact_email} ; +$customer_phone{$custid} = $db{customers}{$custid}{phone} ; +$customer_contact_name{$custid} = $db{customers}{$custid}{contact_name} ; +$customer_vat_nr{$custid} = $db{customers}{$custid}{vat_nr} ; + +&db_min_ro('price_list','id,description','','','') ; +foreach my $id (keys %{$db{price_list}}) { $price_list{$id} = $db{price_list}{$id}{description} ; } + +our $countryid = $db{$table}{$qt_id}{country_shipped} ; +&db_min_ro('countries','*',"`id`='$countryid'",'','') ; +$country{$countryid} = $db{countries}{$countryid}{name} ; + +our $camera_system_id = $db{$table}{$qt_id}{camera_system_id} ; +&db_min_ro('camera_systems','*',"`id`='$camera_system_id'",'','') ; +$camera_system{$camera_system_id} = $db{camera_systems}{$camera_system_id}{name} ; + +&db_min_ro('cameras','*',"`quote_nr`='$quote_nr'",'','') ; + +foreach my $id (keys %{$db{cameras}}) { + $camera_nr{$id} = $db{cameras}{$id}{camera_nr} ; + $serial_nr{$id} = $db{cameras}{$id}{serial_nr} ; + $camera_desc{$id} = $db{cameras}{$id}{quote_cam_desc} ; + $linked_vpu{$id} = $db{cameras}{$id}{quote_linked_vpu} ; + $date_start{$id} = $db{cameras}{$id}{quote_ew_date_from}; + $date_end{$id} = $db{cameras}{$id}{quote_ew_date_to}; + } + +# &db_min_ro('quotes','quote_date, quote_expiry',"`quote_nr`='$quote_nr'",'','') ; + + # + +} #------------------------------------------------------------------------------------------ + +sub exclusions { + +our $exclude_rate = 0 ; +our $exclude_vat = 0 ; + +if ($db{$table}{$qt_id}{currency} ne 'ZAR') { + + $exclude_vat = 1 ; + +} + +} #------------------------------------------------------------------------------------------ + +sub start_pdf { + +my $qtpdfpath = "$pdfpath/warranty" ; +our $pdfname = "EW-$qt_id-" . $now_ccyymmdd . '.pdf' ; + +&pdf_delete_previous_pdf($qtpdfpath) ; +&pdf_initialise($qtpdfpath,$pdfname,'ITV Extended Warranty') ; + +} #------------------------------------------------------------------------------------------ + +sub build_pdf { + +&tab_curr_symbols; +&pdf_initialise_page ; +$up = 292 ; +# &warranty_pdf_page_header ; + +&pdf_box_block_top(5,205,'#009bc8') ; + + $up = 260 ; + $across = 1 ; + $blue_box = 1 ; + &pdf_page_header ; + &warranty_pdf_vars ; + &warranty_out_to_pdf ; + #&warranty_pdf_footer ; +$up = 5 ; +&pdf_box_block_bottom(5,205,'#009bc8') ; +} #------------------------------------------------------------------------------------------ + +# sub warranty_pdf_page_header { + +# $page_num++ ; + +# my $image1 = $page->gfx(1) ; +# my $image1_thumb = "$htmlpath/img/pdf_logo.png"; +# $pdf_image1_file = $pdf->image_png($image1_thumb); +# $image1->image($pdf_image1_file, 7/mm, $up/mm, 90/mm, 29/mm); + +# $up+=18 ; + +# &pdf_nl_gap_3 ; +# &pdf_xx_large_bold_text (156,$up,"QUOTE") ; +# &pdf_nl_gap_1 ; + +# } #------------------------------------------------------------------------------- + +sub warranty_out_to_pdf { + +&pdf_nl_t; +# # unless ($db{$table}{$qt_id}{currency} eq 'ZAR') { &pdf_medium_red_bold_text (70, $up, "$db{$table}{$qt_id}{currency} ROE : $db{$table}{$qt_id}{roe}") ; } # hidden for client +# # &pdf_medium_bold_text (157, $up, "Nr. :") ; +# &pdf_small_bold_text_right (180, $up, "Quote Nr. :") ; +# # &pdf_small_text_right (198, $up, $qt_id) ; +# &pdf_small_text_right (198, $up, $db{$table}{$qt_id}{warranty_nr}) ; +# &pdf_nl; + +#&pdf_small_bold_text_right (180, $up, "Date :") ; +# my $dttxt = &custom_date_txt($db{$table}{$qt_id}{warranty_date}); +#&pdf_small_text_right (198, $up, $dttxt) ; + +# &pdf_large_bold_text (10, $up, $db{$table}{$qt_id}{ref}) if $db{$table}{$qt_id}{ref} ; + +# &pdf_nl_gap_1; +&pdf_nl; +&pdf_nl_t; +# &pdf_bar(10,$up,200,$up,'#009bc8','WARRANTY CERTIFICATE',20,98) ; +# &pdf_large_bold_text(85,$up,'WARRANTY CERTIFICATE') ; +$up = $up - 10; +&pdf_xxx_large_bold_text(53,$up,'WARRANTY CERTIFICATE') ; +&pdf_nl; + + # # start block ------------------------------------- + + # if ($custid) { + + # my ($warranty_year,$warranty_month,$warranty_day) = split(/\-/,$db{$table}{$qt_id}{quote_date}); + # my ($expiry_year,$expiry_month,$expiry_day) = Add_Delta_Days($warranty_year,$warranty_month,$warranty_day,14); # Add 7 days to warranty date + # $expiry_month = sprintf("%02s", $expiry_month) ; + # $expiry_day = sprintf("%02s", $expiry_day) ; + # my $expiry_date = &custom_date_txt("$expiry_year-$expiry_month-$expiry_day"); + # # my $expiry_date = "$expiry_year-$expiry_month-$expiry_day"; + # &pdf_box_block_top(10,200,'#009bc8') ; + # &pdf_nl_gap_1; + # &pdf_small_bold_text (13, $up, "Customer :") ; + # &pdf_small_text (29, $up, $customer_name{$custid}) ; + # &pdf_small_bold_text (113, $up, "Country :") ; + # &pdf_small_text (133, $up, $country{$countryid}) ; + # &pdf_nl; + # &pdf_small_bold_text (13, $up, "Adress :") ; + # &pdf_small_text (29, $up, $customer_address{$custid}) ; + # &pdf_small_bold_text (113, $up, "Tax/VAT Nr :") ; + # &pdf_small_text (133, $up, $customer_vat_nr{$custid}) ; + # &pdf_nl; + # &pdf_nl; + # &pdf_small_bold_text (13, $up, "Contact :") ; + # &pdf_small_text (29, $up, $customer_contact_name{$custid}) ; + # &pdf_small_bold_text (113, $up, "Quote Expiry :") ; + # &pdf_small_text (133, $up, $expiry_date) ; + # &pdf_nl; + # &pdf_small_bold_text (13, $up, "Phone Nr :") ; + # &pdf_small_text (29, $up, $customer_phone{$custid}) ; + # &pdf_nl; + # &pdf_small_bold_text (13, $up, "Email :") ; + # &pdf_small_text (29, $up, $customer_email{$custid}) ; + # &pdf_small_bold_text (113, $up, "Reference :") ; + # &pdf_small_text (133, $up, $db{$table}{$qt_id}{ref}) ; + # &pdf_nl; + # &pdf_small_bold_text (113, $up, "PO Nr :") ; + # &pdf_small_text (133, $up, $db{$table}{$qt_id}{po_nr}) ; + # &pdf_nl; + # &pdf_small_bold_text (13, $up, "Notes :") ; + # # &pdf_small_text (29, $up, $db{$table}{$qt_id}{notes}) ; + # &pdf_text_block (29,$db{$table}{$qt_id}{notes},60,5) ; $up+=2.7; + # &pdf_small_bold_text (113, $up, "System :") ; + # &pdf_small_text (133, $up, $camera_system{$camera_system_id}) ; + # &pdf_nl; + # &pdf_box_block_bottom(10,200,'#009bc8') ; + # } + + + # # end block ------------------------------------- +&pdf_nl_gap_1; +&pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; +$top = $up - 30; +&pdf_thin_black_line ($blocks[1],$top,$blocks[1],$up,'#009bc8') ; +pdf_thin_black_line (200,$top,200,$up,'#009bc8') ; +&vertical_lines_inner_box; +$up = $up - 4; +&pdf_medium_bold_text ($boxtxt[1],$up,'Issued To') ; +&pdf_medium_text ($boxtxt[2],$up, $customer_name{$custid}) ; +&pdf_medium_bold_text ($boxtxt[3],$up,'Invoice Nr') ; +&pdf_medium_text ($boxtxt[3]+30, $up, $db{$table}{$qt_id}{invoice_nr}) ; +$up = $up - 2; +&pdf_thin_black_line ($blocks[2],$up,200,$up,'#009bc8') ; +$up = $up - 4; +&pdf_medium_bold_text ($boxtxt[3],$up,'PO Nr') ; +&pdf_medium_text ($boxtxt[3]+30, $up, $db{$table}{$qt_id}{po_nr}) ; +$up = $up - 2; +&pdf_thin_black_line ($blocks[2],$up,200,$up,'#009bc8') ; +$up = $up - 4; +&pdf_medium_bold_text ($boxtxt[3],$up,'Quote Nr') ; +&pdf_medium_text ($boxtxt[3]+30, $up, $db{$table}{$qt_id}{quote_nr}) ; +$up = $up - 2; +&pdf_thin_black_line ($blocks[2],$up,200,$up,'#009bc8') ; +$up = $up - 4; +&pdf_medium_bold_text ($boxtxt[3],$up,'Ref') ; +&pdf_medium_text ($boxtxt[3]+30, $up, $db{$table}{$qt_id}{ref}) ; +$up = $up - 2; +&pdf_thin_black_line ($blocks[2],$up,200,$up,'#009bc8') ; +$up = $up - 6; +&pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; +&pdf_nl_gap_1; +#&pdf_nl_gap_3;#&pdf_nl; + +#$top = $up - 55; +#&pdf_thin_black_line (10,$top,10,$up,'#009bc8') ; +#&pdf_thin_black_line (200,$top,200,$up,'#009bc8') ; +#&pdf_thin_black_line (10,$up,200,$up,'#009bc8') ; +#&pdf_thin_black_line (10,$top,200,$top,'#009bc8') ; +$top = $up ; + +#&pdf_box_block_top(0,200,'#009bc8') ; # start block ------------------------------------- + +$up = $up - 7.5; + +#my $txt = qq~This certificate serves to extend the existing warranty on the exact same terms and conditions of the initial warranty applicable to the following items as described below and for a period of 36 months from the date of delivery. This extended warranty only covers the repair or replacement of a broken item or part thereof, which shall be at the sole descretion of Interactive Television Africa (Pty) Ltd, or Pixellot Ltd. The extended warranty is limited to the replacement value of part or the item concerned.~; +my $txt = "This certificate serves as a warranty as per the terms and conditions of Interactivce Televisision Africa (Pty) Ltd for a +period of 15 months from the date of delivery. This warranty only covers the repair or replacement of a broken item or +part thereof, which shall be at the sole descretion of Interactive Television Africa (Pty) Ltd, or Pixellot Ltd. The warranty +is limited to the replacement value of part or the item concerned and do not cover any damage caused by lightning. The +warranty shall be void if repairs are not done by an authorized Pixellot technician"; +&pdf_text_block (15, $txt ,130,3) ; + +$up = $up - 2.5; + +# my $txt1 = qq~This certificate does not provide coverage:~; +# &pdf_tiny_text (15,$up,$txt1) ; +# $up = $up - 5; +# my $txt3 = qq~1. for lost parts/items; ~; +# &pdf_tiny_text (15,$up,$txt3) ; +# $up = $up - 5; +# my $txt4 = qq~2. for parts/items which are damaged or destroyed as a result of the fault or negligence of the purchaser or of its employees/agents;~; +# &pdf_tiny_text (15,$up,$txt4) ; +# $up = $up - 5; +# my $txt5 = qq~3. for loss or damage caused by lightning or fire;~; +# &pdf_tiny_text (15,$up,$txt5) ; +# $up = $up - 5; +# my $txt6 = qq~4. for parts/items which are not supplied by Interactive Television Africa (Pty) Ltd;~; +# &pdf_tiny_text (15,$up,$txt6) ; +# $up = $up - 5; +# my $txt7 = qq~5. where re-used or recycled parts/items have been used or attached;~; +# &pdf_tiny_text (15,$up,$txt7) ; +# $up = $up - 5; +# my $txt8 = qq~6. in the event of loss or damage due to faulty installation or negligent tampering;~; +# &pdf_tiny_text (15,$up,$txt8) ; +# $up = $up - 5; +# my $txt9 = qq~7. in the event of loss or damage due to use of non-compliant parts/items on installation~; +# &pdf_tiny_text (15,$up,$txt9) ; +# $up = $up - 5; +# my $txt10 = qq~The extended warranty shall be void if repairs are not done by an authorized Pixellot technician.~; +# &pdf_tiny_text (15,$up,$txt10) ; +# $up = $up - 5; +#&pdf_box_block_bottom($blocks[1],200,'#009bc8') ; # end block ------------------------------------- +#&pdf_nl_gap_3; &pdf_nl_gap_3; +#&pdf_tiny_bold_text (15,$up,'Notes:') ; +#for (1 .. 20) { +# unless ($db{$table}{$qt_id}{"excl_$_\_notes"}) { +# my $note = $db{$table}{$qt_id}{"note_$_"}; +# if ($note) { +# &pdf_nl; +# &pdf_tiny_text (15,$up,"* $note") ; +# } +# } +#} + +&pdf_thin_black_line (200,$top,200,$up,'#009bc8') ; +&pdf_thin_black_line ($blocks[1],$top,$blocks[1],$up,'#009bc8') ; +&pdf_thin_black_line (200,$top,$blocks[1],$top,'#009bc8') ; +&pdf_thin_black_line (200,$up,$blocks[1],$up,'#009bc8') ; + +$up = $up - 5; +$top = $up - 8; +&pdf_box_block_top(0,200,'#009bc8') ; # start block ------------------------------------- +&pdf_thin_black_line ($blocks[1],$top,$blocks[1],$up,'#009bc8') ; +&pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up,'#009bc8') ; +&pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up,'#009bc8') ; +&pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up,'#009bc8') ; +&pdf_thin_black_line (200,$top,200,$up,'#009bc8') ; + $up = $up - 5; + #&pdf_nl_t; + &pdf_medium_bold_text ($boxtxt[1]+4,$up,'Valid From') ; + &pdf_small_text ($boxtxt[2]+22,$up, $date_start{$cam_id}) ; + &pdf_small_text ($boxtxt[4]+22,$up, "$date_end{$cam_id}") ; + &pdf_medium_bold_text ($boxtxt[3]+6,$up,'Valid To') ; +$up = $up - 3; +&pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; +$up = $up - 5; +# &pdf_bar(10,$up,200,$up,'#009bc8','Item List',20,97) ; +&pdf_check_value_of_up(20); +&pdf_box_block_top($blocks[1],200,'#009bc8') ; # start block ------------------------------------- +$top=$up; + &pdf_nl_gap_1; + #&pdf_nl_t; + &pdf_medium_bold_text ($boxtxt[1]+7,$up,'Unit Nr') ; + &pdf_medium_bold_text ($boxtxt[2]+20,$up,'Description') ; + &pdf_medium_bold_text ($boxtxt[3]+9.5,$up,'Qty') ; + &pdf_medium_bold_text ($boxtxt[4]+19,$up,'Serial Number') ; + &pdf_nl_t; + &vertical_lines_inner_box; + &pdf_box_block_bottom($blocks[1],200,'#009bc8') ; # end block ------------------------------------- + #&pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + $up = $up - 3; + #&pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + &pdf_box_block_top($blocks[1],200,'#009bc8') ; # start block ------------------------------------- + $up = $up ; + $inner_blue_box = 1 ; + $top=$up ; + #$up = $up - 5; + # foreach (sort keys %sec_cnt) { + # &pdf_check_value_of_up(15); if ($up>280){ $up=280; } + # $_k = substr($_,1) ; + # my @parts = split(/\-/,$sec_cnt{$_}) ; + + # my $sec = '_costing' ; my $suffix = "$sec$_k" ; + + # unless ($db{$table}{$qt_id}{"item_1$suffix"}) { next ; } + + # # &pdf_small_bold_text ($boxtxt[1],$up,$parts[1]) ; + # # &pdf_nl; + # # + + # for (1 .. $parts[0]) { + # $up = $up - 4; + # if ($db{$table}{$qt_id}{"excl_$_$suffix"}) { next ; } + + # &pdf_check_value_of_up(15); if ($up>280){ $up=280; } + + # my $disp_item = $price_list{$db{$table}{$qt_id}{"item_$_$suffix"}} ? $price_list{$db{$table}{$qt_id}{"item_$_$suffix"}} : $db{$table}{$qt_id}{"item_$_$suffix"} ; + + # &pdf_medium_text($boxtxt[1]+2,$up,'') ; # unit nr + # &pdf_medium_text($boxtxt[2]+2,$up,$disp_item) ; + # &pdf_medium_text($boxtxt[3]+2,$up,$db{$table}{$qt_id}{"qty_$_$suffix"}) ; + # &pdf_medium_text($boxtxt[4],$up,$db{$table}{$qt_id}{"serial_nr_$_$suffix"}) ; + # # &pdf_small_text_right($rboxtxt[4],$up,&common_commify($db{$table}{$qt_id}{"curr_amnt_$_$suffix"})) ; + + # $up = $up - 2; + # &pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + # } + # } + my $count = 0; + foreach (sort keys %serial_nr) { + next unless $cam_id eq $_ or $serial_nr{$cam_id} eq $linked_vpu{$_} ; + &pdf_check_value_of_up(15); if ($up>280){ $up=280; } + $up = $up - 4; + &pdf_small_text($boxtxt[1]+2,$up,$camera_nr{$_}) ; # unit nr + &pdf_small_text($boxtxt[2]+2,$up,$camera_desc{$_}) ; + &pdf_small_text($boxtxt[3]+12,$up,1) ; + &pdf_small_text($boxtxt[4],$up,$serial_nr{$_}) ; + $up = $up - 2; + &pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + $count++; + } + + if($count < 9){ + + while ($count < 9){ + + $up = $up - 6; + &pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + $count++; + + } + + + } + + &vertical_lines_inner_box; + +&pdf_box_block_bottom($blocks[1],200,'#009bc8') ; # end block ------------------------------------- + +$inner_blue_box = 0 ; +#&pdf_nl_gap_1; +#&pdf_nl_gap_3; +&pdf_check_value_of_up(50); + +###OWN CODE _------------------------------------------------------------------------- + +$up = $up - 5; +$top = $up; + #&pdf_nl_t; + &pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; + $up = $up - 9; + &pdf_medium_bold_text ($boxtxt[1]+3.75,$up,'Date Issued') ; &pdf_small_text ($boxtxt[2]+22,$up, $date_start{$cam_id}) ; + &pdf_medium_bold_text ($boxtxt[3]+5,$up,'Signature') ; + +$up = $up - 7; +&pdf_thin_black_line ($blocks[1],$up,200,$up,'#009bc8') ; +&vertical_lines_inner_box; +&pdf_thin_black_line (200,$top,200,$up,'#009bc8') ; +&pdf_thin_black_line (10,$top,10,$up,'#009bc8') ; + +} #------------------------------------------------------------------------------------------ +#&pdf_nl_gap_3; +#&pdf_box_block_top($blocks[1],200,'#009bc8') + +#&vertical_lines_inner_box + +sub vertical_lines_inner_box { + +&pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up,'#009bc8') ; # vertical +&pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up,'#009bc8') ; # vertical +&pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up,'#009bc8') ; # vertical +#&pdf_thin_black_line ($blocks[6],$top,$blocks[6],$up,'#009bc8') ; # vertical + +} #---------------------------------------------------------------------------------------------------- + +sub warranty_pdf_footer { + +&pdf_check_value_of_up(70); +&pdf_nl_gap_3;&pdf_nl_gap_3;&pdf_nl_gap_3; +#&pdf_nl_gap_3;&pdf_nl_gap_3;&pdf_nl_gap_3; + + +&pdf_tiny_bold_text (10, $up, "Name:") ; &pdf_tiny_text (30, $up, "__________________________________________") ; +&pdf_tiny_bold_text (140, $up, "Date:") ; &pdf_tiny_text (155, $up, "__________________________") ; +&pdf_nl; +&pdf_tiny_text (10, $up, "(Duly Authorised)") ; +&pdf_nl_gap_3; +&pdf_tiny_bold_text (10, $up, "Company:") ; &pdf_tiny_text (30, $up, "__________________________________________") ; +&pdf_tiny_bold_text (140, $up, "Signature:") ; &pdf_tiny_text (155, $up, "__________________________") ; +&pdf_nl_gap_2; +&pdf_tiny_bold_text (10, $up, "Name:") ; &pdf_tiny_text (30, $up, "__________________________________________") ; +&pdf_tiny_bold_text (140, $up, "Date:") ; &pdf_tiny_text (155, $up, "__________________________") ; +&pdf_nl; +&pdf_tiny_text (10, $up, "(Duly Authorised on behalf of Interactive Television Africa)") ; +&pdf_nl; +&pdf_nl; +&pdf_tiny_bold_text (140, $up, "Signature:") ; &pdf_tiny_text (155, $up, "__________________________") ; + +} #------------------------------------------------------------------------------------------ + +sub warranty_pdf_vars { + +# our @htxt = (0,0,115,0,146,172,0) ; +# our @boxtxt = (0,12,102,117,142,167) ; +# our @blocks = (0,10,100,115,140,165) ; + +# our @rboxtxt = (0,97,122,147,172,197) ; +# our @boxtxt = (0,12,102,127,152,177) ; +# our @blocks = (0,10,100,125,150,175) ; + +our @rboxtxt = (0,30,103,116,143,170,197) ; +our @boxtxt = (0,12,42,107,137,157,174) ; +our @blocks = (0,10,40,105,135,155,172) ; + +# our @tboxrtxt = (0,77,107,137,167,197) ; +# our @tboxtxt = (0,12,82,112,142,172) ; +# our @tblocks = (0,10,80,110,140,170) ; + +} #------------------------------------------------------------------------------- + +sub custom_date_txt { + +my ($date) = @_ ; +my $dt_txt = Date_to_Text(substr($date,0,4),substr($date,5,2),substr($date,8,2)); +$dt_txt = substr($dt_txt,4) ; +return ($dt_txt) ; + +} #------------------------------------------------------------------------------------------ + +sub check_space_on_page_custom { +my ($value) = @_ ; +if ($up < $value) { + &pdf_thin_black_line (10,$top,10,$up) ; + &vertical_lines_table; # draw vertical_lines on prematurely ended table + &pdf_initialise_page ; + $up=282 ; + $top=$up; + &pdf_thin_black_line(10,$up,200,$up) ; + $across = 1 ; + } + +} #---------------------------------------------------------------------------------------------------- + +sub get_val { + +my ($val,$cur) = @_ ; +my $disp_val = $val ; +if ($val eq '0.00') { + $disp_val = '' ; + } +elsif ($val) { + $disp_val = $cur . ' ' . $val ; + } + +# &common_min_debug($val); + +return($disp_val); + +} #------------------------------------------------------------------------------------------ + +sub vertical_lines_table { + +unless ($exclude_rate) { + &pdf_thin_black_line ($blocks[2],$top,$blocks[2],$up) ; # vertical + &pdf_thin_black_line ($blocks[3],$top,$blocks[3],$up) ; # vertical + } + +unless ($exclude_vat) { + &pdf_thin_black_line ($blocks[4],$top,$blocks[4],$up) ; # vertical + } + +&pdf_thin_black_line ($blocks[5],$top,$blocks[5],$up) ; # vertical +&pdf_thin_black_line ($blocks[6],$top,$blocks[6],$up) ; # vertical + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + +print < +
    + + + + +
    + +
    + + + +ENDOFTEXT +# + +} #------------------------------------------------------------------------------------------ + +use db ; +use db_min ; +use dialog ; +use today ; +use common ; +use pdf ; +use tabs ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/pdf/warranty_report.pl b/scripts/_FromProd/v1.0/pdf/warranty_report.pl new file mode 100644 index 0000000..0114415 --- /dev/null +++ b/scripts/_FromProd/v1.0/pdf/warranty_report.pl @@ -0,0 +1,290 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our $srchscr = 1 ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + if ($iaction eq ''){ &report_screen ; } + &common_min_action; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub report_ifields { + +&load_search_vars ; + +# if ($i{camera_id}) { + # push @report_sql, "(`id`='$i{camera_id}')" ; + # push @report_results, "camera = $camera_name{$i{camera_id}}" ; + # $xlsreportname .= '-' . $i{camera_id} ; + # # our $acc_id_sql_where = "`camera_id`='$i{camera_id}'" + # } + +# if ($i{camera_system_id}) { + # push @report_sql, "(`camera_system_id`='$i{camera_system_id}')" ; + # push @report_results, "camera_system = $camera_system{$i{camera_id}}" ; + # $xlsreportname .= '-' . $i{camera_system_id} ; + # } + +if ($i{camera_system_id} and $i{camera_system_id} ne 'main' and $i{camera_system_id} ne 'other' and $i{camera_system_id} ne 'all') { + push @report_sql, "(`camera_system_id`='$i{camera_system_id}')" ; + push @report_results, "camera_system = $camera_system{$i{camera_system_id}}" ; + $xlsreportname .= '-' . $i{camera_id} ; + # our $acc_id_sql_where = "`camera_id`='$i{camera_id}'" +} elsif ($i{camera_system_id} eq 'main' or $i{camera_system_id} eq 'other' or $i{camera_system_id} eq 'all') { + push @report_results, "camera_system = $i{camera_system_id}" ; +} + +if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { $error = qq(CAMERAS FROM ($i{date_from}) > CAMERAS TO ($i{date_to})); &report_screen; } + } + +if ($i{date_from}) { + # push @report_sql, "(`date_active` >= '$i{date_from}')" ; + # push @report_results, "date_active >= $i{date_from}" ; + push @report_sql, "(`date_time` >= '$i{date_from}')" ; + push @report_results, "date_time >= $i{date_from}" ; + } + +if ($i{date_to}) { + # push @report_sql, "(`date_active` <= '$i{date_to}')" ; + # push @report_results, "date_active <= $i{date_to}" ; + push @report_sql, "(`date_time` <= '$i{date_to}')" ; + push @report_results, "date_time <= $i{date_to}" ; + } + +if ($i{client_id}) { + # push @report_sql, "(`client_id` = '$i{client_id}')" ; + push @report_results, "Client = $client{$i{client_id}}" ; + } + +$report_results_msg = uc join(', ', @report_results) ; + +unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); &report_screen; } else { $isaved = qq(SELECT WHERE $report_results_msg) ; } + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + # my $cameras_sql_where = "`id`='$i{camera_id}'" ; + # &db_min_ro('cameras','id,camera_nr',$cameras_sql_where,'','') ; + # foreach my $id (keys %{$db{cameras}}) { $camera_name{$id} = $db{cameras}{$id}{camera_nr} ; } + + my $camera_systems_sql_where = "`id`='$i{camera_system_id}'" if $i{camera_system_id} ; + &db_min_ro('camera_systems','id,name',$camera_systems_sql_where,'','') ; + foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + + # my $price_list_sql_where = " AND `id`='$i{camera_system_id}'" if $i{camera_system_id} ; + # &db_min_ro('price_list','id,description',"`excl`<>'1' AND `type`='systems'$price_list_sql_where",'','') ; + # foreach my $id (keys %{$db{price_list}}) { $camera_system{$id} = $db{price_list}{$id}{name} ; } + + # my $customers_sql_where = "`id`='$i{client_id}'" if $i{client_id} ; + # &db_min_ro('customers','*',$customers_sql_where,'','') ; + # foreach my $id (keys %{$db{customers}}) { $client{$id} = $db{customers}{$id}{name} ; } + + if ($i{client_id}) { + my $customers_sql_where = "`id`='$i{client_id}'" ; + &db_min_ro('customers','*',$customers_sql_where,'','') ; + foreach my $id (keys %{$db{customers}}) { $client{$id} = $db{customers}{$id}{name} ; } + } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +my $srch_where_sql = join(' AND ', @report_sql) ; + +my $add_sql_where = '' ; + +# our @sql_col_display = ("id","camera_nr","camera_serial_nr","date_received","client_id","ref_nr","ref","date_delivered","extended_warranty") ; +our @sql_col_display = ("camera_nr","camera_system_id","camera_serial_nr","vpu_serial_nr","date_received","client_id","ref_nr","ref","date_delivered","extended_warranty") ; + +&report_xls_export_header("Extended_Warranty_Report$xlsreportname",'warrantyreport') ; + +&load_list_vars("$srch_where_sql$add_sql_where") ; + +foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) { + + next unless $db{$table}{$id}{quote_ew_date_from} or $db{$table}{$id}{quote_ew_date_to} ; + + next if (&common_camera_system_filter($table,$id)) ; + + if ($i{client_id}) { + next unless $client{$i{client_id}} eq $quote_customer{$id} ; + } + + $print_tbody .= qq~~ ; + + $xlscol=0; + + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$table}{$id}{$_} ; + my $align = '' ; + + my $center = qq~ class="dt-center"~ ; + + if ($_ eq 'date_received') { $align = $center ; } + if ($_ eq 'date_delivered') { $val = $db{$table}{$id}{quote_delivery_date} ; $align = $center ; } + if ($_ eq 'client_id') { $val = $quote_customer{$id} ; } + if ($_ eq 'ref_nr') { $val = $db{$table}{$id}{quote_nr} ; $align = $center ; } + # if ($_ eq 'ref') { $val = $db{$table}{$id}{quote_ref} ? "$db{$table}{$id}{quote_ref}" : $quote_ref{$id} ; } + if ($_ eq 'ref') { $val = $db{$table}{$id}{quote_ref} ? $db{$table}{$id}{quote_ref} : $quote_ref{$id} ; } + if ($_ eq 'camera_system_id') { $val = $camera_system{$val} ; } + if ($_ eq 'camera_serial_nr') { $val = $db{$table}{$id}{serial_nr} ; } + + if ($_ eq 'extended_warranty') { + $val = $db{$table}{$id}{quote_ew_date_from} if $db{$table}{$id}{quote_ew_date_from} ; + $val .= "/$db{$table}{$id}{quote_ew_date_to}" if $db{$table}{$id}{quote_ew_date_to} ; + $align = $center ; + } + + # if ($_ eq 'vpu_serial_nr') { $val = &common_check_for_linked_vpu($db{$table}{$id}{camera_nr},$quote_nr{$id},$id,'SN') ; } + if ($_ eq 'vpu_serial_nr') { $val = $linked_sn{$db{$table}{$id}{serial_nr}} ; } + + &report_xls_export_process_cell('','',$val) ; # ------------------------------------------------------------------------- HTML AFTER + $xlscol++; + + $val = &common_camera_links($table,$id,$val) if $_ eq 'camera_nr' or $_ eq 'ref_nr' ; + + $print_tbody .= qq~$val~ ; + } + + $print_tbody .= qq~~ ; + $xlsrow++ ; + } + +&report_xls_export_footer('L',15,'warrantyreport') ; + +$fnsortcol = 3 ; +$fnsortorder = 'asc' ; + +$print_more_boxes .= qq~


    ~ ; + +&common_min_extra_crumb("$lcpage-report","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub set_tick { + +my ($color,$tooltip) = @_ ; + +$tick{green} = qq~2~ ; +$tick{orange} = qq~1~ ; +$tick{red} = qq~0~ ; + +return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub load_list_vars { + +my ($where) = @_ ; + +&db_min_ro('camera_systems','id,name','','','') ; +foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + +&db_min_ro('customers','id,name','','','') ; +foreach my $id (keys %{$db{customers}}) { $customer{$id} = $db{customers}{$id}{name} ; } + +# &common_load_quote_vars('>0'); +&common_load_quote_vars("cameras.quote_nr>0 AND cameras.quote_nr=quotes.quote_nr"); + +&db_min_ro($table,'*',$where,'','') ; + +# foreach my $id (keys %{$db{$table}}) { + # $cam_nr{$id} = $db{$table}{$id}{camera_nr} ; + # $serial_nr{$id} = $db{$table}{$id}{serial_nr} ; +# } + +} #------------------------------------------------------------------------------------------ + +sub thead { + +&common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'list' ; +our $lcpage = 'extended' ; + +&common_page_name ; + +our $table = 'cameras' ; +$page_title = 'Extended Warranty' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + +our $lcol = 3 ; +our $fcol = 5 ; + +$print_box_content_rows .= &common_min_forms_start('report') ; + +&common_camera_opts ; +&common_min_select_opts('camera_system_id','camera_systems','code',$i{camera_system_id},'') ; +&common_min_select_opts('client_id','customers','name',$i{client_id},'') ; + +$print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-01-01") ; +$print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$now_dd") ; +$print_box_content_rows .= &common_min_form_select('camera_system_id','') ; +$print_box_content_rows .= &common_min_form_select('client_id','') ; +$print_box_content_rows .= &common_min_forms_end('','','report') ; + +&common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +use common ; +use report ; +use xlsxcreator ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/pocs.pl b/scripts/_FromProd/v1.0/pocs.pl new file mode 100644 index 0000000..c1a33c1 --- /dev/null +++ b/scripts/_FromProd/v1.0/pocs.pl @@ -0,0 +1,316 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + + my $exists = '' ; + + $i{name} = &common_fix_str($i{name}) ; + + &db_min_ro($table,'*',"name='$i{name}'",'name','') ; + + foreach my $id (keys %{$db{$table}}) { if (lc $db{$table}{$id}{name} eq lc $i{name}) { $exists = 1 ; } } + + if ($exists) { + $alert = &common_min_alert('warning',"POC NAME ALREADY EXISTS!",'ok') ; + %col_name = () ; + &common_min_add_screen ; + &common_min_screen1 ; + } + +# REMOVE LATER ----------------- + + &db_min_ro('regions','id,code',"id='$i{region_id}'",'','') if $i{region_id} ; + + $i{region_code} = $db{regions}{$i{region_id}}{code} if $i{region_id} ; + +# REMOVE LATER ----------------- + +} #------------------------------------------------------------------------------------------ + +sub insert { + + &add_db_fields ; + + $i{id} = &db_min_get_max($table,'id') ; + + $i{contact_nr} = &process_number($i{contact_nr}) ; + + &db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + unless ($i{id}) { $error = qq(NO ID) ; return ; } + + &edit_db_fields ; + + $i{contact_nr} = &process_number($i{contact_nr}) ; + + &db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub process_number { + + my ($number) = @_ ; + $number =~ s/ //g ; + $number =~ s/\+//g ; + return $number ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + our %poc_is_used = () ; + + &db_min_ro('event_quotes',"id,poc_id","`poc_id` <> '0'",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + $poc_is_used{aisa}{$db{event_quotes}{$_id}{poc_id}} .= qq~$_id;~ ; + } + + &db_switch_conn('sss') ; + + &db_min_ro('event_quotes',"id,poc_id","`poc_id` <> '0'",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + $poc_is_used{sss}{$db{event_quotes}{$_id}{poc_id}} .= qq~$_id;~ ; + } + + &db_switch_conn('aisa') ; + + &db_min_ro($table,'*','','','') ; + + foreach my $id (keys %{$db{$table}}) { + + my $edit_butt = qq~ ~ ; + my $del_butt = qq~ ~ ; + + if ($glod_user_level >= 3) { + $edit_butt = qq~ ~ ; + } + + if ($glod_user_level >= 3) { + $del_butt = qq~ ~ ; + } + + + if (($poc_is_used{aisa}{$id} || $poc_is_used{sss}{$id}) && $db{$table}{$id}{name} && $db{$table}{$id}{contact_nr}) { + $edit_butt = qq~~ ; + } + + if ($poc_is_used{aisa}{$id} || $poc_is_used{sss}{$id}) { + # $edit_butt = qq~ ~ ; + $del_butt = qq~ ~ ; + + if ($poc_is_used{aisa}{$id}) { + my $row_cnt = 1 ; my $flag_cnt = 0 ; + foreach (split(/\;/,$poc_is_used{aisa}{$id})) { + next unless $_ ; + $flag_cnt++ ; + if (($flag_cnt == 20 && $row_cnt == 1 && $edit_butt) || ($flag_cnt == 22 && $row_cnt == 1 && !$edit_butt) || ($flag_cnt == 23 && $row_cnt > 1 && $edit_butt) || ($flag_cnt == 23 && $row_cnt > 1 && !$edit_butt)) { + $del_butt .= qq~
    ~ ; + $row_cnt++ ; + $flag_cnt = 0 ; + } + $del_butt .= qq~~ ; + } + } + + } + + my $disp_nr = $db{$table}{$id}{contact_nr} ; + + if (length($disp_nr) == 11) { + $disp_nr = substr($disp_nr,0,2) . ' ' . substr($disp_nr,2,2) . ' ' . substr($disp_nr,4,3) . ' ' . substr($disp_nr,7,4) ; + $disp_nr = '+' . $disp_nr if $disp_nr =~ /^27/ ; + } + + $print_tbody .= qq~ + + $id + $db{$table}{$id}{name} + $disp_nr + + $edit_butt + $del_butt + + + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + &sort_fields; + + &hidden_db_fields; + + # $ignore{id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &hidden_db_fields; + + &sort_fields; + + $hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + + $ignore{iaction} = 1 ; + $required{name} = 1 ; + $required{contact_nr} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + our %poc_is_used = () ; + + &db_min_ro('event_quotes',"id,poc_id","`poc_id` <> '0'",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + $poc_is_used{aisa}{$db{event_quotes}{$_id}{poc_id}} .= qq~$_id;~ ; + } + + &db_switch_conn('sss') ; + + &db_min_ro('event_quotes',"id,poc_id","`poc_id` <> '0'",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + $poc_is_used{sss}{$db{event_quotes}{$_id}{poc_id}} .= qq~$_id;~ ; + } + + &db_switch_conn('aisa') ; + + %sort_field = () ; + + $sort_field{1} = 'name' ; + $sort_field{2} = 'contact_nr' ; + + if ($poc_id_used{aisa}{$i{id}} || $poc_id_used{sss}{$i{id}}) { + $required{name} = 0 ; + $required{contact_nr} = 0 ; + $readonly{contact_nr} = "READONLY" ; + $readonly{name} = "READONLY" ; + } else { + $required{name} = 1 ; + $required{contact_nr} = 1 ; + } + + if ($db{$table}{$i{id}}{name} && !$db{$table}{$i{id}}{contact_nr}) { + $readonly{name} = "READONLY" ; + $readonly{contact_nr} = "" ; + } elsif ($db{$table}{$i{id}}{name} && $db{$table}{$i{id}}{contact_nr}) { + $readonly{contact_nr} = "READONLY" ; + $readonly{name} = "READONLY" ; + } else { + $readonly{contact_nr} = "" ; + $readonly{name} = "" ; + } + + my $disp_nr = $db{$table}{$i{id}}{contact_nr} ; + + if (length($disp_nr) == 11) { + $disp_nr = substr($disp_nr,0,2) . ' ' . substr($disp_nr,2,2) . ' ' . substr($disp_nr,4,3) . ' ' . substr($disp_nr,7,4) ; + $disp_nr = '+' . $disp_nr if $disp_nr =~ /^27/ ; + } + + $db{$table}{$i{id}}{contact_nr} = $disp_nr ; + +} #------------------------------------------------------------------------------- + +sub add_screen { + + # called from common_add_screen + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + +} #------------------------------------------------------------------------------------------ + +sub thead { + + $print_thead = qq~ + + + ID + NAME + CONTACT NUMBER +   + + + ~ ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'map-marker' ; + our $lcpage = 'pocs' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'event_quotes_poc' ; + + $s{no} = 1 ; + + &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/price_list.pl b/scripts/_FromProd/v1.0/price_list.pl new file mode 100644 index 0000000..1108f77 --- /dev/null +++ b/scripts/_FromProd/v1.0/price_list.pl @@ -0,0 +1,606 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; +# our $testing = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our $srchscr = 0 ; +our $fnsortcol = 0 ; +our $redirtype = 'summary' ; # our $redirtype = 'list' ; # $redirtype = 'search' ; + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + +# called from common_min_action + +# my $exists = '' ; + +# &db_min_ro($table,'*',"name='$i{name}'",'','') ; + +# foreach my $id (keys %{$db{$table}}) { + # if ($db{$table}{$id}{name} eq $i{name}) { + # $exists = 1 ; + # } + # } + +# if ($exists) { + # $alert = &common_min_alert('warning',"NAME ALREADY EXISTS!",'ok') ; + # %col_name = (); + # # &add_screen; + # # &screen1; + # &common_min_add_screen; + # &common_min_screen1; + # } + +} #------------------------------------------------------------------------------------------ + +sub insert { + +&add_db_fields ; + +$i{last_edited_by} = $userid ; +$i{added_by} = $userid ; + +$i{id} = &db_min_get_max($table,'id') ; +$i{type_cnt} = &db_min_get_max($table,'type_cnt',"`type`='$i{type}'") ; + +if ($i{type} =~ /\_/g) { my @t = split(/\_/,$i{type}); $code_start = substr($t[0],0,2) . substr($t[1],0,1) ; } else { $code_start = substr($i{type},0,3) ;} + +$i{item_code} = uc $code_start . sprintf("%03s", $i{type_cnt}) ; + +&val_check ; + +$i{date_added} = "$now_ccyy_mm_dd" ; +$i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + +unless ($i{id}) { $error = qq(NO ID) ; return ; } + +&edit_db_fields ; + +if ($userid) { $i{last_edited_by} = $userid ; } + +&val_check ; + +$i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub val_check { + +unless ($i{excl}) { $i{excl} = '0' ; } +unless ($i{excl_from_summary}) { $i{excl_from_summary} = '0' ; } + +$i{nett} = sprintf("%.2f",$i{nett}) ; +$i{freight} = sprintf("%.2f",$i{freight}) ; +$i{main_price} = sprintf("%.2f",$i{main_price}) ; + +# $i{gross_10_1_50} = sprintf("%.2f",$i{gross_10_1_50}) ; +# $i{gross_10_51_plus} = sprintf("%.2f",$i{gross_10_51_plus}) ; +# $i{gross_20_1_50} = sprintf("%.2f",$i{gross_20_1_50}) ; +# $i{gross_20_51_plus} = sprintf("%.2f",$i{gross_20_51_plus}) ; +# $i{gross_50} = sprintf("%.2f",$i{gross_50}) ; + +$i{'source_admin'} = sprintf("%.2f",$i{'source_admin'}) ; +$i{'3_perc'} = sprintf("%.2f",$i{'3_perc'}) ; +$i{'5_perc'} = sprintf("%.2f",$i{'5_perc'}) ; +$i{'6_perc'} = sprintf("%.2f",$i{'6_perc'}) ; +$i{'8_perc'} = sprintf("%.2f",$i{'8_perc'}) ; +$i{'10_perc'} = sprintf("%.2f",$i{'10_perc'}) ; +$i{'15_perc'} = sprintf("%.2f",$i{'15_perc'}) ; +$i{'20_perc'} = sprintf("%.2f",$i{'20_perc'}) ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + +%sort_field = () ; + +$sort_field{1} = 'description' ; +$sort_field{2} = 'type' if $iaction eq 'add' ; +$sort_field{3} = 'excl' ; +$sort_field{4} = 'excl_from_summary' ; +$sort_field{6} = 'nett' ; +$sort_field{7} = 'freight' ; +$sort_field{8} = 'source_admin' ; +$sort_field{9} = 'main_price' ; +$sort_field{10} = '3_perc' ; $preferred_title{'3_perc'} = '3%' ; +$sort_field{11} = '5_perc' ; $preferred_title{'5_perc'} = '5%' ; +$sort_field{12} = '6_perc' ; $preferred_title{'6_perc'} = '6%' ; +$sort_field{13} = '8_perc' ; $preferred_title{'8_perc'} = '8%' ; +$sort_field{14} = '10_perc' ; $preferred_title{'10_perc'} = '10%' ; +$sort_field{15} = '15_perc' ; $preferred_title{'15_perc'} = '15%' ; +$sort_field{16} = '20_perc' ; $preferred_title{'20_perc'} = '20%' ; + +} #------------------------------------------------------------------------------- + +sub report_ifields { + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &load_search_vars ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +if ($i{date_added_from} and $i{date_added_to}) { # check dates + my $date_added_from_check = $i{date_added_from} ; + $date_added_from_check =~ s/\-//g ; + my $date_added_to_check = $i{date_added_to} ; + $date_added_to_check =~ s/\-//g ; + if ($date_added_from_check > $date_added_to_check) { $error = qq(PRICE LIST FROM ($i{date_added_from}) > PRICE LIST TO ($i{date_added_to})); &report_screen; } + } + +if ($i{date_added_from}) { + push @report_sql, "(`date_added` >= '$i{date_added_from}')" ; + push @report_results, "date_added >= $i{date_added_from}" ; + } + +if ($i{date_added_to}) { + push @report_sql, "(`date_added` <= '$i{date_added_to}')" ; + push @report_results, "date_added <= $i{date_added_to}" ; + } + +$report_results_msg = uc join(', ', @report_results) ; + +unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); &report_screen; } else { $isaved = qq(SELECT WHERE $report_results_msg) ; } + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + +# &db_min_ro('camera','id,name','','','') ; +# foreach my $id (keys %{$db{camera}}) { $camera_name{$id} = $db{camera}{$id}{name} ; } + +# &db_min_ro('company','id,name','','','') ; +# foreach my $id (keys %{$db{company}}) { $company_name{$id} = $db{company}{$id}{name} ; } + +# &db_min_ro('insurer','id,name','','','') ; +# foreach my $id (keys %{$db{insurer}}) { $asset_insurer_name{$id} = $db{insurer}{$id}{name} ; } + +} #------------------------------------------------------------------------------------------ + +sub sort_prefixes { + + if ($iaction eq 'summary') { + $sort_prefix_title{systems} = 'aaa' ; + $sort_prefix{systems} = 'bbb' ; + $sort_prefix_title{software_licence} = 'ccc' ; + $sort_prefix{software_licence} = 'ddd' ; + $sort_prefix_title{installation_kits} = 'eee' ; + $sort_prefix{installation_kits} = 'fff' ; + $sort_prefix_title{hardware_add_ons} = 'ggg' ; + $sort_prefix{hardware_add_ons} = 'hhh' ; + $sort_prefix_title{game_breakdown_analytics} = 'iii' ; + $sort_prefix{game_breakdown_analytics} = 'jjj' ; + $sort_prefix_title{additional_services} = 'kkk' ; + $sort_prefix{additional_services} = 'lll' ; + $sort_prefix_title{match_credits} = 'sss' ; + $sort_prefix{match_credits} = 'ttt' ; + } else { + $sort_prefix_title{systems} = 'aaa' ; + $sort_prefix{systems} = 'bbb' ; + $sort_prefix_title{software_licence} = 'ccc' ; + $sort_prefix{software_licence} = 'ddd' ; + $sort_prefix_title{installation_kits} = 'eee' ; + $sort_prefix{installation_kits} = 'fff' ; + $sort_prefix_title{hardware_add_ons} = 'ggg' ; + $sort_prefix{hardware_add_ons} = 'hhh' ; + $sort_prefix_title{game_breakdown_analytics} = 'iii' ; + $sort_prefix{game_breakdown_analytics} = 'jjj' ; + $sort_prefix_title{additional_services} = 'kkk' ; + $sort_prefix{additional_services} = 'lll' ; + $sort_prefix_title{extended_services} = 'mmm' ; + $sort_prefix{extended_services} = 'nnn' ; + $sort_prefix_title{training_services} = 'ooo' ; + $sort_prefix{training_services} = 'ppp' ; + $sort_prefix_title{other_services} = 'qqq' ; + $sort_prefix{other_services} = 'rrr' ; + $sort_prefix_title{match_credits} = 'sss' ; + $sort_prefix{match_credits} = 'ttt' ; + } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +&sort_prefixes ; + +my $srch_where_sql = join(' AND ', @report_sql) ; + +my $add_sql_where = '' ; + +# our @sql_col_display = ("id","item_code","excl","main_price","nett","type","type_cnt","description","freight","gross_10_1_50","gross_10_51_plus","gross_20_1_50","gross_20_51_plus","gross_50","last_updated","last_edited_by","") ; +# our @sql_col_display = ("id","item_code","excl","main_price","nett","type","type_cnt","description","freight","source_admin","3_perc","5_perc","8_perc","10_perc","15_perc","20_perc","") ; +# our @sql_col_display = ("description","main_price","3_perc","5_perc","6_perc","8_perc","10_perc","15_perc","20_perc") ; +our @sql_col_display = ("description") ; +push @sql_col_display, "nett" if $useropts{boss}{$username} ; +push @sql_col_display, "main_price" ; +push @sql_col_display, "3_perc" ; +push @sql_col_display, "5_perc" ; +push @sql_col_display, "6_perc" ; +push @sql_col_display, "8_perc" ; +push @sql_col_display, "10_perc" ; +push @sql_col_display, "15_perc" ; +push @sql_col_display, "20_perc" ; +push @sql_col_display, "" ; + +our $exportdir = 'pricelist' ; + +&report_xls_export_header("Price-list$xlsreportname",$exportdir) ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &load_list_vars("$srch_where_sql$add_sql_where") ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +my $table_colspan = scalar @sql_col_display ; # get number ioif columns + +# foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) { +foreach my $id (sort {$db{$table}{$b}{type} cmp $db{$table}{$a}{type}} keys %{$db{$table}}) { + + # if (($i{active} == 1) and ($camera_id_in_use_for_devices{$id} < 1)) { next ; } # Active with devices + # if (($i{active} == 2) and ($camera_id_in_use_for_devices{$id} > 0)) { next ; } # Active without devices + + # &common_debug("$iaction - $db{$table}{$id}{excl_from_summary} [description=$db{$table}{$id}{description}]") ; + + if ($iaction eq 'summary') { + next if $db{$table}{$id}{excl_from_summary} ; + next unless $sort_prefix_title{$db{$table}{$id}{type}} ; + } + + my $print_type = uc $db{$table}{$id}{type} ; $print_type =~ s/\_/ /g ;# my @type_parts = split(/\_/,$print_type) ; @type_parts = map ucfirst, @type_parts; $print_type = join(" ", @type_parts) ; + unless ($done_type_group{$db{$table}{$id}{type}}){ + # $print_tbody .= qq~$sort_prefix_title{$db{$table}{$id}{type}}$print_type~ ; + $print_tbody .= qq~$sort_prefix_title{$db{$table}{$id}{type}}$print_type~ ; + for (1 .. $table_colspan-1) { + # $print_tbody .= qq~ ~ ; + $print_tbody .= qq~ ~ ; + } + $print_tbody .= qq~~ ; + $done_type_group{$db{$table}{$id}{type}} = 1 ; + } + + # $print_tbody .= qq~$print_type~ unless $done_type_group{$db{$table}{$id}{type}} ; $done_type_group{$db{$table}{$id}{type}} = 1 ; + # $print_tbody .= qq~$print_type        ~ unless $done_type_group{$db{$table}{$id}{type}} ; $done_type_group{$db{$table}{$id}{type}} = 1 ; + + $print_tbody .= qq~~ ; + + $xlscol=0; my $style = '' ; + + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$table}{$id}{$_} ; + my $align = '' ; + + # if ($_ eq 'item_code') { $val .= " [$db{$table}{$id}{type}]" ; } + + my $center = qq~ class="dt-center"~ ; + my $right = qq~ class="dt-right"~ ; + + # if ($_ eq 'active') { if ($val == 1) { $val = &set_tick('green', '') ; } else { $val = &set_tick('red', '') ; } $align = $center ; } + + &report_xls_export_process_cell('','',$val) ; # ------------------------------------------------------------------------- HTML AFTER + $xlscol++; + + $align = $right unless $_ eq 'description' ; + $val = &common_commify($val) unless $_ eq 'description' ; + + # $val = qq~$sort_prefix{$db{$table}{$id}{type}}~ . $val if $_ eq 'description' ; + $val = qq~$sort_prefix{$db{$table}{$id}{type}}$val~ . $val if $_ eq 'description' ; + + $style = ($db{$table}{$id}{excl}) ? qq~style="background-color:#cb2c2c;color:white;"~ : '' ; + + $print_tbody .= qq~$val~ ; + } + + my $delete_butt = '' ; my $edit_butt = '' ; + + if ($useropts{boss}{$username} or $useropts{super}{$username}) { + $edit_butt = qq() ; + # $delete_butt = qq() ; + } + + # if ($camera_id_in_use_for_devices{$id}) { $delete_butt = '' ; } + + $print_tbody .= qq~ $edit_butt $delete_butt~ ; + $xlsrow++ ; + } + +&report_xls_export_footer('L',15,$exportdir) ; + +# $glob_sort_col = 0 ; # order by ol devices col +# $glob_sort_asc_desc = 'desc' ; +$fnsortorder = 'asc' ; + +$print_more_boxes .= qq~
    ~ ; + +&common_min_extra_crumb("search-$lcpage\s","Search Screen") ; + +$box_icon .= qq~
    ~ ; + +} #------------------------------------------------------------------------------------------ + +# sub set_tick { + +# my ($color,$tooltip) = @_ ; + +# $tick{green} = qq~2~ ; +# $tick{orange} = qq~1~ ; +# $tick{red} = qq~0~ ; + +# return ($tick{$color}) ; + +# } #------------------------------------------------------------------------------------------ + +sub load_list_vars { + +my ($where) = @_ ; + +# &db_min_ro('device','id,camera_id,online,type_id',$acc_id_sql_where,'','') ; +# foreach my $id (keys %{$db{device}}) { + # $camera_id_in_use_for_devices{$db{device}{$id}{camera_id}}++ ; + # $cnt_dev_typ{$db{device}{$id}{camera_id}}{$dev_nam}++ ; + # } + +&db_min_ro($table,'*',$where,'type DESC','') ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + +&common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub hidden_db_fields { + +$ignore{iaction} = 1 ; + +$checkbox{excl} = 1 ; +$checkbox{excl_from_summary} = 1 ; + +$hidden{last_updated} = 2 ; +$hidden{last_edited_by} = 2 ; +$hidden{date_added} = 2 ; +$hidden{added_by} = 2 ; +$hidden{type_cnt} = 2 ; +$hidden{item_code} = 2 ; + +# $required{nett} = 1 ; +# $required{freight} = 1 ; +# $required{gross_10_1_50} = 1 ; +# $required{gross_10_51_plus} = 1 ; +# $required{gross_20_1_50} = 1 ; +# $required{gross_20_51_plus} = 1 ; +# $required{gross_50} = 1 ; +# $required{main_price} = 1 ; + +$required{description} = 1 ; + +# $required{item_code} = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + +&sort_fields; + +&hidden_db_fields ; + +$hidden{id} = 2 ; + +$db{$table}{''}{nett} = '0.00' ; +$db{$table}{''}{freight} = '0.00' ; +$db{$table}{''}{main_price} = '0.00' ; +$db{$table}{''}{source_admin} = '0.00' ; + +$db{$table}{''}{'3_perc'} = '0.00' ; +$db{$table}{''}{'5_perc'} = '0.00' ; +$db{$table}{''}{'6_perc'} = '0.00' ; +$db{$table}{''}{'8_perc'} = '0.00' ; +$db{$table}{''}{'10_perc'} = '0.00' ; +$db{$table}{''}{'15_perc'} = '0.00' ; +$db{$table}{''}{'20_perc'} = '0.00' ; + +# $db{$table}{''}{gross_10_1_50} = '0.00' ; +# $db{$table}{''}{gross_10_51_plus} = '0.00' ; +# $db{$table}{''}{gross_20_1_50} = '0.00' ; +# $db{$table}{''}{gross_20_51_plus} = '0.00' ; +# $db{$table}{''}{gross_50} = '0.00' ; + +if ($iaction eq 'add'){ &build_boxes_add ; } # can't be in add_screen, only works if here + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + +&sort_fields; + +&hidden_db_fields ; + +$ignore{date_added} = 1 ; +$ignore{added_by} = 1 ; +$ignore{last_updated} = 1 ; +$hidden{id} = 1 ; # 1 = bypass for db update +$hidden{type_cnt} = 2 ; # 1 = bypass for db update +$hidden{type} = 2 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + +my ($id) = @_ ; + +&common_min_select_opts('type',"itv_admin_db.$table",'type',$db{$table}{$id}{type},1,'','','type','','DISTINCT type') ; # + +# &common_min_select_opts('client_id','customers','name',$db{$table}{$id}{client_id},1) ; + +} #------------------------------------------------------------------------------- + +sub add_screen { + +# called from common_add_screen + +# $db{$table}{''}{camera_id} = $client_id ; # set for input box + +&select_opts('') ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes_add { + +$print_box_content_rows .= &common_min_forms_start($table) ; + +$print_box_content_rows .= qq(
    ) ; +$print_box_content_rows .= &common_min_box_top('list-alt',"  $page_title",$box_main_bg) ; +$print_box_content_rows .= &common_min_add_form($table,'save',3,9,1,1) ; +$print_box_content_rows .= &common_min_box_foot ; +$print_box_content_rows .= qq(
    ) ; + +&build_boxes_right; + +$print_box_content_rows .= qq(
    ) ; + +$print_box_content_rows .= &common_min_forms_end('',$table,'save') ; + +} #---------------------------------------------------------------------------------------- + +sub edit_screen { + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +$db{$table}{$i{id}}{source_admin} = '0.00' unless $db{$table}{$i{id}}{source_admin} ; + +&select_opts($i{id}) ; + +&build_boxes_edit($i{id}) ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes_edit { + +my ($id) = @_ ; + +$print_box_content_rows .= &common_min_forms_start($table) ; +$print_box_content_rows .= qq(
    ) ; +$print_box_content_rows .= &common_min_box_top('user',"  $page_title : $db{$table}{$id}{id}",$box_main_bg) ; +$print_box_content_rows .= &common_min_edit_form($i{id},$table,'update',3,9,1,1) ; +$print_box_content_rows .= &common_min_box_foot ; +$print_box_content_rows .= qq(
    ) ; + +&build_boxes_right($id); + +$print_box_content_rows .= qq(
    ) ; + +$print_box_content_rows .= &common_min_forms_end($id,$table,'update',$skip) ; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_right { + +my ($id) = @_ ; + +# my $box_icon = '' ; + +# $print_box_content_rows .= &common_min_box_top('picture','Logo Upload',$box_right_bg,$box_icon) ; + +# $print_box_content_rows .= qq(
     
    ); + +# $print_box_content_rows .= qq(
    ); + +# $print_box_content_rows .= &common_min_box_foot ; + +} #---------------------------------------------------------------------------------------- + +sub page_opts { + +$s{no}=1; # don't add an s + +our $glyphicon = 'list' ; +our $lcpage = 'price-list' ; + +&common_page_name ; + +our $table = 'price_list' ; + +$page_title = 'Price List' ; + +&common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + +our $lcol = 2 ; +our $fcol = 5 ; + +my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-42); # 6 weeks back + +$set_month = sprintf("%02s", $set_month) ; +$set_day = sprintf("%02s", $set_day) ; + +my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ; + +$print_box_content_rows .= &common_min_forms_start('report') ; + +$print_box_content_rows .= &common_min_form_datepicker('date_added_from',$set_ccyy_dd_mm) ; +$print_box_content_rows .= &common_min_form_datepicker('date_added_to',$now_ccyy_mm_dd) ; + +$print_box_content_rows .= &common_min_forms_end('','','report') ; + +&common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +use common ; +use report ; +use xlsxcreator ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/quote_defaults.pl b/scripts/_FromProd/v1.0/quote_defaults.pl new file mode 100644 index 0000000..cbd7eff --- /dev/null +++ b/scripts/_FromProd/v1.0/quote_defaults.pl @@ -0,0 +1,343 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI::Carp qw(fatalsToBrowser); + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI; +use Crypt::PasswdMD5; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +if ($iaction eq 'add') { unless ($username eq 'rory') { print "UNAUTHORISED" ; exit ; } } + +unless ($useropts{super}{$username}) { print "UNAUTHORISED" ; exit ; } + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + +my $exists = '' ; + +&db_min_ro($table,'*',"`field_name`='$i{field_name}' AND `type`='$i{type}'",'','') ; + +foreach my $id (keys %{$db{$table}}) { if ($db{$table}{$id}{field_name} eq $i{field_name}) { $exists = 1 ; } } + +if ($exists) { + $alert = &common_min_alert('warning',"FIELD_NAME ALREADY EXISTS!",'ok') ; + %col_name = (); + &common_min_add_screen; + &common_min_screen1; + } + +} #------------------------------------------------------------------------------------------ + +sub insert { + +&add_db_fields ; + +$i{last_update} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + +unless ($i{id}) { $error = qq(NO ID) ; return ; } + +&edit_db_fields ; + +# unless ($i{Active}) { $i{Active} = '0' ; } + +$i{last_update} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&db_min_upd($table,"`id`='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +&db_min_ro($table,'*','','','') ; + +foreach my $id (keys %{$db{$table}}) { + + # my $del_butt = qq( ) ; + my $edit_butt = qq( ) ; + + my $def_zar = &replace_zero($db{$table}{$id}{default_zar}) ; + my $def_qty = &replace_zero($db{$table}{$id}{default_qty}) ; + my $min_zar = &replace_zero($db{$table}{$id}{min_zar}) ; + + $print_tbody .= qq( + $id + $db{$table}{$id}{type} + $db{$table}{$id}{field_name} + $def_zar + $def_qty + $min_zar + $db{$table}{$id}{last_update} + + $edit_butt + $view_butt + $del_butt + + ) ; + } + +} #------------------------------------------------------------------------------------------ + +sub replace_zero { + +my ($val) = @_ ; + +if ($val eq '0.00') { $val = '' ; } + +return ($val) ; + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + +&hidden_db_fields; + +$hidden{id} = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + +&hidden_db_fields; + +$readonly{field_name} = 'READONLY' ; +$required{field_name} = 1 ; +$readonly{type} = 'READONLY' ; +$required{type} = 1 ; + +$hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + +$ignore{iaction} = 1 ; +$hidden{last_update} = 2 ; + +&sort_fields; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + +$sort_field{1} = 'field_name' ; +$sort_field{2} = 'type' ; +$sort_field{3} = 'default_zar' ; $preferred_title{default_zar} = 'Default ZAR' ; +$sort_field{4} = 'default_qty' ; +$sort_field{5} = 'min_zar' ; $preferred_title{min_zar} = 'Min ZAR' ; + +} #------------------------------------------------------------------------------- + +sub add_screen { + +# called from common_add_screen + +&select_opts('') ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +$selected{field_name}{$db{$table}{$i{id}}{field_name}} = 'SELECTED'; +# $selected{type}{$db{$table}{$i{id}}{type}} = 'SELECTED'; + +# load quote defaults +# &db_min_ro($table,'*','','','') ; +foreach (keys %{$db{$table}}) { + $defzar{$db{$table}{$_}{type}}{$db{$table}{$_}{field_name}} = $db{$table}{$_}{default_zar}; + $minzar{$db{$table}{$_}{type}}{$db{$table}{$_}{field_name}} = $db{$table}{$_}{min_zar}; + $defqty{$db{$table}{$_}{type}}{$db{$table}{$_}{field_name}} = $db{$table}{$_}{default_qty}; + } + +&select_opts($i{id}) ; + +# $extra_form_fields .= &common_min_form_input('new_password','','password') ; + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + +my ($id) = @_ ; + +unless ($id) { # don't display dropdown on edit + $select{field_name} = 1 ; + $select{type} = 1 ; + } + +$opts{type} = qq(); + +if ($db{$table}{$id}{type} eq 'Inbound') { + &clear_hashes; + &tab_build_qt_sa_in; + &field_name_opts($id); + } + +if ($db{$table}{$id}{type} eq 'Outbound') { + &clear_hashes; + &tab_build_qt_sa_out; + &field_name_opts($id); + } + +if ($db{$table}{$id}{type} eq 'Domestic') { + &clear_hashes; + &tab_sec_det('_cour_dom'); + $cost_desc{25} = 'Fuel & Security'; # Bodge it for this one + $def_qty{25} = $defqty{Domestic}{$cost_desc{25}} ; # '32.5' + &field_name_opts($id); + } + +if ($db{$table}{$id}{type} eq 'International') { + &clear_hashes; + &tab_sec_det('_cour_intl'); + $cost_desc{25} = 'Fuel & Security'; # Bodge it for this one + $def_qty{25} = $defqty{International}{$cost_desc{25}} ; # '32.5' + &field_name_opts($id); + } + +if ($db{$table}{$id}{type} eq 'Carnet') { + &clear_hashes; + &tab_sec_det('_ata_car'); + &field_name_opts($id); + } + +$print_box_content_rows .= &common_min_form_select('field_name','','',1,'') ; + +} #------------------------------------------------------------------------------- + +sub clear_hashes { + +%cost_desc = () ; %def_qty = () ; %def_zar = () ; + +} #------------------------------------------------------------------------------- + +sub field_name_opts { + +my ($id) = @_ ; + +$opts{field_name} = qq(); + +if ($id) { # only on edit + $readonly{default_zar} = 'READONLY' ; + $readonly{min_zar} = 'READONLY' ; + $readonly{default_qty} = 'READONLY' ; + $required{default_zar} = 0 ; + $required{min_zar} = 0 ; + $required{default_qty} = 0 ; + } + +foreach (keys %cost_desc) { + if ($def_qty{$_}) { + unless ($got_opts{$cost_desc{$_}}) { $opts{field_name} .= qq(); } + $got_opts{$cost_desc{$_}} = 1 ; + if (($selected{field_name}{$cost_desc{$_}}) and ($id)) { + $readonly{default_qty} = '' ; + $required{default_qty} = 1 ; + } + } + + if ($def_zar{$_}) { + unless ($got_opts{$cost_desc{$_}}) { $opts{field_name} .= qq(); } + $got_opts{$cost_desc{$_}} = 1 ; + if (($selected{field_name}{$cost_desc{$_}}) and ($id)) { + $readonly{default_zar} = '' ; + $required{default_zar} = 1 ; + } + } + + if ($min_zar{$_}) { + unless ($got_opts{$cost_desc{$_}}) { $opts{field_name} .= qq(); } + $got_opts{$cost_desc{$_}} = 1 ; + if (($selected{field_name}{$cost_desc{$_}}) and ($id)) { + $readonly{min_zar} = '' ; + $required{min_zar} = 1 ; + } + } + } + +} #------------------------------------------------------------------------------- + +sub view_screen { + +my ($iid) = @_ ; + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +foreach my $cnt (sort {$a <=> $b} keys %sort_field) { + my $col = $sort_field{$cnt} ; + if ($ignore{$col}) { next ; } + my $val = $db{$table}{$iid}{$col} ; + $print_box_content_rows .= &common_min_form_view($col,$val) ; + } + +} #------------------------------------------------------------------------------------------ + +sub thead { + +$print_thead = qq(IDTypeField NameDefault ZARDefault QtyMin ZARLast Update ) ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'qrcode' ; +our $lcpage = 'quote-default' ; # $ucpage = uc $lcpage ; # $ucfirstpage = ucfirst $lcpage ; + +my @splitlcpage = split(/\-/,$lcpage) ; +my @ucfirstpage = map(ucfirst, map(lc,@splitlcpage)); +$ucfirstpage = join(' ', @ucfirstpage); +$ucpage = uc $ucfirstpage ; + +our $table = 'quote_defaults' ; + +$page_title = 'Quote Defaults' ; + +our $glob_sort_col = 1 ; +our $glob_sort_asc_desc = 'asc' ; + +# &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use tabs ; +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/quote_notes.pl b/scripts/_FromProd/v1.0/quote_notes.pl new file mode 100644 index 0000000..ddf2092 --- /dev/null +++ b/scripts/_FromProd/v1.0/quote_notes.pl @@ -0,0 +1,275 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI::Carp qw(fatalsToBrowser); + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI; +use Crypt::PasswdMD5; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +if ($iaction eq 'add') { unless ($username eq 'rory') { print "UNAUTHORISED" ; exit ; } } + +unless ($useropts{super}{$username}) { print "UNAUTHORISED" ; exit ; } + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + +my $exists = '' ; + +# &db_min_ro($table,'*',"`field_name`='$i{field_name}' AND `type`='$i{type}'",'','') ; + +# foreach my $id (keys %{$db{$table}}) { if ($db{$table}{$id}{field_name} eq $i{field_name}) { $exists = 1 ; } } + +# if ($exists) { + # $alert = &common_min_alert('warning',"FIELD_NAME ALREADY EXISTS!",'ok') ; + # %col_name = (); + # &common_min_add_screen; + # &common_min_screen1; + # } + +} #------------------------------------------------------------------------------------------ + +sub insert { + +&add_db_fields ; + +$i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + +unless ($i{id}) { $error = qq(NO ID) ; return ; } + +&edit_db_fields ; + +# unless ($i{Active}) { $i{Active} = '0' ; } + +$i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&db_min_upd($table,"`id`='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +&db_min_ro($table,'*','','','') ; + +# id date_time last_edited_by last_updated note_1 note_2 note_3 note_4 note_5 note_6 note_7 note_8 note_9 note_10 note_11 note_12 note_13 note_14 note_15 payment_term_1 payment_term_2 payment_term_3 payment_term_4 payment_term_5 payment_term_6 payment_term_7 payment_term_8 payment_term_9 payment_term_10 payment_term_11 payment_term_12 payment_term_13 payment_term_14 payment_term_15 roe_1 roe_2 roe_3 roe_4 roe_5 roe_6 roe_7 roe_8 roe_9 roe_10 roe_11 roe_12 roe_13 roe_14 roe_15 delivery_time_1 delivery_time_2 delivery_time_3 delivery_time_4 delivery_time_5 delivery_time_6 delivery_time_7 delivery_time_8 delivery_time_9 delivery_time_10 delivery_time_11 delivery_time_12 delivery_time_13 delivery_time_14 delivery_time_15 + + &hidden_db_fields; + + foreach my $id (keys %{$db{$table}}) { + + # $print_tbody .= qq~~; + + foreach my $col (keys %{$db{$table}{$id}}) { + + next if $ignore{$col} || $hidden{$col} ; + next if $col eq 'id' || $col eq '' ; + next unless $db{$table}{$id}{$col} ; + + # my $del_butt = qq( ) ; + my $edit_butt = qq( ) ; + + $print_tbody .= qq~ + $col + $db{$table}{$id}{$col} + + $edit_butt + ~ ; + } + + # $print_tbody .= qq~~; + } + +our $fnsortcol = -1 ; + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + +&hidden_db_fields; + +$hidden{id} = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + +&hidden_db_fields; + +# $readonly{field_name} = 'READONLY' ; +# $required{field_name} = 1 ; +# $readonly{type} = 'READONLY' ; +# $required{type} = 1 ; + +$hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + +$ignore{iaction} = 1 ; +$hidden{date_time} = 2 ; +$hidden{last_edited_by} = 2 ; +$hidden{last_updated} = 2 ; + +# &sort_fields; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + our %sort_field = () ; + my $col_count = 15 ; + for (1 .. $col_count) { + + $sort_field{$_ + 0*$col_count} = "delivery_time_$_" ; + $sort_field{$_ + 1*$col_count} = "note_$_" ; + $sort_field{$_ + 2*$col_count} = "payment_term_$_" ; + $sort_field{$_ + 3*$col_count} = "roe_$_" ; + } + for (1 .. 5){ + $sort_field{$_ + 4*$col_count} = "terms_$_" ; + } + +# $sort_field{1} = 'field_name' ; +# $sort_field{2} = 'type' ; +# $sort_field{3} = 'default_zar' ; $preferred_title{default_zar} = 'Default ZAR' ; +# $sort_field{4} = 'default_qty' ; +# $sort_field{5} = 'min_zar' ; $preferred_title{min_zar} = 'Min ZAR' ; + +} #------------------------------------------------------------------------------- + +sub add_screen { + +# called from common_add_screen + +&select_opts('') ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +$selected{field_name}{$db{$table}{$i{id}}{field_name}} = 'SELECTED'; +# $selected{type}{$db{$table}{$i{id}}{type}} = 'SELECTED'; + +# load quote defaults +# &db_min_ro($table,'*','','','') ; +# foreach (keys %{$db{$table}}) { + # $defzar{$db{$table}{$_}{type}}{$db{$table}{$_}{field_name}} = $db{$table}{$_}{default_zar}; + # $minzar{$db{$table}{$_}{type}}{$db{$table}{$_}{field_name}} = $db{$table}{$_}{min_zar}; + # $defqty{$db{$table}{$_}{type}}{$db{$table}{$_}{field_name}} = $db{$table}{$_}{default_qty}; + # } + +&select_opts($i{id}) ; + +&sort_fields; + +# $extra_form_fields .= &common_min_form_input('new_password','','password') ; + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + +my ($id) = @_ ; + +# unless ($id) { # don't display dropdown on edit + # $select{field_name} = 1 ; + # $select{type} = 1 ; + # } + +# $opts{type} = qq(); + +# $print_box_content_rows .= &common_min_form_select('field_name','','',1,'') ; + +} #------------------------------------------------------------------------------- + +sub clear_hashes { + +%cost_desc = () ; %def_qty = () ; %def_zar = () ; + +} #------------------------------------------------------------------------------- + +sub view_screen { + +my ($iid) = @_ ; + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +foreach my $cnt (sort {$a <=> $b} keys %sort_field) { + my $col = $sort_field{$cnt} ; + if ($ignore{$col}) { next ; } + my $val = $db{$table}{$iid}{$col} ; + $print_box_content_rows .= &common_min_form_view($col,$val) ; + } + +} #------------------------------------------------------------------------------------------ + +sub thead { + +$print_thead = qq(NAMEVALUE ) ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'qrcode' ; +our $lcpage = 'quote-note' ; # $ucpage = uc $lcpage ; # $ucfirstpage = ucfirst $lcpage ; + +my @splitlcpage = split(/\-/,$lcpage) ; +my @ucfirstpage = map(ucfirst, map(lc,@splitlcpage)); +$ucfirstpage = join(' ', @ucfirstpage); +$ucpage = uc $ucfirstpage ; + +our $table = 'quote_notes' ; + +$page_title = 'Quote Notes' ; + +our $glob_sort_col = 1 ; +our $glob_sort_asc_desc = 'asc' ; + +# &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use tabs ; +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/quotes.pl b/scripts/_FromProd/v1.0/quotes.pl new file mode 100644 index 0000000..0577d92 --- /dev/null +++ b/scripts/_FromProd/v1.0/quotes.pl @@ -0,0 +1,2578 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); + +require cfg ; + +print header; # CGI.pm method + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $redirtype = 'search' ; +# our $debug = 1 ; +# our $testing = 1 ; + +our $cust_cols = 1 ; # display _blank_3.pm + +our $camera_cnt_allowed = 1000 ; our $max_cams = 10 ; + +if ($useropts{tickets}{$username}) { print "Content-type: text/html\n\n"; require '401.pm' ; exit ; } + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +# unless ($username eq 'handre' or $username eq 'rory') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } +# &db_open_ro; +# $db_ignore_open_close=1; +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +$ignore{"yearly_total"} = 1 ; +$ignore{"yearly_totals_1"} = 1 ; +$ignore{"yearly_totals_2"} = 1 ; +$ignore{"yearly_totals_3"} = 1 ; +$ignore{"yearly_totals_4"} = 1 ; +$ignore{"yearly_totals_5"} = 1 ; + +if ($iaction eq 'add'){ + &add_screen; + &common_min_screen1; + } + +if ($iaction eq 'edit'){ + &common_min_load_params ; + &edit_screen ; + &common_min_screen1; + } + +if ($iaction eq 'save'){ + &common_min_load_params ; + &insert ; + &edit_or_list ; + } + +if ($iaction eq 'update'){ + &common_min_load_params ; + &update ; + &edit_or_list ; + } + +if ($iaction eq 'copy'){ + &common_min_load_params ; + &duplicate ; + &edit_screen; + &common_min_screen1; + } + +if ($iaction eq 'delete'){ + &common_min_load_params ; + &delete ; + &common_min_screen2; +} + +&common_min_action; +&db_min_insert('quotes_min') ; + +# $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +# &db_close_conn ; +exit; + +#------------------------------------------------------------------------------------------ + +sub edit_or_list { + +# if ($i{saveandexit} eq 'yes') { + # &list_screen ; + # &common_min_screen3; + # } +# else + # { + &edit_screen ; + &common_min_screen1; + # } + +} #------------------------------------------------------------------------------------------ + +sub insert { + +&add_db_fields ; + +$i{last_update} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; +$i{datetime} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; +$i{user_id} = $userid ; + +&set_default_i_vals; + +# &creat_db_cols; + +$i{id} = &db_min_get_max($table,'id') ; +&titles_for_pdf ; +&common_upload_files("costings/$i{id}") ; +&process_upload_ifields; +&process_totals ; + +&db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &switch_table ; + &db_min_insert($table) ; + &update_camera; + &new_table ; + &db_min_insert('quotes_min') ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +sub update { + +unless ($i{id}) { $error = qq(NO ID) ; return ; } + +&edit_db_fields ; + +# &creat_db_cols; +&titles_for_pdf ; +&set_default_i_vals ; + +$i{last_update} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&common_upload_files("costings/$i{id}") ; +&process_upload_ifields ; +&process_totals ; + +&db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &switch_table ; + &log_changes_1 ; + &db_min_upd($table,"id='$i{id}'") ; + &update_camera ; + &new_table ; + &log_changes_2 ; + &db_min_upd('quotes_min',"id='$i{id}'") ; + foreach (keys %ignore_for_now) { + $ignore{$_} = '' ; + } + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +sub process_totals { + + my @ttlarr = ("one_time_fee","monthly_recurring_fee","annual_fee") ; + my @ttlarr2 = ("subtotal","vat","total") ; + + foreach my $a (@ttlarr) { + foreach my $b (@ttlarr2) { + my $field = "$b\_$a" ; + my $field_1 = "$b\_$a\_1" ; + my $field_2 = "$b\_$a\_2" ; + $ignore{$field_1} = 1 ; + $ignore{$field_2} = 1 ; + $i{$field} = qq~$i{$field_1};$i{$field_2}~ ; + } + } + +} #------------------------------------------------------------------------------------------ + +sub log_changes_1 { + + &db_min_ro($table,"*","`id`='$i{id}'",'','') ; + our $line = qq~$now_year$now_mm$now_dd$now_hour$now_min$now_sec|$now_year-$now_mm-$now_dd $now_hour:$now_min:$now_sec|quote_id='$i{id}'|user_id=$userid|changed_from|~ ; + my %col_to_be_updated = () ; my %ignore_for_now = () ; + + foreach (keys %i) { + $col_to_be_updated{$_} = 1 ; + } + + foreach my $col (keys %{$db{$table}{$i{id}}}) { + next if $ignore{$col} or $hidden{$col} == 1 or substr($col,0,3) eq 'new' or not $col_to_be_updated{$col} ; + if (($i{$col} or $db{$table}{$i{id}}{$col}) and $db{$table}{$i{id}}{$col} ne $i{$col}) { + # $line .= qq~$col='$i{$col}',~ ; + $line .= qq~$col='$db{$table}{$i{id}}{$col}',~ ; + } elsif ((not $i{$col} and not $db{$table}{$i{id}}{$col}) or (($i{$col} or $db{$table}{$i{id}}{$col}) and $db{$table}{$i{id}}{$col} eq $i{$col})) { + $ignore{$col} = 1 ; $ignore_for_now{$col} = 1 ; + } + } + +} #------------------------------------------------------------------------------------------ + +sub log_changes_2 { + + &db_min_ro('quotes_min','*',"id='$i{id}'",'','') ; + + foreach (keys %i) { + $col_to_be_updated{$_} = 1 ; + } + + foreach my $col (keys %{$db{quotes_min}{$i{id}}}) { + next if $ignore{$col} or $hidden{$col} == 1 or substr($col,0,3) eq 'new' or not $col_to_be_updated{$col} ; + if (($i{$col} or $db{quotes_min}{$i{id}}{$col}) and $db{quotes_min}{$i{id}}{$col} ne $i{$col}) { + # $line .= qq~$col='$i{$col}',~ ; + $line .= qq~$col='$db{quotes_min}{$i{id}}{$col}',~ ; + } elsif ((not $i{$col} and not $db{quotes_min}{$i{id}}{$col}) or (($i{$col} or $db{quotes_min}{$i{id}}{$col}) and $db{quotes_min}{$i{id}}{$col} eq $i{$col})) { + $ignore{$col} = 1 ; $ignore_for_now{$col} = 1 ; + } + } + + chop $line if $line ; + + &common_log_changes("events/changes_quotes.dat",$line) if $line ; + + # exit ; + +} #------------------------------------------------------------------------------------------ + +sub db_min_upd_raw { + +my ($sql) = @_ ; + +&common_debug($sql) ; + +my $sth = $dbh->prepare($sql) ; + +$sth->execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; + +$sth->finish(); + +} #------------------------------------------------------------------------------------------ + +sub titles_for_pdf { + + my $do_insert = 0; + # our %sec_cnt = ('a_systems' => "3-Systems", 'b_software_licence' => "3-Software Licence (Monthly Fee)", 'c_game_breakdown_analytics' => "2-Game Breakdown and Analytics (Annual Fee)", 'd_installation_kits' => "7-Installation Kits", 'e_hardware_add_ons' => "7-Hardware Add Ons", 'f_additional_services' => "7-Additional Services", 'g_match_credits' => "4-Match Credits", 'h_other' => "5-Other", 'i_rental' => "2-Rental"); + $sql_insert_pdf = qq~INSERT INTO `quotes_pdf_titles` (quote_id, old_name, new_name) VALUES ~ ; + db_min_ro('quotes_pdf_titles', '*', "quote_id = $i{id}", '', '') ; + foreach (keys %{$db{quotes_pdf_titles}}){ + next unless $db{quotes_pdf_titles}{$_}{quote_id} == $i{id} ; + $quote_id_old_pdf_titles{$db{quotes_pdf_titles}{$_}{quote_id}}{$db{quotes_pdf_titles}{$_}{old_name}} = 1 ; + # &common_debug("ABC: $db{quotes_pdf_titles}{$_}{quote_id}, $db{quotes_pdf_titles}{$_}{old_name} $i{id}\n") ; + } + # &common_debug("ABC: ") ; + $do_insert = 0 ; + foreach(keys %sec_cnt){ + $first_name = substr($sec_cnt{$_}, 2) ; + $_k = substr($_,1) ; + $ignore{$_k} = 1 ; + if ($quote_id_old_pdf_titles{$i{id}}{$first_name} and $i{$_k}){ + $sql_update_pdf = qq(UPDATE `quotes_pdf_titles` SET new_name = '$i{$_k}' WHERE old_name = '$first_name' and quote_id = $i{id} ;) ; + &db_min_upd_raw($sql_update_pdf) ; + } + elsif (not $quote_id_old_pdf_titles{$i{id}}{$first_name} and $i{$_k}){ + $sql_insert_pdf .= qq(($i{id}, '$first_name', '$i{$_k}'),) ; + $do_insert = 1 ; + + } + elsif ($quote_id_old_pdf_titles{$i{id}}{$first_name} and not $i{$_k}) { + + $sql_update_pdf = qq(UPDATE `quotes_pdf_titles` SET new_name = '$first_name' WHERE old_name = '$first_name' and quote_id = $i{id} ;) ; + &db_min_upd_raw($sql_update_pdf) ; + } + elsif (not $quote_id_old_pdf_titles{$i{id}}{$first_name} and not $i{$_k}) { + + $sql_insert_pdf .= qq(($i{id}, '$first_name', '$first_name'),) ; + $do_insert = 1 ; + } + + } + if ($do_insert){ + chop $sql_insert_pdf ; + $sql_insert_pdf .= ";" ; + &db_min_upd_raw($sql_insert_pdf) ; + } + +} #------------------------------------------------------------------------------------------ + +sub switch_table { + + &db_min_ro('quote_notes','*',"id='1'",'','') ; + + my @note_fields = ("note","payment_term","roe","delivery_time") ; + + for my $row_cnt (1 .. 12) { + foreach my $fields (@note_fields) { + my $field = "$fields\_$row_cnt" ; + $ignore{$field} = (($i{$field} && $i{$field} eq $db{quote_notes}{1}{$field}) || (($fields eq "payment_term" || $fields eq "roe") && $row_cnt > 6) || ($fields eq "delivery_time" && $row_cnt > 4)) ? 1 : 0 ; + $i{$field} = (!$i{$field} && $db{quote_notes}{1}{$field}) ? "-1" : $i{$field} ; + } + } + + # local @ttlarr = ("one_time_fee","monthly_recurring_fee","annual_fee") ; + # local @ttlarr2 = ("subtotal","vat","total") ; + + # foreach my $a (@ttlarr) { + # foreach my $b (@ttlarr2) { + # my $field_1 = "1_$b\_$a" ; + # my $field_2 = "2_$b\_$a" ; + # my $field = "$b\_$a" ; + # $i{$field} = qq~$i{$field_1};$i{$field_2}~ ; + # $ignore{$field_1} = 1 ; + # $ignore{$field_2} = 1 ; + # } + # } + + %y = () ; + for (1 .. 12) { + + $y{1}{$_} = "curr_amnt_" . "$_" . "_costing_additional_services"; + $y{2}{$_} = "curr_amnt_" . "$_" . "_costing_game_breakdown_analytics"; + $y{3}{$_} = "curr_amnt_" . "$_" . "_costing_hardware_add_ons"; + $y{4}{$_} = "curr_amnt_" . "$_" . "_costing_installation_kits"; + $y{5}{$_} = "curr_amnt_" . "$_" . "_costing_match_credits"; + $y{6}{$_} = "curr_amnt_" . "$_" . "_costing_other"; + $y{7}{$_} = "curr_amnt_" . "$_" . "_costing_rental"; + $y{8}{$_} = "curr_amnt_" . "$_" . "_costing_software_licence"; + $y{9}{$_} = "curr_amnt_" . "$_" . "_costing_systems"; + $y{10}{$_} = "excl_" . "$_" . "_costing_additional_services"; + $y{11}{$_} = "excl_" . "$_" . "_costing_game_breakdown_analytics"; + $y{12}{$_} = "excl_" . "$_" . "_costing_hardware_add_ons"; + $y{13}{$_} = "excl_" . "$_" . "_costing_installation_kits"; + $y{14}{$_} = "excl_" . "$_" . "_costing_match_credits"; + $y{15}{$_} = "excl_" . "$_" . "_costing_other"; + $y{16}{$_} = "excl_" . "$_" . "_costing_rental"; + $y{17}{$_} = "excl_" . "$_" . "_costing_software_licence"; + $y{18}{$_} = "excl_" . "$_" . "_costing_systems"; + $y{19}{$_} = "excl_" . "$_" . "_delivery_times"; + $y{20}{$_} = "excl_" . "$_" . "_notes"; + $y{21}{$_} = "excl_" . "$_" . "_payment_terms"; + $y{22}{$_} = "excl_" . "$_" . "_purchase_summary"; + $y{23}{$_} = "excl_" . "$_" . "_roes"; + $y{24}{$_} = "excl_" . "$_" . "_terms"; + $y{25}{$_} = "item_" . "$_" . "_costing_additional_services"; + $y{26}{$_} = "item_" . "$_" . "_costing_game_breakdown_analytics"; + $y{27}{$_} = "item_" . "$_" . "_costing_hardware_add_ons"; + $y{28}{$_} = "item_" . "$_" . "_costing_installation_kits"; + $y{29}{$_} = "item_" . "$_" . "_costing_match_credits"; + $y{30}{$_} = "item_" . "$_" . "_costing_other"; + $y{31}{$_} = "item_" . "$_" . "_costing_rental"; + $y{32}{$_} = "item_" . "$_" . "_costing_software_licence"; + $y{33}{$_} = "item_" . "$_" . "_costing_systems"; + $y{34}{$_} = "item_" . "$_" . "_purchase_summary"; + $y{35}{$_} = "item_ttl_" . "$_" . "_costing_additional_services"; + $y{36}{$_} = "item_ttl_" . "$_" . "_costing_game_breakdown_analytics"; + $y{37}{$_} = "item_ttl_" . "$_" . "_costing_hardware_add_ons"; + $y{38}{$_} = "item_ttl_" . "$_" . "_costing_installation_kits"; + $y{39}{$_} = "item_ttl_" . "$_" . "_costing_match_credits"; + $y{40}{$_} = "item_ttl_" . "$_" . "_costing_other"; + $y{41}{$_} = "item_ttl_" . "$_" . "_costing_rental"; + $y{42}{$_} = "item_ttl_" . "$_" . "_costing_software_licence"; + $y{43}{$_} = "item_ttl_" . "$_" . "_costing_systems"; + $y{44}{$_} = "qty_" . "$_" . "_costing_additional_services"; + $y{45}{$_} = "qty_" . "$_" . "_costing_game_breakdown_analytics"; + $y{46}{$_} = "qty_" . "$_" . "_costing_hardware_add_ons"; + $y{47}{$_} = "qty_" . "$_" . "_costing_installation_kits"; + $y{48}{$_} = "qty_" . "$_" . "_costing_match_credits"; + $y{49}{$_} = "qty_" . "$_" . "_costing_other"; + $y{50}{$_} = "qty_" . "$_" . "_costing_rental"; + $y{51}{$_} = "qty_" . "$_" . "_costing_software_licence"; + $y{52}{$_} = "qty_" . "$_" . "_costing_systems"; + $y{53}{$_} = "usd_amnt_" . "$_" . "_costing_additional_services"; + $y{54}{$_} = "usd_amnt_" . "$_" . "_costing_game_breakdown_analytics"; + $y{55}{$_} = "usd_amnt_" . "$_" . "_costing_hardware_add_ons"; + $y{56}{$_} = "usd_amnt_" . "$_" . "_costing_installation_kits"; + $y{57}{$_} = "usd_amnt_" . "$_" . "_costing_match_credits"; + $y{58}{$_} = "usd_amnt_" . "$_" . "_costing_other"; + $y{59}{$_} = "usd_amnt_" . "$_" . "_costing_rental"; + $y{60}{$_} = "usd_amnt_" . "$_" . "_costing_software_licence"; + $y{61}{$_} = "usd_amnt_" . "$_" . "_costing_systems"; + $y{62}{$_} = "vat_" . "$_" . "_costing_additional_services"; + $y{63}{$_} = "vat_" . "$_" . "_costing_game_breakdown_analytics"; + $y{64}{$_} = "vat_" . "$_" . "_costing_hardware_add_ons"; + $y{65}{$_} = "vat_" . "$_" . "_costing_installation_kits"; + $y{66}{$_} = "vat_" . "$_" . "_costing_match_credits"; + $y{67}{$_} = "vat_" . "$_" . "_costing_other"; + $y{68}{$_} = "vat_" . "$_" . "_costing_rental"; + $y{69}{$_} = "vat_" . "$_" . "_costing_software_licence"; + $y{70}{$_} = "vat_" . "$_" . "_costing_systems"; + + foreach my $a (keys %y){ + foreach my $b (keys %{$y{$a}}){ + $ignore{$y{$a}{$b}} = 1 ; + $x{$a}{$b} = $i{$y{$a}{$b}} ; + } + } + } + + + +} #------------------------------------------------------------------------------------------ + +sub new_table { + + # my ($insert_part) = @_ ; + $iid = $i{id} ; + %i = () ; + $i{id} = $iid ; + for (1 .. 12){ + + $i{curr_amnt_costing_additional_services} .= "$x{1}{$_};" ; + $i{curr_amnt_costing_game_breakdown_analytics} .= "$x{2}{$_};" ; + $i{curr_amnt_costing_hardware_add_ons} .= "$x{3}{$_};" ; + $i{curr_amnt_costing_installation_kits} .= "$x{4}{$_};" ; + $i{curr_amnt_costing_match_credits} .= "$x{5}{$_};" ; + $i{curr_amnt_costing_other} .= "$x{6}{$_};" ; + $i{curr_amnt_costing_rental} .= "$x{7}{$_};" ; + $i{curr_amnt_costing_software_licence} .= "$x{8}{$_};" ; + $i{curr_amnt_costing_systems} .= "$x{9}{$_};" ; + $i{excl_costing_additional_services} .= "$x{10}{$_};" ; + $i{excl_costing_game_breakdown_analytics} .= "$x{11}{$_};" ; + $i{excl_costing_hardware_add_ons} .= "$x{12}{$_};" ; + $i{excl_costing_installation_kits} .= "$x{13}{$_};" ; + $i{excl_costing_match_credits} .= "$x{14}{$_};" ; + $i{excl_costing_other} .= "$x{15}{$_};" ; + $i{excl_costing_rental} .= "$x{16}{$_};" ; + $i{excl_costing_software_licence} .= "$x{17}{$_};" ; + $i{excl_costing_systems} .= "$x{18}{$_};" ; + $i{excl_delivery_times} .= "$x{19}{$_};" ; + $i{excl_notes} .= "$x{20}{$_};" if $x{20}{$_}; + $i{excl_notes} .= "0;" if not $x{20}{$_}; + $i{excl_payment_terms} .= "$x{21}{$_};" ; + $i{excl_purchase_summary} .= "$x{22}{$_};" if $x{22}{$_}; + $i{excl_purchase_summary} .= "0;" if not $x{22}{$_}; + $i{excl_roes} .= "$x{23}{$_};" ; + $i{excl_terms} .= "$x{24}{$_};" ; + $i{item_costing_additional_services} .= "$x{25}{$_};" ; + $i{item_costing_game_breakdown_analytics} .= "$x{26}{$_};" ; + $i{item_costing_hardware_add_ons} .= "$x{27}{$_};" ; + $i{item_costing_installation_kits} .= "$x{28}{$_};" ; + $i{item_costing_match_credits} .= "$x{29}{$_};" ; + $i{item_costing_other} .= "$x{30}{$_};" ; + $i{item_costing_rental} .= "$x{31}{$_};" ; + $i{item_costing_software_licence} .= "$x{32}{$_};" ; + $i{item_costing_systems} .= "$x{33}{$_};" ; + $i{item_purchase_summary} .= "$x{34}{$_};" ; + $i{item_ttl_costing_additional_services} .= "$x{35}{$_};" ; + $i{item_ttl_costing_game_breakdown_analytics} .= "$x{36}{$_};" ; + $i{item_ttl_costing_hardware_add_ons} .= "$x{37}{$_};" ; + $i{item_ttl_costing_installation_kits} .= "$x{38}{$_};" ; + $i{item_ttl_costing_match_credits} .= "$x{39}{$_};" ; + $i{item_ttl_costing_other} .= "$x{40}{$_};" ; + $i{item_ttl_costing_rental} .= "$x{41}{$_};" ; + $i{item_ttl_costing_software_licence} .= "$x{42}{$_};" ; + $i{item_ttl_costing_systems} .= "$x{43}{$_};" ; + $i{qty_costing_additional_services} .= "$x{44}{$_};" ; + $i{qty_costing_game_breakdown_analytics} .= "$x{45}{$_};" ; + $i{qty_costing_hardware_add_ons} .= "$x{46}{$_};" ; + $i{qty_costing_installation_kits} .= "$x{47}{$_};" ; + $i{qty_costing_match_credits} .= "$x{48}{$_};" ; + $i{qty_costing_other} .= "$x{49}{$_};" ; + $i{qty_costing_rental} .= "$x{50}{$_};" ; + $i{qty_costing_software_licence} .= "$x{51}{$_};" ; + $i{qty_costing_systems} .= "$x{52}{$_};" ; + $i{usd_amnt_costing_additional_services} .= "$x{53}{$_};" ; + $i{usd_amnt_costing_game_breakdown_analytics} .= "$x{54}{$_};" ; + $i{usd_amnt_costing_hardware_add_ons} .= "$x{55}{$_};" ; + $i{usd_amnt_costing_installation_kits} .= "$x{56}{$_};" ; + $i{usd_amnt_costing_match_credits} .= "$x{57}{$_};" ; + $i{usd_amnt_costing_other} .= "$x{58}{$_};" ; + $i{usd_amnt_costing_rental} .= "$x{59}{$_};" ; + $i{usd_amnt_costing_software_licence} .= "$x{60}{$_};" ; + $i{usd_amnt_costing_systems} .= "$x{61}{$_};" ; + $i{vat_costing_additional_services} .= "$x{62}{$_};" ; + $i{vat_costing_game_breakdown_analytics} .= "$x{63}{$_};" ; + $i{vat_costing_hardware_add_ons} .= "$x{64}{$_};" ; + $i{vat_costing_installation_kits} .= "$x{65}{$_};" ; + $i{vat_costing_match_credits} .= "$x{66}{$_};" ; + $i{vat_costing_other} .= "$x{67}{$_};" ; + $i{vat_costing_rental} .= "$x{68}{$_};" ; + $i{vat_costing_software_licence} .= "$x{69}{$_};" ; + $i{vat_costing_systems} .= "$x{70}{$_};" ; + + } + # if ($insert_part){ + # $sql_insert_1 = qq~INSERT INTO `quotes_min` (~ ; + # $sql_insert_2 = qq~VALUES (~ ; + # } + foreach (keys %i){ + next if $_ eq 'id' ; + chop $i{$_} ; + # if ($insert_part){ + # $sql_insert_1 .= qq~$_,~ ; + # $sql_insert_2 .= qq~'$i{$_}',~ ; + # } + } + # if ($insert_part){ + # chop $sql_insert_1 ; + # chop $sql_insert_2 ; + # $sql_insert_2 .= qq~) ;~ ; + # $final_insert = $sql_insert_1 . $sql_insert_2 ; + # &db_min_upd_raw($final_insert) ; + # } +} #------------------------------------------------------------------------------------------ + + +sub update_camera { + + # &common_debug("1. update_camera : $i{quote_nr}"); + unless ($i{quote_nr}) { $error = qq~NO QUOTE NR~ ; return ; } # &common_debug("update_camera : $error"); + + $q{quote_nr} = $i{quote_nr} ; + # $q{quote_ref} = $i{ref} ; + $q{id} = $i{id} ; + + %i=(); + + $i{quote_delivery_date} = NULL ; + $i{quote_active_date} = NULL ; + $i{quote_ew_date_from} = NULL ; + $i{quote_ew_date_to} = NULL ; + $i{quote_cam_desc} = NULL ; + $i{quote_cam_excl} = 0 ; + $i{quote_cam_num} = 0 ; + $i{quote_nr} = 0 ; + $i{quote_ref} = NULL ; + + # &db_min_ro('cameras','*',"quote_nr='$q{quote_nr}'",'','') ; # &db_min_ro('quotes','*','','','') ; + + &db_min_upd('cameras',"quote_nr='$q{quote_nr}'") ; # remove all previous links to this quote + + # $i{quote_nr} = $q{quote_nr} ; + # $i{quote_ref} = $q{quote_ref} ; + + for (1 .. $camera_cnt_allowed) { + # &common_debug("$_. camera_nr_$_\_camera_details [".$q{"camera_nr_$_\_camera_details"}."]"); + + next unless $q{"camera_nr_$_\_camera_details"} ; + + %i=(); + + $i{quote_nr} = $q{quote_nr} ; + $i{quote_delivery_date} = $q{"delivery_date_$_\_camera_details"} if $q{"delivery_date_$_\_camera_details"} ; + $i{quote_active_date} = $q{"active_date_$_\_camera_details"} if $q{"active_date_$_\_camera_details"} ; + $i{quote_ew_date_from} = $q{"ew_date_from_$_\_camera_details"} if $q{"ew_date_from_$_\_camera_details"} ; + $i{quote_ew_date_to} = $q{"ew_date_to_$_\_camera_details"} if $q{"ew_date_to_$_\_camera_details"} ; + $i{quote_cam_desc} = $q{"description_$_\_camera_details"} if $q{"description_$_\_camera_details"} ; + $i{quote_cam_excl} = $q{"excl_$_\_camera_details"} if $q{"excl_$_\_camera_details"} ; + $i{quote_cam_num} = $_ if $_ ; + $i{quote_ref} = $q{"ref_$_\_camera_details"} if $q{"ref_$_\_camera_details"} ; + + my @valarr = split(/\:/,$q{"camera_nr_$_\_camera_details"}) ; # $id:camera_nr:camera_system_id:serial_nr:date_delivered:camera_system:item_code:date_active + + my $abrv_cam_system = substr($valarr[1],0,3); + # &common_debug("[".$q{"camera_nr_$_\_camera_details"}."] abrv_cam_system=$abrv_cam_system, abrv_prev_cam_system=$abrv_prev_cam_system, prev_cam_nr=$prev_cam_nr, link to: c_excl_$_\_camera_details") ; + if ($abrv_cam_system eq 'VPU' and ($abrv_prev_cam_system eq 'S1' or $abrv_prev_cam_system eq 'S2' or $abrv_prev_cam_system_other eq 'Prime' or $abrv_prev_cam_system_other eq 'Coach')) { + # $trigger_jquery .= qq~\$("#c_excl_$_\_camera_details").append("");\$('[data-toggle="tooltip"]').tooltip({html:true}) ;~; + my $s1_cnt = $_-1; + $i{quote_linked_vpu} = $q{"serial_nr_$s1_cnt\_camera_details"} if $q{"serial_nr_$s1_cnt\_camera_details"} ; + } + $abrv_prev_cam_system = substr($abrv_cam_system,0,2); + $abrv_prev_cam_system_other = substr($abrv_cam_system,0,5); + $prev_cam_nr = $valarr[1] ; + + my $cam_id = $valarr[0] ; + next unless $cam_id ; + + &db_min_upd('cameras',"id='$cam_id'") ; # add the new details from the screen + + # $i{quote_linked_vpu} = '' ; + } + + $i{id} = $q{id} ; + +} #------------------------------------------------------------------------------------------ + +sub duplicate { + +unless ($i{id}) { $error = qq~NO ID~ ; return ; } + +local $copy_id = $i{id} ; + +&db_min_copy($table,$copy_id) ; + +&db_min_copy('quotes_min',$copy_id) ; + +&common_min_copy_files("$htmlpath/uploads/workings/$copy_id","$htmlpath/uploads/workings/$i{id}") ; + +} #------------------------------------------------------------------------------------------ + +sub delete { + +my $dbid = 'id' ; if ($uniq_id) { $dbid = $uniq_id ; } + +unless ($i{$dbid}) { $error = uc "NO $dbid" ; return ; } + +&db_min_delete('quotes',"$dbid='$i{$dbid}'") ; + +&db_min_delete('quotes_min',"$dbid='$i{$dbid}'") ; + +&common_min_delete_files("$htmlpath/uploads/workings/$i{$dbid}") ; + +}#------------------------------------------------------------------------------------------ + +sub process_upload_ifields { + +foreach (keys %uploads_file) { $i{$_} = $uploads_file{$_} ; $ignore{$_} = '' ; } + +} #------------------------------------------------------------------------------------------ + +sub set_default_i_vals { + +my @camera_details = ('camera_nr_','serial_nr_','description_','active_date_','delivery_date_','ew_date_from_','ew_date_to_','ref_','excl_') ; + + + +for (1 .. $camera_cnt_allowed) { + foreach my $cdet_ (@camera_details) { + my $col = "$cdet_$_\_camera_details"; + $ignore{$col} = 1 ; # set the value to only be the id + $q{$col} = $i{$col} ; # set the value to only be the id + } +} + +my $srch_where_sql = "`id`='$i{id}'" ; + +$iaction eq 'save' ? &db_min_ro($table,'*','','id DESC',1) : &db_min_ro($table,'*',$srch_where_sql,'','') ; + +foreach (sort { $col_name{$a} cmp $col_name{$b} } keys %col_name) { + $col = $col_name{$_} ; + + &common_min_debug("1. [$col] [$i{$col}]"); + + if (substr($col,0,4) eq 'vat_' or substr($col,0,5) eq 'excl_' or substr($col,0,4) eq 'qty_') { + unless ($i{$col}) { $i{$col} = 0 ; } + } # only create the column if it doesn't exist + + if (substr($col,0,9) eq 'usd_amnt_' or substr($col,0,10) eq 'curr_amnt_' or substr($col,0,9) eq 'item_ttl_' or substr($col,-6,6) eq '_total') { + unless ($i{$col}) { $i{$col} = '0.00' ; } + } + + # # if (substr($col,0,14) eq 'delivery_date_' or substr($col,0,12) eq 'active_date_') { + # if (substr($col,0,14) eq 'delivery_date_' or substr($col,0,12) eq 'active_date_' or substr($col,0,8) eq 'ew_date_') { + # unless ($i{$col}) { $i{$col} = NULL ; } + # } + + # if ((substr($col,6,9) eq '_costing_' and substr($col,0,5) eq 'item_' and $i{$col}) or ($col eq 'quote_to' and $i{$col}) or (substr($col,-15,15) eq '_camera_details' and substr($col,0,10) eq 'camera_nr_' and $i{$col})) { + # if ((substr($col,6,9) eq '_costing_' and substr($col,0,5) eq 'item_' and $i{$col}) or ($col eq 'quote_to' and $i{$col})) { + if (((substr($col,6,9) eq '_costing_' or substr($col,7,9) eq '_costing_') and substr($col,0,5) eq 'item_' and $i{$col}) or ($col eq 'quote_to' and $i{$col})) { # item_1_costing_match_credits + my @valarr = split(/\:/,$i{$col}) ; + $i{$col} = $valarr[0] ; # set the value to only be the id + } + + # if (substr($col,-15,15) eq '_camera_details') { + # # if (substr($col,0,9) eq 'camera_nr') { + # # my @valarr = split(/\:/,$i{$col}) ; + # # $q{$col} = $i{$col} ; # set the value to only be the id + # # $i{$col} = $valarr[0] ; # set the value to only be the id + # # } elsif (substr($col,0,5) eq 'excl_') { + # # # do nothing + # # } else { + # $ignore{$col} = 1 ; # set the value to only be the id + # $q{$col} = $i{$col} ; # set the value to only be the id + # # } + # } + + # &common_min_debug("2. [$col] [$i{$col}]"); +} + +$i{terms} = 0 unless $i{terms} ; +$i{quote_accepted} = 0 unless $i{quote_accepted} ; +$i{quote_pending} = 0 unless $i{quote_pending} ; +$i{quote_cancelled} = 0 unless $i{quote_cancelled} ; +$i{annual_invoice} = 0 unless $i{annual_invoice} ; +$i{period} = 0 unless $i{period} ; +$i{max_cams} = 0 unless $i{max_cams} ; +$ignore{invoice_date} = 1 unless length($i{invoice_date}) == 10 ; + +} #---------------------------------------------------------------------------------------- + +sub list_screen { + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + # my $tables = 'towns,airport_codes' ; + + # &db_min_ro($tables,'towns.id,towns.airport_code,airport_codes.name,towns.name','towns.airport_code=airport_codes.iata_code','','') ; + # foreach my $id (keys %{$db{$tables}}) { $user{$id} = $db{$tables}{$id}{name} ; } + + # &db_min_ro('users','id,name','','','') ; + # foreach my $id (keys %{$db{users}}) { $user{$id} = $db{users}{$id}{name} ; } + + # &db_min_ro('customers','id,name','','','') ; + # foreach my $id (keys %{$db{customers}}) { $customers{$id} = $db{customers}{$id}{name} ; } + + # &db_min_ro('camera_systems','*','','','') ; + # foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + + # &db_min_ro('countries','*','','','') ; + # foreach my $id (keys %{$db{countries}}) { $country{$id} = $db{countries}{$id}{name} ; } + + if ($iaction eq 'accepted' or $i{options} eq 'accepted') { push @report_sql, "$table.quote_accepted='1'" ; } + if ($iaction eq 'closed' or $i{options} eq 'closed') { push @report_sql, "($table.quote_cancelled='1' OR ($table.quote_expiry<'$now_year-$now_mm-$now_dd' AND $table.quote_accepted<>'1'))" ; } + if ($iaction eq 'pending' or $i{options} eq 'pending') { push @report_sql, "$table.quote_pending='1'" ; } + if ($iaction eq 'list' or $i{options} eq 'list') { push @report_sql, "$table.quote_cancelled<>'1'" ; } + + my $t1 = $table ; + my $t2 = 'countries' ; + my $t3 = 'camera_systems' ; + my $t4 = 'customers' ; + our $tables = "$t1,$t2,$t3,$t4" ; + + push @report_sql, "($t1.country_shipped=$t2.id)" ; + push @report_sql, "($t1.camera_system_id=$t3.id)" ; + push @report_sql, "($t1.quote_to=$t4.id)" ; + + my $srch_where_sql = join(' AND ', @report_sql) ; + + &db_min_ro($tables,"$t1.id AS 'quote_id',$t1.quote_nr,$t1.ref,$t1.qty,$t1.quote_expiry,$t1.quote_to,$t1.invoice_nr,$t1.quote_date,$t1.type,$t1.currency,$t1.country_shipped,$t1.total_1_purchase_summary,$t1.total_2_purchase_summary,$t1.total_3_purchase_summary,$t1.quote_cancelled,$t1.quote_accepted,$t1.quote_pending,$t1.activetab,$t2.name AS 'country',$t3.name AS 'camera_system',$t4.name AS 'customer'",$srch_where_sql,'','') ; + + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +&tab_hash ; # load for PDF links + +# &common_load_quote_vars("cameras.quote_nr>0 AND cameras.quote_cam_num='1' AND (cameras.quote_delivery_date IS NOT NULL or cameras.quote_active_date IS NOT NULL) AND cameras.quote_nr=quotes.quote_nr"); +&common_load_quote_vars("cameras.quote_nr>0 AND cameras.quote_nr=quotes.quote_nr"); + + +# foreach (keys %quote_cam_delivery_date) { + # $store_quote_cam_delivery_date{$_}{1} = $quote_cam_delivery_date{$_}{1} ; +# } + +# foreach (keys %quote_cam_delivery_date) { + # $store_quote_cam_active_date{$_}{1} = $quote_cam_active_date{$_}{1} ; +# } + +"e_list ; # load for PDF links + +# our $fnsort = 1 ; # used &common_min_screen3 for fnsort column &common_min_table + +if ($iaction eq 'update' or $iaction eq 'save'){ + &common_min_extra_crumb("list-$lcpage\s","List $ucfirstpage\s") ; +} + +} #------------------------------------------------------------------------------------------ + +sub quote_list { + +our @sql_col_display = ("nr","date","customer","ref","country","camera_system_id","qty","curr","amount","invoice_nr","type","date_delivered","date_active","flag","") ; + +if ($i{export_to_excel}) { &report_xls_export_header("Quotes",'quotes') ; } + +# &common_min_debug("[$table]"); + +our $open_new_tab = qq~target="_blank"~ ; + +foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) { + + # &common_min_debug("[$id] [$tables] [$db{$tables}{$id}{quote_nr} ]"); + + unless ($id) { next ; } + + our $quote_expiry = $db{$tables}{$id}{quote_expiry} ; $quote_expiry =~ s/\-//iog ; + # my $quote_date = $db{$tables}{$id}{quote_date} ; $quote_date =~ s/\-//iog ; + # if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all') { next ; } + + # $yr = substr($quote_date, 0, 4) ; + # $mm = substr($quote_date, 4, 2) ; + # $dd = substr($quote_date, 6, 2) ; + + # my ($yr2,$mm2,$dd2) = Add_Delta_Days($yr,$mm,$dd,60); # + + # $mm2 = sprintf("%02s", $mm2) ; + # $dd2 = sprintf("%02s", $dd2) ; + + # $quote_date = "$yr2$mm2$dd2" ; + + # if ($quote_date and $quote_date<"$now_year$now_mm$now_dd" and $db{$tables}{$id}{quote_accepted}!=1 and + # $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all' and + # $i{options} ne 'accepted' and $i{options} ne 'closed' and $i{options} ne 'all') + # { next ; } + + if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $db{$tables}{$id}{quote_accepted}!=1 and + $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all' and + $i{options} ne 'accepted' and $i{options} ne 'closed' and $i{options} ne 'all') + { next ; } + # &common_min_debug("[$id] [$tables] [$db{$tables}{$id}{quote_nr} ]"); + + $print_tbody .= qq~~ ; + + $xlscol=0; + + my $quote_nr = $db{$tables}{$id}{quote_nr} ; + + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$tables}{$id}{$_} ; + my $align = '' ; my $nowrap = '' ; + + if ($_ eq 'ref') { $nowrap = 'nowrap' ; ; } + if ($_ eq 'customer') { $val = $db{$tables}{$id}{customer} ; $nowrap = 'nowrap' ; ; } + if ($_ eq 'date') { $val = $db{$tables}{$id}{quote_date} ; } + if ($_ eq 'date_delivered') { $val = $quote_cam_delivery_date{$quote_nr}{1} ; $align = qq~ class="dt-center"~ ; } + if ($_ eq 'date_active') { $val = $quote_cam_active_date{$quote_nr}{1} ; $align = qq~ class="dt-center"~ ; } + if ($_ eq 'type') { $val = ucfirst $db{$tables}{$id}{type} ; $align = qq~ class="dt-center"~ ; } + if ($_ eq 'camera_system_id') { $val = $db{$tables}{$id}{camera_system} ; } + if ($_ eq 'curr') { $val = $db{$tables}{$id}{currency} ; $align = qq~ class="dt-center"~ ; } + if ($_ eq 'country') { $val = $db{$tables}{$id}{country} ; } + # if ($_ eq 'qty') { $val = $cnt_cams{$quote_nr} ; } + if ($_ eq 'qty') { $val = $db{$tables}{$id}{qty} ; $val = '' if $val==0; $align = qq~ class="dt-center"~ ; } + if ($_ eq 'currency') { $align = qq~ class="dt-center"~ ; } + + if ($_ eq 'amount') { + my $ttl = sprintf("%0.2f",($db{$tables}{$id}{total_1_purchase_summary} + $db{$tables}{$id}{total_2_purchase_summary} + $db{$tables}{$id}{total_3_purchase_summary})) ; + $val = &common_commify($ttl) ; + $align = qq~ class="dt-right"~ ; + } + + if ($_ eq 'nr') { + + $val = &common_min_get_quote_button($id,$tables) ; + + # my $class = 'info' ; + # if ($db{$tables}{$id}{quote_cancelled}) { + # $class = 'danger' ; + # } elsif ($db{$tables}{$id}{quote_accepted}) { + # $class = 'success' ; + # } elsif ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd") { + # $class = 'danger' ; + # } elsif ($db{$tables}{$id}{quote_pending}) { + # $class = 'warning' ; + # } + # $val = qq~$quote_nr~ ; + } + + if ($i{export_to_excel}) { + &report_xls_export_process_cell('','',$val) ; # ------------------------------------------------------------------------- HTML AFTER + $xlscol++; + } + + $print_tbody .= qq~$val~ ; + } + + my $delete_butt = '' ; my $edit_butt = '' ; + + my $quote_nr = $quote_nr ; $quote_nr =~ s/'//iog; unless ($quote_nr) { $quote_nr = $id ; } + + # if ($useropts{boss}{$username} or $useropts{super}{$username}) { } + + $edit_butt = qq~~ ; + $delete_butt = qq~~ ; + $copy_butt = qq~~; + $pdf_butt = qq~~; + + $print_tbody .= qq~ $edit_butt $copy_butt $delete_butt $pdf_butt~ ; + if ($i{export_to_excel}) { $xlsrow++ ; } +} + +if ($i{export_to_excel}) { &report_xls_export_footer('L',15,'quotes') ; } + +# $fnsortcol = 8 ; # order by ol devices col + +$print_more_boxes .= qq~


    ~ ; + +&common_min_extra_crumb("search-$lcpage\s","Search Screen") ; + +} #------------------------------------------------------------------------------- + +sub thead { + +&common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub add_db_fields { + +&hidden_fields ; + +$hidden{id} = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + +&hidden_fields ; + +$hidden{id} = 1 ; +# $readonly{ref} = 'READONLY' ; + +} #------------------------------------------------------------------------------------------ + +sub hidden_fields { + +$ignore{iattachcosting_delivery_note} = 1 ; +$ignore{iattachcosting_other_1} = 1 ; +$ignore{iattachcosting_other_2} = 1 ; +$ignore{iattachcosting_other_3} = 1 ; +$ignore{iattachcosting_photos} = 1 ; +$ignore{iattachcosting_po} = 1 ; +$ignore{iattachcosting_signed_quote} = 1 ; +$ignore{iattachcosting_sla} = 1 ; +$ignore{iattachcosting_t_cs} = 1 ; +$ignore{date_to} = 1 ; +$ignore{date_from} = 1 ; + +$ignore{iaction} = 1 ; +$required{qty} = 4 ; # number +$required{quote_to} = 1 ; +$required{quote_nr} = 1 ; +$readonly{quote_nr} = 'READONLY' ; +$required{currency} = 1 ; +$required{roe} = 1 ; +$required{period} = 1 ; +$required{max_cams} = 1 ; +$hidden{quote_date} = 2 ; +$hidden{last_update} = 2 ; +$hidden{user_id} = 2 ; +$hidden{datetime} = 2 ; + +$ignore{saveandexit} = 1 ; + +$trigger_jquery_raw .= qq~var curr_changed=0;~; +$trigger_jquery_raw .= qq~\$.validate();~; + +$extra_js .= qq~~; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + +&db_open_ro; +$db_ignore_open_close=1; + + $selected{max_cams}{10} = 'SELECTED'; + &select_opts('') ; + %col_name = () ; + &db_min_ro($table,'*',"id > 1 AND id < 10",'','') ; + $page_title = substr($page_title,0,-1) ; + $db{$table}{''}{quote_nr} = &db_min_get_max($table,'quote_nr') ; + $db{$table}{''}{qty} = 0 ; + + # if ($username eq 'rory') { $db{$table}{''}{quote_nr} = 1000 ; } + + &add_db_fields ; + &build_boxes('','save') ; + +$db_ignore_open_close=0; +&db_close_conn; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + +unless ($i{id}) { $warning = qq(NO ID) ; return ; } + +&db_open_ro; +$db_ignore_open_close=1; + + # DO NOT DELETE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ---------------------------------------------------------------------- + #transfer data from event_quotes to event_quotes_min + + # &common_debug("DELETE FROM quotes_min WHERE id != 203 ") ; + # &common_debug("") ; + # $sql_insert = "INSERT INTO quotes_min ( + # id, + + # curr_amnt_costing_additional_services , + # curr_amnt_costing_game_breakdown_analytics , + # curr_amnt_costing_hardware_add_ons , + # curr_amnt_costing_installation_kits , + # curr_amnt_costing_match_credits, + # curr_amnt_costing_other , + # curr_amnt_costing_rental , + # curr_amnt_costing_software_licence , + # curr_amnt_costing_systems , + + # excl_costing_additional_services , + # excl_costing_game_breakdown_analytics , + # excl_costing_hardware_add_ons , + # excl_costing_installation_kits , + # excl_costing_match_credits , + # excl_costing_other, + # excl_costing_rental , + # excl_costing_software_licence , + # excl_costing_systems , + # excl_delivery_times, + # excl_notes, + # excl_payment_terms , + # excl_purchase_summary , + # excl_roes , + # excl_terms , + + # item_costing_additional_services, + # item_costing_game_breakdown_analytics, + # item_costing_hardware_add_ons, + # item_costing_installation_kits, + # item_costing_match_credits, + # item_costing_other, + # item_costing_rental, + # item_costing_software_licence, + # item_costing_systems, + # item_purchase_summary , + + # item_ttl_costing_additional_services, + # item_ttl_costing_game_breakdown_analytics, + # item_ttl_costing_hardware_add_ons, + # item_ttl_costing_installation_kits, + # item_ttl_costing_match_credits, + # item_ttl_costing_other, + # item_ttl_costing_rental, + # item_ttl_costing_software_licence, + # item_ttl_costing_systems, + + # qty_costing_additional_services, + # qty_costing_game_breakdown_analytics, + # qty_costing_hardware_add_ons, + # qty_costing_installation_kits, + # qty_costing_match_credits, + # qty_costing_other, + # qty_costing_rental, + # qty_costing_software_licence, + # qty_costing_systems, + + # usd_amnt_costing_additional_services, + # usd_amnt_costing_game_breakdown_analytics, + # usd_amnt_costing_hardware_add_ons, + # usd_amnt_costing_installation_kits, + # usd_amnt_costing_match_credits, + # usd_amnt_costing_other, + # usd_amnt_costing_rental, + # usd_amnt_costing_software_licence, + # usd_amnt_costing_systems, + + # vat_costing_additional_services, + # vat_costing_game_breakdown_analytics, + # vat_costing_hardware_add_ons, + # vat_costing_installation_kits, + # vat_costing_match_credits, + # vat_costing_other, + # vat_costing_rental, + # vat_costing_software_licence, + # vat_costing_systems + # ) VALUES " ; + + # $sql_select = "" ; + # %concat = () ; + # for (1 .. 12){ + # $concat{20} .= "excl_" . "$_" . "_notes,';',"; + # } + + # for (1 .. 7){ + # $concat{1} .= "curr_amnt_" . "$_" . "_costing_additional_services,';',"; + # $concat{3} .= "curr_amnt_" . "$_" . "_costing_hardware_add_ons,';',"; + # $concat{4} .= "curr_amnt_" . "$_" . "_costing_installation_kits,';',"; + # $concat{10} .= "excl_" . "$_" . "_costing_additional_services,';',"; + # $concat{12} .= "excl_" . "$_" . "_costing_hardware_add_ons,';',"; + # $concat{13} .= "excl_" . "$_" . "_costing_installation_kits,';',"; + # $concat{25} .= "item_" . "$_" . "_costing_additional_services,';',"; + # $concat{27} .= "item_" . "$_" . "_costing_hardware_add_ons,';',"; + # $concat{28} .= "item_" . "$_" . "_costing_installation_kits,';',"; + # $concat{35} .= "item_ttl_" . "$_" . "_costing_additional_services,';',"; + # $concat{37} .= "item_ttl_" . "$_" . "_costing_hardware_add_ons,';',"; + # $concat{38} .= "item_ttl_" . "$_" . "_costing_installation_kits,';',"; + # $concat{44} .= "qty_" . "$_" . "_costing_additional_services,';',"; + # $concat{46} .= "qty_" . "$_" . "_costing_hardware_add_ons,';',"; + # $concat{47} .= "qty_" . "$_" . "_costing_installation_kits,';',"; + # $concat{53} .= "usd_amnt_" . "$_" . "_costing_additional_services,';',"; + # $concat{55} .= "usd_amnt_" . "$_" . "_costing_hardware_add_ons,';',"; + # $concat{56} .= "usd_amnt_" . "$_" . "_costing_installation_kits,';',"; + # $concat{62} .= "vat_" . "$_" . "_costing_additional_services,';',"; + # $concat{64} .= "vat_" . "$_" . "_costing_hardware_add_ons,';',"; + # $concat{65} .= "vat_" . "$_" . "_costing_installation_kits,';',"; + + # } + # for (1 .. 6){ + # $concat{21} .= "excl_" . "$_" . "_payment_terms,';',"; + # $concat{23} .= "excl_" . "$_" . "_roes,';',"; + + # } + # for (1 .. 5){ + # $concat{6} .= "curr_amnt_" . "$_" . "_costing_other,';',"; + # $concat{15} .= "excl_" . "$_" . "_costing_other,';',"; + # $concat{30} .= "item_" . "$_" . "_costing_other,';',"; + # $concat{40} .= "item_ttl_" . "$_" . "_costing_other,';',"; + # $concat{49} .= "qty_" . "$_" . "_costing_other,';',"; + # $concat{58} .= "usd_amnt_" . "$_" . "_costing_other,';',"; + # $concat{67} .= "vat_" . "$_" . "_costing_other,';',"; + # } + # for (1 .. 4){ + # $concat{5} .= "curr_amnt_" . "$_" . "_costing_match_credits,';',"; + # $concat{14} .= "excl_" . "$_" . "_costing_match_credits,';',"; + # $concat{19} .= "excl_" . "$_" . "_delivery_times,';',"; + # $concat{29} .= "item_" . "$_" . "_costing_match_credits,';',"; + # $concat{39} .= "item_ttl_" . "$_" . "_costing_match_credits,';',"; + # $concat{48} .= "qty_" . "$_" . "_costing_match_credits,';',"; + # $concat{57} .= "usd_amnt_" . "$_" . "_costing_match_credits,';',"; + # $concat{66} .= "vat_" . "$_" . "_costing_match_credits,';',"; + # } + # for (1 .. 3){ + # $concat{8} .= "curr_amnt_" . "$_" . "_costing_software_licence,';',"; + # $concat{9} .= "curr_amnt_" . "$_" . "_costing_systems,';',"; + # $concat{17} .= "excl_" . "$_" . "_costing_software_licence,';',"; + # $concat{18} .= "excl_" . "$_" . "_costing_systems,';',"; + # $concat{22} .= "excl_" . "$_" . "_purchase_summary,';',"; + # $concat{32} .= "item_" . "$_" . "_costing_software_licence,';',"; + # $concat{33} .= "item_" . "$_" . "_costing_systems,';',"; + # $concat{34} .= "item_" . "$_" . "_purchase_summary,';',"; + # $concat{42} .= "item_ttl_" . "$_" . "_costing_software_licence,';',"; + # $concat{43} .= "item_ttl_" . "$_" . "_costing_systems,';',"; + # $concat{51} .= "qty_" . "$_" . "_costing_software_licence,';',"; + # $concat{52} .= "qty_" . "$_" . "_costing_systems,';',"; + # $concat{60} .= "usd_amnt_" . "$_" . "_costing_software_licence,';',"; + # $concat{61} .= "usd_amnt_" . "$_" . "_costing_systems,';',"; + # $concat{69} .= "vat_" . "$_" . "_costing_software_licence,';',"; + # $concat{70} .= "vat_" . "$_" . "_costing_systems,';',"; + # } + # for (1 .. 2){ + # $concat{2} .= "curr_amnt_" . "$_" . "_costing_game_breakdown_analytics,';',"; + # $concat{7} .= "curr_amnt_" . "$_" . "_costing_rental,';',"; + # $concat{11} .= "excl_" . "$_" . "_costing_game_breakdown_analytics,';',"; + # $concat{16} .= "excl_" . "$_" . "_costing_rental,';',"; + # $concat{26} .= "item_" . "$_" . "_costing_game_breakdown_analytics,';',"; + # $concat{31} .= "item_" . "$_" . "_costing_rental,';',"; + # $concat{36} .= "item_ttl_" . "$_" . "_costing_game_breakdown_analytics,';',"; + # $concat{41} .= "item_ttl_" . "$_" . "_costing_rental,';',"; + # $concat{45} .= "qty_" . "$_" . "_costing_game_breakdown_analytics,';',"; + # $concat{50} .= "qty_" . "$_" . "_costing_rental,';',"; + # $concat{54} .= "usd_amnt_" . "$_" . "_costing_game_breakdown_analytics,';',"; + # $concat{59} .= "usd_amnt_" . "$_" . "_costing_rental,';',"; + # $concat{63} .= "vat_" . "$_" . "_costing_game_breakdown_analytics,';',"; + # $concat{68} .= "vat_" . "$_" . "_costing_rental,';',"; + # } + + # for (1 .. 1){ + # $concat{24} .= "excl_" . "$_" . "_terms,';',"; + # } + + # for (1 .. 70){ + # chop $concat{$_} ; + # chop $concat{$_} ; + # chop $concat{$_} ; + # chop $concat{$_} ; + # chop $concat{$_} ; + # $sql_select .= "concat($concat{$_}) AS 'concat_$_'," ; + # } + # chop $sql_select ; + + # &db_min_ro('quotes',"id, $sql_select","",'','') ; + # foreach my $iid (sort keys %{$db{quotes}}){ + # next if $iid == 203 ; + # $sql_insert .= "($iid" ; + # for (1 .. 70){ + # $c = "concat_" . "$_" ; + # $sql_insert .= qq(,'$db{quotes}{$iid}{$c}') ; + # } + # $sql_insert .= ")," ; + # } + + # chop $sql_insert ; + # $sql_insert .= ";" ; + # &common_debug("TRANSFER DATA: $sql_insert") ; + + #---------------------------------------------------------------------------- + + &db_min_ro('quotes_pdf_titles','*',"quote_id='$i{id}'",'','') ; + &db_min_ro('quotes_min','*',"id='$i{id}'",'','') ; + # unless ($iaction eq 'save' or $iaction eq 'update') { + &db_min_ro($table,'*',"id='$i{id}'",'','') ; + # } + + $max_cams = $db{$table}{$i{id}}{max_cams} if $db{$table}{$i{id}}{max_cams} ; + + $page_title = substr($page_title,0,-1) ; + $page_title .= " : $i{id}" ; + + # our $open_new_tab = qq(target="_blank") ; # opens booking page in a new tab + &common_min_footer('id',"$lcpage\s"); + + &edit_db_fields ; + + $selected{max_cams}{$db{$table}{$i{id}}{max_cams}} = 'SELECTED'; + + &select_opts($i{id}) ; + + our $saveandexit = 1 ; + + &build_boxes($i{id},'update') ; + +$db_ignore_open_close=0; +&db_close_conn; + +&common_min_extra_crumb("search-$lcpage\s","Search $ucfirstpage\s") ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes { + +my ($id,$action) = @_ ; + +our @jquery_trigger_fields = () ; our @jquery_custom_vat_ids = () ; our @jquery_duty_ids = () ; + +push @jquery_trigger_fields, 'inputRoe' ; +push @jquery_trigger_fields, 'selectPeriod' ; +# push @jquery_trigger_fields, 'selectDiscount' ; + +&tab_curr_symbols; + +foreach $col(keys %required) { + &common_min_forms_required ; + } + +&tabs_get_default_totals($id) ; + +our $tab_cnt = 0 ; + +$print_box_content_rows .= &common_min_forms_start($table) ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq(
    ) ; + &build_boxes_top($id); + $print_box_content_rows .= qq(
    ) ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq(
    ) ; + + &tab_cnt; + + $print_box_content_rows .= qq(
    + +
    ); + + our %tab_sections = () ; + + foreach (sort {$a <=> $b} keys %cntxt) { + my $tab_name = &tab_names($_) ; my $active = '' ; + + if (($_==1) and ($db{$table}{$id}{activetab} eq '')) { + $active = 'active' ; + } elsif ($db{$table}{$id}{activetab} eq $tab_name) { + $active = 'active' ; + } + + my $colsleft = 12 ; my $showright = '' ; + + if ($cntxt{$_} eq 'one' or $cntxt{$_} eq 'seven') { + $colsleft = 6 ; $showright = 1 ; + } + + # &common_min_debug("activetab [$tab_name] $active "); + + $print_box_content_rows .= qq~
    ~; + + $print_box_content_rows .= qq~
    ~ ; + + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_left($id,$_); + $print_box_content_rows .= qq~
    ~ ; + + if ($showright) { + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_right($id,$_); + $print_box_content_rows .= qq~
    ~ ; + } + + $print_box_content_rows .= qq~
    ~ ; + + $print_box_content_rows .= qq~
    ~ ; + + $print_box_content_rows .= qq~
    ~ ; + + if ($id) { + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~~; + # # if ($username eq 'rory') { $print_box_content_rows .= qq~ ~; } + # if ($username eq 'rory' or $username eq 'handre') { $print_box_content_rows .= qq~ ~; } + # # $print_box_content_rows .= qq~ ~; + $print_box_content_rows .= &common_min_box_foot; + } + + $print_box_content_rows .= qq~
    ~ ; + + $print_box_content_rows .= qq~
    ~ ; + + $print_box_content_rows .= qq~
    ~ ; + } + + $print_box_content_rows .= qq( +
    +
    + ) ; + + $print_box_content_rows .= qq(
    ) ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq(
    ) ; + &build_boxes_bottom($id); + $print_box_content_rows .= qq(
    ) ; + + #-------------------------------------------------------------------------- + +$print_box_content_rows .= &common_min_forms_end($id,$table,$action,$skip) ; + +my $jquery_trigger_ids = '#' . join(",#",@jquery_trigger_fields) ; + +my $jq_tab_var = '' ; my $jq_tab = '' ; my $inp_tab_val = '' ; foreach (keys %cntxt) { $jq_tab_var .= qq(var totalTab_$_=0 ; ) ; $jq_tab .= qq(totalTab_$_=0 ; ) ; } # $inp_tab_val .= qq(\$("#inputTotal_tab_$_").val(totalTab_$_.toFixed(2)) ;) ; + +$trigger_jquery_raw .= qq~ +\$("#selectCurrency").change(function() { + curr_changed=1; + // console.log("1. curr_changed: "+curr_changed) ; + calcCurr(); +}); + +\$('#quotes-form:checkbox').change(function() { + calcAll(); +}); + + function calcCosting(excl,item,qty,usd,conv,vat,ttl) { + + var itval = item.val(); + var uval = usd.val(); + var cval = conv.val(); // currency amount + var qval = qty.val(); + var vval = vat.val(); + // var tval = ttl.val(); + var xval = excl.val(); + var dis = \$("#selectDiscount").val(); + var roe = \$("#inputRoe").val(); // getNum() + + if (!itval) { calcAll(); return ; } + + var arrP = itval.split(":"); // 3:0.00:100.00:200.00:223.00:223.00:250.00:250.00:200.00 // id:freight:nett:main_price:gross_10_1_50:gross_10_51_plus:gross_20_1_50:gross_20_51_plus:gross_50 // + + // // var list = { freight:arrP[0], nett:arrP[1], main_price:arrP[2], gross_10_1_50:arrP[3], gross_10_51_plus:arrP[4], gross_20_1_50:arrP[5], gross_20_51_plus:arrP[6], gross_50:arrP[7] }; + // var list = { freight:arrP[1], nett:arrP[2], main_price:arrP[3], gross_10_1_50:arrP[4], gross_10_51_plus:arrP[5], gross_20_1_50:arrP[6], gross_20_51_plus:arrP[7], gross_50:arrP[8] }; + + var list = { freight:arrP[1], nett:arrP[2], main_price:arrP[3], source_admin:arrP[4], perc3:arrP[5], perc5:arrP[6], perc6:arrP[6], perc8:arrP[7], perc10:arrP[8], perc15:arrP[9], perc20:arrP[10] }; + + if (!qval) { qval=1; qty.val(qval); } // set quantity if blank + + if (!uval) // set USD amount if no amount + { + var uval = list.main_price; + if (dis==3 && qval>0) { + uval=list.perc3; + } else if (dis==5 && qval>0) { + uval=list.perc5; + } else if (dis==6 && qval>0) { + uval=list.perc6; + } else if (dis==8 && qval>0) { + uval=list.perc8; + } else if (dis==10 && qval>0) { + uval=list.perc10; + } else if (dis==15 && qval>0) { + uval=list.perc15; + } else if (dis==20 && qval>0) { + uval=list.perc20; + } + } + + // console.log('item: '+item+', uval: '+uval) ; + + // if (!uval) // set USD amount if no amount + // { + // var uval = list.main_price; + // // alert('main_price:'+uval) ; + // if (dis==10 && qval>0 && qval<=50) + // { + // uval=list.gross_10_1_50; + // } + // else if (dis==10 && qval>50) + // { + // uval=list.gross_10_51_plus; + // } + // else if (dis==20 && qval>0 && qval<=50) + // { + // uval=list.gross_20_1_50; + // } + // else if (dis==20 && qval>50) + // { + // uval=list.gross_20_51_plus; + // } + // else if (dis==50) + // { + // uval=list.gross_50; + // } + // } + + var usdAmnt = uval * 1 ; + // var currAmnt = usdAmnt / roe ; + var currAmnt = usdAmnt * roe ; + var ttlAmnt = currAmnt * qval ; + + usd.val(usdAmnt.toFixed(2)) ; // set USD currency amount + conv.val(currAmnt.toFixed(2)) ; // set foreign currency amount + ttl.val(ttlAmnt.toFixed(2)) ; // set total amount + + calcAll(); // recalculate the entire sheet + + // alert(usdAmnt+'(inputUsd_amnt_$field):'+usd+':'+qty+'(inputQty_$field)') ; // 0.00:100.00:200.00:223.00:223.00:250.00:250.00:200.00 // + } + + function dispCamDetails(excl,camnr,qty,itcode,desc,snr,ddate,adate,f) { + var camval = camnr.val(); + var arrP = camval.split(":"); + var qval = qty.val(); + + if (!camval) { + excl.prop("checked", true); + snr.val(""); + adate.val(""); + ddate.val(""); + desc.val(""); + //itcode.val(""); + qty.val(""); + return ; + } + + var prev = getNum(f-1); + var pcamval = \$("#selectCamera_nr_"+prev+"_camera_details").val(); + + // console.log("#selectCamera_nr_"+prev+"_camera_details"+", pcamval="+pcamval) ; + + if (typeof pcamval!="undefined") { + + console.log(pcamval) ; + var arrpP = pcamval.split(":"); + var checkS1 = arrpP[1].substring(0,2); + var checkOther = arrpP[1].substring(0,5); + + if (checkS1=='S1' || checkOther=='Prime' || checkOther=='Coach') { \$("#c_excl_"+f+"_camera_details").append("");\$('[data-toggle="tooltip"]').tooltip({html:true}) ; } + } + + var list = { id:arrP[0], camera_nr:arrP[1], camera_system_id:arrP[2], serial_nr:arrP[3], date_delivered:arrP[4], description:arrP[5], itemcode:arrP[6], date_active:arrP[7] }; + + if (!qval || qval<1) { qval=1; qty.val(qval); } // set quantity if blank + + snr.val(list.serial_nr); + //ddate.val(list.date_delivered); + //adate.val(list.date_active); + desc.val(list.description); + //itcode.val(list.itemcode); + + excl.prop("checked", false); + } + + function calcCurr() { + var roe = \$("#inputRoe") ; + var curr = \$("#selectCurrency").val() ; + + var url = "$useropts{scripts}/get/get_roe.pl?" + curr ; + \$.get(url, function(json) { + \$.each(json, function(key, data) { + roe.val(data.sell_rate); + }); + calcAll(); + }, + 'json'); + } +~; + +$trigger_jquery_raw .= qq( + var currArr = {}; // var vat_total = {} ; var total_total = {} ; var subtotal = {} ; var fs_total = {} ; + + $js_curr_arr + + var currVal = \$("#selectCurrency").val() ; + var prevRoe = '' ; + var curRoe = '' ; + + var grandTtl = 0 ; var grandSub = 0 ; var grandVat = 0 ; + $jq_tab_var + \$("$jquery_trigger_ids").change(function() { + calcAll(); + }); + + + calcAll() ; + + + \$("#inputYear_1_3_purchase_summary").on("change", function() { + // calcAll() ; + if (\$(this).val()) { + \$(this).val(parseFloat(\$(this).val()).toFixed(2)); + } else { + \$(this).val("0.00"); + } + + calcAll() ; + + }); + + function calcAll() + { + if (!\$("#selectCurrency").val()) { \$("#selectCurrency").val('ZAR'); \$("#selectCurrency").trigger("chosen:updated"); } // if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) } + + grandTtl = 0 ; grandSub = 0 ; grandVat = 0 ; + totalOne_time_fee_1 = 0 ; subtotalOne_time_fee_1 = 0 ; vatOne_time_fee_1 = 0 ; + totalMonthly_recurring_fee_1 = 0 ; subtotalMonthly_recurring_fee_1 = 0 ; vatMonthly_recurring_fee_1 = 0 ; + totalAnnual_fee_1 = 0 ; subtotalAnnual_fee_1 = 0 ; vatAnnual_fee_1 = 0 ; + + totalOne_time_fee_2 = 0 ; subtotalOne_time_fee_2 = 0 ; vatOne_time_fee_2 = 0 ; + totalMonthly_recurring_fee_2 = 0 ; subtotalMonthly_recurring_fee_2 = 0 ; vatMonthly_recurring_fee_2 = 0 ; + totalAnnual_fee_2 = 0 ; subtotalAnnual_fee_2 = 0 ; vatAnnual_fee_2 = 0 ; + + totalYear_1_2_purchase_summary=0; totalYear_2_2_purchase_summary=0; totalYear_3_2_purchase_summary=0; totalYear_4_2_purchase_summary=0; totalYear_5_2_purchase_summary=0; totalTotal_2_purchase_summary=0; + totalYear_1_3_purchase_summary=0; totalYear_2_3_purchase_summary=0; totalYear_3_3_purchase_summary=0; totalYear_4_3_purchase_summary=0; totalYear_5_3_purchase_summary=0; totalTotal_3_purchase_summary=0; + + $jq_tab + $re_calc_jquery + + \$("#inputSub_total").val(grandSub.toFixed(2)) ; + \$("#inputVat_total").val(grandVat.toFixed(2)) ; + \$("#inputGrand_total").val(grandTtl.toFixed(2)) ; + + \$("#inputTotal_one_time_fee_1").val(totalOne_time_fee_1.toFixed(2)) ; + \$("#inputSubtotal_one_time_fee_1").val(subtotalOne_time_fee_1.toFixed(2)) ; + \$("#inputVat_one_time_fee_1").val(vatOne_time_fee_1.toFixed(2)) ; + + \$("#inputTotal_one_time_fee_2").val(totalOne_time_fee_2.toFixed(2)) ; + \$("#inputSubtotal_one_time_fee_2").val(subtotalOne_time_fee_2.toFixed(2)) ; + \$("#inputVat_one_time_fee_2").val(vatOne_time_fee_2.toFixed(2)) ; + + \$("#inputTotal_monthly_recurring_fee_1").val(totalMonthly_recurring_fee_1.toFixed(2)) ; + \$("#inputSubtotal_monthly_recurring_fee_1").val(subtotalMonthly_recurring_fee_1.toFixed(2)) ; + \$("#inputVat_monthly_recurring_fee_1").val(vatMonthly_recurring_fee_1.toFixed(2)) ; + + \$("#inputTotal_annual_fee_1").val(totalAnnual_fee_1.toFixed(2)) ; + \$("#inputSubtotal_annual_fee_1").val(subtotalAnnual_fee_1.toFixed(2)) ; + \$("#inputVat_annual_fee_1").val(vatAnnual_fee_1.toFixed(2)) ; + + \$("#inputYear_1_2_purchase_summary").val(totalYear_1_2_purchase_summary.toFixed(2)) ; + \$("#inputYear_2_2_purchase_summary").val(totalYear_2_2_purchase_summary.toFixed(2)) ; + \$("#inputYear_3_2_purchase_summary").val(totalYear_3_2_purchase_summary.toFixed(2)) ; + \$("#inputTotal_2_purchase_summary").val(totalTotal_2_purchase_summary.toFixed(2)) ; + + let totalAnnual_fee = totalAnnual_fee_1 + totalAnnual_fee_2 ; + + totalYear_1_3_purchase_summary = totalAnnual_fee ; + totalYear_2_3_purchase_summary = totalAnnual_fee ; + totalYear_3_3_purchase_summary = totalAnnual_fee ; + + \$("#inputYear_2_3_purchase_summary").val(totalYear_2_3_purchase_summary.toFixed(2)) ; + \$("#inputYear_3_3_purchase_summary").val(totalYear_3_3_purchase_summary.toFixed(2)) ; + + let totalOne_time_fee = totalOne_time_fee_1 + totalOne_time_fee_2 ; + + \$("#inputYear_1_1_purchase_summary").val(totalOne_time_fee.toFixed(2)) ; + \$("#inputYear_2_1_purchase_summary").val('0.00') ; + \$("#inputYear_3_1_purchase_summary").val('0.00') ; + \$("#inputYear_4_1_purchase_summary").val('0.00') ; + \$("#inputYear_5_1_purchase_summary").val('0.00') ; + \$("#inputTotal_1_purchase_summary").val(totalOne_time_fee.toFixed(2)) ; + + let year_1_tot = totalOne_time_fee + totalYear_1_2_purchase_summary + parseFloat(\$("#inputYear_1_3_purchase_summary").val()) ; + let year_2_tot = totalYear_2_2_purchase_summary + totalAnnual_fee ; + let year_3_tot = totalYear_3_2_purchase_summary + totalAnnual_fee ; + let year_4_tot = totalYear_4_2_purchase_summary + totalAnnual_fee ; + let year_5_tot = totalYear_5_2_purchase_summary + totalAnnual_fee ; + let grand_tot_pur = 0 ; + + \$("#inputYearly_totals_1").val(parseFloat(year_1_tot).toFixed(2)) ; + \$("#inputYearly_totals_2").val(year_2_tot.toFixed(2)) ; + \$("#inputYearly_totals_3").val(year_3_tot.toFixed(2)) ; + + if (\$("#selectPeriod").val() == 60) { + + \$("#inputYear_4_2_purchase_summary").val(totalYear_4_2_purchase_summary.toFixed(2)) ; + \$("#inputYear_5_2_purchase_summary").val(totalYear_5_2_purchase_summary.toFixed(2)) ; + + totalYear_4_3_purchase_summary = totalAnnual_fee ; + totalYear_5_3_purchase_summary = totalAnnual_fee ; + totalTotal_3_purchase_summary = totalAnnual_fee * 4 + parseFloat(\$("#inputYear_1_3_purchase_summary").val()) ; + + \$("#inputYear_4_3_purchase_summary").val(totalYear_4_3_purchase_summary.toFixed(2)) ; + \$("#inputYear_5_3_purchase_summary").val(totalYear_5_3_purchase_summary.toFixed(2)) ; + + \$("#inputYearly_totals_4").val(year_4_tot.toFixed(2)) ; + \$("#inputYearly_totals_5").val(year_5_tot.toFixed(2)) ; + + grand_tot_pur = year_1_tot + year_2_tot + year_3_tot + year_4_tot + year_5_tot ; + + } else if (\$("#selectPeriod").val() == 36) { + + \$("#inputYear_4_2_purchase_summary").val('0.00') ; + \$("#inputYear_5_2_purchase_summary").val('0.00') ; + + totalYear_4_3_purchase_summary = 0 ; + totalYear_5_3_purchase_summary = 0 ; + totalTotal_3_purchase_summary = totalAnnual_fee * 2 + parseFloat(\$("#inputYear_1_3_purchase_summary").val()) ; + + \$("#inputYear_4_3_purchase_summary").val('0.00') ; + \$("#inputYear_5_3_purchase_summary").val('0.00') ; + \$("#inputYearly_totals_4").val('0.00') ; + \$("#inputYearly_totals_5").val('0.00') ; + + grand_tot_pur = year_1_tot + year_2_tot + year_3_tot ; + } + console.log("inputYear_4_2_purchase_summary : "+\$('#inputYear_4_2_purchase_summary').val()) ; + \$("inputTotal_3_purchase_summary").val() ; + \$("#inputTotal_3_purchase_summary").val(parseFloat(totalTotal_3_purchase_summary).toFixed(2)) ; + \$("#inputYearly_total").val(parseFloat(grand_tot_pur).toFixed(2)) ; + + curr_changed=0; + }); + +# $onload .= qq(onload="calcAll();"); +if ($iaction eq 'add'){ $onload .= qq~onload="calcCurr();"~ ; } +# $onload .= qq~onload="calcCurr();"~ ; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_top { + +my ($id) = @_ ; + +our ($lcol,$fcol) = &common_min_columns(3,6) ; + +$add_form_fields = '' ; + +$fcol = 8 ; + +$add_form_fields .= qq~
    ~ ; + # $preferred_title{quote_nr} = "Ref" ; + $preferred_title{quote_nr} = "Nr" ; + $add_form_fields .= &common_min_form_input('quote_nr',$db{$table}{$id}{quote_nr},'') ; + $add_form_fields .= &common_min_form_input('ref',$db{$table}{$id}{ref},'') ; + # $add_form_fields .= &common_min_form_input('po_nr',$db{$table}{$id}{po_nr},'') ; +$add_form_fields .= qq~
    ~ ; + +$add_form_fields .= qq~
    ~ ; + if (($db{$table}{$id}{quote_date} eq '') or ($db{$table}{$id}{quote_date} eq '0000-00-00')) { $db{$table}{$id}{quote_date} = $now_ccyy_mm_dd ; } + $add_form_fields .= &common_min_form_datepicker('quote_date',$db{$table}{$id}{quote_date}) ; + my $plus_n_days_ccyy_mm_dd = &common_add_delta_days(14) ; + if (($db{$table}{$id}{quote_expiry} eq '') or ($db{$table}{$id}{quote_expiry} eq '0000-00-00')) { $db{$table}{$id}{quote_expiry} = $plus_n_days_ccyy_mm_dd ; } + $add_form_fields .= &common_min_form_datepicker('quote_expiry',$db{$table}{$id}{quote_expiry}) ; +$add_form_fields .= qq~
    ~ ; + +$add_form_fields .= qq~
    ~ ; + $dlg{quote_to} = qq~
    ~ ; + $fcol=8; + $add_form_fields .= &common_min_form_select('quote_to',$db{$table}{$id}{quote_to},'') ; + $required{max_cams} = 1 ; + $select{max_cams} = 1 ; + $opts{max_cams} = qq~ + + + + + + + + + + + + + + + ~ ; + $fcol=6; + # $add_form_fields .= &common_min_form_select('max_cams',$db{$table}{$id}{max_cams},'') ; + + $add_form_fields .= qq~
    ~ ; #
    + $fcol=2; + $add_form_fields .= &common_min_form_label_col('max_cams') ; + $fcol=2; + $add_form_fields .= &common_min_form_select_col('max_cams',$db{$table}{$id}{max_cams},'') ; + $fcol=2;$lcol=1; + $add_form_fields .= &common_min_form_label_col('qty') ; + $fcol=2; + $add_form_fields .= &common_min_form_input_col('qty',$db{$table}{$id}{qty}) ; + + # $add_form_fields .= &common_min_form_label_col('period') ; + $add_form_fields .= &common_min_form_label_col('prd') ; + $sel = '' ; $sel = 'SELECTED' if $db{$table}{$id}{period} eq '36' ; + $opts{period} .= qq~~ ; + $sel = '' ; $sel = 'SELECTED' if $db{$table}{$id}{period} eq '60' ; + $opts{period} .= qq~~ ; + $sel = '' ; + $required{period} = 1 ; + $add_form_fields .= &common_min_form_select_col('period',$db{$table}{$id}{period}) ; + + $add_form_fields .= qq~
    ~ ; + + $fcol=7;# $add_form_fields .= &common_min_form_select('ship_to',$db{$table}{$id}{ship_to},'') ; + # if ($username eq 'rory') { $add_form_fields .= qq~
     
    ~ ; } +$add_form_fields .= qq~
    ~ ; + +$add_form_fields .= qq~
    ~ ; + $lcol=3; + $preferred_title{'country_shipped'} = 'Country' ; + $add_form_fields .= &common_min_form_select('country_shipped',$db{$table}{$id}{country_shipped},'') ; + $preferred_title{'camera_system_id'} = 'System' ; + $add_form_fields .= &common_min_form_select('camera_system_id',$db{$table}{$id}{camera_system_id},'') ; +$add_form_fields .= qq~
    ~ ; + +$print_box_content_rows .= &common_min_box_top('qrcode',"Quote",'BABEC2'); +$print_box_content_rows .= qq~
    +
    + $add_form_fields +
    +
    ~; +$print_box_content_rows .= qq~
     
    ~ ; +$print_box_content_rows .= &common_min_box_foot; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_left { + +my ($id,$tab) = @_ ; + +our ($lcol,$fcol) = &common_min_columns(3,6) ; + +&tab_build_qt_left($id,$tab); + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_right { + +my ($id,$tab) = @_ ; + +our ($lcol,$fcol) = &common_min_columns(3,6) ; + +&tab_build_qt_right($id,$tab); + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_bottom { + +my ($id) = @_ ; + +our ($lcol,$fcol) = &common_min_columns(2,2) ; + +$add_form_fields = '' ; + +# --------------- START GRAND TOTAL ---------------------------------------------------------------------------------------------------------------------- + +$print_box_content_rows .= &common_min_form_input('activetab',$db{$table}{$id}{activetab},'hidden') ; + +# # $print_box_content_rows .= &common_min_form_input('grand_total','0.00','hidden') ; + +# my @ttlarr = ("sub_total","vat_total","grand_total") ; +# $lcol=1;$fcol=2; +# foreach (@ttlarr) { + # $readonly{$_} = "READONLY"; + # $add_form_fields .= qq~
    ~ ; #
    + # $add_form_fields .= &common_min_form_label_col($_) ; + # $add_form_fields .= &common_min_form_input_col($_,'0.00') ; + # $add_form_fields .= qq~
    ~ ; + # } + +# $print_box_content_rows .= qq~
    ~ ; +# $print_box_content_rows .= $add_form_fields ; +# $print_box_content_rows .= &common_min_box_foot; + +# --------------- END RAND TOTAL ------------------------------------------------------------------------------------------------------------------------ + +} #---------------------------------------------------------------------------------------- + +sub build_cost_form { + +my ($id,$tab,$rcnt,$suffix) = @_ ; + +$tab_sections{$tab} .= "$suffix+$rcnt|" ; + +$jq_cal = qq~var vat_total$suffix = 0 ; var total_total$suffix = 0 ; var subtotal$suffix = 0 ; var vat_amount = 0 ; ~ ; +$jq_fs = '' ; + +%cnt_specific_jquery = () ; + +&set_check_boxes_checked($id,$rcnt,"excl",$suffix); +&set_check_boxes_checked($id,$rcnt,"vat",$suffix); + +my $cntloop=1; + +# my %saved_field = () ; +my @prefexes = ("excl", "item", "qty", "usd_amnt", "curr_amnt", "item_ttl", "vat") ; +# my @b = ( +# "_costing_additional_services", +# "_costing_game_breakdown_analytics", +# "_costing_hardware_add_ons", +# "_costing_installation_kits", +# "_costing_match_credits", +# "_costing_other", +# "_costing_rental", +# "_costing_software_licence", +# "_costing_systems", +# "_delivery_times", +# "_notes", +# "_payment_terms", +# "_purchase_summary", +# "_roes", +# "_terms") ; + +foreach my $prefex (@prefexes){ + + $col_name = "$prefex" . "$suffix" ; + $cnt = 0 ; + if($db{quotes_min}{$id}{$col_name}){ + foreach my $col_input (split(";", $db{quotes_min}{$id}{$col_name})){ + $cnt++ ; + $saved_field{$prefex}{$suffix}{$cnt} = $col_input ; + # &common_debug("$aa/$suffix : $cc") ; + } + } +} + +for (1 .. $rcnt) { + + $display_style = '' ; $display_plus_btn = '' ; + + # unless ($_==1 or $db{$table}{$id}{"item_$_$suffix"}) { + unless ($_==1 or $saved_field{"item"}{$suffix}{$_}) { + $display_style = qq~style='display:none;'~ ; + $trigger_jquery_raw .= qq~ \$("#btn_$_$suffix").click(function () { + \$("#$_$suffix").toggle(); + \$("#btn_$_$suffix").hide(); + var v = $_ + 1 ; + \$("#btn_"+v+"$suffix").show(); + });~ ; + if ($_>$cntloop) { $display_butt = qq~display:none;~ ; } else { $display_butt = '' ; } + $display_plus_btn = qq~~; + } else { $cntloop++ ; } + + $add_form_fields .= qq~
    ~ ; + #---------------------------------------------------------------------------------------------------- + $field = "excl_$_$suffix" ; $fcol=1 ; + # if ($checkit{$field} == 1) { + if ($saved_field{"excl"}{$suffix}{$_}){ + $checked = 'CHECKED'; } elsif (($excl_tick{$_}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } + $label{$field} = 1 ; + $add_form_fields .= &common_min_form_checkbox_col($field,$checkit{$field},$checked) ; + #---------------------------------------------------------------------------------------------------- + my $field = "item_$_$suffix" ; $fcol=2 ; + $allow_deselect{$field} = 1 ; + $preferred_placeholder{$field} = "Item $_" ; + if ($suffix eq '_costing_other' or $suffix eq '_costing_rental' or ($suffix eq '_costing_systems' and $_>1) or ($suffix eq '_costing_software_licence' and $_>2) or ($suffix eq '_costing_game_breakdown_analytics' and $_>1)) { + # $add_form_fields .= &common_min_form_input_col($field,$db{$table}{$id}{$field}) ; + $add_form_fields .= &common_min_form_input_col($field,$saved_field{"item"}{$suffix}{$_}) ; + } else { + # &common_min_debug("[$field] $db{$table}{$id}{$field}") ; + # $add_form_fields .= &common_min_form_select_col($field,$db{$table}{$id}{$field}) ; + $add_form_fields .= &common_min_form_select_col($field,$saved_field{"item"}{$suffix}{$_}) ; + } + #---------------------------------------------------------------------------------------------------- + $field = "qty_$_$suffix" ; $fcol=1 ; $input_style{$field} = qq(style="text-align:right;"); + $preferred_placeholder{$field} = "Qty $_" ; + # my $val = $db{$table}{$id}{$field} ; + my $val = $saved_field{"qty"}{$suffix}{$_} ; + unless ($val) { $val = $def_qty{$_} ; } $val = &q_get_val($val) ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + $field = "usd_amnt_$_$suffix" ; $input_style{$field} = qq(style="text-align:right;"); + # my $val = $db{$table}{$id}{$field} ; + my $val = $saved_field{"usd_amnt"}{$suffix}{$_} ; + unless ($val) { $val = $def_usd{$_} ;} $val = &q_get_val($val) ; + $preferred_placeholder{$field} = "USD Amnt $_" ; + $add_form_fields .= &common_min_form_input_col($field,$val,1) ; + #---------------------------------------------------------------------------------------------------- + $field = "curr_amnt_$_$suffix" ; $input_style{$field} = qq(style="text-align:right;"); $readonly{$field} = 'READONLY' ; # $fcol=2 ; + $preferred_placeholder{$field} = "ZAR Amnt $_" ; + # my $val = &q_get_val($db{$table}{$id}{$field}) ; + my $val = &q_get_val($saved_field{"curr_amnt"}{$suffix}{$_}) ; + $add_form_fields .= &common_min_form_input_col($field,$val,1) ; + #---------------------------------------------------------------------------------------------------- + $field = "item_ttl_$_$suffix" ; $input_style{$field} = qq(style="text-align:right;"); $readonly{$field} = 'READONLY' ; # $fcol=2 ; + $preferred_placeholder{$field} = "Item Total $_" ; + # my $val = &q_get_val($db{$table}{$id}{$field}) ; + my $val = &q_get_val($saved_field{"item_ttl"}{$suffix}{$_}) ; + $add_form_fields .= &common_min_form_input_col($field,$val,1) ; + #---------------------------------------------------------------------------------------------------- + $field = "vat_$_$suffix" ; $fcol=1 ; + # if ($checkit{$field} == 1) { $checked = 'CHECKED'; } elsif (($vat_tick{$_}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } + if ($saved_field{"vat"}{$suffix}{$_} == 1) { + # if ($checkit{$field} == 1) { + $checked = 'CHECKED'; } elsif ($iaction eq 'add') { $checked = 'CHECKED'; } else { $checked = ''; } + $label{$field} = 1 ; + if ($no_vat{$suffix}) { $style_field{$field} = 'style="display:none;"' ; } + $add_form_fields .= &common_min_form_checkbox_col($field,$checkit{$field},$checked) ; + #---------------------------------------------------------------------------------------------------- + # $add_form_fields .= qq~$display_plus_btn~ ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    $display_plus_btn
    ~ ; + $add_form_fields .= qq~
    ~ ; + + my $added_ttl_js = '' ; + + if ($suffix eq '_costing_systems' or $suffix eq '_costing_installation_kits' or $suffix eq '_costing_hardware_add_ons' or $suffix eq '_costing_additional_services' or $suffix eq '_costing_match_credits') { + + # if ($suffix eq '_costing_additional_services' and $db{$table}{$id}{"item_$_$suffix"}) { # OTT Monthly Management fee + # $added_ttl_js = qq~ + # totalMonthly_recurring_fee += (amnts[2] + amnts[1]) ; + # subtotalMonthly_recurring_fee += amnts[2] ; + # vatMonthly_recurring_fee += amnts[1] ; + + # var yrTtl = (amnts[2] + amnts[1]) * 12 + + # totalYear_1_2_purchase_summary += yrTtl; + # totalYear_2_2_purchase_summary += yrTtl; + # totalYear_3_2_purchase_summary += yrTtl; + # totalTotal_2_purchase_summary += (yrTtl*3); ~; + # } else { + $added_ttl_js = qq~totalOne_time_fee_1 += (amnts[2] + amnts[1]) ; + subtotalOne_time_fee_1 += amnts[2] ; + vatOne_time_fee_1 += amnts[1] ; ~; + # } + } + + if ($suffix eq '_costing_other') { + + $added_ttl_js = qq~ + totalOne_time_fee_2 += (amnts[2] + amnts[1]) ; + subtotalOne_time_fee_2 += amnts[2] ; + vatOne_time_fee_2 += amnts[1] ; + ~ ; + + } + + if ($suffix eq '_costing_software_licence' or $suffix eq '_costing_rental') { + $added_ttl_js = qq~ + + totalMonthly_recurring_fee_1 += (amnts[2] + amnts[1]) ; + subtotalMonthly_recurring_fee_1 += amnts[2] ; + vatMonthly_recurring_fee_1 += amnts[1] ; + + var yrTtl = (amnts[2] + amnts[1]) * 12 + + totalYear_1_2_purchase_summary += yrTtl; + totalYear_2_2_purchase_summary += yrTtl; + totalYear_3_2_purchase_summary += yrTtl; + + if (\$("#selectPeriod").val() == 60) { + totalYear_4_2_purchase_summary += yrTtl; + totalYear_5_2_purchase_summary += yrTtl; + totalTotal_2_purchase_summary += (yrTtl*2); + } + + totalTotal_2_purchase_summary += (yrTtl*3); + + \$("#selectPeriod").on("change", function() { + if (\$(this).val() == 36) { + totalYear_4_2_purchase_summary = 0; + totalYear_5_2_purchase_summary = 0; + totalTotal_2_purchase_summary -= (yrTtl*5); + totalTotal_2_purchase_summary += (yrTtl*3); + + } else if (\$(this).val() == 60) { + totalYear_4_2_purchase_summary += yrTtl; + totalYear_5_2_purchase_summary += yrTtl; + totalTotal_2_purchase_summary -= (yrTtl*3); + totalTotal_2_purchase_summary += (yrTtl*5); + } + }); + ~; + } + + if ($suffix eq '_costing_game_breakdown_analytics') { + $added_ttl_js = qq~ + totalAnnual_fee_1 += (amnts[2] + amnts[1]) ; + subtotalAnnual_fee_1 += amnts[2] ; + vatAnnual_fee_1 += amnts[1] ; + ~; + } + + $jq_cal .= qq~ + var amnts = calcSection('$suffix','$_'); + + vat_total$suffix += amnts[1] ; + subtotal$suffix += amnts[2] ; + total_total$suffix += (amnts[2] + amnts[1]) ; + $added_ttl_js + + ~; +} + +$jq_cal .= qq~ + grandSub+=subtotal$suffix; + grandVat+=vat_total$suffix; + grandTtl+=total_total$suffix; + ~ ; + +$re_calc_jquery .= qq~calc$suffix();setRoe('$suffix','$rcnt');~; + +$trigger_jquery_raw .= qq~ + function calc$suffix() + { + $jq_cal + } + ~; + +} #---------------------------------------------------------------------------------------- + +sub q_get_val { + +my ($val) = @_ ; + +my $disp_val = $val ; + +if ($val eq '0.00') { + $disp_val = '' ; + } + +return ($disp_val); + +} #------------------------------------------------------------------------------------------ + +sub set_check_boxes_checked { + +my ($id,$rcnt,$prefix,$suffix) = @_ ; + +# my $dbfield = "$prefix$suffix" ; + +# my $val = $db{$table}{$id}{$dbfield} ; + +# if ($suffix eq '_camera_details') { &common_min_debug("[$dbfield] $val [$id,$rcnt,$prefix,$suffix]") ; } + +for (1 .. $rcnt) { + # my $sstr = $_-1 ; + my $ifield = $prefix . '_' . "$_$suffix" ; + # $checkit{$ifield} = substr($val,$sstr,1) ; + my $val = $db{$table}{$id}{$ifield} ; + $checkit{$ifield} = $val ; + # if ($suffix eq '_camera_details') { &common_min_debug(" --- [$ifield] $checkit{$ifield} [$val]") ; } + } + +} #---------------------------------------------------------------------------------------- + +sub select_opts { + +my ($id) = @_ ; + +$required{type} = 1 ; +$select{type} = 1 ; +$selected{type}{$db{$table}{$id}{type}} = 'SELECTED' ; unless ($db{$table}{$id}{type}) { $selected{type}{purchase} = 'SELECTED' ; } +$opts{type} = qq~~ ; +$trigger_jquery .= qq~\$("#selectType\_chosen").css( "width", "60%" );~ ; + +my @currency_arr = qw( currency ); + +foreach my $curr (@currency_arr) { + if ($db{$table}{$id}{$curr}) { $selected{$curr}{$db{$table}{$id}{$curr}} = 'SELECTED'; } else { $selected{$curr}{ZAR} = 'SELECTED'; } + $select{$curr} = 1 ; + $opts{$curr} = qq~ + + ~ ; + +} + +# $select{discount} = 1 ; +# $selected{discount}{$db{$table}{$id}{discount}} = 'SELECTED' ; +# $opts{discount} = qq~~ ; +# $opts{discount} = qq~~ ; +# $trigger_jquery .= qq~\$("#selectItem_$field\_chosen").css( "width", "96%" ) +# ~ ; + +my $selcntry = $db{$table}{$id}{country_shipped} ; $selcntry = 242 unless $selcntry ; # Default South Africa +&common_min_select_opts('country_shipped','countries','name',$selcntry,1,'country',''); +&common_min_select_opts('camera_system_id','camera_systems','name',$db{$table}{$id}{camera_system_id},1,'',''); +# &common_min_select_opts('quote_to','customers','name',$db{$table}{$id}{quote_to},1,'',''); + +&tab_customer_select_opts('customers','name','','quote_to'); + +# $select{ship_to} = 1 ; $required{ship_to} = 1 ; +# &db_min_ro('towns','*','','','') ; +# foreach (keys %{$db{'towns'}}) { + # my $selected = ''; if ($db{towns}{$_}{name} eq $db{$table}{$id}{ship_to}) { $selected = 'selected="selected"'; } + # $opts{ship_to} .= qq() ; + # } + +$trigger_jquery_raw .= qq~ + +function calcSection(sufx,cnt) { + + var inpItemTtl = \$("#inputItem_ttl_"+cnt+sufx) ; + var inpCurrAmnt = \$("#inputCurr_amnt_"+cnt+sufx) ; + var inpItem = \$("#inputItem_"+cnt+sufx) ; + var initUsdVal = \$("#inputUsd_amnt_"+cnt+sufx).val() ; + var inpUsd = \$("#inputUsd_amnt_"+cnt+sufx) ; + var qty = \$("#inputQty_"+cnt+sufx).val() ; + var vatChkBox = \$("#checkboxVat_"+cnt+sufx) ; + var exclChkBox = \$("#checkboxExcl_"+cnt+sufx) ; + var selCurr = \$("#selectCurrency") ; + + var exclChk = 'excl_'+cnt+sufx ; + var vatChk = 'vat_'+cnt+sufx ; + + var usdAmnt = 0 ; + var vatAmnt = 0 ; + + if (selCurr.val() != 'ZAR') { vatChkBox.prop("checked", false) ; } + + // console.log("3. curr_changed: "+curr_changed +" : "+ selCurr.val()) ; + + if (curr_changed==1 && selCurr.val()=='ZAR') { + vatChkBox.prop("checked", true); + } + + //if (selCurr.val() != 'ZAR') { vatChkBox.prop("checked", false) ; } else { vatChkBox.prop("checked", true); } // set VAT checkbox + // if (!inpItem.val()) { exclChkBox.prop("checked", false); } else { exclChkBox.prop("checked", true); } // set EXCL checkbox + + curRoe = \$("#inputRoe").val(); + + if ( (qty>0) && (inpUsd.val()>0) ) { + var convPrice = convertCurr(initUsdVal,curRoe) ; + var ttlPrice = convPrice * qty ; + inpCurrAmnt.val(convPrice.toFixed(2)); + inpItemTtl.val(ttlPrice.toFixed(2)); + exclChkBox.prop("checked", false); + } else { + exclChkBox.prop("checked", true); + } + + if (\$('input[name='+exclChk+']:checked').length > 0) { // only calculate if included + // inpCurrAmnt.prop('readonly', true); // inpCurrAmnt.val(''); + // inpUsd.prop('readonly', true); //inpUsd.val(''); + // inpItemTtl.val(''); inpItemTtl.prop('readonly', true); + // \$("#inputQty_"+cnt+sufx).prop('readonly', true); + var ttlPrice = 0 ; + inpItemTtl.val(ttlPrice.toFixed(2)); + return [0,0,0]; + } + + vatAmnt = 0 ; + + if ((\$('input[name='+vatChk+']:checked').length > 0) && (selCurr.val() == 'ZAR')) { + // var vat = addVat(inpCurrAmnt.val()) ; + var vat = addVat(inpItemTtl.val()) ; + vatAmnt = vat[0]; + } + + // usdAmnt = getNum(parseFloat(inpUsd.val())); + currAmnt = getNum(parseFloat(inpCurrAmnt.val())); + ttlAmnt = getNum(parseFloat(inpItemTtl.val())); + + // return [usdAmnt,vatAmnt]; + return [currAmnt,vatAmnt,ttlAmnt]; +} + +function getNum(val) +{ + if (isNaN(val)) { + return 0; + } + return val; +} + +function convertCurr(val,curRoe) +{ + // val = val / curRoe ; + val = val * curRoe ; + return val; +} + +function addVat(amnt) +{ + var vat_amnt = amnt*0.15 ; + var subtotal = amnt - vat_amnt + return [vat_amnt,subtotal]; +} + +function setRoe(sx,rcnt) +{ + var labelCurrAmntSx = \$("#lab_curr_amnt$sec"+sx) ; + var curr = \$("#selectCurrency").val() ; if (!curr) { curr = 'Curr' ; } + + labelCurrAmntSx.html('Price ['+curr+']'); + + for (i = 0; i <= rcnt; i++) { + var inpCurrAmntSx = \$("#inputCurr_amnt_"+i+sx) ; ; + inpCurrAmntSx.attr("placeholder",curr+' Amnt '+i); + var inpQcPh = \$("#inputqty_"+i+sx).attr("placeholder"); + } +} + +function calcTtl(qc,ica,iz) +{ + var zar_amnt = getNum(parseFloat(\$("#inputWeight").val())) * getNum(parseFloat(qc.val())) ; + iz.val(zar_amnt.toFixed(2)) ; +} + +\$("li").click(function(){ + var activeTab = \$(this).text(); + \$("#inputActivetab").val(activeTab) ; + }); + +// function selectTabs() +// { + // activeTab = \$("#inputActivetab").val(); + // if (!activeTab) { activeTab = 'Quote Details' ; } + // var tabs = \$("#myTab li"); + // tabs.each(function(idx, li) { + // var tab = \$(li); + // if (tab.text == activeTab) + // { + // tab.addClass("active"); + // } else { + // tab.removeClass("active"); + // } + // }); +// } + +~; + +# $trigger_jquery .= qq~ +# \$(window).bind('beforeunload', function() + # { + # // window.location = 'https://$ENV{SERVER_NAME}/list-quotes' ; + # alert('beforeunload'); +# }); + +# ~; + +$extra_css .= qq() ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'global' ; +our $lcpage = 'quote' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; +our $table = 'quotes' ; + +&common_min_add_box_icon ; + +} #------------------------------------------------------------------------------- + +sub creat_db_cols { + +&db_min_ro('quotes','*','','','') ; + +my %col_exists ; + +foreach (sort { $col_name{$a} cmp $col_name{$b} } keys %col_name) { + $col = $col_name{$_} ; + $col_exists{$col} = 1 ; +} + +my $mysql = "ALTER TABLE `quotes`" ; + +# foreach (sort keys %i) { + # if ($_ =~ /qty_/g) { + # $mysql .= qq~ +# DROP `$_`,~ ; + # } +# } + +foreach (sort keys %i) { + if ($_ eq 'iaction') { next ; } + + if ($ignore{$_}) { next ; } + if ($col_exists{$_}) { next ; } # only create the column if it doesn't exist + + if (((substr($_,0,3) eq 'vat') or (substr($_,0,4) eq 'excl')) and (substr($_,0,9) ne 'vat_total')) { + $mysql .= qq~ +ADD `$_` INT(1) NOT NULL DEFAULT '0',~ ; + } elsif ($_ =~ /qty_/g) { + $mysql .= qq~ +ADD `$_` INT(3) NULL DEFAULT '0',~ ; + } elsif ($_ =~ /roe_/g) { + $mysql .= qq~ +ADD `$_` VARCHAR( 120 ) NOT NULL ,~ ; + } elsif ($_ =~ /description_/g) { + $mysql .= qq~ +ADD `$_` VARCHAR( 255 ) NOT NULL ,~ ; + } elsif (substr($_,0,3) eq 'roe') { + $mysql .= qq~ +ADD `$_` DECIMAL(4,2) NOT NULL ,~ ; # 999999.99 to -999999.99 + } elsif ($_ =~ /date_/g or $_ =~ /_date/g) { + $mysql .= qq~ +ADD `$_` DATE DEFAULT NULL ,~ ; + } elsif ($_ =~ /datetime/g) { + $mysql .= qq~ +ADD `$_` datetime DEFAULT NULL ,~ ; + } elsif ($_ =~ /_costing_/g or $_ =~ /_total/g or $_ =~ /total_/g or $_ =~ /year_/g or $_ =~ /_amnt_/g) { # } elsif (substr($_,0,5) eq 'item_') { + $mysql .= qq~ +ADD `$_` DECIMAL( 8, 2 ) NOT NULL ,~ ; # 999999.99 to -999999.99 + } elsif ($_ =~ /_included/g) { + $mysql .= qq~ +ADD `$_` TEXT NOT NULL ,~ ; + } elsif ($_ =~ /_id/g) { + $mysql .= qq~ +ADD `$_` INT( 6 ) NOT NULL DEFAULT '0',~ ; + } else { + $mysql .= qq~ +ADD `$_` VARCHAR( 120 ) NOT NULL ,~ ; + } +} + +print $mysql ; +exit ; + +} #------------------------------------------------------------------------------------------ + +sub report_ifields { + +# my $account_sql_where = '' ; if ($i{account_id}) { $account_sql_where = "`id`='$i{account_id}'" ; } elsif ($glob_account_id) { $account_sql_where = "`id`='$glob_account_id'" ; } + +# &db_common_ro('account','id,name',$account_sql_where,'','') ; +# foreach my $id (keys %{$db{account}}) { $account_name{$id} = $db{account}{$id}{name} ; } + +if ($i{quote_to}) { + push @report_sql, "($table.quote_to = '$i{quote_to}')" ; + push @report_results, "`quote_to` = '$i{quote_to}'" ; + } + +# if ($i{ship_to}) { + # push @report_sql, "(`ship_to` = '$i{ship_to}')" ; + # push @report_results, "ship_to = $i{ship_to}" ; + # } + +if ($i{quotes_from} and $i{quotes_to}) { # check dates + my $quotes_from_check = $i{quotes_from} ; + $quotes_from_check =~ s/\-//g ; + my $quotes_to_check = $i{quotes_to} ; + $quotes_to_check =~ s/\-//g ; + if ($quotes_from_check > $quotes_to_check) { $error = qq(QUOTES FROM ($i{quotes_from}) > QUOTES TO ($i{quotes_to})); &report_screen; } + } + +if ($i{quotes_from}) { + push @report_sql, "($table.quote_date >= '$i{quotes_from}')" ; + push @report_results, "`quote_date` >= '$i{quotes_from}'" ; + } + +if ($i{quotes_to}) { + push @report_sql, "($table.quote_date <= '$i{quotes_to}')" ; + push @report_results, "`quote_date` <= '$i{quotes_to}'" ; + } + +if ($i{po_nr}) { + push @report_sql, "($table.po_nr LIKE '%$i{po_nr}%')" ; + push @report_results, "`po_nr` LIKE '$i{po_nr}'" ; + } + +if ($i{invoice_nr}) { + push @report_sql, "($table.invoice_nr LIKE '%$i{invoice_nr}%')" ; + push @report_results, "`invoice_nr` LIKE '$i{invoice_nr}'" ; + } + +if ($i{quote_nr}) { + push @report_sql, "($table.quote_nr LIKE '%$i{quote_nr}%')" ; + push @report_results, "`quote_nr` = '$i{quote_nr}'" ; + } + +# if ($i{serial_nr}) { + # for (1 .. 10) { + # push @report_sql_or, "(`serial_nr_$_\_camera_details` LIKE '%$i{serial_nr}%')" ; + # } + # push @report_results, "serial_nr LIKE `$i{serial_nr}`" ; + # my $sql_or = join(' OR ', @report_sql_or) ; + # push @report_sql, "($sql_or)" ; + # } + +if ($i{country}) { + push @report_sql, "($table.country_shipped = '$i{country}')" ; + push @report_results, "`country_shipped` = '$i{country}'" ; + } + +if ($i{customer_name}) { + push @report_sql, "($table.quote_to = '$i{customer_name}')" ; + push @report_results, "`customer` = '$i{customer_name}'" ; + } + +if ($i{accepted} or $i{options} eq 'accepted') { + push @report_sql, "($table.quote_accepted='1')" ; + push @report_results, "`quote_accepted` = 'Yes'" ; + } +elsif ($i{closed} or $i{options} eq 'closed') { + # push @report_sql, "(`quote_cancelled`='1')" ; + # push @report_sql, "(`quote_cancelled`='1' OR `quote_expiry`<'$now_year-$now_mm-$now_dd')" ; + push @report_sql, "($table.quote_cancelled='1' OR ($table.quote_expiry<'$now_year-$now_mm-$now_dd' AND $table.quote_accepted<>'1'))" ; + push @report_results, "`quote_closed` = 'Yes'" ; + } +elsif ($i{options} && $i{options} ne 'all') { + push @report_results, "`quote` = '$i{options}'" ; + } +elsif ($i{options} && $i{options} eq 'all') { + push @report_results, "(`quote_accepted` = 'Yes' OR `quote_pending` = 'Yes' OR `quote_closed` = 'Yes')" ; + } + +if ($i{type}) { + push @report_sql, "($table.type='$i{type}')" ; + push @report_results, "`type` = '$i{type}'" ; + } + +$report_results_msg = uc join(', ', @report_results) ; + +unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); &report_screen; } else { $isaved = qq(SELECT WHERE $report_results_msg) ; } + +} #------------------------------------------------------------------------------------------ + +sub report_screen { + +&filter_screen if $ENV{QUERY_STRING} eq 'filter' ; + +our $lcol = 2 ; +our $fcol = 5 ; + +my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-42); # 6 weeks back + +$set_month = sprintf("%02s", $set_month) ; +$set_day = sprintf("%02s", $set_day) ; + +my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ; + +$print_box_content_rows .= &common_min_forms_start('report') ; + + $allow_deselect{customer_name} = 1 ; + $allow_deselect{camera_system} = 1 ; + $allow_deselect{country} = 1 ; + $allow_deselect{options} = 1 ; + $allow_deselect{type} = 1 ; + + &common_min_select_opts('customer_name','customers','name','','','',''); + $print_box_content_rows .= &common_min_form_select('customer_name','') ; + # $print_box_content_rows .= &common_min_form_input('customer_name','') ; + $print_box_content_rows .= &common_min_form_input('quote_nr','') ; + + $print_box_content_rows .= &common_min_form_datepicker('quotes_from','') ; # $set_ccyy_dd_mm + $print_box_content_rows .= &common_min_form_datepicker('quotes_to','') ; # $now_ccyy_mm_dd + + $print_box_content_rows .= &common_min_form_input('po_nr','') ; + $print_box_content_rows .= &common_min_form_input('invoice_nr','') ; + &common_min_select_opts('camera_system','camera_systems','name','','','',''); + $print_box_content_rows .= &common_min_form_select('camera_system','') ; + # $print_box_content_rows .= &common_min_form_input('serial_nr','') ; + # $print_box_content_rows .= &common_min_form_input('country','') ; + &common_min_select_opts('country','countries','name','','','',''); + $print_box_content_rows .= &common_min_form_select('country','') ; + # $print_box_content_rows .= &common_min_form_checkbox('invoiced','','') ; # Display all quotes that is Invoiced + + # $print_box_content_rows .= &common_min_form_checkbox('accepted','','') ; # Display all quotes that is Accepted + # $print_box_content_rows .= &common_min_form_checkbox('closed','','') ; # Display all quotes that is Cancelled + + my $options_selected = 'SELECTED' if $useropts{boss}{$username} or $useropts{super}{$username} ; + + $opts{options} = qq~~ ; + $print_box_content_rows .= &common_min_form_select('options','') ; + + $opts{type} = qq~~ ; + $print_box_content_rows .= &common_min_form_select('type','') ; + +$print_box_content_rows .= &common_min_forms_end('','','report') ; + +&common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub filter_screen { + +our $lcol = 2 ; +our $fcol = 5 ; + +my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-42); # 6 weeks back + +$set_month = sprintf("%02s", $set_month) ; +$set_day = sprintf("%02s", $set_day) ; + +my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ; + +$print_box_content_rows .= &common_min_forms_start('report') ; + + &common_min_select_opts('customer_name','customers','name','','','',''); + $print_box_content_rows .= &common_min_form_select('customer_name','') ; + + $print_box_content_rows .= &common_min_form_datepicker('quotes_from','') ; # $set_ccyy_dd_mm + $print_box_content_rows .= &common_min_form_datepicker('quotes_to','') ; # $now_ccyy_mm_dd + + $opts{type} = qq~~ ; + $print_box_content_rows .= &common_min_form_select('type','') ; + + my $options_selected = 'SELECTED' if $useropts{boss}{$username} or $useropts{super}{$username} ; + + $opts{options} = qq~~ ; + $print_box_content_rows .= &common_min_form_select('options','') ; + +$print_box_content_rows .= &common_min_forms_end('','','report') ; + +&common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +# use tabs_test2 ; +use tabs ; +use common ; +use today ; +use report ; +use xlsxcreator ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/quotes_test.pl b/scripts/_FromProd/v1.0/quotes_test.pl new file mode 100644 index 0000000..0916c5d --- /dev/null +++ b/scripts/_FromProd/v1.0/quotes_test.pl @@ -0,0 +1,2787 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); + +require cfg ; + +print header; # CGI.pm method + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $redirtype = 'search' ; +# our $debug = 1 ; +# our $testing = 1 ; + +our $cust_cols = 1 ; # display _blank_3.pm + +our $camera_cnt_allowed = 1000 ; our $max_cams = 10 ; + +if ($useropts{tickets}{$username}) { print "Content-type: text/html\n\n"; require '401.pm' ; exit ; } + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +# unless ($username eq 'handre' or $username eq 'rory') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } +# &db_open_ro; +# $db_ignore_open_close=1; +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +$ignore{"yearly_total"} = 1 ; +$ignore{"yearly_totals_1"} = 1 ; +$ignore{"yearly_totals_2"} = 1 ; +$ignore{"yearly_totals_3"} = 1 ; +$ignore{"yearly_totals_4"} = 1 ; +$ignore{"yearly_totals_5"} = 1 ; + +if ($iaction eq 'add') { + &add_screen ; + &common_min_screen1 ; +} + +if ($iaction eq 'edit') { + &common_min_load_params ; + &edit_screen ; + &common_min_screen1 ; +} + +if ($iaction eq 'save') { + &common_min_load_params ; + &insert ; + &edit_or_list ; +} + +if ($iaction eq 'update') { + &common_min_load_params ; + &update ; + &edit_or_list ; +} + +if ($iaction eq 'copy') { + &common_min_load_params ; + &duplicate ; + &edit_screen ; + &common_min_screen1 ; +} + +if ($iaction eq 'delete') { + &common_min_load_params ; + &delete ; + &common_min_screen2 ; +} + +&common_min_action; + +# $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +# &db_close_conn ; +exit; + +#------------------------------------------------------------------------------------------ + +sub edit_or_list { + +# if ($i{saveandexit} eq 'yes') { + # &list_screen ; + # &common_min_screen3; + # } +# else + # { + &edit_screen ; + &common_min_screen1; + # } + +} #------------------------------------------------------------------------------------------ + +sub insert { + +&add_db_fields ; + +$i{last_update} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; +$i{datetime} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; +$i{user_id} = $userid ; + +&set_default_i_vals; + +# &creat_db_cols; + +$i{id} = &db_min_get_max($table,'id') ; +&titles_for_pdf ; +&common_upload_files("costings/$i{id}") ; +&process_upload_ifields; +&process_totals ; + +our $nr_of_costing_rows = $i{nr_of_costing_rows} ; + +&db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &switch_table ; + &db_min_insert($table) ; + &new_table ; + &db_min_insert('quotes_min') ; + &update_camera; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +# exit ; + +} #------------------------------------------------------------------------------------------ + +sub update { + +unless ($i{id}) { $error = qq(NO ID) ; return ; } + +&edit_db_fields ; + +# &creat_db_cols; +&titles_for_pdf ; +&set_default_i_vals ; + +$i{last_update} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&common_upload_files("costings/$i{id}") ; +&process_upload_ifields ; +&process_totals ; + +our $nr_of_costing_rows = $i{nr_of_costing_rows} ; + +&db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &switch_table ; + &log_changes_1 ; + # &db_min_upd($table,"id='$i{id}'") ; + &common_shared_log_update_changes($table) ; + &new_table ; + &log_changes_2 ; + &common_shared_log_update_changes("quotes_min","quotes_changes","changes") ; + foreach (keys %ignore_for_now) { + $ignore{$_} = '' ; + } + &update_camera ; + + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +sub process_totals { + + my @ttlarr = ("one_time_fee","monthly_recurring_fee","annual_fee") ; + my @ttlarr2 = ("subtotal","vat","total") ; + + foreach my $a (@ttlarr) { + foreach my $b (@ttlarr2) { + my $field = "$b\_$a" ; + my $field_1 = "$b\_$a\_1" ; + my $field_2 = "$b\_$a\_2" ; + $ignore{$field_1} = 1 ; + $ignore{$field_2} = 1 ; + # $i{$field} = qq~$i{$field_1};$i{$field_2}~ ; + } + } + + $ignore{subtotal} = 1 ; + $ignore{total} = 1 ; + $ignore{vat} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub log_changes_1 { + + &db_min_ro($table,"*","`id`='$i{id}'",'','') ; + our $line = qq~$now_year$now_mm$now_dd$now_hour$now_min$now_sec|$now_year-$now_mm-$now_dd $now_hour:$now_min:$now_sec|quote_id='$i{id}'|user_id=$userid|changed_from|~ ; + my %col_to_be_updated = () ; my %ignore_for_now = () ; + + foreach (keys %i) { + $col_to_be_updated{$_} = 1 ; + } + + foreach my $col (keys %{$db{$table}{$i{id}}}) { + next if $ignore{$col} or $hidden{$col} == 1 or substr($col,0,3) eq 'new' or not $col_to_be_updated{$col} ; + if (($i{$col} or $db{$table}{$i{id}}{$col}) and $db{$table}{$i{id}}{$col} ne $i{$col}) { + # $line .= qq~$col='$i{$col}',~ ; + $line .= qq~$col='$db{$table}{$i{id}}{$col}',~ ; + } elsif ((not $i{$col} and not $db{$table}{$i{id}}{$col}) or (($i{$col} or $db{$table}{$i{id}}{$col}) and $db{$table}{$i{id}}{$col} eq $i{$col})) { + $ignore{$col} = 1 ; $ignore_for_now{$col} = 1 ; + } + } + +} #------------------------------------------------------------------------------------------ + +sub log_changes_2 { + + &db_min_ro('quotes_min','*',"id='$i{id}'",'','') ; + + foreach (keys %i) { + $col_to_be_updated{$_} = 1 ; + } + + foreach my $col (keys %{$db{quotes_min}{$i{id}}}) { + next if $ignore{$col} or $hidden{$col} == 1 or substr($col,0,3) eq 'new' or not $col_to_be_updated{$col} ; + if (($i{$col} or $db{quotes_min}{$i{id}}{$col}) and $db{quotes_min}{$i{id}}{$col} ne $i{$col}) { + # $line .= qq~$col='$i{$col}',~ ; + $line .= qq~$col='$db{quotes_min}{$i{id}}{$col}',~ ; + } elsif ((not $i{$col} and not $db{quotes_min}{$i{id}}{$col}) or (($i{$col} or $db{quotes_min}{$i{id}}{$col}) and $db{quotes_min}{$i{id}}{$col} eq $i{$col})) { + $ignore{$col} = 1 ; $ignore_for_now{$col} = 1 ; + } + } + + chop $line if $line ; + + &common_log_changes("events/changes_quotes.dat",$line) if $line ; + + # exit ; + +} #------------------------------------------------------------------------------------------ + +sub db_min_upd_raw { + +my ($sql) = @_ ; + +&common_debug($sql) ; + +my $sth = $dbh->prepare($sql) ; + +$sth->execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; + +$sth->finish(); + +} #------------------------------------------------------------------------------------------ + +sub titles_for_pdf { + + my $do_insert = 0; + # our %sec_cnt = ('a_systems' => "3-Systems", 'b_software_licence' => "3-Software Licence (Monthly Fee)", 'c_game_breakdown_analytics' => "2-Game Breakdown and Analytics (Annual Fee)", 'd_installation_kits' => "7-Installation Kits", 'e_hardware_add_ons' => "7-Hardware Add Ons", 'f_additional_services' => "7-Additional Services", 'g_match_credits' => "4-Match Credits", 'h_other' => "5-Other", 'i_rental' => "2-Rental"); + $sql_insert_pdf = qq~INSERT INTO `quotes_pdf_titles` (quote_id, old_name, new_name) VALUES ~ ; + db_min_ro('quotes_pdf_titles', '*', "quote_id = $i{id}", '', '') ; + foreach (keys %{$db{quotes_pdf_titles}}){ + next unless $db{quotes_pdf_titles}{$_}{quote_id} == $i{id} ; + $quote_id_old_pdf_titles{$db{quotes_pdf_titles}{$_}{quote_id}}{$db{quotes_pdf_titles}{$_}{old_name}} = 1 ; + # &common_debug("ABC: $db{quotes_pdf_titles}{$_}{quote_id}, $db{quotes_pdf_titles}{$_}{old_name} $i{id}\n") ; + } + # &common_debug("ABC: ") ; + $do_insert = 0 ; + foreach(keys %sec_cnt){ + $first_name = substr($sec_cnt{$_}, 2) ; + $_k = substr($_,1) ; + $ignore{$_k} = 1 ; + if ($quote_id_old_pdf_titles{$i{id}}{$first_name} and $i{$_k}){ + $sql_update_pdf = qq(UPDATE `quotes_pdf_titles` SET new_name = '$i{$_k}' WHERE old_name = '$first_name' and quote_id = $i{id} ;) ; + &db_min_upd_raw($sql_update_pdf) ; + } + elsif (not $quote_id_old_pdf_titles{$i{id}}{$first_name} and $i{$_k}){ + $sql_insert_pdf .= qq(($i{id}, '$first_name', '$i{$_k}'),) ; + $do_insert = 1 ; + + } + elsif ($quote_id_old_pdf_titles{$i{id}}{$first_name} and not $i{$_k}) { + + $sql_update_pdf = qq(UPDATE `quotes_pdf_titles` SET new_name = '$first_name' WHERE old_name = '$first_name' and quote_id = $i{id} ;) ; + &db_min_upd_raw($sql_update_pdf) ; + } + elsif (not $quote_id_old_pdf_titles{$i{id}}{$first_name} and not $i{$_k}) { + + $sql_insert_pdf .= qq(($i{id}, '$first_name', '$first_name'),) ; + $do_insert = 1 ; + } + + } + if ($do_insert){ + chop $sql_insert_pdf ; + $sql_insert_pdf .= ";" ; + &db_min_upd_raw($sql_insert_pdf) ; + } + +} #------------------------------------------------------------------------------------------ + +sub switch_table { + + &db_min_ro('quote_notes','*',"id='1'",'','') ; + + my @note_fields = ("note","payment_term","roe","delivery_time") ; + + for my $row_cnt (1 .. 12) { + foreach my $fields (@note_fields) { + my $field = "$fields\_$row_cnt" ; + $ignore{$field} = (($i{$field} && $i{$field} eq $db{quote_notes}{1}{$field}) || (($fields eq "payment_term" || $fields eq "roe") && $row_cnt > 6) || ($fields eq "delivery_time" && $row_cnt > 4)) ? 1 : 0 ; + $i{$field} = (!$i{$field} && $db{quote_notes}{1}{$field}) ? "-1" : $i{$field} ; + } + } + + # local @ttlarr = ("one_time_fee","monthly_recurring_fee","annual_fee") ; + # local @ttlarr2 = ("subtotal","vat","total") ; + + # foreach my $a (@ttlarr) { + # foreach my $b (@ttlarr2) { + # my $field_1 = "1_$b\_$a" ; + # my $field_2 = "2_$b\_$a" ; + # my $field = "$b\_$a" ; + # $i{$field} = qq~$i{$field_1};$i{$field_2}~ ; + # $ignore{$field_1} = 1 ; + # $ignore{$field_2} = 1 ; + # } + # } + + %y = () ; + + foreach (keys %i) { + if ($_ =~ /^excl_costing_/ || $_ =~ /^description_costing_/ || $_ =~ /^qty_costing_/ || $_ =~ /^zar_amount_costing_/ || $_ =~ /^total_costing_/ || $_ =~ /^vat_costing_/) { + $ignore{$_} = 1 ; + } + } + + for (1 .. $nr_of_costing_rows) { + + # $y{1}{$_} = "curr_amnt_" . "$_" . "_costing_additional_services"; + # $y{2}{$_} = "curr_amnt_" . "$_" . "_costing_game_breakdown_analytics"; + # $y{3}{$_} = "curr_amnt_" . "$_" . "_costing_hardware_add_ons"; + # $y{4}{$_} = "curr_amnt_" . "$_" . "_costing_installation_kits"; + # $y{5}{$_} = "curr_amnt_" . "$_" . "_costing_match_credits"; + # $y{6}{$_} = "curr_amnt_" . "$_" . "_costing_other"; + # $y{7}{$_} = "curr_amnt_" . "$_" . "_costing_rental"; + # $y{8}{$_} = "curr_amnt_" . "$_" . "_costing_software_licence"; + # $y{9}{$_} = "curr_amnt_" . "$_" . "_costing_systems"; + # $y{10}{$_} = "excl_" . "$_" . "_costing_additional_services"; + # $y{11}{$_} = "excl_" . "$_" . "_costing_game_breakdown_analytics"; + # $y{12}{$_} = "excl_" . "$_" . "_costing_hardware_add_ons"; + # $y{13}{$_} = "excl_" . "$_" . "_costing_installation_kits"; + # $y{14}{$_} = "excl_" . "$_" . "_costing_match_credits"; + # $y{15}{$_} = "excl_" . "$_" . "_costing_other"; + # $y{16}{$_} = "excl_" . "$_" . "_costing_rental"; + # $y{17}{$_} = "excl_" . "$_" . "_costing_software_licence"; + # $y{18}{$_} = "excl_" . "$_" . "_costing_systems"; + # $y{19}{$_} = "excl_" . "$_" . "_delivery_times"; + # $y{20}{$_} = "excl_" . "$_" . "_notes"; + # $y{21}{$_} = "excl_" . "$_" . "_payment_terms"; + # $y{22}{$_} = "excl_" . "$_" . "_purchase_summary"; + # $y{23}{$_} = "excl_" . "$_" . "_roes"; + # $y{24}{$_} = "excl_" . "$_" . "_terms"; + # $y{25}{$_} = "item_" . "$_" . "_costing_additional_services"; + # $y{26}{$_} = "item_" . "$_" . "_costing_game_breakdown_analytics"; + # $y{27}{$_} = "item_" . "$_" . "_costing_hardware_add_ons"; + # $y{28}{$_} = "item_" . "$_" . "_costing_installation_kits"; + # $y{29}{$_} = "item_" . "$_" . "_costing_match_credits"; + # $y{30}{$_} = "item_" . "$_" . "_costing_other"; + # $y{31}{$_} = "item_" . "$_" . "_costing_rental"; + # $y{32}{$_} = "item_" . "$_" . "_costing_software_licence"; + # $y{33}{$_} = "item_" . "$_" . "_costing_systems"; + # $y{34}{$_} = "item_" . "$_" . "_purchase_summary"; + # $y{35}{$_} = "item_ttl_" . "$_" . "_costing_additional_services"; + # $y{36}{$_} = "item_ttl_" . "$_" . "_costing_game_breakdown_analytics"; + # $y{37}{$_} = "item_ttl_" . "$_" . "_costing_hardware_add_ons"; + # $y{38}{$_} = "item_ttl_" . "$_" . "_costing_installation_kits"; + # $y{39}{$_} = "item_ttl_" . "$_" . "_costing_match_credits"; + # $y{40}{$_} = "item_ttl_" . "$_" . "_costing_other"; + # $y{41}{$_} = "item_ttl_" . "$_" . "_costing_rental"; + # $y{42}{$_} = "item_ttl_" . "$_" . "_costing_software_licence"; + # $y{43}{$_} = "item_ttl_" . "$_" . "_costing_systems"; + # $y{44}{$_} = "qty_" . "$_" . "_costing_additional_services"; + # $y{45}{$_} = "qty_" . "$_" . "_costing_game_breakdown_analytics"; + # $y{46}{$_} = "qty_" . "$_" . "_costing_hardware_add_ons"; + # $y{47}{$_} = "qty_" . "$_" . "_costing_installation_kits"; + # $y{48}{$_} = "qty_" . "$_" . "_costing_match_credits"; + # $y{49}{$_} = "qty_" . "$_" . "_costing_other"; + # $y{50}{$_} = "qty_" . "$_" . "_costing_rental"; + # $y{51}{$_} = "qty_" . "$_" . "_costing_software_licence"; + # $y{52}{$_} = "qty_" . "$_" . "_costing_systems"; + # $y{53}{$_} = "usd_amnt_" . "$_" . "_costing_additional_services"; + # $y{54}{$_} = "usd_amnt_" . "$_" . "_costing_game_breakdown_analytics"; + # $y{55}{$_} = "usd_amnt_" . "$_" . "_costing_hardware_add_ons"; + # $y{56}{$_} = "usd_amnt_" . "$_" . "_costing_installation_kits"; + # $y{57}{$_} = "usd_amnt_" . "$_" . "_costing_match_credits"; + # $y{58}{$_} = "usd_amnt_" . "$_" . "_costing_other"; + # $y{59}{$_} = "usd_amnt_" . "$_" . "_costing_rental"; + # $y{60}{$_} = "usd_amnt_" . "$_" . "_costing_software_licence"; + # $y{61}{$_} = "usd_amnt_" . "$_" . "_costing_systems"; + # $y{62}{$_} = "vat_" . "$_" . "_costing_additional_services"; + # $y{63}{$_} = "vat_" . "$_" . "_costing_game_breakdown_analytics"; + # $y{64}{$_} = "vat_" . "$_" . "_costing_hardware_add_ons"; + # $y{65}{$_} = "vat_" . "$_" . "_costing_installation_kits"; + # $y{66}{$_} = "vat_" . "$_" . "_costing_match_credits"; + # $y{67}{$_} = "vat_" . "$_" . "_costing_other"; + # $y{68}{$_} = "vat_" . "$_" . "_costing_rental"; + # $y{69}{$_} = "vat_" . "$_" . "_costing_software_licence"; + # $y{70}{$_} = "vat_" . "$_" . "_costing_systems"; + + $y{71}{$_} = "excl_costing_$_" ; + $y{72}{$_} = "description_costing_$_" ; + $y{73}{$_} = "qty_costing_$_" ; + $y{74}{$_} = "zar_amount_costing_$_" ; + $y{75}{$_} = "vat_costing_$_"; + $y{76}{$_} = "total_costing_$_"; + + foreach my $a (keys %y){ + foreach my $b (keys %{$y{$a}}){ + # $ignore{$y{$a}{$b}} = 1 ; + $x{$a}{$b} = $i{$y{$a}{$b}} ; + } + } + } + +} #------------------------------------------------------------------------------------------ + +sub new_table { + + # my ($insert_part) = @_ ; + $iid = $i{id} ; + my $quote_nr = $i{quote_nr} ; + %i = () ; + $i{id} = $iid ; + $i{quote_nr} = $quote_nr ; + $ignore{quote_nr} = 1 ; + + for (1 .. $nr_of_costing_rows) { + + # $i{curr_amnt_costing_additional_services} .= "$x{1}{$_};" ; + # $i{curr_amnt_costing_game_breakdown_analytics} .= "$x{2}{$_};" ; + # $i{curr_amnt_costing_hardware_add_ons} .= "$x{3}{$_};" ; + # $i{curr_amnt_costing_installation_kits} .= "$x{4}{$_};" ; + # $i{curr_amnt_costing_match_credits} .= "$x{5}{$_};" ; + # $i{curr_amnt_costing_other} .= "$x{6}{$_};" ; + # $i{curr_amnt_costing_rental} .= "$x{7}{$_};" ; + # $i{curr_amnt_costing_software_licence} .= "$x{8}{$_};" ; + # $i{curr_amnt_costing_systems} .= "$x{9}{$_};" ; + # $i{excl_costing_additional_services} .= "$x{10}{$_};" ; + # $i{excl_costing_game_breakdown_analytics} .= "$x{11}{$_};" ; + # $i{excl_costing_hardware_add_ons} .= "$x{12}{$_};" ; + # $i{excl_costing_installation_kits} .= "$x{13}{$_};" ; + # $i{excl_costing_match_credits} .= "$x{14}{$_};" ; + # $i{excl_costing_other} .= "$x{15}{$_};" ; + # $i{excl_costing_rental} .= "$x{16}{$_};" ; + # $i{excl_costing_software_licence} .= "$x{17}{$_};" ; + # $i{excl_costing_systems} .= "$x{18}{$_};" ; + # $i{excl_delivery_times} .= "$x{19}{$_};" ; + # $i{excl_notes} .= "$x{20}{$_};" if $x{20}{$_}; + # $i{excl_notes} .= "0;" if not $x{20}{$_}; + # $i{excl_payment_terms} .= "$x{21}{$_};" ; + # $i{excl_purchase_summary} .= "$x{22}{$_};" if $x{22}{$_}; + # $i{excl_purchase_summary} .= "0;" if not $x{22}{$_}; + # $i{excl_roes} .= "$x{23}{$_};" ; + # $i{excl_terms} .= "$x{24}{$_};" ; + # $i{item_costing_additional_services} .= "$x{25}{$_};" ; + # $i{item_costing_game_breakdown_analytics} .= "$x{26}{$_};" ; + # $i{item_costing_hardware_add_ons} .= "$x{27}{$_};" ; + # $i{item_costing_installation_kits} .= "$x{28}{$_};" ; + # $i{item_costing_match_credits} .= "$x{29}{$_};" ; + # $i{item_costing_other} .= "$x{30}{$_};" ; + # $i{item_costing_rental} .= "$x{31}{$_};" ; + # $i{item_costing_software_licence} .= "$x{32}{$_};" ; + # $i{item_costing_systems} .= "$x{33}{$_};" ; + # $i{item_purchase_summary} .= "$x{34}{$_};" ; + # $i{item_ttl_costing_additional_services} .= "$x{35}{$_};" ; + # $i{item_ttl_costing_game_breakdown_analytics} .= "$x{36}{$_};" ; + # $i{item_ttl_costing_hardware_add_ons} .= "$x{37}{$_};" ; + # $i{item_ttl_costing_installation_kits} .= "$x{38}{$_};" ; + # $i{item_ttl_costing_match_credits} .= "$x{39}{$_};" ; + # $i{item_ttl_costing_other} .= "$x{40}{$_};" ; + # $i{item_ttl_costing_rental} .= "$x{41}{$_};" ; + # $i{item_ttl_costing_software_licence} .= "$x{42}{$_};" ; + # $i{item_ttl_costing_systems} .= "$x{43}{$_};" ; + # $i{qty_costing_additional_services} .= "$x{44}{$_};" ; + # $i{qty_costing_game_breakdown_analytics} .= "$x{45}{$_};" ; + # $i{qty_costing_hardware_add_ons} .= "$x{46}{$_};" ; + # $i{qty_costing_installation_kits} .= "$x{47}{$_};" ; + # $i{qty_costing_match_credits} .= "$x{48}{$_};" ; + # $i{qty_costing_other} .= "$x{49}{$_};" ; + # $i{qty_costing_rental} .= "$x{50}{$_};" ; + # $i{qty_costing_software_licence} .= "$x{51}{$_};" ; + # $i{qty_costing_systems} .= "$x{52}{$_};" ; + # $i{usd_amnt_costing_additional_services} .= "$x{53}{$_};" ; + # $i{usd_amnt_costing_game_breakdown_analytics} .= "$x{54}{$_};" ; + # $i{usd_amnt_costing_hardware_add_ons} .= "$x{55}{$_};" ; + # $i{usd_amnt_costing_installation_kits} .= "$x{56}{$_};" ; + # $i{usd_amnt_costing_match_credits} .= "$x{57}{$_};" ; + # $i{usd_amnt_costing_other} .= "$x{58}{$_};" ; + # $i{usd_amnt_costing_rental} .= "$x{59}{$_};" ; + # $i{usd_amnt_costing_software_licence} .= "$x{60}{$_};" ; + # $i{usd_amnt_costing_systems} .= "$x{61}{$_};" ; + # $i{vat_costing_additional_services} .= "$x{62}{$_};" ; + # $i{vat_costing_game_breakdown_analytics} .= "$x{63}{$_};" ; + # $i{vat_costing_hardware_add_ons} .= "$x{64}{$_};" ; + # $i{vat_costing_installation_kits} .= "$x{65}{$_};" ; + # $i{vat_costing_match_credits} .= "$x{66}{$_};" ; + # $i{vat_costing_other} .= "$x{67}{$_};" ; + # $i{vat_costing_rental} .= "$x{68}{$_};" ; + # $i{vat_costing_software_licence} .= "$x{69}{$_};" ; + # $i{vat_costing_systems} .= "$x{70}{$_};" ; + + $i{excl_costing} .= "$x{71}{$_};" ; + $i{description_costing} .= "$x{72}{$_}:;:" ; + $i{qty_costing} .= "$x{73}{$_};" ; + $i{amount_costing} .= "$x{74}{$_};" ; + $i{vat_costing} .= "$x{75}{$_};" ; + + } + + # if ($insert_part){ + # $sql_insert_1 = qq~INSERT INTO `quotes_min` (~ ; + # $sql_insert_2 = qq~VALUES (~ ; + # } + + foreach (keys %i) { + + next if $_ eq 'id' ; + + if ($_ =~ /^excl_/ || $_ =~ /^vat_/) { + $i{$_} =~ s/\0//g ; + } elsif ($_ =~ /_amnt_/ || $_ =~ /_amount_/) { + $i{$_} =~ s/^0.00//g ; + $i{$_} =~ s/\;0.00/\;/g ; + } + $i{$_} =~ s/;+$//g ; + $i{$_} =~ s/\:;:+$//g if $_ =~ /^description_/ ; + + } + + # if ($insert_part){ + # $sql_insert_1 .= qq~$_,~ ; + # $sql_insert_2 .= qq~'$i{$_}',~ ; + # } + # } + # if ($insert_part){ + # chop $sql_insert_1 ; + # chop $sql_insert_2 ; + # $sql_insert_2 .= qq~) ;~ ; + # $final_insert = $sql_insert_1 . $sql_insert_2 ; + # &db_min_upd_raw($final_insert) ; + # } +} #------------------------------------------------------------------------------------------ + + +sub update_camera { + + # &common_debug("1. update_camera : $i{quote_nr}"); + unless ($i{quote_nr}) { $error = qq~NO QUOTE NR~ ; return ; } # &common_debug("update_camera : $error"); + + $ignore{quote_nr} = '' ; + $q{quote_nr} = $i{quote_nr} ; + # $q{quote_ref} = $i{ref} ; + $q{id} = $i{id} ; + + %i=(); + + $i{quote_delivery_date} = NULL ; + $i{quote_active_date} = NULL ; + $i{quote_ew_date_from} = NULL ; + $i{quote_ew_date_to} = NULL ; + $i{quote_cam_desc} = NULL ; + $i{quote_cam_excl} = 0 ; + $i{quote_cam_num} = 0 ; + $i{quote_nr} = 0 ; + $i{quote_ref} = NULL ; + + # &db_min_ro('cameras','*',"quote_nr='$q{quote_nr}'",'','') ; # &db_min_ro('quotes','*','','','') ; + + &db_min_upd('cameras',"quote_nr='$q{quote_nr}'") ; # remove all previous links to this quote + + # $i{quote_nr} = $q{quote_nr} ; + # $i{quote_ref} = $q{quote_ref} ; + + for (1 .. $camera_cnt_allowed) { + # &common_debug("$_. camera_nr_$_\_camera_details [".$q{"camera_nr_$_\_camera_details"}."]"); + + next unless $q{"camera_nr_$_\_camera_details"} ; + + %i=(); + + $i{quote_nr} = $q{quote_nr} ; + $i{quote_delivery_date} = $q{"delivery_date_$_\_camera_details"} if $q{"delivery_date_$_\_camera_details"} ; + $i{quote_active_date} = $q{"active_date_$_\_camera_details"} if $q{"active_date_$_\_camera_details"} ; + $i{quote_ew_date_from} = $q{"ew_date_from_$_\_camera_details"} if $q{"ew_date_from_$_\_camera_details"} ; + $i{quote_ew_date_to} = $q{"ew_date_to_$_\_camera_details"} if $q{"ew_date_to_$_\_camera_details"} ; + $i{quote_cam_desc} = $q{"description_$_\_camera_details"} if $q{"description_$_\_camera_details"} ; + $i{quote_cam_excl} = $q{"excl_$_\_camera_details"} if $q{"excl_$_\_camera_details"} ; + $i{quote_cam_num} = $_ if $_ ; + $i{quote_ref} = $q{"ref_$_\_camera_details"} if $q{"ref_$_\_camera_details"} ; + + my @valarr = split(/\:/,$q{"camera_nr_$_\_camera_details"}) ; # $id:camera_nr:camera_system_id:serial_nr:date_delivered:camera_system:item_code:date_active + + my $abrv_cam_system = substr($valarr[1],0,3); + # &common_debug("[".$q{"camera_nr_$_\_camera_details"}."] abrv_cam_system=$abrv_cam_system, abrv_prev_cam_system=$abrv_prev_cam_system, prev_cam_nr=$prev_cam_nr, link to: c_excl_$_\_camera_details") ; + if ($abrv_cam_system eq 'VPU' and ($abrv_prev_cam_system eq 'S1' or $abrv_prev_cam_system eq 'S2' or $abrv_prev_cam_system_other eq 'Prime' or $abrv_prev_cam_system_other eq 'Coach')) { + # $trigger_jquery .= qq~\$("#c_excl_$_\_camera_details").append("");\$('[data-toggle="tooltip"]').tooltip({html:true}) ;~; + my $s1_cnt = $_-1; + $i{quote_linked_vpu} = $q{"serial_nr_$s1_cnt\_camera_details"} if $q{"serial_nr_$s1_cnt\_camera_details"} ; + } + $abrv_prev_cam_system = substr($abrv_cam_system,0,2); + $abrv_prev_cam_system_other = substr($abrv_cam_system,0,5); + $prev_cam_nr = $valarr[1] ; + + my $cam_id = $valarr[0] ; + next unless $cam_id ; + + &db_min_upd('cameras',"id='$cam_id'") ; # add the new details from the screen + + # $i{quote_linked_vpu} = '' ; + } + + $i{id} = $q{id} ; + +} #------------------------------------------------------------------------------------------ + +sub duplicate { + +unless ($i{id}) { $error = qq~NO ID~ ; return ; } + +local $copy_id = $i{id} ; + +&db_min_copy($table,$copy_id) ; + +&db_min_copy('quotes_min',$copy_id) ; + +&common_min_copy_files("$htmlpath/uploads/workings/$copy_id","$htmlpath/uploads/workings/$i{id}") ; + +} #------------------------------------------------------------------------------------------ + +sub delete { + +my $dbid = 'id' ; if ($uniq_id) { $dbid = $uniq_id ; } + +unless ($i{$dbid}) { $error = uc "NO $dbid" ; return ; } + +&db_min_delete('quotes',"$dbid='$i{$dbid}'") ; + +&db_min_delete('quotes_min',"$dbid='$i{$dbid}'") ; + +&common_min_delete_files("$htmlpath/uploads/workings/$i{$dbid}") ; + +}#------------------------------------------------------------------------------------------ + +sub process_upload_ifields { + +$ignore{costing_1} = 1 ; +$ignore{costing_2} = 1 ; +$ignore{costing_3} = 1 ; + +$ignore{iattachcosting_1} = 1 ; +$ignore{iattachcosting_2} = 1 ; +$ignore{iattachcosting_3} = 1 ; + +$i{costing_uploads} = qq~$i{iattachcosting_1}:;:$i{iattachcosting_2}:;:$i{iattachcosting_3}~ ; + +$i{costing_uploads} =~ s/\:;:+$//g ; + +# foreach (keys %uploads_file) { $i{$_} = $uploads_file{$_} ; $ignore{$_} = '' ; } + +} #------------------------------------------------------------------------------------------ + +sub set_default_i_vals { + +my @camera_details = ('camera_nr_','serial_nr_','description_','active_date_','delivery_date_','ew_date_from_','ew_date_to_','ref_','excl_') ; + +for (1 .. $camera_cnt_allowed) { + foreach my $cdet_ (@camera_details) { + my $col = "$cdet_$_\_camera_details"; + $ignore{$col} = 1 ; # set the value to only be the id + $q{$col} = $i{$col} ; # set the value to only be the id + } +} + +my $srch_where_sql = "`id`='$i{id}'" ; + +$iaction eq 'save' ? &db_min_ro($table,'*','','id DESC',1) : &db_min_ro($table,'*',$srch_where_sql,'','') ; + +foreach (sort { $col_name{$a} cmp $col_name{$b} } keys %col_name) { + $col = $col_name{$_} ; + + &common_min_debug("1. [$col] [$i{$col}]"); + + if (substr($col,0,4) eq 'vat_' or substr($col,0,5) eq 'excl_' or substr($col,0,4) eq 'qty_') { + unless ($i{$col}) { $i{$col} = 0 ; } + } # only create the column if it doesn't exist + + if (substr($col,0,9) eq 'usd_amnt_' or substr($col,0,10) eq 'curr_amnt_' or substr($col,0,9) eq 'item_ttl_' or substr($col,-6,6) eq '_total') { + unless ($i{$col}) { $i{$col} = '0.00' ; } + } + + # # if (substr($col,0,14) eq 'delivery_date_' or substr($col,0,12) eq 'active_date_') { + # if (substr($col,0,14) eq 'delivery_date_' or substr($col,0,12) eq 'active_date_' or substr($col,0,8) eq 'ew_date_') { + # unless ($i{$col}) { $i{$col} = NULL ; } + # } + + # if ((substr($col,6,9) eq '_costing_' and substr($col,0,5) eq 'item_' and $i{$col}) or ($col eq 'quote_to' and $i{$col}) or (substr($col,-15,15) eq '_camera_details' and substr($col,0,10) eq 'camera_nr_' and $i{$col})) { + # if ((substr($col,6,9) eq '_costing_' and substr($col,0,5) eq 'item_' and $i{$col}) or ($col eq 'quote_to' and $i{$col})) { + if (((substr($col,6,9) eq '_costing_' or substr($col,7,9) eq '_costing_') and substr($col,0,5) eq 'item_' and $i{$col}) or ($col eq 'quote_to' and $i{$col})) { # item_1_costing_match_credits + my @valarr = split(/\:/,$i{$col}) ; + $i{$col} = $valarr[0] ; # set the value to only be the id + } + + # if (substr($col,-15,15) eq '_camera_details') { + # # if (substr($col,0,9) eq 'camera_nr') { + # # my @valarr = split(/\:/,$i{$col}) ; + # # $q{$col} = $i{$col} ; # set the value to only be the id + # # $i{$col} = $valarr[0] ; # set the value to only be the id + # # } elsif (substr($col,0,5) eq 'excl_') { + # # # do nothing + # # } else { + # $ignore{$col} = 1 ; # set the value to only be the id + # $q{$col} = $i{$col} ; # set the value to only be the id + # # } + # } + + # &common_min_debug("2. [$col] [$i{$col}]"); +} + +$i{terms} = 0 unless $i{terms} ; +$i{quote_accepted} = 0 unless $i{quote_accepted} ; +$i{quote_pending} = 0 unless $i{quote_pending} ; +$i{quote_cancelled} = 0 unless $i{quote_cancelled} ; +$i{annual_invoice} = 0 unless $i{annual_invoice} ; +$i{period} = 0 unless $i{period} ; +$i{max_cams} = 0 unless $i{max_cams} ; +$i{camera_system_id} = 0 unless $i{camera_system_id} ; +$i{country_shipped} = 0 unless $i{country_shipped} ; +$i{discount} = 0 unless $i{discount} ; +$i{systems_included} = 0 unless $i{systems_included} ; +$i{rental_included} = 0 unless $i{rental_included} ; +$i{total_1_purchase_summary} = "0.00" unless $i{total_1_purchase_summary} ; +$i{total_2_purchase_summary} = "0.00" unless $i{total_2_purchase_summary} ; +$i{total_3_purchase_summary} = "0.00" unless $i{total_3_purchase_summary} ; + +for my $a (1 .. 3) { + for my $b (1 .. 3) { + $i{"year_$a\_$b\_purchase_summary"} = "0.00" unless $i{"year_$a\_$b\_purchase_summary"} ; + } +} + +$ignore{invoice_date} = 1 unless length($i{invoice_date}) == 10 ; + +} #---------------------------------------------------------------------------------------- + +sub list_screen { + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + # my $tables = 'towns,airport_codes' ; + + # &db_min_ro($tables,'towns.id,towns.airport_code,airport_codes.name,towns.name','towns.airport_code=airport_codes.iata_code','','') ; + # foreach my $id (keys %{$db{$tables}}) { $user{$id} = $db{$tables}{$id}{name} ; } + + # &db_min_ro('users','id,name','','','') ; + # foreach my $id (keys %{$db{users}}) { $user{$id} = $db{users}{$id}{name} ; } + + # &db_min_ro('customers','id,name','','','') ; + # foreach my $id (keys %{$db{customers}}) { $customers{$id} = $db{customers}{$id}{name} ; } + + # &db_min_ro('camera_systems','*','','','') ; + # foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + + # &db_min_ro('countries','*','','','') ; + # foreach my $id (keys %{$db{countries}}) { $country{$id} = $db{countries}{$id}{name} ; } + + if ($iaction eq 'accepted' or $i{options} eq 'accepted') { push @report_sql, "$table.quote_accepted='1'" ; } + if ($iaction eq 'closed' or $i{options} eq 'closed') { push @report_sql, "($table.quote_cancelled='1' OR ($table.quote_expiry<'$now_year-$now_mm-$now_dd' AND $table.quote_accepted<>'1'))" ; } + if ($iaction eq 'pending' or $i{options} eq 'pending') { push @report_sql, "$table.quote_pending='1'" ; } + if ($iaction eq 'list' or $i{options} eq 'list') { push @report_sql, "$table.quote_cancelled<>'1'" ; } + + my $t1 = $table ; + my $t2 = 'countries' ; + my $t3 = 'camera_systems' ; + my $t4 = 'customers' ; + my $t5 = 'quote_type' ; + my $t6 = 'quotes_min' ; + our $tables = "$t1,$t2,$t3,$t4,$t5,$t6" ; + + # push @report_sql, "($t1.country_shipped=$t2.id)" ; + # push @report_sql, "($t1.camera_system_id=$t3.id)" ; + # push @report_sql, "($t1.quote_to=$t4.id)" ; + # push @report_sql, "($t1.type_id=$t5.id)" ; + + my $srch_where_sql = join(' AND ', @report_sql) ; + $srch_where_sql = "1" unless $srch_where_sql ; + + # &db_min_ro($tables,"$t1.id AS 'quote_id',$t1.quote_nr,$t1.ref,$t1.qty,$t1.quote_expiry,$t1.quote_to,$t1.invoice_nr,$t1.quote_date,$t1.type,$t1.currency,$t1.country_shipped,$t1.total_1_purchase_summary,$t1.total_2_purchase_summary,$t1.total_3_purchase_summary,$t1.quote_cancelled,$t1.quote_accepted,$t1.quote_pending,$t1.activetab,$t2.name AS 'country',$t3.name AS 'camera_system',$t4.name AS 'customer',$t5.name AS 'type'",$srch_where_sql,'','') ; + + &db_min_raw(" + SELECT + $t1.id AS 'quote_id', + $t1.quote_nr, + $t1.ref, + $t1.qty, + $t1.quote_expiry, + $t1.quote_to, + $t1.invoice_nr, + $t1.quote_date, + $t1.type, + $t1.currency, + $t1.country_shipped, + $t1.total_1_purchase_summary, + $t1.total_2_purchase_summary, + $t1.total_3_purchase_summary, + $t1.quote_cancelled, + $t1.quote_accepted, + $t1.quote_pending, + $t1.activetab, + $t1.roe, + $t2.name AS 'country', + $t3.name AS 'camera_system', + $t4.name AS 'customer', + $t5.name AS 'type', + $t6.qty_costing, + $t6.amount_costing, + $t6.vat_costing, + $t6.excl_costing + FROM $t1 LEFT JOIN $t2 ON $t1.country_shipped=$t2.id + LEFT JOIN $t3 ON $t1.camera_system_id=$t3.id + LEFT JOIN $t4 ON $t1.quote_to=$t4.id + LEFT JOIN $t5 ON $t1.type_id=$t5.id + LEFT JOIN $t6 ON $t1.id=$t6.id + WHERE + $srch_where_sql ; + ") ; + + foreach $row (@$rows_array_ref) { + for (0 .. $col_cnt){ + # &common_debug("[$_] $col_name{$_} -> @$row[$_]") ; + $db{$tables}{@$row[0]}{$col_name{$_}} = @$row[$_] ; + } + } + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +&tab_hash ; # load for PDF links + +# &common_load_quote_vars("cameras.quote_nr>0 AND cameras.quote_cam_num='1' AND (cameras.quote_delivery_date IS NOT NULL or cameras.quote_active_date IS NOT NULL) AND cameras.quote_nr=quotes.quote_nr"); +&common_load_quote_vars("cameras.quote_nr>0 AND cameras.quote_nr=quotes.quote_nr"); + + +# foreach (keys %quote_cam_delivery_date) { + # $store_quote_cam_delivery_date{$_}{1} = $quote_cam_delivery_date{$_}{1} ; +# } + +# foreach (keys %quote_cam_delivery_date) { + # $store_quote_cam_active_date{$_}{1} = $quote_cam_active_date{$_}{1} ; +# } + +"e_list ; # load for PDF links + +# our $fnsort = 1 ; # used &common_min_screen3 for fnsort column &common_min_table + +if ($iaction eq 'update' or $iaction eq 'save'){ + &common_min_extra_crumb("list-$lcpage\s","List $ucfirstpage\s") ; +} + +} #------------------------------------------------------------------------------------------ + +sub quote_list { + +our @sql_col_display = ("nr","date","customer","country","type","qty","CUR","amount","invoice_nr","") ; +# our @sql_col_display = ("nr","date","customer","ref","country","camera_system_id","qty","curr","amount","invoice_nr","type","date_delivered","date_active","flag","") ; +# our @sql_col_display = ("nr","date","customer","ref","invoice_nr","type","") ; + +if ($i{export_to_excel}) { &report_xls_export_header("Quotes",'quotes') ; } + +# &common_min_debug("[$table]"); + +our $open_new_tab = qq~target="_blank"~ ; + +foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) { + + # &common_min_debug("[$id] [$tables] [$db{$tables}{$id}{quote_nr} ]"); + + unless ($id) { next ; } + + our $quote_expiry = $db{$tables}{$id}{quote_expiry} ; $quote_expiry =~ s/\-//iog ; + # my $quote_date = $db{$tables}{$id}{quote_date} ; $quote_date =~ s/\-//iog ; + # if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all') { next ; } + + # $yr = substr($quote_date, 0, 4) ; + # $mm = substr($quote_date, 4, 2) ; + # $dd = substr($quote_date, 6, 2) ; + + # my ($yr2,$mm2,$dd2) = Add_Delta_Days($yr,$mm,$dd,60); # + + # $mm2 = sprintf("%02s", $mm2) ; + # $dd2 = sprintf("%02s", $dd2) ; + + # $quote_date = "$yr2$mm2$dd2" ; + + # if ($quote_date and $quote_date<"$now_year$now_mm$now_dd" and $db{$tables}{$id}{quote_accepted}!=1 and + # $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all' and + # $i{options} ne 'accepted' and $i{options} ne 'closed' and $i{options} ne 'all') + # { next ; } + + if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $db{$tables}{$id}{quote_accepted}!=1 and + $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all' and + $i{options} ne 'accepted' and $i{options} ne 'closed' and $i{options} ne 'all') + { next ; } + # &common_min_debug("[$id] [$tables] [$db{$tables}{$id}{quote_nr} ]"); + + $print_tbody .= qq~~ ; + + $xlscol=0; + + my $quote_nr = $db{$tables}{$id}{quote_nr} ; + + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$tables}{$id}{$_} ; + my $align = '' ; my $nowrap = '' ; + + if ($_ eq 'ref') { $nowrap = 'nowrap' ; ; } + if ($_ eq 'customer') { $val = $db{$tables}{$id}{customer} ; $nowrap = 'nowrap' ; ; } + if ($_ eq 'date') { $val = &common_min_date_as_string($db{$tables}{$id}{quote_date}) ; } + if ($_ eq 'date_delivered') { $val = $quote_cam_delivery_date{$quote_nr}{1} ; $align = qq~ class="dt-center"~ ; } + if ($_ eq 'date_active') { $val = $quote_cam_active_date{$quote_nr}{1} ; $align = qq~ class="dt-center"~ ; } + if ($_ eq 'type') { $val = $db{$tables}{$id}{type} ; $align = qq~ class="dt-center"~ ; } + if ($_ eq 'camera_system_id') { $val = $db{$tables}{$id}{camera_system} ; } + if ($_ eq 'CUR') { $val = $db{$tables}{$id}{currency} ; $align = qq~ class="dt-center"~ ; } + if ($_ eq 'country') { $val = $db{$tables}{$id}{country} ; } + # if ($_ eq 'qty') { $val = $cnt_cams{$quote_nr} ; } + if ($_ eq 'qty') { $val = $db{$tables}{$id}{qty} ; $val = '' if $val==0; $align = qq~ class="dt-center"~ ; } + if ($_ eq 'currency') { $align = qq~ class="dt-center"~ ; } + + if ($_ eq 'amount') { + # my $ttl = sprintf("%0.2f",($db{$tables}{$id}{total_1_purchase_summary} + $db{$tables}{$id}{total_2_purchase_summary} + $db{$tables}{$id}{total_3_purchase_summary})) ; + + my $ttl = 0 ; + + my @excl_arr = split(/\;/,$db{$tables}{$id}{excl_costing}) ; + my @qty_arr = split(/\;/,$db{$tables}{$id}{qty_costing}) ; + my @amount_arr = split(/\;/,$db{$tables}{$id}{amount_costing}) ; + my @vat_arr = split(/\;/,$db{$tables}{$id}{vat_costing}) ; + + my $counter = 0 ; + foreach (split(/\;/,$db{$tables}{$id}{qty_costing})) { + $ttl += $qty_arr[$counter]*$amount_arr[$counter] + 0.15*$qty_arr[$counter]*$amount_arr[$counter]*$vat_arr[$counter] unless $excl_arr[$counter] ; + $counter++ ; + } + + $ttl = sprintf("%0.2f",$ttl) ; + $val = &common_commify($ttl) ; + $val = '' if $val eq '0.00' ; + $align = qq~ class="dt-right"~ ; + } + + if ($_ eq 'nr') { + + $val = &common_min_get_quote_button($id,$tables) ; + + # my $class = 'info' ; + # if ($db{$tables}{$id}{quote_cancelled}) { + # $class = 'danger' ; + # } elsif ($db{$tables}{$id}{quote_accepted}) { + # $class = 'success' ; + # } elsif ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd") { + # $class = 'danger' ; + # } elsif ($db{$tables}{$id}{quote_pending}) { + # $class = 'warning' ; + # } + # $val = qq~$quote_nr~ ; + } + + if ($i{export_to_excel}) { + &report_xls_export_process_cell('','',$val) ; # ------------------------------------------------------------------------- HTML AFTER + $xlscol++; + } + + $print_tbody .= qq~$val~ ; + } + + my $delete_butt = '' ; my $edit_butt = '' ; + + my $quote_nr = $quote_nr ; $quote_nr =~ s/'//iog; unless ($quote_nr) { $quote_nr = $id ; } + + # if ($useropts{boss}{$username} or $useropts{super}{$username}) { } + + $edit_butt = qq~~ ; + $delete_butt = qq~~ ; + $copy_butt = qq~~; + # $pdf_butt = qq~~; + + $print_tbody .= qq~ $edit_butt $copy_butt $delete_butt $pdf_butt~ ; + if ($i{export_to_excel}) { $xlsrow++ ; } +} + +if ($i{export_to_excel}) { &report_xls_export_footer('L',15,'quotes') ; } + +# $fnsortcol = 8 ; # order by ol devices col + +$print_more_boxes .= qq~


    ~ ; + +&common_min_extra_crumb("search-$lcpage\s","Search Screen") ; + +} #------------------------------------------------------------------------------- + +sub thead { + +&common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub add_db_fields { + +&hidden_fields ; + +$hidden{id} = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + +&hidden_fields ; + +$hidden{id} = 1 ; +# $readonly{ref} = 'READONLY' ; + +} #------------------------------------------------------------------------------------------ + +sub hidden_fields { + +$ignore{iattachcosting_delivery_note} = 1 ; +$ignore{iattachcosting_other_1} = 1 ; +$ignore{iattachcosting_other_2} = 1 ; +$ignore{iattachcosting_other_3} = 1 ; +$ignore{iattachcosting_photos} = 1 ; +$ignore{iattachcosting_po} = 1 ; +$ignore{iattachcosting_signed_quote} = 1 ; +$ignore{iattachcosting_sla} = 1 ; +$ignore{iattachcosting_t_cs} = 1 ; +$ignore{date_to} = 1 ; +$ignore{date_from} = 1 ; +$ignore{nr_of_costing_rows} = 1 ; + +$ignore{iaction} = 1 ; +$required{qty} = 4 ; # number +$required{quote_to} = 1 ; +$required{quote_nr} = 1 ; +$readonly{quote_nr} = 'READONLY' ; +$required{currency} = 1 ; +$required{roe} = 1 ; +$required{period} = 1 ; +$required{max_cams} = 1 ; +$hidden{quote_date} = 2 ; +$hidden{last_update} = 2 ; +$hidden{user_id} = 2 ; +$hidden{datetime} = 2 ; + +$ignore{saveandexit} = 1 ; + +$ignore{costing_1} = 1 ; +$ignore{costing_2} = 1 ; +$ignore{costing_3} = 1 ; + +$ignore{iattachcosting_1} = 1 ; +$ignore{iattachcosting_2} = 1 ; +$ignore{iattachcosting_3} = 1 ; + + +$trigger_jquery_raw .= qq~var curr_changed=0;~; +$trigger_jquery_raw .= qq~\$.validate();~; + +$extra_js .= qq~~; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + +&db_open_ro; +$db_ignore_open_close=1; + + $selected{max_cams}{10} = 'SELECTED'; + &select_opts('') ; + %col_name = () ; + &db_min_ro($table,'*',"id > 1 AND id < 10",'','') ; + $page_title = substr($page_title,0,-1) ; + $db{$table}{''}{quote_nr} = &db_min_get_max($table,'quote_nr') ; + $db{$table}{''}{qty} = 0 ; + + # if ($username eq 'rory') { $db{$table}{''}{quote_nr} = 1000 ; } + + &add_db_fields ; + &build_boxes('','save') ; + +$db_ignore_open_close=0; +&db_close_conn; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + +unless ($i{id}) { $warning = qq(NO ID) ; return ; } + +&db_open_ro; +$db_ignore_open_close=1; + + # DO NOT DELETE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ---------------------------------------------------------------------- + #transfer data from event_quotes to event_quotes_min + + # &common_debug("DELETE FROM quotes_min WHERE id != 203 ") ; + # &common_debug("") ; + # $sql_insert = "INSERT INTO quotes_min ( + # id, + + # curr_amnt_costing_additional_services , + # curr_amnt_costing_game_breakdown_analytics , + # curr_amnt_costing_hardware_add_ons , + # curr_amnt_costing_installation_kits , + # curr_amnt_costing_match_credits, + # curr_amnt_costing_other , + # curr_amnt_costing_rental , + # curr_amnt_costing_software_licence , + # curr_amnt_costing_systems , + + # excl_costing_additional_services , + # excl_costing_game_breakdown_analytics , + # excl_costing_hardware_add_ons , + # excl_costing_installation_kits , + # excl_costing_match_credits , + # excl_costing_other, + # excl_costing_rental , + # excl_costing_software_licence , + # excl_costing_systems , + # excl_delivery_times, + # excl_notes, + # excl_payment_terms , + # excl_purchase_summary , + # excl_roes , + # excl_terms , + + # item_costing_additional_services, + # item_costing_game_breakdown_analytics, + # item_costing_hardware_add_ons, + # item_costing_installation_kits, + # item_costing_match_credits, + # item_costing_other, + # item_costing_rental, + # item_costing_software_licence, + # item_costing_systems, + # item_purchase_summary , + + # item_ttl_costing_additional_services, + # item_ttl_costing_game_breakdown_analytics, + # item_ttl_costing_hardware_add_ons, + # item_ttl_costing_installation_kits, + # item_ttl_costing_match_credits, + # item_ttl_costing_other, + # item_ttl_costing_rental, + # item_ttl_costing_software_licence, + # item_ttl_costing_systems, + + # qty_costing_additional_services, + # qty_costing_game_breakdown_analytics, + # qty_costing_hardware_add_ons, + # qty_costing_installation_kits, + # qty_costing_match_credits, + # qty_costing_other, + # qty_costing_rental, + # qty_costing_software_licence, + # qty_costing_systems, + + # usd_amnt_costing_additional_services, + # usd_amnt_costing_game_breakdown_analytics, + # usd_amnt_costing_hardware_add_ons, + # usd_amnt_costing_installation_kits, + # usd_amnt_costing_match_credits, + # usd_amnt_costing_other, + # usd_amnt_costing_rental, + # usd_amnt_costing_software_licence, + # usd_amnt_costing_systems, + + # vat_costing_additional_services, + # vat_costing_game_breakdown_analytics, + # vat_costing_hardware_add_ons, + # vat_costing_installation_kits, + # vat_costing_match_credits, + # vat_costing_other, + # vat_costing_rental, + # vat_costing_software_licence, + # vat_costing_systems + # ) VALUES " ; + + # $sql_select = "" ; + # %concat = () ; + # for (1 .. 12){ + # $concat{20} .= "excl_" . "$_" . "_notes,';',"; + # } + + # for (1 .. 7){ + # $concat{1} .= "curr_amnt_" . "$_" . "_costing_additional_services,';',"; + # $concat{3} .= "curr_amnt_" . "$_" . "_costing_hardware_add_ons,';',"; + # $concat{4} .= "curr_amnt_" . "$_" . "_costing_installation_kits,';',"; + # $concat{10} .= "excl_" . "$_" . "_costing_additional_services,';',"; + # $concat{12} .= "excl_" . "$_" . "_costing_hardware_add_ons,';',"; + # $concat{13} .= "excl_" . "$_" . "_costing_installation_kits,';',"; + # $concat{25} .= "item_" . "$_" . "_costing_additional_services,';',"; + # $concat{27} .= "item_" . "$_" . "_costing_hardware_add_ons,';',"; + # $concat{28} .= "item_" . "$_" . "_costing_installation_kits,';',"; + # $concat{35} .= "item_ttl_" . "$_" . "_costing_additional_services,';',"; + # $concat{37} .= "item_ttl_" . "$_" . "_costing_hardware_add_ons,';',"; + # $concat{38} .= "item_ttl_" . "$_" . "_costing_installation_kits,';',"; + # $concat{44} .= "qty_" . "$_" . "_costing_additional_services,';',"; + # $concat{46} .= "qty_" . "$_" . "_costing_hardware_add_ons,';',"; + # $concat{47} .= "qty_" . "$_" . "_costing_installation_kits,';',"; + # $concat{53} .= "usd_amnt_" . "$_" . "_costing_additional_services,';',"; + # $concat{55} .= "usd_amnt_" . "$_" . "_costing_hardware_add_ons,';',"; + # $concat{56} .= "usd_amnt_" . "$_" . "_costing_installation_kits,';',"; + # $concat{62} .= "vat_" . "$_" . "_costing_additional_services,';',"; + # $concat{64} .= "vat_" . "$_" . "_costing_hardware_add_ons,';',"; + # $concat{65} .= "vat_" . "$_" . "_costing_installation_kits,';',"; + + # } + # for (1 .. 6){ + # $concat{21} .= "excl_" . "$_" . "_payment_terms,';',"; + # $concat{23} .= "excl_" . "$_" . "_roes,';',"; + + # } + # for (1 .. 5){ + # $concat{6} .= "curr_amnt_" . "$_" . "_costing_other,';',"; + # $concat{15} .= "excl_" . "$_" . "_costing_other,';',"; + # $concat{30} .= "item_" . "$_" . "_costing_other,';',"; + # $concat{40} .= "item_ttl_" . "$_" . "_costing_other,';',"; + # $concat{49} .= "qty_" . "$_" . "_costing_other,';',"; + # $concat{58} .= "usd_amnt_" . "$_" . "_costing_other,';',"; + # $concat{67} .= "vat_" . "$_" . "_costing_other,';',"; + # } + # for (1 .. 4){ + # $concat{5} .= "curr_amnt_" . "$_" . "_costing_match_credits,';',"; + # $concat{14} .= "excl_" . "$_" . "_costing_match_credits,';',"; + # $concat{19} .= "excl_" . "$_" . "_delivery_times,';',"; + # $concat{29} .= "item_" . "$_" . "_costing_match_credits,';',"; + # $concat{39} .= "item_ttl_" . "$_" . "_costing_match_credits,';',"; + # $concat{48} .= "qty_" . "$_" . "_costing_match_credits,';',"; + # $concat{57} .= "usd_amnt_" . "$_" . "_costing_match_credits,';',"; + # $concat{66} .= "vat_" . "$_" . "_costing_match_credits,';',"; + # } + # for (1 .. 3){ + # $concat{8} .= "curr_amnt_" . "$_" . "_costing_software_licence,';',"; + # $concat{9} .= "curr_amnt_" . "$_" . "_costing_systems,';',"; + # $concat{17} .= "excl_" . "$_" . "_costing_software_licence,';',"; + # $concat{18} .= "excl_" . "$_" . "_costing_systems,';',"; + # $concat{22} .= "excl_" . "$_" . "_purchase_summary,';',"; + # $concat{32} .= "item_" . "$_" . "_costing_software_licence,';',"; + # $concat{33} .= "item_" . "$_" . "_costing_systems,';',"; + # $concat{34} .= "item_" . "$_" . "_purchase_summary,';',"; + # $concat{42} .= "item_ttl_" . "$_" . "_costing_software_licence,';',"; + # $concat{43} .= "item_ttl_" . "$_" . "_costing_systems,';',"; + # $concat{51} .= "qty_" . "$_" . "_costing_software_licence,';',"; + # $concat{52} .= "qty_" . "$_" . "_costing_systems,';',"; + # $concat{60} .= "usd_amnt_" . "$_" . "_costing_software_licence,';',"; + # $concat{61} .= "usd_amnt_" . "$_" . "_costing_systems,';',"; + # $concat{69} .= "vat_" . "$_" . "_costing_software_licence,';',"; + # $concat{70} .= "vat_" . "$_" . "_costing_systems,';',"; + # } + # for (1 .. 2){ + # $concat{2} .= "curr_amnt_" . "$_" . "_costing_game_breakdown_analytics,';',"; + # $concat{7} .= "curr_amnt_" . "$_" . "_costing_rental,';',"; + # $concat{11} .= "excl_" . "$_" . "_costing_game_breakdown_analytics,';',"; + # $concat{16} .= "excl_" . "$_" . "_costing_rental,';',"; + # $concat{26} .= "item_" . "$_" . "_costing_game_breakdown_analytics,';',"; + # $concat{31} .= "item_" . "$_" . "_costing_rental,';',"; + # $concat{36} .= "item_ttl_" . "$_" . "_costing_game_breakdown_analytics,';',"; + # $concat{41} .= "item_ttl_" . "$_" . "_costing_rental,';',"; + # $concat{45} .= "qty_" . "$_" . "_costing_game_breakdown_analytics,';',"; + # $concat{50} .= "qty_" . "$_" . "_costing_rental,';',"; + # $concat{54} .= "usd_amnt_" . "$_" . "_costing_game_breakdown_analytics,';',"; + # $concat{59} .= "usd_amnt_" . "$_" . "_costing_rental,';',"; + # $concat{63} .= "vat_" . "$_" . "_costing_game_breakdown_analytics,';',"; + # $concat{68} .= "vat_" . "$_" . "_costing_rental,';',"; + # } + + # for (1 .. 1){ + # $concat{24} .= "excl_" . "$_" . "_terms,';',"; + # } + + # for (1 .. 70){ + # chop $concat{$_} ; + # chop $concat{$_} ; + # chop $concat{$_} ; + # chop $concat{$_} ; + # chop $concat{$_} ; + # $sql_select .= "concat($concat{$_}) AS 'concat_$_'," ; + # } + # chop $sql_select ; + + # &db_min_ro('quotes',"id, $sql_select","",'','') ; + # foreach my $iid (sort keys %{$db{quotes}}){ + # next if $iid == 203 ; + # $sql_insert .= "($iid" ; + # for (1 .. 70){ + # $c = "concat_" . "$_" ; + # $sql_insert .= qq(,'$db{quotes}{$iid}{$c}') ; + # } + # $sql_insert .= ")," ; + # } + + # chop $sql_insert ; + # $sql_insert .= ";" ; + # &common_debug("TRANSFER DATA: $sql_insert") ; + + #---------------------------------------------------------------------------- + + &db_min_ro('quotes_pdf_titles','*',"quote_id='$i{id}'",'','') ; + &db_min_ro('quotes_min','*',"id='$i{id}'",'','') ; + # unless ($iaction eq 'save' or $iaction eq 'update') { + &db_min_ro($table,'*',"id='$i{id}'",'','') ; + # } + + $max_cams = $db{$table}{$i{id}}{max_cams} if $db{$table}{$i{id}}{max_cams} ; + + $page_title = substr($page_title,0,-1) ; + $page_title .= " : $i{id}" ; + + # our $open_new_tab = qq(target="_blank") ; # opens booking page in a new tab + &common_min_footer('id',"$lcpage\s"); + + &edit_db_fields ; + + $selected{max_cams}{$db{$table}{$i{id}}{max_cams}} = 'SELECTED'; + + &select_opts($i{id}) ; + + our $saveandexit = 1 ; + + &build_boxes($i{id},'update') ; + +$db_ignore_open_close=0; +&db_close_conn; + +&common_min_extra_crumb("search-$lcpage\s","Search $ucfirstpage\s") ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes { + +my ($id,$action) = @_ ; + +our @jquery_trigger_fields = () ; our @jquery_custom_vat_ids = () ; our @jquery_duty_ids = () ; + +push @jquery_trigger_fields, 'inputRoe' ; +push @jquery_trigger_fields, 'selectPeriod' ; +# push @jquery_trigger_fields, 'selectDiscount' ; + +&tab_curr_symbols; + +foreach $col(keys %required) { + &common_min_forms_required ; + } + +&tabs_get_default_totals($id) ; + +our $tab_cnt = 0 ; + +$print_box_content_rows .= &common_min_forms_start($table) ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq(
    ) ; + &build_boxes_top($id); + $print_box_content_rows .= qq(
    ) ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq(
    ) ; + + &tab_cnt; + + $print_box_content_rows .= qq(
    + +
    ); + + our %tab_sections = () ; + + foreach (sort {$a <=> $b} keys %cntxt) { + my $tab_name = &tab_names($_) ; my $active = '' ; + + if (($_==1) and ($db{$table}{$id}{activetab} eq '')) { + $active = 'active' ; + } elsif ($db{$table}{$id}{activetab} eq $tab_name) { + $active = 'active' ; + } + + my $colsleft = 12 ; my $showright = '' ; + + if ($cntxt{$_} eq 'one' or $cntxt{$_} eq 'four') { + $colsleft = 6 ; $showright = 1 ; + } + + # &common_min_debug("activetab [$tab_name] $active "); + + $print_box_content_rows .= qq~
    ~; + + $print_box_content_rows .= qq~
    ~ ; + + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_left($id,$_); + $print_box_content_rows .= qq~
    ~ ; + + if ($showright) { + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_right($id,$_); + $print_box_content_rows .= qq~
    ~ ; + } + + $print_box_content_rows .= qq~
    ~ ; + + $print_box_content_rows .= qq~
    ~ ; + + $print_box_content_rows .= qq~
    ~ ; + + # if ($id) { + # $print_box_content_rows .= qq~
    ~ ; + # # $print_box_content_rows .= qq~~; + # # # if ($username eq 'rory') { $print_box_content_rows .= qq~ ~; } + # # if ($username eq 'rory' or $username eq 'handre') { $print_box_content_rows .= qq~ ~; } + # # # $print_box_content_rows .= qq~ ~; + # $print_box_content_rows .= &common_min_box_foot; + # } + + $print_box_content_rows .= qq~
    ~ ; + + $print_box_content_rows .= qq~
    ~ ; + + $print_box_content_rows .= qq~
    ~ ; + } + + $print_box_content_rows .= qq( +
    +
    + ) ; + + $print_box_content_rows .= qq(
    ) ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq(
    ) ; + &build_boxes_bottom($id); + $print_box_content_rows .= qq(
    ) ; + + #-------------------------------------------------------------------------- + +$print_box_content_rows .= &common_min_forms_end($id,$table,$action,$skip) ; + +my $jquery_trigger_ids = '#' . join(",#",@jquery_trigger_fields) ; + +my $jq_tab_var = '' ; my $jq_tab = '' ; my $inp_tab_val = '' ; foreach (keys %cntxt) { $jq_tab_var .= qq(var totalTab_$_=0 ; ) ; $jq_tab .= qq(totalTab_$_=0 ; ) ; } # $inp_tab_val .= qq(\$("#inputTotal_tab_$_").val(totalTab_$_.toFixed(2)) ;) ; + +&tabs_costings_forms_jquery ; + +# $trigger_jquery_raw .= qq~ +# \$("#selectCurrency").change(function() { + # curr_changed=1; + # // console.log("1. curr_changed: "+curr_changed) ; + # calcCurr(); +# }); + +# \$('#quotes-form:checkbox').change(function() { + # calcAll(); +# }); + + # function calcCosting(excl,item,qty,usd,conv,vat,ttl) { + + # var itval = item.val(); + # var uval = usd.val(); + # var cval = conv.val(); // currency amount + # var qval = qty.val(); + # var vval = vat.val(); + # // var tval = ttl.val(); + # var xval = excl.val(); + # var dis = \$("#selectDiscount").val(); + # var roe = \$("#inputRoe").val(); // getNum() + + # if (!itval) { calcAll(); return ; } + + # var arrP = itval.split(":"); // 3:0.00:100.00:200.00:223.00:223.00:250.00:250.00:200.00 // id:freight:nett:main_price:gross_10_1_50:gross_10_51_plus:gross_20_1_50:gross_20_51_plus:gross_50 // + + # // // var list = { freight:arrP[0], nett:arrP[1], main_price:arrP[2], gross_10_1_50:arrP[3], gross_10_51_plus:arrP[4], gross_20_1_50:arrP[5], gross_20_51_plus:arrP[6], gross_50:arrP[7] }; + # // var list = { freight:arrP[1], nett:arrP[2], main_price:arrP[3], gross_10_1_50:arrP[4], gross_10_51_plus:arrP[5], gross_20_1_50:arrP[6], gross_20_51_plus:arrP[7], gross_50:arrP[8] }; + + # var list = { freight:arrP[1], nett:arrP[2], main_price:arrP[3], source_admin:arrP[4], perc3:arrP[5], perc5:arrP[6], perc6:arrP[6], perc8:arrP[7], perc10:arrP[8], perc15:arrP[9], perc20:arrP[10] }; + + # if (!qval) { qval=1; qty.val(qval); } // set quantity if blank + + # if (!uval) // set USD amount if no amount + # { + # var uval = list.main_price; + # if (dis==3 && qval>0) { + # uval=list.perc3; + # } else if (dis==5 && qval>0) { + # uval=list.perc5; + # } else if (dis==6 && qval>0) { + # uval=list.perc6; + # } else if (dis==8 && qval>0) { + # uval=list.perc8; + # } else if (dis==10 && qval>0) { + # uval=list.perc10; + # } else if (dis==15 && qval>0) { + # uval=list.perc15; + # } else if (dis==20 && qval>0) { + # uval=list.perc20; + # } + # } + + # // console.log('item: '+item+', uval: '+uval) ; + + # // if (!uval) // set USD amount if no amount + # // { + # // var uval = list.main_price; + # // // alert('main_price:'+uval) ; + # // if (dis==10 && qval>0 && qval<=50) + # // { + # // uval=list.gross_10_1_50; + # // } + # // else if (dis==10 && qval>50) + # // { + # // uval=list.gross_10_51_plus; + # // } + # // else if (dis==20 && qval>0 && qval<=50) + # // { + # // uval=list.gross_20_1_50; + # // } + # // else if (dis==20 && qval>50) + # // { + # // uval=list.gross_20_51_plus; + # // } + # // else if (dis==50) + # // { + # // uval=list.gross_50; + # // } + # // } + + # var usdAmnt = uval * 1 ; + # // var currAmnt = usdAmnt / roe ; + # var currAmnt = usdAmnt * roe ; + # var ttlAmnt = currAmnt * qval ; + + # usd.val(usdAmnt.toFixed(2)) ; // set USD currency amount + # conv.val(currAmnt.toFixed(2)) ; // set foreign currency amount + # ttl.val(ttlAmnt.toFixed(2)) ; // set total amount + + # calcAll(); // recalculate the entire sheet + + # // alert(usdAmnt+'(inputUsd_amnt_$field):'+usd+':'+qty+'(inputQty_$field)') ; // 0.00:100.00:200.00:223.00:223.00:250.00:250.00:200.00 // + # } + +# ~ ; +$trigger_jquery_raw .= qq~ + + function dispCamDetails(excl,camnr,qty,itcode,desc,snr,ddate,adate,f) { + var camval = camnr.val(); + var arrP = camval.split(":"); + var qval = qty.val(); + + if (!camval) { + excl.prop("checked", true); + snr.val(""); + adate.val(""); + ddate.val(""); + desc.val(""); + //itcode.val(""); + qty.val(""); + return ; + } + + var prev = getNum(f-1); + var pcamval = \$("#selectCamera_nr_"+prev+"_camera_details").val(); + + // console.log("#selectCamera_nr_"+prev+"_camera_details"+", pcamval="+pcamval) ; + + if (typeof pcamval!="undefined") { + + console.log(pcamval) ; + var arrpP = pcamval.split(":"); + var checkS1 = arrpP[1].substring(0,2); + var checkOther = arrpP[1].substring(0,5); + + if (checkS1=='S1' || checkOther=='Prime' || checkOther=='Coach') { \$("#c_excl_"+f+"_camera_details").append("");\$('[data-toggle="tooltip"]').tooltip({html:true}) ; } + } + + var list = { id:arrP[0], camera_nr:arrP[1], camera_system_id:arrP[2], serial_nr:arrP[3], date_delivered:arrP[4], description:arrP[5], itemcode:arrP[6], date_active:arrP[7] }; + + if (!qval || qval<1) { qval=1; qty.val(qval); } // set quantity if blank + + snr.val(list.serial_nr); + //ddate.val(list.date_delivered); + //adate.val(list.date_active); + desc.val(list.description); + //itcode.val(list.itemcode); + + excl.prop("checked", false); + } + +~ ; +# $trigger_jquery_raw .= qq~ + + # function calcCurr() { + # var roe = \$("#inputRoe") ; + # var curr = \$("#selectCurrency").val() ; + + # var url = "$useropts{scripts}/get/get_roe.pl?" + curr ; + # \$.get(url, function(json) { + # \$.each(json, function(key, data) { + # roe.val(data.sell_rate); + # }); + # calcAll(); + # }, + # 'json'); + # } +# ~; + +# $trigger_jquery_raw .= qq( + # var currArr = {}; // var vat_total = {} ; var total_total = {} ; var subtotal = {} ; var fs_total = {} ; + + # $js_curr_arr + + # var currVal = \$("#selectCurrency").val() ; + # var prevRoe = '' ; + # var curRoe = '' ; + + # var grandTtl = 0 ; var grandSub = 0 ; var grandVat = 0 ; + # $jq_tab_var + # \$("$jquery_trigger_ids").change(function() { + # calcAll(); + # }); + + + # calcAll() ; + + + # \$("#inputYear_1_3_purchase_summary").on("change", function() { + # // calcAll() ; + # if (\$(this).val()) { + # \$(this).val(parseFloat(\$(this).val()).toFixed(2)); + # } else { + # \$(this).val("0.00"); + # } + + # calcAll() ; + + # }); + + # function calcAll() + # { + # if (!\$("#selectCurrency").val()) { \$("#selectCurrency").val('ZAR'); \$("#selectCurrency").trigger("chosen:updated"); } // if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) } + + # grandTtl = 0 ; grandSub = 0 ; grandVat = 0 ; + # totalOne_time_fee_1 = 0 ; subtotalOne_time_fee_1 = 0 ; vatOne_time_fee_1 = 0 ; + # totalMonthly_recurring_fee_1 = 0 ; subtotalMonthly_recurring_fee_1 = 0 ; vatMonthly_recurring_fee_1 = 0 ; + # totalAnnual_fee_1 = 0 ; subtotalAnnual_fee_1 = 0 ; vatAnnual_fee_1 = 0 ; + + # totalOne_time_fee_2 = 0 ; subtotalOne_time_fee_2 = 0 ; vatOne_time_fee_2 = 0 ; + # totalMonthly_recurring_fee_2 = 0 ; subtotalMonthly_recurring_fee_2 = 0 ; vatMonthly_recurring_fee_2 = 0 ; + # totalAnnual_fee_2 = 0 ; subtotalAnnual_fee_2 = 0 ; vatAnnual_fee_2 = 0 ; + + # totalYear_1_2_purchase_summary=0; totalYear_2_2_purchase_summary=0; totalYear_3_2_purchase_summary=0; totalYear_4_2_purchase_summary=0; totalYear_5_2_purchase_summary=0; totalTotal_2_purchase_summary=0; + # totalYear_1_3_purchase_summary=0; totalYear_2_3_purchase_summary=0; totalYear_3_3_purchase_summary=0; totalYear_4_3_purchase_summary=0; totalYear_5_3_purchase_summary=0; totalTotal_3_purchase_summary=0; + + # $jq_tab + # $re_calc_jquery + + # \$("#inputSub_total").val(grandSub.toFixed(2)) ; + # \$("#inputVat_total").val(grandVat.toFixed(2)) ; + # \$("#inputGrand_total").val(grandTtl.toFixed(2)) ; + + # \$("#inputTotal_one_time_fee_1").val(totalOne_time_fee_1.toFixed(2)) ; + # \$("#inputSubtotal_one_time_fee_1").val(subtotalOne_time_fee_1.toFixed(2)) ; + # \$("#inputVat_one_time_fee_1").val(vatOne_time_fee_1.toFixed(2)) ; + + # \$("#inputTotal_one_time_fee_2").val(totalOne_time_fee_2.toFixed(2)) ; + # \$("#inputSubtotal_one_time_fee_2").val(subtotalOne_time_fee_2.toFixed(2)) ; + # \$("#inputVat_one_time_fee_2").val(vatOne_time_fee_2.toFixed(2)) ; + + # \$("#inputTotal_monthly_recurring_fee_1").val(totalMonthly_recurring_fee_1.toFixed(2)) ; + # \$("#inputSubtotal_monthly_recurring_fee_1").val(subtotalMonthly_recurring_fee_1.toFixed(2)) ; + # \$("#inputVat_monthly_recurring_fee_1").val(vatMonthly_recurring_fee_1.toFixed(2)) ; + + # \$("#inputTotal_annual_fee_1").val(totalAnnual_fee_1.toFixed(2)) ; + # \$("#inputSubtotal_annual_fee_1").val(subtotalAnnual_fee_1.toFixed(2)) ; + # \$("#inputVat_annual_fee_1").val(vatAnnual_fee_1.toFixed(2)) ; + + # \$("#inputYear_1_2_purchase_summary").val(totalYear_1_2_purchase_summary.toFixed(2)) ; + # \$("#inputYear_2_2_purchase_summary").val(totalYear_2_2_purchase_summary.toFixed(2)) ; + # \$("#inputYear_3_2_purchase_summary").val(totalYear_3_2_purchase_summary.toFixed(2)) ; + # \$("#inputTotal_2_purchase_summary").val(totalTotal_2_purchase_summary.toFixed(2)) ; + + # let totalAnnual_fee = totalAnnual_fee_1 + totalAnnual_fee_2 ; + + # totalYear_1_3_purchase_summary = totalAnnual_fee ; + # totalYear_2_3_purchase_summary = totalAnnual_fee ; + # totalYear_3_3_purchase_summary = totalAnnual_fee ; + + # \$("#inputYear_2_3_purchase_summary").val(totalYear_2_3_purchase_summary.toFixed(2)) ; + # \$("#inputYear_3_3_purchase_summary").val(totalYear_3_3_purchase_summary.toFixed(2)) ; + + # let totalOne_time_fee = totalOne_time_fee_1 + totalOne_time_fee_2 ; + + # \$("#inputYear_1_1_purchase_summary").val(totalOne_time_fee.toFixed(2)) ; + # \$("#inputYear_2_1_purchase_summary").val('0.00') ; + # \$("#inputYear_3_1_purchase_summary").val('0.00') ; + # \$("#inputYear_4_1_purchase_summary").val('0.00') ; + # \$("#inputYear_5_1_purchase_summary").val('0.00') ; + # \$("#inputTotal_1_purchase_summary").val(totalOne_time_fee.toFixed(2)) ; + + # let year_1_tot = totalOne_time_fee + totalYear_1_2_purchase_summary + parseFloat(\$("#inputYear_1_3_purchase_summary").val()) ; + # let year_2_tot = totalYear_2_2_purchase_summary + totalAnnual_fee ; + # let year_3_tot = totalYear_3_2_purchase_summary + totalAnnual_fee ; + # let year_4_tot = totalYear_4_2_purchase_summary + totalAnnual_fee ; + # let year_5_tot = totalYear_5_2_purchase_summary + totalAnnual_fee ; + # let grand_tot_pur = 0 ; + + # \$("#inputYearly_totals_1").val(parseFloat(year_1_tot).toFixed(2)) ; + # \$("#inputYearly_totals_2").val(year_2_tot.toFixed(2)) ; + # \$("#inputYearly_totals_3").val(year_3_tot.toFixed(2)) ; + + # if (\$("#selectPeriod").val() == 60) { + + # \$("#inputYear_4_2_purchase_summary").val(totalYear_4_2_purchase_summary.toFixed(2)) ; + # \$("#inputYear_5_2_purchase_summary").val(totalYear_5_2_purchase_summary.toFixed(2)) ; + + # totalYear_4_3_purchase_summary = totalAnnual_fee ; + # totalYear_5_3_purchase_summary = totalAnnual_fee ; + # totalTotal_3_purchase_summary = totalAnnual_fee * 4 + parseFloat(\$("#inputYear_1_3_purchase_summary").val()) ; + + # \$("#inputYear_4_3_purchase_summary").val(totalYear_4_3_purchase_summary.toFixed(2)) ; + # \$("#inputYear_5_3_purchase_summary").val(totalYear_5_3_purchase_summary.toFixed(2)) ; + + # \$("#inputYearly_totals_4").val(year_4_tot.toFixed(2)) ; + # \$("#inputYearly_totals_5").val(year_5_tot.toFixed(2)) ; + + # grand_tot_pur = year_1_tot + year_2_tot + year_3_tot + year_4_tot + year_5_tot ; + + # } else if (\$("#selectPeriod").val() == 36) { + + # \$("#inputYear_4_2_purchase_summary").val('0.00') ; + # \$("#inputYear_5_2_purchase_summary").val('0.00') ; + + # totalYear_4_3_purchase_summary = 0 ; + # totalYear_5_3_purchase_summary = 0 ; + # totalTotal_3_purchase_summary = totalAnnual_fee * 2 + parseFloat(\$("#inputYear_1_3_purchase_summary").val()) ; + + # \$("#inputYear_4_3_purchase_summary").val('0.00') ; + # \$("#inputYear_5_3_purchase_summary").val('0.00') ; + # \$("#inputYearly_totals_4").val('0.00') ; + # \$("#inputYearly_totals_5").val('0.00') ; + + # grand_tot_pur = year_1_tot + year_2_tot + year_3_tot ; + # } + # console.log("inputYear_4_2_purchase_summary : "+\$('#inputYear_4_2_purchase_summary').val()) ; + # \$("inputTotal_3_purchase_summary").val() ; + # \$("#inputTotal_3_purchase_summary").val(parseFloat(totalTotal_3_purchase_summary).toFixed(2)) ; + # \$("#inputYearly_total").val(parseFloat(grand_tot_pur).toFixed(2)) ; + + # curr_changed=0; + # }); + +# # $onload .= qq(onload="calcAll();"); +# if ($iaction eq 'add'){ $onload .= qq~onload="calcCurr();"~ ; } +# # $onload .= qq~onload="calcCurr();"~ ; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_top { + +my ($id) = @_ ; + +our ($lcol,$fcol) = &common_min_columns(3,6) ; + +$add_form_fields = '' ; + +$fcol = 8 ; + +$add_form_fields .= qq~
    ~ ; + # $preferred_title{quote_nr} = "Ref" ; + $preferred_title{quote_nr} = "Nr" ; + $add_form_fields .= &common_min_form_input('quote_nr',$db{$table}{$id}{quote_nr},'') ; + $add_form_fields .= &common_min_form_input('ref',$db{$table}{$id}{ref},'') ; + # $add_form_fields .= &common_min_form_input('po_nr',$db{$table}{$id}{po_nr},'') ; +$add_form_fields .= qq~
    ~ ; + +$add_form_fields .= qq~
    ~ ; + if (($db{$table}{$id}{quote_date} eq '') or ($db{$table}{$id}{quote_date} eq '0000-00-00')) { $db{$table}{$id}{quote_date} = $now_ccyy_mm_dd ; } + $add_form_fields .= &common_min_form_datepicker('quote_date',$db{$table}{$id}{quote_date}) ; + my $plus_n_days_ccyy_mm_dd = &common_add_delta_days(14) ; + if (($db{$table}{$id}{quote_expiry} eq '') or ($db{$table}{$id}{quote_expiry} eq '0000-00-00')) { $db{$table}{$id}{quote_expiry} = $plus_n_days_ccyy_mm_dd ; } + $add_form_fields .= &common_min_form_datepicker('quote_expiry',$db{$table}{$id}{quote_expiry}) ; +$add_form_fields .= qq~
    ~ ; + +$add_form_fields .= qq~
    ~ ; + $dlg{quote_to} = qq~
    ~ ; + $fcol=8; + $preferred_title{quote_to} = "Customer" ; + $add_form_fields .= &common_min_form_select('quote_to',$db{$table}{$id}{quote_to},'') ; + $required{max_cams} = 1 ; + $select{max_cams} = 1 ; + $opts{max_cams} = qq~ + + + + + + + + + + + + + + + ~ ; + $fcol=6; + # $add_form_fields .= &common_min_form_select('max_cams',$db{$table}{$id}{max_cams},'') ; + + $add_form_fields .= qq~
    ~ ; #
    + $fcol=2; + $add_form_fields .= &common_min_form_label_col('max_cams') ; + $fcol=3; + $add_form_fields .= &common_min_form_select_col('max_cams',$db{$table}{$id}{max_cams},'') ; + $fcol=2;$lcol=2; + $add_form_fields .= &common_min_form_label_col('qty') ; + $fcol=3; + $db{$table}{$id}{qty} = "" unless $db{$table}{$id}{qty} ; + $add_form_fields .= &common_min_form_input_col('qty',$db{$table}{$id}{qty}) ; + $add_form_fields .= qq~
     
    ~ ; + + # $add_form_fields .= &common_min_form_label_col('period') ; + # $add_form_fields .= &common_min_form_label_col('prd') ; + $sel = '' ; $sel = 'SELECTED' if $db{$table}{$id}{period} eq '36' ; + $opts{period} .= qq~~ ; + $sel = '' ; $sel = 'SELECTED' if $db{$table}{$id}{period} eq '60' ; + # $opts{period} .= qq~~ ; + $sel = '' ; + $required{period} = 1 ; + # $add_form_fields .= &common_min_form_select_col('period',$db{$table}{$id}{period}) ; + + $add_form_fields .= qq~
    ~ ; + + $fcol=7;# $add_form_fields .= &common_min_form_select('ship_to',$db{$table}{$id}{ship_to},'') ; + # if ($username eq 'rory') { $add_form_fields .= qq~
     
    ~ ; } +$add_form_fields .= qq~
    ~ ; + +$add_form_fields .= qq~
    ~ ; + $lcol=3; + $preferred_title{'country_shipped'} = 'Country' ; + $add_form_fields .= &common_min_form_select('country_shipped',$db{$table}{$id}{country_shipped},'') ; + # $preferred_title{'camera_system_id'} = 'System' ; + $fcol=7; + $dlg{type_id} .= qq~
    ~ ; + + $add_form_fields .= &common_min_form_select('type_id',$db{$table}{$id}{type_id},'') ; + + # $add_form_fields .= &common_min_form_select('camera_system_id',$db{$table}{$id}{camera_system_id},'') ; +$add_form_fields .= qq~
    ~ ; + +$print_box_content_rows .= &common_min_box_top('qrcode',"Quote",'BABEC2'); +$print_box_content_rows .= qq~
    +
    + $add_form_fields +
    +
    ~; +$print_box_content_rows .= qq~
     
    ~ ; +$print_box_content_rows .= &common_min_box_foot; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_left { + +my ($id,$tab) = @_ ; + +our ($lcol,$fcol) = &common_min_columns(3,6) ; + +&tab_build_qt_left($id,$tab); + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_right { + +my ($id,$tab) = @_ ; + +our ($lcol,$fcol) = &common_min_columns(3,6) ; + +&tab_build_qt_right($id,$tab); + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_bottom { + +my ($id) = @_ ; + +our ($lcol,$fcol) = &common_min_columns(2,2) ; + +$add_form_fields = '' ; + +# --------------- START GRAND TOTAL ---------------------------------------------------------------------------------------------------------------------- + +$print_box_content_rows .= &common_min_form_input('activetab',$db{$table}{$id}{activetab},'hidden') ; + +# # $print_box_content_rows .= &common_min_form_input('grand_total','0.00','hidden') ; + +# my @ttlarr = ("sub_total","vat_total","grand_total") ; +# $lcol=1;$fcol=2; +# foreach (@ttlarr) { + # $readonly{$_} = "READONLY"; + # $add_form_fields .= qq~
    ~ ; #
    + # $add_form_fields .= &common_min_form_label_col($_) ; + # $add_form_fields .= &common_min_form_input_col($_,'0.00') ; + # $add_form_fields .= qq~
    ~ ; + # } + +# $print_box_content_rows .= qq~
    ~ ; +# $print_box_content_rows .= $add_form_fields ; +# $print_box_content_rows .= &common_min_box_foot; + +# --------------- END RAND TOTAL ------------------------------------------------------------------------------------------------------------------------ + +} #---------------------------------------------------------------------------------------- + +sub build_cost_form { + +my ($id,$tab,$rcnt,$suffix) = @_ ; + +$tab_sections{$tab} .= "$suffix+$rcnt|" ; + +$jq_cal = qq~var vat_total$suffix = 0 ; var total_total$suffix = 0 ; var subtotal$suffix = 0 ; var vat_amount = 0 ; ~ ; +$jq_fs = '' ; + +%cnt_specific_jquery = () ; + +&set_check_boxes_checked($id,$rcnt,"excl",$suffix); +&set_check_boxes_checked($id,$rcnt,"vat",$suffix); + +my $cntloop=1; + +# my %saved_field = () ; +# my @prefexes = ("excl", "item", "qty", "usd_amnt", "curr_amnt", "item_ttl", "vat") ; +my @prefexes = ("excl","description","qty","amount","vat") ; +# my @b = ( +# "_costing_additional_services", +# "_costing_game_breakdown_analytics", +# "_costing_hardware_add_ons", +# "_costing_installation_kits", +# "_costing_match_credits", +# "_costing_other", +# "_costing_rental", +# "_costing_software_licence", +# "_costing_systems", +# "_delivery_times", +# "_notes", +# "_payment_terms", +# "_purchase_summary", +# "_roes", +# "_terms") ; + +my $max_cnt = 0 ; +foreach my $prefex (@prefexes){ + + $col_name = "$prefex" . "_$suffix" ; + $cnt = 0 ; + if ($db{quotes_min}{$id}{$col_name} && $prefex ne 'description') { + foreach my $col_input (split(";", $db{quotes_min}{$id}{$col_name})) { + $cnt++ ; + $saved_field{$prefex}{$suffix}{$cnt} = $col_input ; + } + } elsif ($db{quotes_min}{$id}{$col_name} && $prefex eq 'description') { + foreach my $col_input (split(":;:", $db{quotes_min}{$id}{$col_name})) { + $cnt++ ; + $saved_field{$prefex}{$suffix}{$cnt} = $col_input ; + $max_cnt = $cnt if $col_input ; + } + } +} + +$rcnt = $max_cnt if $max_cnt > $rcnt ; + +for (1 .. $rcnt) { + + $display_style = '' ; $display_plus_btn = '' ; + + # unless ($_==1 or $db{$table}{$id}{"item_$_$suffix"}) { + + $add_form_fields .= qq~
    ~ ; + #---------------------------------------------------------------------------------------------------- + $field = "excl_$suffix\_$_" ; $fcol=1 ; + # if ($checkit{$field} == 1) { + if ($saved_field{"excl"}{$suffix}{$_} || !$saved_field{"description"}{$suffix}{$_}){ + $checked = 'CHECKED'; } elsif (($excl_tick{$_}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } + $label{$field} = 1 ; + $add_form_fields .= &common_min_form_checkbox_col($field,$checkit{$field},$checked) ; + #---------------------------------------------------------------------------------------------------- + my $field = "description_$suffix\_$_" ; $fcol=2 ; + $input_style{$field} = qq(style="text-align:right;"); + $allow_deselect{$field} = 1 ; + $preferred_placeholder{$field} = "Description $_" ; + if ($suffix eq 'costing' or $suffix eq '_costing_other' or $suffix eq '_costing_rental' or ($suffix eq '_costing_systems' and $_>1) or ($suffix eq '_costing_software_licence' and $_>2) or ($suffix eq '_costing_game_breakdown_analytics' and $_>1)) { + # $add_form_fields .= &common_min_form_input_col($field,$db{$table}{$id}{$field}) ; + $add_form_fields .= &common_min_form_input_col($field,$saved_field{"description"}{$suffix}{$_}) ; + $nr_of_costing_rows = $_ if $saved_field{"description"}{$suffix}{$_} ; + } else { + # &common_min_debug("[$field] $db{$table}{$id}{$field}") ; + # $add_form_fields .= &common_min_form_select_col($field,$db{$table}{$id}{$field}) ; + $add_form_fields .= &common_min_form_select_col($field,$saved_field{"description"}{$suffix}{$_}) ; + } + #---------------------------------------------------------------------------------------------------- + $field = "qty_$suffix\_$_" ; $fcol=1 ; $input_style{$field} = qq(style="text-align:right;"); + $preferred_placeholder{$field} = "Qty $_" ; + # my $val = $db{$table}{$id}{$field} ; + my $val = $saved_field{"qty"}{$suffix}{$_} ; + unless ($val) { $val = $def_qty{$_} ; } $val = &q_get_val($val) ; + $add_form_fields .= &common_min_form_input_col($field,$val) ; + #---------------------------------------------------------------------------------------------------- + $field = "zar_amount_$suffix\_$_" ; $input_style{$field} = qq(style="text-align:right;"); + # my $val = $db{$table}{$id}{$field} ; + my $val = $saved_field{"amount"}{$suffix}{$_} ; + unless ($val) { $val = $def_usd{$_} ;} $val = &q_get_val($val) ; + $preferred_placeholder{$field} = "Amount $_" ; + $add_form_fields .= &common_min_form_input_col($field,$val,1) ; + #---------------------------------------------------------------------------------------------------- + # $field = "curr_amnt_$_$suffix" ; $input_style{$field} = qq(style="text-align:right;"); $readonly{$field} = 'READONLY' ; # $fcol=2 ; + # $preferred_placeholder{$field} = "ZAR Amnt $_" ; + # # my $val = &q_get_val($db{$table}{$id}{$field}) ; + # my $val = &q_get_val($saved_field{"curr_amnt"}{$suffix}{$_}) ; + # $add_form_fields .= &common_min_form_input_col($field,$val,1) ; + #---------------------------------------------------------------------------------------------------- + $field = "total_$suffix\_$_" ; $input_style{$field} = qq(style="text-align:right;"); $readonly{$field} = 'READONLY' ; # $fcol=2 ; + + # $preferred_placeholder{} + + $preferred_placeholder{$field} = "Total Amount $_" ; + # my $val = &q_get_val($db{$table}{$id}{$field}) ; + my $val = &q_get_val(sprintf("%0.2f",$saved_field{"amount"}{$suffix}{$_} * $saved_field{"qty"}{$suffix}{$_} * $db{$table}{$id}{roe})) ; + $add_form_fields .= &common_min_form_input_col($field,$val,1) ; + #---------------------------------------------------------------------------------------------------- + $field = "vat_$suffix\_$_" ; $fcol=1 ; + # if ($checkit{$field} == 1) { $checked = 'CHECKED'; } elsif (($vat_tick{$_}) and ($iaction eq 'add')) { $checked = 'CHECKED'; } else { $checked = ''; } + if ($saved_field{"vat"}{$suffix}{$_} == 1) { + # if ($checkit{$field} == 1) { + $checked = 'CHECKED'; } elsif ($iaction eq 'add') { $checked = 'CHECKED'; } else { $checked = ''; } + $label{$field} = 1 ; + if ($no_vat{$suffix}) { $style_field{$field} = 'style="display:none;"' ; } + $add_form_fields .= &common_min_form_checkbox_col($field,$checkit{$field},$checked) ; + #---------------------------------------------------------------------------------------------------- + # $add_form_fields .= qq~$display_plus_btn~ ; + $add_form_fields .= qq~
    ~ ; + + $display_plus_btn = qq~~ if $_ eq $rcnt ; + $add_form_fields .= qq~
    $display_plus_btn
    ~ ; + $add_form_fields .= qq~
    ~ ; + + my $added_ttl_js = '' ; + + # if ($suffix eq '_costing_systems' or $suffix eq '_costing_installation_kits' or $suffix eq '_costing_hardware_add_ons' or $suffix eq '_costing_additional_services' or $suffix eq '_costing_match_credits') { + + # # if ($suffix eq '_costing_additional_services' and $db{$table}{$id}{"item_$_$suffix"}) { # OTT Monthly Management fee + # # $added_ttl_js = qq~ + # # totalMonthly_recurring_fee += (amnts[2] + amnts[1]) ; + # # subtotalMonthly_recurring_fee += amnts[2] ; + # # vatMonthly_recurring_fee += amnts[1] ; + + # # var yrTtl = (amnts[2] + amnts[1]) * 12 + + # # totalYear_1_2_purchase_summary += yrTtl; + # # totalYear_2_2_purchase_summary += yrTtl; + # # totalYear_3_2_purchase_summary += yrTtl; + # # totalTotal_2_purchase_summary += (yrTtl*3); ~; + # # } else { + # $added_ttl_js = qq~totalOne_time_fee_1 += (amnts[2] + amnts[1]) ; + # subtotalOne_time_fee_1 += amnts[2] ; + # vatOne_time_fee_1 += amnts[1] ; ~; + # # } + # } + + # if ($suffix eq 'costing') { + + # $added_ttl_js = qq~ + # totalOne_time_fee_2 += (amnts[2] + amnts[1]) ; + # subtotalOne_time_fee_2 += amnts[2] ; + # vatOne_time_fee_2 += amnts[1] ; + # ~ ; + + # } + + # if ($suffix eq '_costing_software_licence' or $suffix eq '_costing_rental') { + # $added_ttl_js = qq~ + + # totalMonthly_recurring_fee_1 += (amnts[2] + amnts[1]) ; + # subtotalMonthly_recurring_fee_1 += amnts[2] ; + # vatMonthly_recurring_fee_1 += amnts[1] ; + + # var yrTtl = (amnts[2] + amnts[1]) * 12 + + # totalYear_1_2_purchase_summary += yrTtl; + # totalYear_2_2_purchase_summary += yrTtl; + # totalYear_3_2_purchase_summary += yrTtl; + + # if (\$("#selectPeriod").val() == 60) { + # totalYear_4_2_purchase_summary += yrTtl; + # totalYear_5_2_purchase_summary += yrTtl; + # totalTotal_2_purchase_summary += (yrTtl*2); + # } + + # totalTotal_2_purchase_summary += (yrTtl*3); + + # \$("#selectPeriod").on("change", function() { + # if (\$(this).val() == 36) { + # totalYear_4_2_purchase_summary = 0; + # totalYear_5_2_purchase_summary = 0; + # totalTotal_2_purchase_summary -= (yrTtl*5); + # totalTotal_2_purchase_summary += (yrTtl*3); + + # } else if (\$(this).val() == 60) { + # totalYear_4_2_purchase_summary += yrTtl; + # totalYear_5_2_purchase_summary += yrTtl; + # totalTotal_2_purchase_summary -= (yrTtl*3); + # totalTotal_2_purchase_summary += (yrTtl*5); + # } + # }); + # ~; + # } + + # if ($suffix eq '_costing_game_breakdown_analytics') { + # $added_ttl_js = qq~ + # totalAnnual_fee_1 += (amnts[2] + amnts[1]) ; + # subtotalAnnual_fee_1 += amnts[2] ; + # vatAnnual_fee_1 += amnts[1] ; + # ~; + # } + + # $jq_cal .= qq~ + # var amnts = calcSection('$suffix','$_'); + + # vat_total$suffix += amnts[1] ; + # subtotal$suffix += amnts[2] ; + # total_total$suffix += (amnts[2] + amnts[1]) ; + # $added_ttl_js + + # ~; +} + +$trigger_jquery_raw .= qq~ + // \$("#btn_$suffix\_$_").click( function () { + \$("#two").on("click","[id^='btn_$suffix\_']", function () { + event.preventDefault(); + console.log("Hello World : "+this.id) ; + let row_nr = get_row_nr(this.id) ; + \$("#btn_$suffix\_"+row_nr).hide() ; + let html_row = add_costing_row(row_nr,"$suffix") ; + \$("#btn_row_$suffix\_"+row_nr).after(html_row) ; + }) ; +~ ; + +# if ($_>$cntloop) { $display_butt = qq~display:none;~ ; } else { $display_butt = '' ; } + +# $jq_cal .= qq~ + # grandSub+=subtotal$suffix; + # grandVat+=vat_total$suffix; + # grandTtl+=total_total$suffix; + # ~ ; + +# $re_calc_jquery .= qq~calc$suffix();setRoe('$suffix','$rcnt');~; + +# $trigger_jquery_raw .= qq~ + # function calc$suffix() + # { + # $jq_cal + # } + # ~; + +} #---------------------------------------------------------------------------------------- + +sub q_get_val { + +my ($val) = @_ ; + +my $disp_val = $val ; + +if ($val eq '0.00') { + $disp_val = '' ; + } + +return ($disp_val); + +} #------------------------------------------------------------------------------------------ + +sub set_check_boxes_checked { + +my ($id,$rcnt,$prefix,$suffix) = @_ ; + +# my $dbfield = "$prefix$suffix" ; + +# my $val = $db{$table}{$id}{$dbfield} ; + +# if ($suffix eq '_camera_details') { &common_min_debug("[$dbfield] $val [$id,$rcnt,$prefix,$suffix]") ; } + +for (1 .. $rcnt) { + # my $sstr = $_-1 ; + my $ifield = $prefix . '_' . "$_$suffix" ; + # $checkit{$ifield} = substr($val,$sstr,1) ; + my $val = $db{$table}{$id}{$ifield} ; + $checkit{$ifield} = $val ; + # if ($suffix eq '_camera_details') { &common_min_debug(" --- [$ifield] $checkit{$ifield} [$val]") ; } + } + +} #---------------------------------------------------------------------------------------- + +sub select_opts { + +my ($id) = @_ ; + +$required{type_id} = 1 ; +$select{type_id} = 1 ; +$selected{type_id}{$db{$table}{$id}{type_id}} = 'SELECTED' ; # unless ($db{$table}{$id}{type}) { $selected{type}{purchase} = 'SELECTED' ; } + +# $opts{type} = qq~~ ; + +&db_min_ro('quote_type','*','','','') ; + +my $other_id = 0 ; + +foreach (sort { $db{quote_type}{$a}{name} cmp $db{quote_type}{$b}{name} } keys %{$db{quote_type}}) { + if ($db{quote_type}{$_}{name} eq 'Other') { + $other_id = $_ ; + next ; + } + $opts{type_id} .= qq~~ ; +} + +$opts{type_id} .= qq~~ ; + +$trigger_jquery .= qq~\$("#selectType\_chosen").css( "width", "100%" );~ ; + +# my @currency_arr = qw( currency ); + +# foreach my $curr (@currency_arr) { + # if ($db{$table}{$id}{$curr}) { $selected{$curr}{$db{$table}{$id}{$curr}} = 'SELECTED'; } else { $selected{$curr}{ZAR} = 'SELECTED'; } + # $select{$curr} = 1 ; + # $opts{$curr} = qq~ + # + # ~ ; + +# } + +# $select{discount} = 1 ; +# $selected{discount}{$db{$table}{$id}{discount}} = 'SELECTED' ; +# $opts{discount} = qq~~ ; +# $opts{discount} = qq~~ ; +# $trigger_jquery .= qq~\$("#selectItem_$field\_chosen").css( "width", "96%" ) +# ~ ; + +my $selcntry = $db{$table}{$id}{country_shipped} ; $selcntry = 242 unless $selcntry ; # Default South Africa +&common_min_select_opts('country_shipped','countries','name',$selcntry,1,'country',''); +&common_min_select_opts('camera_system_id','camera_systems','name',$db{$table}{$id}{camera_system_id},1,'',''); +# &common_min_select_opts('quote_to','customers','name',$db{$table}{$id}{quote_to},1,'',''); + +&tab_customer_select_opts('customers','name','','quote_to'); + +# $select{ship_to} = 1 ; $required{ship_to} = 1 ; +# &db_min_ro('towns','*','','','') ; +# foreach (keys %{$db{'towns'}}) { + # my $selected = ''; if ($db{towns}{$_}{name} eq $db{$table}{$id}{ship_to}) { $selected = 'selected="selected"'; } + # $opts{ship_to} .= qq() ; + # } + +# $trigger_jquery_raw .= qq~ + +# function calcSection(sufx,cnt) { + + # var inpItemTtl = \$("#inputItem_ttl_"+cnt+sufx) ; + # var inpCurrAmnt = \$("#inputCurr_amnt_"+cnt+sufx) ; + # var inpItem = \$("#inputItem_"+cnt+sufx) ; + # var initUsdVal = \$("#inputUsd_amnt_"+cnt+sufx).val() ; + # var inpUsd = \$("#inputUsd_amnt_"+cnt+sufx) ; + # var qty = \$("#inputQty_"+cnt+sufx).val() ; + # var vatChkBox = \$("#checkboxVat_"+cnt+sufx) ; + # var exclChkBox = \$("#checkboxExcl_"+cnt+sufx) ; + # var selCurr = \$("#selectCurrency") ; + + # var exclChk = 'excl_'+cnt+sufx ; + # var vatChk = 'vat_'+cnt+sufx ; + + # var usdAmnt = 0 ; + # var vatAmnt = 0 ; + + # if (selCurr.val() != 'ZAR') { vatChkBox.prop("checked", false) ; } + + # // console.log("3. curr_changed: "+curr_changed +" : "+ selCurr.val()) ; + + # if (curr_changed==1 && selCurr.val()=='ZAR') { + # vatChkBox.prop("checked", true); + # } + + # //if (selCurr.val() != 'ZAR') { vatChkBox.prop("checked", false) ; } else { vatChkBox.prop("checked", true); } // set VAT checkbox + # // if (!inpItem.val()) { exclChkBox.prop("checked", false); } else { exclChkBox.prop("checked", true); } // set EXCL checkbox + + # curRoe = \$("#inputRoe").val(); + + # if ( (qty>0) && (inpUsd.val()>0) ) { + # var convPrice = convertCurr(initUsdVal,curRoe) ; + # var ttlPrice = convPrice * qty ; + # inpCurrAmnt.val(convPrice.toFixed(2)); + # inpItemTtl.val(ttlPrice.toFixed(2)); + # exclChkBox.prop("checked", false); + # } else { + # exclChkBox.prop("checked", true); + # } + + # if (\$('input[name='+exclChk+']:checked').length > 0) { // only calculate if included + # // inpCurrAmnt.prop('readonly', true); // inpCurrAmnt.val(''); + # // inpUsd.prop('readonly', true); //inpUsd.val(''); + # // inpItemTtl.val(''); inpItemTtl.prop('readonly', true); + # // \$("#inputQty_"+cnt+sufx).prop('readonly', true); + # var ttlPrice = 0 ; + # inpItemTtl.val(ttlPrice.toFixed(2)); + # return [0,0,0]; + # } + + # vatAmnt = 0 ; + + # if ((\$('input[name='+vatChk+']:checked').length > 0) && (selCurr.val() == 'ZAR')) { + # // var vat = addVat(inpCurrAmnt.val()) ; + # var vat = addVat(inpItemTtl.val()) ; + # vatAmnt = vat[0]; + # } + + # // usdAmnt = getNum(parseFloat(inpUsd.val())); + # currAmnt = getNum(parseFloat(inpCurrAmnt.val())); + # ttlAmnt = getNum(parseFloat(inpItemTtl.val())); + + # // return [usdAmnt,vatAmnt]; + # return [currAmnt,vatAmnt,ttlAmnt]; +# } + +# function getNum(val) +# { + # if (isNaN(val)) { + # return 0; + # } + # return val; +# } + +# function convertCurr(val,curRoe) +# { + # // val = val / curRoe ; + # val = val * curRoe ; + # return val; +# } + +# function addVat(amnt) +# { + # var vat_amnt = amnt*0.15 ; + # var subtotal = amnt - vat_amnt + # return [vat_amnt,subtotal]; +# } + +# function setRoe(sx,rcnt) +# { + # var labelCurrAmntSx = \$("#lab_curr_amnt$sec"+sx) ; + # var curr = \$("#selectCurrency").val() ; if (!curr) { curr = 'Curr' ; } + + # labelCurrAmntSx.html('Price ['+curr+']'); + + # for (i = 0; i <= rcnt; i++) { + # var inpCurrAmntSx = \$("#inputCurr_amnt_"+i+sx) ; ; + # inpCurrAmntSx.attr("placeholder",curr+' Amnt '+i); + # var inpQcPh = \$("#inputqty_"+i+sx).attr("placeholder"); + # } +# } + +# function calcTtl(qc,ica,iz) +# { + # var zar_amnt = getNum(parseFloat(\$("#inputWeight").val())) * getNum(parseFloat(qc.val())) ; + # iz.val(zar_amnt.toFixed(2)) ; +# } + +# \$("li").click(function(){ + # var activeTab = \$(this).text(); + # \$("#inputActivetab").val(activeTab) ; + # }); + +# // function selectTabs() +# // { + # // activeTab = \$("#inputActivetab").val(); + # // if (!activeTab) { activeTab = 'Quote Details' ; } + # // var tabs = \$("#myTab li"); + # // tabs.each(function(idx, li) { + # // var tab = \$(li); + # // if (tab.text == activeTab) + # // { + # // tab.addClass("active"); + # // } else { + # // tab.removeClass("active"); + # // } + # // }); +# // } + +# ~; + +# $trigger_jquery .= qq~ +# \$(window).bind('beforeunload', function() + # { + # // window.location = 'https://$ENV{SERVER_NAME}/list-quotes' ; + # alert('beforeunload'); +# }); + +# ~; + +$extra_css .= qq() ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'global' ; +our $lcpage = 'quote' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; +our $table = 'quotes' ; + +&common_min_add_box_icon ; + +} #------------------------------------------------------------------------------- + +# sub creat_db_cols { + +# &db_min_ro('quotes','*','','','') ; + +# my %col_exists ; + +# foreach (sort { $col_name{$a} cmp $col_name{$b} } keys %col_name) { + # $col = $col_name{$_} ; + # $col_exists{$col} = 1 ; +# } + +# my $mysql = "ALTER TABLE `quotes`" ; + +# # foreach (sort keys %i) { + # # if ($_ =~ /qty_/g) { + # # $mysql .= qq~ +# # DROP `$_`,~ ; + # # } +# # } + +# foreach (sort keys %i) { + # if ($_ eq 'iaction') { next ; } + + # if ($ignore{$_}) { next ; } + # if ($col_exists{$_}) { next ; } # only create the column if it doesn't exist + + # if (((substr($_,0,3) eq 'vat') or (substr($_,0,4) eq 'excl')) and (substr($_,0,9) ne 'vat_total')) { + # $mysql .= qq~ +# ADD `$_` INT(1) NOT NULL DEFAULT '0',~ ; + # } elsif ($_ =~ /qty_/g) { + # $mysql .= qq~ +# ADD `$_` INT(3) NULL DEFAULT '0',~ ; + # } elsif ($_ =~ /roe_/g) { + # $mysql .= qq~ +# ADD `$_` VARCHAR( 120 ) NOT NULL ,~ ; + # } elsif ($_ =~ /description_/g) { + # $mysql .= qq~ +# ADD `$_` VARCHAR( 255 ) NOT NULL ,~ ; + # } elsif (substr($_,0,3) eq 'roe') { + # $mysql .= qq~ +# ADD `$_` DECIMAL(4,2) NOT NULL ,~ ; # 999999.99 to -999999.99 + # } elsif ($_ =~ /date_/g or $_ =~ /_date/g) { + # $mysql .= qq~ +# ADD `$_` DATE DEFAULT NULL ,~ ; + # } elsif ($_ =~ /datetime/g) { + # $mysql .= qq~ +# ADD `$_` datetime DEFAULT NULL ,~ ; + # } elsif ($_ =~ /_costing_/g or $_ =~ /_total/g or $_ =~ /total_/g or $_ =~ /year_/g or $_ =~ /_amnt_/g) { # } elsif (substr($_,0,5) eq 'item_') { + # $mysql .= qq~ +# ADD `$_` DECIMAL( 8, 2 ) NOT NULL ,~ ; # 999999.99 to -999999.99 + # } elsif ($_ =~ /_included/g) { + # $mysql .= qq~ +# ADD `$_` TEXT NOT NULL ,~ ; + # } elsif ($_ =~ /_id/g) { + # $mysql .= qq~ +# ADD `$_` INT( 6 ) NOT NULL DEFAULT '0',~ ; + # } else { + # $mysql .= qq~ +# ADD `$_` VARCHAR( 120 ) NOT NULL ,~ ; + # } +# } + +# print $mysql ; +# exit ; + +# } #------------------------------------------------------------------------------------------ + +sub report_ifields { + +# my $account_sql_where = '' ; if ($i{account_id}) { $account_sql_where = "`id`='$i{account_id}'" ; } elsif ($glob_account_id) { $account_sql_where = "`id`='$glob_account_id'" ; } + +# &db_common_ro('account','id,name',$account_sql_where,'','') ; +# foreach my $id (keys %{$db{account}}) { $account_name{$id} = $db{account}{$id}{name} ; } + +if ($i{quote_to}) { + push @report_sql, "($table.quote_to = '$i{quote_to}')" ; + push @report_results, "`quote_to` = '$i{quote_to}'" ; +} + +# if ($i{ship_to}) { + # push @report_sql, "(`ship_to` = '$i{ship_to}')" ; + # push @report_results, "ship_to = $i{ship_to}" ; + # } + +if ($i{quotes_from} and $i{quotes_to}) { # check dates + my $quotes_from_check = $i{quotes_from} ; + $quotes_from_check =~ s/\-//g ; + my $quotes_to_check = $i{quotes_to} ; + $quotes_to_check =~ s/\-//g ; + if ($quotes_from_check > $quotes_to_check) { $error = qq(QUOTES FROM ($i{quotes_from}) > QUOTES TO ($i{quotes_to})); &report_screen; } + } + +if ($i{quotes_from}) { + push @report_sql, "($table.quote_date >= '$i{quotes_from}')" ; + push @report_results, "`quote_date` >= '$i{quotes_from}'" ; + } + +if ($i{quotes_to}) { + push @report_sql, "($table.quote_date <= '$i{quotes_to}')" ; + push @report_results, "`quote_date` <= '$i{quotes_to}'" ; + } + +if ($i{po_nr}) { + push @report_sql, "($table.po_nr LIKE '%$i{po_nr}%')" ; + push @report_results, "`po_nr` LIKE '$i{po_nr}'" ; + } + +if ($i{invoice_nr}) { + push @report_sql, "($table.invoice_nr LIKE '%$i{invoice_nr}%')" ; + push @report_results, "`invoice_nr` LIKE '$i{invoice_nr}'" ; + } + +if ($i{quote_nr}) { + push @report_sql, "($table.quote_nr LIKE '%$i{quote_nr}%')" ; + push @report_results, "`quote_nr` = '$i{quote_nr}'" ; + } + +# if ($i{serial_nr}) { + # for (1 .. 10) { + # push @report_sql_or, "(`serial_nr_$_\_camera_details` LIKE '%$i{serial_nr}%')" ; + # } + # push @report_results, "serial_nr LIKE `$i{serial_nr}`" ; + # my $sql_or = join(' OR ', @report_sql_or) ; + # push @report_sql, "($sql_or)" ; + # } + +if ($i{country}) { + push @report_sql, "($table.country_shipped = '$i{country}')" ; + push @report_results, "`country_shipped` = '$i{country}'" ; + } + + # if ($i{quote_to}) { + # push @report_sql, "($table.quote_to = '$i{quote_to}')" ; + # &db_min_ro('customers','1,name',"id='$i{quote_to}'",'','') ; + # push @report_results, "Customer Name = '$db{customers}{1}{name}'" ; + +if ($i{customer_name}) { + push @report_sql, "($table.quote_to = '$i{customer_name}')" ; + &db_min_ro('customers','1,name',"id='$i{customer_name}'") ; + push @report_results, "`customer` = '$db{customers}{$i{customer_name}}{name}'" ; + } + +if ($i{accepted} or $i{options} eq 'accepted') { + push @report_sql, "($table.quote_accepted='1')" ; + push @report_results, "`quote_accepted` = 'Yes'" ; + } +elsif ($i{closed} or $i{options} eq 'closed') { + # push @report_sql, "(`quote_cancelled`='1')" ; + # push @report_sql, "(`quote_cancelled`='1' OR `quote_expiry`<'$now_year-$now_mm-$now_dd')" ; + push @report_sql, "($table.quote_cancelled='1' OR ($table.quote_expiry<'$now_year-$now_mm-$now_dd' AND $table.quote_accepted<>'1'))" ; + push @report_results, "`quote_closed` = 'Yes'" ; + } +elsif ($i{options} && $i{options} ne 'all') { + push @report_results, "`quote` = '$i{options}'" ; + } +elsif ($i{options} && $i{options} eq 'all') { + push @report_results, "(`quote_accepted` = 'Yes' OR `quote_pending` = 'Yes' OR `quote_closed` = 'Yes')" ; + } + +if ($i{type}) { + push @report_sql, "($table.type='$i{type}')" ; + push @report_results, "`type` = '$i{type}'" ; + } + +$report_results_msg = uc join(', ', @report_results) ; + +unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); &report_screen; } else { $isaved = qq(SELECT WHERE $report_results_msg) ; } + +} #------------------------------------------------------------------------------------------ + +sub report_screen { + +&filter_screen if $ENV{QUERY_STRING} eq 'filter' ; + +our $lcol = 2 ; +our $fcol = 5 ; + +my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-42); # 6 weeks back + +$set_month = sprintf("%02s", $set_month) ; +$set_day = sprintf("%02s", $set_day) ; + +my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ; + +$print_box_content_rows .= &common_min_forms_start('report') ; + + $allow_deselect{customer_name} = 1 ; + $allow_deselect{camera_system} = 1 ; + $allow_deselect{country} = 1 ; + $allow_deselect{options} = 1 ; + $allow_deselect{type} = 1 ; + + &common_min_select_opts('customer_name','customers','name','','','',''); + $print_box_content_rows .= &common_min_form_select('customer_name','') ; + # $print_box_content_rows .= &common_min_form_input('customer_name','') ; + $print_box_content_rows .= &common_min_form_input('quote_nr','') ; + + $print_box_content_rows .= &common_min_form_datepicker('quotes_from','') ; # $set_ccyy_dd_mm + $print_box_content_rows .= &common_min_form_datepicker('quotes_to','') ; # $now_ccyy_mm_dd + + $print_box_content_rows .= &common_min_form_input('po_nr','') ; + $print_box_content_rows .= &common_min_form_input('invoice_nr','') ; + # &common_min_select_opts('camera_system','camera_systems','name','','','',''); + # $print_box_content_rows .= &common_min_form_select('camera_system','') ; + # $print_box_content_rows .= &common_min_form_input('serial_nr','') ; + # $print_box_content_rows .= &common_min_form_input('country','') ; + &common_min_select_opts('country','countries','name','','','',''); + $print_box_content_rows .= &common_min_form_select('country','') ; + # $print_box_content_rows .= &common_min_form_checkbox('invoiced','','') ; # Display all quotes that is Invoiced + + # $print_box_content_rows .= &common_min_form_checkbox('accepted','','') ; # Display all quotes that is Accepted + # $print_box_content_rows .= &common_min_form_checkbox('closed','','') ; # Display all quotes that is Cancelled + + my $options_selected = 'SELECTED' if $useropts{boss}{$username} or $useropts{super}{$username} ; + + $opts{options} = qq~~ ; + $print_box_content_rows .= &common_min_form_select('options','') ; + + $opts{type} = qq~~ ; + $print_box_content_rows .= &common_min_form_select('type','') ; + +$print_box_content_rows .= &common_min_forms_end('','','report') ; + +&common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub filter_screen { + +our $lcol = 2 ; +our $fcol = 5 ; + +my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-42); # 6 weeks back + +$set_month = sprintf("%02s", $set_month) ; +$set_day = sprintf("%02s", $set_day) ; + +my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ; + +$print_box_content_rows .= &common_min_forms_start('report') ; + + &common_min_select_opts('customer_name','customers','name','','','',''); + $print_box_content_rows .= &common_min_form_select('customer_name','') ; + + $print_box_content_rows .= &common_min_form_datepicker('quotes_from','') ; # $set_ccyy_dd_mm + $print_box_content_rows .= &common_min_form_datepicker('quotes_to','') ; # $now_ccyy_mm_dd + + $opts{type} = qq~~ ; + $print_box_content_rows .= &common_min_form_select('type','') ; + + my $options_selected = 'SELECTED' if $useropts{boss}{$username} or $useropts{super}{$username} ; + + $opts{options} = qq~~ ; + $print_box_content_rows .= &common_min_form_select('options','') ; + +$print_box_content_rows .= &common_min_forms_end('','','report') ; + +&common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +# use tabs_test2 ; +use tabs_test ; +use common ; +use common_shared ; +use today ; +use report ; +use xlsxcreator ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/recipients.pl b/scripts/_FromProd/v1.0/recipients.pl new file mode 100644 index 0000000..68aeb89 --- /dev/null +++ b/scripts/_FromProd/v1.0/recipients.pl @@ -0,0 +1,316 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + + my $exists = '' ; + + $i{name} = &common_fix_str($i{name}) ; + + &db_min_ro($table,'*',"name='$i{name}'",'name','') ; + + foreach my $id (keys %{$db{$table}}) { if (lc $db{$table}{$id}{name} eq lc $i{name}) { $exists = 1 ; } } + + if ($exists) { + $alert = &common_min_alert('warning',"RECIPIENT NAME ALREADY EXISTS!",'ok') ; + %col_name = () ; + &common_min_add_screen ; + &common_min_screen1 ; + } + +# REMOVE LATER ----------------- + + &db_min_ro('regions','id,code',"id='$i{region_id}'",'','') if $i{region_id} ; + + $i{region_code} = $db{regions}{$i{region_id}}{code} if $i{region_id} ; + +# REMOVE LATER ----------------- + +} #------------------------------------------------------------------------------------------ + +sub insert { + + &add_db_fields ; + + $i{id} = &db_min_get_max($table,'id') ; + + $i{contact_nr} = &process_number($i{contact_nr}) ; + + &db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + unless ($i{id}) { $error = qq(NO ID) ; return ; } + + &edit_db_fields ; + + $i{contact_nr} = &process_number($i{contact_nr}) ; + + &db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub process_number { + + my ($number) = @_ ; + $number =~ s/ //g ; + $number =~ s/\+//g ; + return $number ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + our %recipient_is_used = () ; + + &db_min_ro('event_quotes',"id,recipient_id","`recipient_id` <> '0'",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + $recipient_is_used{aisa}{$db{event_quotes}{$_id}{recipient_id}} .= qq~$_id;~ ; + } + + &db_switch_conn('sss') ; + + &db_min_ro('event_quotes',"id,recipient_id","`recipient_id` <> '0'",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + $recipient_is_used{sss}{$db{event_quotes}{$_id}{recipient_id}} .= qq~$_id;~ ; + } + + &db_switch_conn('aisa') ; + + &db_min_ro($table,'*','','','') ; + + foreach my $id (keys %{$db{$table}}) { + + my $edit_butt = qq~ ~ ; + my $del_butt = qq~ ~ ; + + if ($glod_user_level >= 3) { + $edit_butt = qq~ ~ ; + } + + if ($glod_user_level >= 3) { + $del_butt = qq~ ~ ; + } + + + if (($recipient_is_used{aisa}{$id} || $recipient_is_used{sss}{$id}) && $db{$table}{$id}{name} && $db{$table}{$id}{contact_nr}) { + $edit_butt = qq~~ ; + } + + if ($recipient_is_used{aisa}{$id} || $recipient_is_used{sss}{$id}) { + # $edit_butt = qq~ ~ ; + $del_butt = qq~ ~ ; + + if ($recipient_is_used{aisa}{$id}) { + my $row_cnt = 1 ; my $flag_cnt = 0 ; + foreach (split(/\;/,$recipient_is_used{aisa}{$id})) { + next unless $_ ; + $flag_cnt++ ; + if (($flag_cnt == 20 && $row_cnt == 1 && $edit_butt) || ($flag_cnt == 22 && $row_cnt == 1 && !$edit_butt) || ($flag_cnt == 23 && $row_cnt > 1 && $edit_butt) || ($flag_cnt == 23 && $row_cnt > 1 && !$edit_butt)) { + $del_butt .= qq~
    ~ ; + $row_cnt++ ; + $flag_cnt = 0 ; + } + $del_butt .= qq~~ ; + } + } + + } + + my $disp_nr = $db{$table}{$id}{contact_nr} ; + + if (length($disp_nr) == 11) { + $disp_nr = substr($disp_nr,0,2) . ' ' . substr($disp_nr,2,2) . ' ' . substr($disp_nr,4,3) . ' ' . substr($disp_nr,7,4) ; + $disp_nr = '+' . $disp_nr if $disp_nr =~ /^27/ ; + } + + $print_tbody .= qq~ + + $id + $db{$table}{$id}{name} + $disp_nr + + $edit_butt + $del_butt + + + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + &sort_fields; + + &hidden_db_fields; + + # $ignore{id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &hidden_db_fields; + + &sort_fields; + + $hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + + $ignore{iaction} = 1 ; + $required{name} = 1 ; + $required{contact_nr} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + our %poc_is_used = () ; + + &db_min_ro('event_quotes',"id,recipient_id","`recipient_id` <> '0'",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + $recipient_is_used{aisa}{$db{event_quotes}{$_id}{recipient_id}} .= qq~$_id;~ ; + } + + &db_switch_conn('sss') ; + + &db_min_ro('event_quotes',"id,recipient_id","`recipient_id` <> '0'",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + $recipient_is_used{sss}{$db{event_quotes}{$_id}{recipient_id}} .= qq~$_id;~ ; + } + + &db_switch_conn('aisa') ; + + %sort_field = () ; + + $sort_field{1} = 'name' ; + $sort_field{2} = 'contact_nr' ; + + if ($recipient_id_used{aisa}{$i{id}} || $recipient_id_used{sss}{$i{id}}) { + $required{name} = 0 ; + $required{contact_nr} = 0 ; + $readonly{contact_nr} = "READONLY" ; + $readonly{name} = "READONLY" ; + } else { + $required{name} = 1 ; + $required{contact_nr} = 1 ; + } + + if ($db{$table}{$i{id}}{name} && !$db{$table}{$i{id}}{contact_nr}) { + $readonly{name} = "READONLY" ; + $readonly{contact_nr} = "" ; + } elsif ($db{$table}{$i{id}}{name} && $db{$table}{$i{id}}{contact_nr}) { + $readonly{contact_nr} = "READONLY" ; + $readonly{name} = "READONLY" ; + } else { + $readonly{contact_nr} = "" ; + $readonly{name} = "" ; + } + + my $disp_nr = $db{$table}{$i{id}}{contact_nr} ; + + if (length($disp_nr) == 11) { + $disp_nr = substr($disp_nr,0,2) . ' ' . substr($disp_nr,2,2) . ' ' . substr($disp_nr,4,3) . ' ' . substr($disp_nr,7,4) ; + $disp_nr = '+' . $disp_nr if $disp_nr =~ /^27/ ; + } + + $db{$table}{$i{id}}{contact_nr} = $disp_nr ; + +} #------------------------------------------------------------------------------- + +sub add_screen { + + # called from common_add_screen + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + +} #------------------------------------------------------------------------------------------ + +sub thead { + + $print_thead = qq~ + + + ID + NAME + CONTACT NUMBER +   + + + ~ ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'map-marker' ; + our $lcpage = 'recipients' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'event_quotes_recipient' ; + + $s{no} = 1 ; + + &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/regions.pl b/scripts/_FromProd/v1.0/regions.pl new file mode 100644 index 0000000..0b81ab0 --- /dev/null +++ b/scripts/_FromProd/v1.0/regions.pl @@ -0,0 +1,299 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +&db_open_ro ; + $db_ignore_open_close = 1 ; + &common_min_action; + $db_ignore_open_close = 0 ; +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + + my $exists = '' ; + + $i{name} = &common_fix_str($i{name}) ; + + &db_min_ro($table,'*',"name='$i{name}' AND `country_id` = '$i{country_id}'",'name','') ; + + foreach my $id (keys %{$db{$table}}) { + if (lc $db{$table}{$id}{name} eq lc $i{name}) { + $exists = 1 ; + } + } + + if ($exists) { + &db_min_ro('countries','1,name',"id='$i{country_id}'") ; + $alert = &common_min_alert('warning',"`$i{name}` AS A REGION NAME IN THE COUNTRY `$db{countries}{1}{name}` ALREADY EXISTS!",'ok') ; + %col_name = (); + &common_min_add_screen; + &common_min_screen1; + } + +} #------------------------------------------------------------------------------------------ + +sub insert { + + &add_db_fields ; + + $i{id} = &db_min_get_max($table,'id') ; + + &db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + unless ($i{id}) { $error = qq(NO ID) ; return ; } + + &edit_db_fields ; + + &db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + &db_switch_conn('sss') ; + + &db_min_ro('event_quotes',"DISTINCT region_id AS 'region_id'","region_id <> '0'",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + $region_id_used{$_id} = 1 ; + } + + &db_min_ro('users','id,region_ids',"region_ids <> '0'",'','') ; + + foreach my $user_id (keys %{$db{users}}) { + next if $region_id_used{$db{users}{$user_id}{region_ids}} ; + my @region_ids = split(/\,/,$db{users}{$user_id}{region_ids}) ; + foreach (@region_ids) { + $region_id_used{$_} = 1 ; + } + } + + &db_switch_conn('aisa') ; + + &db_min_ro('event_quotes',"DISTINCT region_id AS 'region_id'","region_id <> '0'",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + $region_id_used{$_id} = 1 ; + } + + &db_min_ro('countries','id,name',"",'','') ; + + &db_min_ro('users','id,region_ids',"region_ids <> '0'",'','') ; + + foreach my $user_id (keys %{$db{users}}) { + next if $region_id_used{$db{users}{$user_id}{region_ids}} ; + my @region_ids = split(/\,/,$db{users}{$user_id}{region_ids}) ; + foreach (@region_ids) { + $region_id_used{$_} = 1 ; + } + } + + $region_id_used{13} = 1 ; ## OTHER + + &db_min_ro($table,'*','','','') ; +# extra_edit_hidden_inputs + foreach my $id (keys %{$db{$table}}) { + + my $edit_butt = qq~ ~ ; + my $del_butt = qq~ ~ ; + + if ($glod_user_level >= 3) { + $edit_butt = qq~ ~ ; + } + + if ($glod_user_level >= 3) { + $del_butt = qq~ ~ ; + } + + if ($region_id_used{$id}) { + if ($db{$table}{$id}{code} && $db{$table}{$id}{name}) { + $edit_butt = qq~ ~ ; + } elsif ($glod_user_level >= 3) { + $edit_butt = qq~ ~ ; + $extra_edit_hidden_inputs .= qq~~ ; + } + + $del_butt = qq~ ~ ; + } + + $print_tbody .= qq~ + $id + $db{$table}{$id}{code} + $db{$table}{$id}{name} + $db{$table}{$id}{latitude} + $db{$table}{$id}{longitude} + $db{countries}{$db{$table}{$id}{country_id}}{name} + + $edit_butt + $del_butt + + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + &sort_fields; + + &hidden_db_fields; + + # $ignore{id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &sort_fields; + + &hidden_db_fields; + + $hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + + $ignore{iaction} = 1 ; + $required{code} = 1 ; + $required{name} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + %sort_field = () ; + + $sort_field{1} = 'name' ; $preferred_title{name} = 'Name' ; + $sort_field{2} = 'code' ; $preferred_title{code} = 'Code' ; + $sort_field{3} = 'latitude' ; $preferred_title{latitude} = 'Latitude' ; + $sort_field{4} = 'longitude' ; $preferred_title{longitude} = 'Longitude' ; + $sort_field{5} = 'country_id' ; + + $select{country_id} = 1 ; + $required{country_id} = 1 ; + + if ($i{id}) { + + my $incomplete_field = "incomplete_but_in_system_use_$i{id}" ; + + if ($i{$incomplete_field}) { + + &db_min_ro($table,'*',"`id`='$i{id}'",'','') ; + $readonly{code} = "READONLY" if $db{$table}{$i{id}}{code} ; + $readonly{name} = "READONLY" if $db{$table}{$i{id}}{name} ; + $readonly{latitude} = "READONLY" if $db{$table}{$i{id}}{latitude} ; + $readonly{longitude} = "READONLY" if $db{$table}{$i{id}}{longitude} ; + + } + } + + $db{$table}{$i{id}}{name} = $i{name} ; + $db{$table}{$i{id}}{code} = $i{code} ; + $db{$table}{$i{id}}{latitude} = $i{latitude} ; + $db{$table}{$i{id}}{longitude} = $i{longitude} ; + $db{$table}{$i{id}}{country_id} = $i{country_id} ; + + if ($i{country_id}) { + $trigger_jquery_raw .= qq~ + \$("#selectCountry_id").val("$i{country_id}").trigger("chosen:updated") ; + ~ ; + } + +} #------------------------------------------------------------------------------- + +sub add_screen { + + # called from common_add_screen + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + &select_opts ; + + # &common_min_select_opts('code','regions','name',$db{$table}{$i{id}}{name},'','',$sql_or,'name'); +} #------------------------------------------------------------------------------------------ + +sub select_opts { + + # $required{based_in} = 1 ; + # $select{based_in} = 1 ; + # $opts{based_in} = qq~~ ; + + # my $sql_or = '' ; + + # if ($is_schools_manager || $is_operator) { + # @report_sql_or = () ; + # foreach $_reg_id (keys %{$glob_regids{$userid}}) { + # push @report_sql_or, "id = '$_reg_id'" + # } + # $sql_or = join(' OR ',@report_sql_or) ; + # } + + &common_min_select_opts('country_id','countries','name',$db{$table}{$i{id}}{country_id},'','','','','','','name') ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + $print_thead = qq~IDNAMECODELONGITUDELATITUDECOUNTRY ~ ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'globe' ; + our $lcpage = 'regions' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'regions' ; + + $s{no} = 1 ; + + &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/rma.pl b/scripts/_FromProd/v1.0/rma.pl new file mode 100644 index 0000000..6dcf690 --- /dev/null +++ b/scripts/_FromProd/v1.0/rma.pl @@ -0,0 +1,750 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Excel::Writer::XLSX ; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +our $double_box_layout = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our @all_select_ids = () ; our $minify_jquery = 1 ; + +&db_open_ro ; + $db_ignore_open_close = 1 ; + &common_min_action ; + $db_ignore_open_close = 0 ; +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub report_screen { + + # # &filter_screen if $ENV{QUERY_STRING} eq 'filter' ; + + # our $lcol = 2 ; + # our $fcol = 5 ; + + # # my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-42) ; # 6 weeks back + + # # $set_month = sprintf("%02s", $set_month) ; + # # $set_day = sprintf("%02s", $set_day) ; + + # # my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ; + + # &select_opts ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + # # &common_min_select_opts('customer_name','customers','name','','','','') ; + # $print_box_content_rows .= &common_min_form_select('camera_system','') ; + # $print_box_content_rows .= &common_min_form_input('serial_number','') ; + # $print_box_content_rows .= &common_min_form_input('part_number','') ; + # # $print_box_content_rows .= &common_min_form_datepicker('quotes_from','') ; # $set_ccyy_dd_mm + # # $print_box_content_rows .= &common_min_form_datepicker('quotes_to','') ; # $now_ccyy_mm_dd + # # # $print_box_content_rows .= &common_min_form_input('po_nr','') ; + # # $print_box_content_rows .= &common_min_form_input('invoice_nr','') ; + # # &common_min_select_opts('country','countries','name','','','','') ; + # # $print_box_content_rows .= &common_min_form_select('country','') ; + # # $print_box_content_rows .= &common_min_form_checkbox('accepted','','') ; # Display all event_quotes that is Accepted + # # $print_box_content_rows .= &common_min_form_checkbox('closed','','') ; # Display all event_quotes that is Cancelled + + # # &common_min_select_opts('type','event_types','name','','','','') ; + # # $print_box_content_rows .= &common_min_form_select('type','') ; + + # # &common_min_select_opts('region_id','regions','name','','','',''); + + # # &common_min_select_opts('city_id','cities','city','','','',''); + # # &common_min_select_opts('organisation_ids','organisations','name','','','','') ; + # # &common_min_select_opts('sport_type_ids','sport_types','name','','','','') ; + + # # $preferred_title{region_id} = "Region" ; + # # $preferred_title{city_id} = "City" ; + # # $preferred_title{organisation_ids} = "Venue" ; + # # $preferred_title{sport_type_ids} = "Sport Type" ; + + # # $print_box_content_rows .= &common_min_form_select('region_id','') ; + # # $print_box_content_rows .= &common_min_form_select('city_id','') ; + # # $print_box_content_rows .= &common_min_form_select('organisation_ids','') ; + # # $print_box_content_rows .= &common_min_form_select('sport_type_ids','') ; + + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub report_ifields { + +} #------------------------------------------------------------------------------- + +sub validate { + +# my $exists = '' ; + +# $i{name} = lc $i{name} ; +# $i{name} =~ s/ //gi ; + +# &db_min_ro($table,'*',"name = '$i{name}'",'name','') ; + +# foreach my $id (keys %{$db{$table}}) { if ($db{$table}{$id}{name} eq $i{name}) { $exists = 1 ; } } + +# if ($exists) { + # $alert = &common_min_alert('warning',"NAME ALREADY EXISTS!",'ok') ; + # %col_name = (); + # &common_min_add_screen; + # &common_min_screen1; + # } + +} #------------------------------------------------------------------------------------------ + +sub insert { + +&add_db_fields ; + +# $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&process_table ; + +&defualt_values ; + +foreach (keys %i) { + $ignore{$_} = 1 unless $i{$_} ; +} + +&db_min_insert($table) ; + +# for (keys %i) { + # print "\n $_ : $i{$_}" ; +# } + +# exit ; + +} #------------------------------------------------------------------------------------------ + +sub update { + +unless ($i{id}) { $error = qq(NO ID) ; return ; } + +&db_min_ro('rma',"*","id='$i{id}'","","") ; + +&edit_db_fields ; + +# unless ($i{block}) { $i{block} = '0' ; } +# $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&process_table ; + +&defualt_values ; + +foreach (keys %{$db{rma}{$i{id}}}) { + $ignore{$_} = 1 if $db{rma}{$i{id}}{$_} eq $i{$_} +} + +&db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub defualt_values { + + $i{rma_status_id} = 0 unless $i{rma_status_id} ; + $i{customer_id} = 0 unless $i{customer_id} ; + $i{camera_system_id} = 0 unless $i{camera_system_id} ; + +} #------------------------------------------------------------------------------------------ + +sub process_table { + + for (1 .. 5) { + $ignore{"support_fault_$_"} = 1 ; + $ignore{"date_$_"} = 1 ; + $i{support_faults} .= qq~$i{"support_fault_$_"};~ ; + $i{support_fault_dates} .= qq~$i{"date_$_"};~ ; + } + chop $i{support_faults} if $i{support_faults} ; + chop $i{support_fault_dates} if $i{support_fault_dates} ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + # my %seen_camera = () ; + + # &db_min_ro('event_quotes','id, camera_system_id','','','') ; + + # foreach my $id (keys %{$db{'event_quotes'}}) { + # next if $seen_camera{$db{'event_quotes'}{$id}{camera_system_id}} ; + # $seen_camera{$db{'event_quotes'}{$id}{camera_system_id}} = 1 ; + # } + + # &db_min_ro('quotes','id, camera_system_id','','','') ; + + # foreach my $id (keys %{$db{'quotes'}}) { + # next if $seen_camera{$db{'quotes'}{$id}{camera_system_id}} ; + # $seen_camera{$db{'quotes'}{$id}{camera_system_id}} = 1 ; + # } + + &load_data ; + + our @sql_col_display = ("date_received","client","system","serial_nr","fault_reported","RMA_date","status","date_supplier_returned","date_returned_client","replacement_date","replacement_serial") ; + + our $xlsx_title_heading = "RMA Report" ; + our $xlsxdir = "rma_report" ; + our $xlsxreportname = "RMA_Report" ; + + &report_xlsx_export_header("$xlsxreportname",$xlsxdir,'',$xlsx_title_heading) ; + $xlsxrow-- ; + + foreach my $id (keys %{$db{$table}}) { + my $disp_blocked = qq(); if ($db{$table}{$id}{block}) { $disp_blocked = qq(); } + + # $opts{$lcpage} .= qq~~ ; + + my $edit_butt = '' ; my $del_butt = '' ; + + if ($useropts{super}{$username}) { + $edit_butt = qq~ ~ ; + } + + if ($useropts{boss}{$username} or $useropts{super}{$username}) { + $del_butt = qq~ ~ if not $seen_camera{$id} ; + $del_butt = qq~ ~ if $seen_camera{$id} ; + } + + $print_tbody .= qq~~ ; + + $xlsxcol = 0 ; + + foreach (@sql_col_display) { + + my $val = $db{$table}{$id}{$_} ; + my $val_min = '' ; + my $formatting = $format84 ; + + if ($_ eq 'client') { + $val = $db{customers}{$db{$table}{$id}{customer_id}}{name} ; + } elsif ($_ eq 'system') { + $val = $db{camera_systems}{$db{$table}{$id}{camera_system_id}}{name} ; + $val .= " [" . $db{camera_systems}{$db{$table}{$id}{camera_system_id}}{description} . "]" if $db{camera_systems}{$db{$table}{$id}{camera_system_id}}{description} ; + } elsif ($_ eq 'fault_reported') { + # if ($db{$table}{$id}{replacement}) { + # $val = &set_tick("green") ; + # } else { + # $val = &set_tick("red") ; + # } + + } elsif ($_ eq 'RMA_date') { + + } elsif ($_ eq 'status') { + $val = $db{rma_status}{$db{$table}{$id}{rma_status_id}}{status} + } elsif ($_ eq 'date_supplier_returned') { + + } elsif ($_ eq 'date_returned_client') { + + } elsif ($_ eq 'replacement_date') { + + } elsif ($_ eq 'replacement_serial') { + + } + + if (!$val_min) { + $val_min = $val ; + } + + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_min,$formatting) ; + $xlsxcol++ ; + + $print_tbody .= qq~$val~ ; + + } + + $print_tbody .= qq~$edit_butt$del_butt~ ; + + $xlsxrow++ ; + + # $id + # $db{$table}{$id}{name} + # $db{$table}{$id}{description} + # + # $edit_butt + # $del_butt + # + # ~ ; + } + + &report_xlsx_export_footer('K',15,$xlsxdir) ; + +} #------------------------------------------------------------------------------------------ + +sub set_tick { + +my ($color,$tooltip) = @_ ; + +$tick{green} = qq~2~ ; +$tick{orange} = qq~1~ ; +$tick{red} = qq~0~ ; + +return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub load_data { + + &db_min_ro('camera_systems',"*",'','','') ; + &db_min_ro('customers',"id,name",'','','') ; + &db_min_ro('rma_status',"*",'','','') ; + # &db_min_ro('camera_systems',"*",'','','') ; + # &db_min_ro('camera_systems',"*",'','','') ; + # &db_min_ro('camera_systems',"*",'','','') ; + &db_min_ro($table,'*','','','') ; + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + +&hidden_db_fields; + +$ignore{id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + +&hidden_db_fields; + +$hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + +$ignore{iaction} = 1 ; +$ignore{date_received} = 1 ; + +# $readonly{name} = 'READONLY' ; +# $required{name} = 1 ; +# $required{description} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; +# called from common_add_screen + +&select_opts ; + +our $savjqy = 1 ; # incorporate jquery into the save event to accommodate the multiple chosen options + +&build_boxes_edit ; + +# &common_min_extra_crumb("search-$lcpage\s","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +&select_opts($i{id}) ; + +# $addcpb = 1 ; # add copy button to the edit screen + +our $savjqy = 1 ; # incorporate jquery into the save event to accommodate the multiple chosen options + +&build_boxes_edit($i{id}) ; + +&common_min_extra_crumb("search-$lcpage\s","Search Screen") ; + + +} #------------------------------------------------------------------------------------------ + +sub build_boxes_edit { + +my ($id) = @_ ; + +$allow_deselect{"camera_system_id"} = 1 ; +$allow_deselect{"part_number"} = 1 ; +$allow_deselect{"customer_id"} = 1 ; +$allow_deselect{"rma_status_id"} = 1 ; + +$print_box_content_rows .= &common_min_forms_start($table) ; +$print_box_content_rows .= qq~
    ~ ; + &build_boxes_left($id); +$print_box_content_rows .= qq~
    ~ ; + &build_boxes_right($id); +$print_box_content_rows .= qq~
    ~ ; +$print_box_content_rows .= ($id) ? &common_min_forms_end($id,$table,'update',$skip) : &common_min_forms_end($id,$table,'save',$skip) ; + +my $all_select_ids_str = join(",",@all_select_ids) ; + +$trigger_jquery_raw .= qq~\$("$all_select_ids_str").chosen({allow_single_deselect:true});~ ; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_left { + + my ($id) = @_ ; + + # our ($lcol,$fcol) = &common_min_columns(3,9) ; + + $add_form_fields = ''; + +# Camera System (dropdown pull from database) +# Serial Number (enter nr and pull from database) +# Part Number (pull from database) +# System Name (pull from database) +# Warranty period - From Date to Date (Show date from ‘Date Received’ database from camera page – plus add 15 months from this date which then gets displayed) - this is the automatic warranty period for all system + + $preferred_title{serial_nr} = "Serial Number" ; + + $preferred_title{warranty_start} = "Warranty Period" ; + + + $add_form_fields .= &common_min_form_select('camera_system_id') ; + + if ($db{$table}{$id}{camera_system_id}) { + $trigger_jquery_raw .= qq~ + \$("#selectCamera_system_id").val($db{$table}{$id}{camera_system_id}) ; + \$("#selectCamera_system_id").trigger("chosen:updated") ; + ~ ; + } + + $add_form_fields .= &common_min_form_input('serial_nr',$db{$table}{$id}{serial_nr}) ; + $add_form_fields .= &common_min_form_select('part_number') ; + + if ($db{$table}{$id}{part_number}) { + $trigger_jquery_raw .= qq~ + \$("#selectPart_number").val($db{$table}{$id}{part_number}) ; + \$("#selectPart_number").trigger("chosen:updated") ; + ~ ; + } + + $add_form_fields .= &common_min_form_input('system_name',$db{$table}{$id}{system_name}) ; + $readonly{warranty_start} = "READONLY" ; + + # my $a = &common_min_form_input('warranty_start','','','',1) ; + $readonly{warranty_end} = "READONLY" ; + my $default_date = "$now_ccyy_mm_dd" ; + my $warranty_start = $db{$table}{$id}{warranty_start} ; + $warranty_start = $default_date unless $warranty_start ; + + my $warranty_end = $db{$table}{$id}{warranty_end} ; + $warranty_end = $default_date unless $warranty_end ; + + $add_form_fields .= &common_min_form_input('warranty_start',$warranty_start,'','',1) ; + + $add_form_fields .= qq~ +
    + +
    ~ ; + + $add_form_fields .= &common_min_form_datepicker_col('warranty_end',$warranty_end) ; + $add_form_fields .= qq~
    ~ ; + + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + $print_box_content_rows .= &common_min_box_top('camera',' Camera Details',$box_right_bg); #film + $print_box_content_rows .= $add_form_fields ; + $print_box_content_rows .= &common_min_box_foot; + + $print_box_content_rows .= qq~ +
    +
    +
    +
    ~ ; # fixes row highlighting issue + + # #----------------- NEW BOX LEFT --------------------------------------------------------------------- + + $add_form_fields = '' ; + + + + + $fcol=4 ; + + # if ($_>$cntcamloop) { $cam_display_butt = qq~display:none;~ ; } else { $cam_display_butt = '' ; } + +# Client (select from Dropdown) +# Date Received (capture date it was received by ITV warehouse) +# Client Fault Note –a note box where they can note what client says is faulty +# Support Fault Report: - Note box they can enter what support has found and a date field (to show progress the support team +# ADD button to add more Note box and date fields if there is more work to be done and keep track of dates of each note added +# Remarks + + $preferred_title{customer_id} = "Client" ; + $add_form_fields .= &common_min_form_select('customer_id') ; + + if ($db{$table}{$id}{customer_id}) { + $trigger_jquery_raw .= qq~ + \$("#selectCustomer_id").val($db{$table}{$id}{customer_id}) ; + \$("#selectCustomer_id").trigger("chosen:updated") ; + ~ ; + } + + $add_form_fields .= &common_min_form_textarea('client_fault_note',$db{$table}{$id}{client_fault_note}) ; + $readonly{date_received} = "READONLY" ; + # $default_date = "$now_ccyy_mm_dd 00:00:00" ; + my $date_received = $db{$table}{$id}{date_received} ; + $date_received = $default_date unless $date_received ; + $add_form_fields .= &common_min_form_datepicker('date_received',$date_received) ; + + my %disp_sn_style = () ; + + $lcol=2 ; + + my @a = split(/;/,$db{$table}{$id}{support_faults}) ; + my @b = split(/;/,$db{$table}{$id}{support_fault_dates}) ; + + for (2 .. 5) { + $disp_sn_style{$_} = qq~style="display:none;"~ unless $a[$_-1] ; + + } + + $default_date = "$now_ccyy_mm_dd" ; + + for (1 .. 5) { + $add_form_fields .= qq~ +
    +
    ~ ; + my $col1 = "support_fault_$_" ; + # $required{$col} = 1 ; + &common_min_forms_required ; + $add_form_fields .= &common_min_form_input($col1,$a[$_-1],'','',1) ; + $add_form_fields .= qq~ +
    + +
    + ~ ; + + + my $date = $b[$_-1] ; + $date = $default_date unless $b[$_-1] ; + + my $col2 = "date_$_" ; + $readonly{$col2} = "READONLY" ; + $add_form_fields .= &common_min_form_datepicker_col($col2,$date) ; + # $fcol=3 ; + $add_form_fields .= qq~ +
    ~; + + $add_form_fields .= qq~~ if $_ < 5 ; + + $trigger_jquery_raw .= qq~\$("#btn_serial_nr_$_").css("display","none");~ if ($a[1] and $_ == 1) or ($a[$_] and $a[$_-1]) ; + + $trigger_jquery_raw .= qq~ + \$("#btn_serial_nr_$_").click(function () { + let v = $_ + 1 ; + \$("#btn_serial_nr_$_").hide() ; + \$("#btn_serial_nr_"+v).show() ; + \$("#sn_row_"+v).show() ; + let v2 = $_ + 2 ; + if (\$("#sn_row_"+v2).css("display") !== "none") { \$("#btn_serial_nr_"+v).hide() ; } + }) ; + ~ ; + + $add_form_fields .= qq~ +
    +
    + ~ ; + + } + + # $default_date = "$now_ccyy_mm_dd 00:00:00" ; + + $lcol = 2 ; + # $add_form_fields .= qq~ + #
     
    ~ ; + $add_form_fields .= qq~ +
    +
    ~ ; + $preferred_title{remarks_1} = "Remarks" ; + $add_form_fields .= &common_min_form_textarea('remarks_1',$db{$table}{$id}{remarks_1}) ; + $add_form_fields .= qq~ +
    +
    ~ ; + + $print_box_content_rows .= &common_min_box_top('user',' Client Details',$box_right_bg); #film + $print_box_content_rows .= $add_form_fields ; + $print_box_content_rows .= &common_min_box_foot; + + $print_box_content_rows .= qq~
    ~ ; # fixes row highlighting issue + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_right { + +my ($id) = @_ ; + +my $box_icon = '' ; + +#----------------------------------------------------------------- New box -------------------------------------- + +&db_min_ro('customers','id,name','','','') ; +foreach my $cust_id (keys %{$db{customers}}) { $customer{$cust_id} = $db{customers}{$cust_id}{name} ; } + +my $q_nr = $db{$table}{$id}{quote_nr} ; +my $c_nr = $db{$table}{$id}{camera_nr} ; + +# &common_load_quote_vars("='$id'"); +&common_load_quote_vars("cameras.quote_nr='$q_nr' AND quotes.quote_nr='$q_nr'"); + +$lcol = 3 ; $fcol = 4 ; +$readonly{rma_date_requested} = "READONLY" ;$readonly{rma_accepted} = "READONLY" ; $readonly{date_returned} = "READONLY" ; $readonly{date_to_supplier} = "READONLY" ; +$preferred_title{rma_status_id} = "Status" ; $preferred_title{remarks_2} = "Remarks" ; + +my $rma_date_requested = $db{$table}{$id}{rma_date_requested} ; +$rma_date_requested = $default_date unless $rma_date_requested ; + +my $rma_accepted = $db{$table}{$id}{rma_accepted} ; +$rma_accepted = $default_date unless $rma_accepted ; + +my $date_to_supplier = $db{$table}{$id}{date_to_supplier} ; +$date_to_supplier = $default_date unless $date_to_supplier ; + +my $date_returned = $db{$table}{$id}{date_returned} ; +$date_returned = $default_date unless $date_returned ; + +$print_box_content_rows .= &common_min_box_top('list-alt',' RMA Details',$box_right_bg,$box_icon,'') ; #qrcode + + $print_box_content_rows .= &common_min_form_datepicker('rma_date_requested',$rma_date_requested) ; + $print_box_content_rows .= &common_min_form_input('ticket_nr',$db{$table}{$id}{ticket_nr}) ; + $print_box_content_rows .= &common_min_form_datepicker('rma_accepted',$rma_accepted) ; + $print_box_content_rows .= &common_min_form_textarea('rma_rejected',$db{$table}{$id}{rma_rejected}) ; + $print_box_content_rows .= &common_min_form_datepicker('date_to_supplier',$date_to_supplier) ; + $print_box_content_rows .= &common_min_form_select('rma_status_id') ; + $print_box_content_rows .= &common_min_form_textarea('remarks_2',$db{$table}{$id}{remarks_2}) ; + $print_box_content_rows .= &common_min_form_datepicker('date_returned',$date_returned) ; + +$print_box_content_rows .= &common_min_box_foot ; + +if ($db{$table}{$id}{rma_status_id}) { + $trigger_jquery_raw .= qq~ + \$("#selectRma_status_id").val($db{$table}{$id}{rma_status_id}) ; + \$("#selectRma_status_id").trigger("chosen:updated") ; + ~ ; +} + +#----------------------------------------------------------------- New box -------------------------------------- + +$readonly{replacement_date} = "READONLY" ; $fcol=4; + +my $replacement_date = $db{$table}{$id}{replacement_date} ; +$replacement_date = $default_date unless $replacement_date ; + +$print_box_content_rows .= &common_min_box_top('wrench',' Replacement',$box_right_bg,$box_icon,'camera-replacement-box') ; + + $print_box_content_rows .= &common_min_form_checkbox('replacement',$db{$table}{$id}{replacement},'',1) ; + $print_box_content_rows .= &common_min_form_datepicker('replacement_date',$replacement_date) ; + $print_box_content_rows .= &common_min_form_input('replacement_camera_nr',$db{$table}{$id}{replacement_camera_nr}) ; + + $print_box_content_rows .= qq~ + + ~ ; + + # $trigger_jquery_raw .= qq~ + # \$("#checkboxReplacement").on("change",function () { + # console.log("checkboxReplacement") ; + + # }) ; + # ~ ; + +$print_box_content_rows .= &common_min_box_foot ; + +$trigger_jquery .= qq~ + \$('.iPhoneCheckLabelOff').css("top","-5px") ; + \$('.iPhoneCheckLabelOn').css("top","-5px") ; +~ ; + +if ($db{$table}{$id}{replacement}) { + $trigger_jquery_raw .= qq~ + \$("#checkboxReplacement").prop('checked',true) ; + ~ ; +} + +} #---------------------------------------------------------------------------------------- + +sub select_opts { + +my ($id) = @_ ; + +&db_min_ro($table,'*',"`id`='$id'",'','') if $id ; + +$select{camera_system_id} = 1 ; +$select{customer_id} = 1 ; + +&common_min_select_opts('camera_system_id','camera_systems','name','','','description','','','','','name') ; +&common_min_select_opts('customer_id','customers','name','','','','','','',"id,name",'name') ; +&common_min_select_opts('rma_status_id','rma_status','status','','','','','','','','status') ; + +$trigger_jquery_raw .= qq~ + \$("#savebutt").click(function() { + if (\$("#checkboxReplacement").is(":checked")) { + \$("#inputReplacement").val("1") ; + } else { + \$("#inputReplacement").val("0") ; + } + \$('#rma-form').submit() ; + }); +~ ; + +# $required{based_in} = 1 ; +# $select{based_in} = 1 ; +# $opts{based_in} = qq~~ ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + +# $print_thead = qq~IDNAMEDESCRIPTION ~ ; + +&common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'list' ; +our $lcpage = 'rma' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; +our $table = 'rma' ; + +$page_title = 'RMA' ; + +$s{no} = 1 ; ### ???????????????????????????????????????????????????????????? +&common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; +use report ; +use xlsxcreator ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/rma_test.pl b/scripts/_FromProd/v1.0/rma_test.pl new file mode 100644 index 0000000..77548e1 --- /dev/null +++ b/scripts/_FromProd/v1.0/rma_test.pl @@ -0,0 +1,654 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +our $double_box_layout = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +&db_open_ro ; + $db_ignore_open_close = 1 ; + &common_min_action ; + $db_ignore_open_close = 0 ; +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub report_screen { + + # # &filter_screen if $ENV{QUERY_STRING} eq 'filter' ; + + # our $lcol = 2 ; + # our $fcol = 5 ; + + # # my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-42) ; # 6 weeks back + + # # $set_month = sprintf("%02s", $set_month) ; + # # $set_day = sprintf("%02s", $set_day) ; + + # # my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ; + + # &select_opts ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + # # &common_min_select_opts('customer_name','customers','name','','','','') ; + # $print_box_content_rows .= &common_min_form_select('camera_system','') ; + # $print_box_content_rows .= &common_min_form_input('serial_number','') ; + # $print_box_content_rows .= &common_min_form_input('part_number','') ; + # # $print_box_content_rows .= &common_min_form_datepicker('quotes_from','') ; # $set_ccyy_dd_mm + # # $print_box_content_rows .= &common_min_form_datepicker('quotes_to','') ; # $now_ccyy_mm_dd + # # # $print_box_content_rows .= &common_min_form_input('po_nr','') ; + # # $print_box_content_rows .= &common_min_form_input('invoice_nr','') ; + # # &common_min_select_opts('country','countries','name','','','','') ; + # # $print_box_content_rows .= &common_min_form_select('country','') ; + # # $print_box_content_rows .= &common_min_form_checkbox('accepted','','') ; # Display all event_quotes that is Accepted + # # $print_box_content_rows .= &common_min_form_checkbox('closed','','') ; # Display all event_quotes that is Cancelled + + # # &common_min_select_opts('type','event_types','name','','','','') ; + # # $print_box_content_rows .= &common_min_form_select('type','') ; + + # # &common_min_select_opts('region_id','regions','name','','','',''); + + # # &common_min_select_opts('city_id','cities','city','','','',''); + # # &common_min_select_opts('organisation_ids','organisations','name','','','','') ; + # # &common_min_select_opts('sport_type_ids','sport_types','name','','','','') ; + + # # $preferred_title{region_id} = "Region" ; + # # $preferred_title{city_id} = "City" ; + # # $preferred_title{organisation_ids} = "Venue" ; + # # $preferred_title{sport_type_ids} = "Sport Type" ; + + # # $print_box_content_rows .= &common_min_form_select('region_id','') ; + # # $print_box_content_rows .= &common_min_form_select('city_id','') ; + # # $print_box_content_rows .= &common_min_form_select('organisation_ids','') ; + # # $print_box_content_rows .= &common_min_form_select('sport_type_ids','') ; + + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub report_ifields { + +} #------------------------------------------------------------------------------- + +sub validate { + +# my $exists = '' ; + +# $i{name} = lc $i{name} ; +# $i{name} =~ s/ //gi ; + +# &db_min_ro($table,'*',"name = '$i{name}'",'name','') ; + +# foreach my $id (keys %{$db{$table}}) { if ($db{$table}{$id}{name} eq $i{name}) { $exists = 1 ; } } + +# if ($exists) { + # $alert = &common_min_alert('warning',"NAME ALREADY EXISTS!",'ok') ; + # %col_name = (); + # &common_min_add_screen; + # &common_min_screen1; + # } + +} #------------------------------------------------------------------------------------------ + +sub insert { + +&add_db_fields ; + +# $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&process_table ; + +&db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + +unless ($i{id}) { $error = qq(NO ID) ; return ; } + +&edit_db_fields ; + +# unless ($i{block}) { $i{block} = '0' ; } +# $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&process_table ; + +&db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub process_table { + + for (1 .. 5) { + $ignore{"support_fault_$_"} = 1 ; + $ignore{"date_$_"} = 1 ; + $i{support_faults} .= qq~$i{"support_fault_$_"};~ ; + $i{support_fault_dates} .= qq~$i{"date_$_"};~ ; + } + chop $i{support_faults} if $i{support_faults} ; + chop $i{support_fault_dates} if $i{support_fault_dates} ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + # my %seen_camera = () ; + + # &db_min_ro('event_quotes','id, camera_system_id','','','') ; + + # foreach my $id (keys %{$db{'event_quotes'}}) { + # next if $seen_camera{$db{'event_quotes'}{$id}{camera_system_id}} ; + # $seen_camera{$db{'event_quotes'}{$id}{camera_system_id}} = 1 ; + # } + + # &db_min_ro('quotes','id, camera_system_id','','','') ; + + # foreach my $id (keys %{$db{'quotes'}}) { + # next if $seen_camera{$db{'quotes'}{$id}{camera_system_id}} ; + # $seen_camera{$db{'quotes'}{$id}{camera_system_id}} = 1 ; + # } + + &load_data ; + + our @sql_col_display = ("date_received","client","system","serial_nr","fault_reported","RMA_date","status","date_supplier_returned","date_returned_client","replacement_date","replacement_serial") ; + + foreach my $id (keys %{$db{$table}}) { + my $disp_blocked = qq(); if ($db{$table}{$id}{block}) { $disp_blocked = qq(); } + + # $opts{$lcpage} .= qq~~ ; + + my $edit_butt = '' ; my $del_butt = '' ; + + if ($useropts{super}{$username} || $username eq 'jean') { + $edit_butt = qq~ ~ ; + } + + if ($useropts{boss}{$username} || $useropts{super}{$username} || $username eq 'jean') { + $del_butt = qq~ ~ if not $seen_camera{$id} ; + $del_butt = qq~ ~ if $seen_camera{$id} ; + } + + $print_tbody .= qq~~ ; + + foreach (@sql_col_display) { + my $val = $db{$table}{$id}{$_} ; + if ($_ eq 'client') { + $val = $db{customers}{$db{$table}{$id}{customer_id}}{name} ; + } elsif ($_ eq 'system') { + $val = $db{camera_systems}{$db{$table}{$id}{camera_system_id}}{name} ; + $val .= " [" . $db{camera_systems}{$db{$table}{$id}{camera_system_id}}{description} . "]" if $db{camera_systems}{$db{$table}{$id}{camera_system_id}}{description} ; + } elsif ($_ eq 'fault_reported') { + if ($db{$table}{$id}{replacement}) { + # $val = &set_tick("green") ; + } else { + # $val = &set_tick("red") ; + } + + } elsif ($_ eq 'RMA_date') { + + } elsif ($_ eq 'status') { + $val = $db{rma_status}{$db{$table}{$id}{rma_status_id}}{status} + } elsif ($_ eq 'date_supplier_returned') { + + } elsif ($_ eq 'date_returned_client') { + + } elsif ($_ eq 'replacement_date') { + + } elsif ($_ eq 'replacement_serial') { + + } + $print_tbody .= qq~$val~ ; + + } + + $print_tbody .= qq~$edit_butt$del_butt~ ; + + # $id + # $db{$table}{$id}{name} + # $db{$table}{$id}{description} + # + # $edit_butt + # $del_butt + # + # ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub set_tick { + +my ($color,$tooltip) = @_ ; + +$tick{green} = qq~2~ ; +$tick{orange} = qq~1~ ; +$tick{red} = qq~0~ ; + +return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub load_data { + + &db_min_ro('camera_systems',"*",'','','') ; + &db_min_ro('customers',"id,name",'','','') ; + &db_min_ro('rma_status',"*",'','','') ; + # &db_min_ro('camera_systems',"*",'','','') ; + # &db_min_ro('camera_systems',"*",'','','') ; + # &db_min_ro('camera_systems',"*",'','','') ; + &db_min_ro($table,'*','','','') ; + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + +&hidden_db_fields; + +$ignore{id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + +&hidden_db_fields; + +$hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + +$ignore{iaction} = 1 ; +$ignore{date_received} = 1 ; + +# $readonly{name} = 'READONLY' ; +# $required{name} = 1 ; +# $required{description} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + +# called from common_add_screen + +&select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +&select_opts($i{id}) ; + +# $addcpb = 1 ; # add copy button to the edit screen + +our $savjqy = 1 ; # incorporate jquery into the save event to accommodate the multiple chosen options + +&build_boxes_edit($i{id}) ; + +&common_min_extra_crumb("search-$lcpage\s","Search Screen") ; + + +} #------------------------------------------------------------------------------------------ + +sub build_boxes_edit { + +my ($id) = @_ ; + +$print_box_content_rows .= &common_min_forms_start($table) ; +$print_box_content_rows .= qq~
    ~ ; +# $print_box_content_rows .= &common_min_box_top('camera',"  Camera : $db{$table}{$id}{id}",$box_main_bg) ; +# $print_box_content_rows .= &common_min_edit_form($id,$table,'',3,9,1,1) ; +# $print_box_content_rows .= &common_min_box_foot ; + &build_boxes_left($id); +$print_box_content_rows .= qq~
    ~ ; + &build_boxes_right($id); +$print_box_content_rows .= qq~
    ~ ; +$print_box_content_rows .= &common_min_forms_end($id,$table,'update',$skip) ; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_left { + + my ($id) = @_ ; + + # our ($lcol,$fcol) = &common_min_columns(3,9) ; + + $add_form_fields = ''; + +# Camera System (dropdown pull from database) +# Serial Number (enter nr and pull from database) +# Part Number (pull from database) +# System Name (pull from database) +# Warranty period - From Date to Date (Show date from ‘Date Received’ database from camera page – plus add 15 months from this date which then gets displayed) - this is the automatic warranty period for all system + + $preferred_title{serial_nr} = "Serial Number" ; + + $preferred_title{warranty_start} = "Warranty Period" ; + + $add_form_fields .= &common_min_form_select('camera_system_id') ; + + if ($db{$table}{$id}{camera_system_id}) { + $trigger_jquery_raw .= qq~ + \$("#selectCamera_system_id").val($db{$table}{$id}{camera_system_id}) ; + \$("#selectCamera_system_id").trigger("chosen:updated") ; + ~ ; + } + + $add_form_fields .= &common_min_form_input('serial_nr',$db{$table}{$id}{serial_nr}) ; + $add_form_fields .= &common_min_form_select('part_number') ; + + if ($db{$table}{$id}{part_number}) { + $trigger_jquery_raw .= qq~ + \$("#selectPart_number").val($db{$table}{$id}{part_number}) ; + \$("#selectPart_number").trigger("chosen:updated") ; + ~ ; + } + + $add_form_fields .= &common_min_form_input('system_name',$db{$table}{$id}{system_name}) ; + $readonly{warranty_start} = "READONLY" ; + + # my $a = &common_min_form_input('warranty_start','','','',1) ; + $readonly{warranty_end} = "READONLY" ; + my $default_date = "$now_ccyy_mm_dd" ; + my $warranty_start = $db{$table}{$id}{warranty_start} ; + $warranty_start = $default_date unless $warranty_start ; + + my $warranty_end = $db{$table}{$id}{warranty_end} ; + $warranty_end = $default_date unless $warranty_end ; + + $add_form_fields .= &common_min_form_input('warranty_start',$warranty_start,'','',1) ; + + $add_form_fields .= qq~ +
    + +
    ~ ; + + $add_form_fields .= &common_min_form_datepicker_col('warranty_end',$warranty_end) ; + $add_form_fields .= qq~
    ~ ; + + # $add_form_fields .= qq~
    ~ ; + # $add_form_fields .= qq~
    ~ ; + $print_box_content_rows .= &common_min_box_top('','',$box_right_bg); #film + $print_box_content_rows .= $add_form_fields ; + $print_box_content_rows .= &common_min_box_foot; + + $print_box_content_rows .= qq~ +
    +
    +
    +
    ~ ; # fixes row highlighting issue + + # #----------------- NEW BOX LEFT --------------------------------------------------------------------- + + $add_form_fields = '' ; + + + + + $fcol=4 ; + + # if ($_>$cntcamloop) { $cam_display_butt = qq~display:none;~ ; } else { $cam_display_butt = '' ; } + +# Client (select from Dropdown) +# Date Received (capture date it was received by ITV warehouse) +# Client Fault Note –a note box where they can note what client says is faulty +# Support Fault Report: - Note box they can enter what support has found and a date field (to show progress the support team +# ADD button to add more Note box and date fields if there is more work to be done and keep track of dates of each note added +# Remarks + + $preferred_title{customer_id} = "Client" ; + $add_form_fields .= &common_min_form_select('customer_id') ; + + if ($db{$table}{$id}{customer_id}) { + $trigger_jquery_raw .= qq~ + \$("#selectCustomer_id").val($db{$table}{$id}{customer_id}) ; + \$("#selectCustomer_id").trigger("chosen:updated") ; + ~ ; + } + + $add_form_fields .= &common_min_form_textarea('client_fault_note',$db{$table}{$id}{client_fault_note}) ; + $readonly{date_received} = "READONLY" ; + # $default_date = "$now_ccyy_mm_dd 00:00:00" ; + my $date_received = $db{$table}{$id}{date_received} ; + $date_received = $default_date unless $date_received ; + $add_form_fields .= &common_min_form_datepicker('date_received',$date_received) ; + + my %disp_sn_style = () ; + + $lcol=2 ; + + my @a = split(/;/,$db{$table}{$id}{support_faults}) ; + my @b = split(/;/,$db{$table}{$id}{support_fault_dates}) ; + + for (2 .. 5) { + $disp_sn_style{$_} = qq~style="display:none;"~ unless $a[$_-1] ; + + } + + $default_date = "$now_ccyy_mm_dd" ; + + for (1 .. 5) { + $add_form_fields .= qq~ +
    +
    ~ ; + my $col1 = "support_fault_$_" ; + # $required{$col} = 1 ; + &common_min_forms_required ; + $add_form_fields .= &common_min_form_input($col1,$a[$_-1],'','',1) ; + $add_form_fields .= qq~ +
    + +
    + ~ ; + + + my $date = $b[$_-1] ; + $date = $default_date unless $b[$_-1] ; + + my $col2 = "date_$_" ; + $readonly{$col2} = "READONLY" ; + $add_form_fields .= &common_min_form_datepicker_col($col2,$date) ; + # $fcol=3 ; + $add_form_fields .= qq~ +
    ~; + + $add_form_fields .= qq~~ if $_ < 5 ; + + $trigger_jquery_raw .= qq~\$("#btn_serial_nr_$_").css("display","none");~ if ($a[1] and $_ == 1) or ($a[$_] and $a[$_-1]) ; + + $trigger_jquery_raw .= qq~ + \$("#btn_serial_nr_$_").click(function () { + let v = $_ + 1 ; + \$("#btn_serial_nr_$_").hide() ; + \$("#btn_serial_nr_"+v).show() ; + \$("#sn_row_"+v).show() ; + let v2 = $_ + 2 ; + if (\$("#sn_row_"+v2).css("display") !== "none") { \$("#btn_serial_nr_"+v).hide() ; } + }) ; + ~ ; + + $add_form_fields .= qq~ +
    +
    + ~ ; + + } + + # $default_date = "$now_ccyy_mm_dd 00:00:00" ; + + $lcol = 2 ; + # $add_form_fields .= qq~ + #
     
    ~ ; + $add_form_fields .= qq~ +
    +
    ~ ; + $preferred_title{remarks_1} = "Remarks" ; + $add_form_fields .= &common_min_form_textarea('remarks_1',$db{$table}{$id}{remarks_1}) ; + $add_form_fields .= qq~ +
    +
    ~ ; + + $print_box_content_rows .= &common_min_box_top('','',$box_right_bg); #film + $print_box_content_rows .= $add_form_fields ; + $print_box_content_rows .= &common_min_box_foot; + + $print_box_content_rows .= qq~
    ~ ; # fixes row highlighting issue + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_right { + +my ($id) = @_ ; + +my $box_icon = '' ; + +#----------------------------------------------------------------- New box -------------------------------------- + +&db_min_ro('customers','id,name','','','') ; +foreach my $cust_id (keys %{$db{customers}}) { $customer{$cust_id} = $db{customers}{$cust_id}{name} ; } + +my $q_nr = $db{$table}{$id}{quote_nr} ; +my $c_nr = $db{$table}{$id}{camera_nr} ; + +# &common_load_quote_vars("='$id'"); +&common_load_quote_vars("cameras.quote_nr='$q_nr' AND quotes.quote_nr='$q_nr'"); + +$lcol = 3 ; $fcol = 4 ; +$readonly{rma_date_requested} = "READONLY" ;$readonly{rma_accepted} = "READONLY" ; $readonly{date_returned} = "READONLY" ; $readonly{date_to_supplier} = "READONLY" ; +$preferred_title{rma_status_id} = "Status" ; $preferred_title{remarks_2} = "Remarks" ; + +my $rma_date_requested = $db{$table}{$id}{rma_date_requested} ; +$rma_date_requested = $default_date unless $rma_date_requested ; + +my $rma_accepted = $db{$table}{$id}{rma_accepted} ; +$rma_accepted = $default_date unless $rma_accepted ; + +my $date_to_supplier = $db{$table}{$id}{date_to_supplier} ; +$date_to_supplier = $default_date unless $date_to_supplier ; + +my $date_returned = $db{$table}{$id}{date_returned} ; +$date_returned = $default_date unless $date_returned ; + +$print_box_content_rows .= &common_min_box_top('','',$box_right_bg,$box_icon,'') ; #qrcode + + $print_box_content_rows .= &common_min_form_datepicker('rma_date_requested',$rma_date_requested) ; + $print_box_content_rows .= &common_min_form_input('ticket_nr',$db{$table}{$id}{ticket_nr}) ; + $print_box_content_rows .= &common_min_form_datepicker('rma_accepted',$rma_accepted) ; + $print_box_content_rows .= &common_min_form_textarea('rma_rejected',$db{$table}{$id}{rma_rejected}) ; + $print_box_content_rows .= &common_min_form_datepicker('date_to_supplier',$date_to_supplier) ; + $print_box_content_rows .= &common_min_form_select('rma_status_id') ; + $print_box_content_rows .= &common_min_form_textarea('remarks_2',$db{$table}{$id}{remarks_2}) ; + $print_box_content_rows .= &common_min_form_datepicker('date_returned',$date_returned) ; + +$print_box_content_rows .= &common_min_box_foot ; + +if ($db{$table}{$id}{rma_status_id}) { + $trigger_jquery_raw .= qq~ + \$("#selectRma_status_id").val($db{$table}{$id}{rma_status_id}) ; + \$("#selectRma_status_id").trigger("chosen:updated") ; + ~ ; +} + +#----------------------------------------------------------------- New box -------------------------------------- + +$readonly{replacement_date} = "READONLY" ; $fcol=4; + +my $replacement_date = $db{$table}{$id}{replacement_date} ; +$replacement_date = $default_date unless $replacement_date ; + +$print_box_content_rows .= &common_min_box_top('wrench','Replacement',$box_right_bg,$box_icon,'camera-replacement-box') ; + + $print_box_content_rows .= &common_min_form_checkbox('replacement',$db{$table}{$id}{replacement},'',1) ; + $print_box_content_rows .= &common_min_form_datepicker('replacement_date',$replacement_date) ; + $print_box_content_rows .= &common_min_form_input('replacement_camera_nr',$db{$table}{$id}{replacement_camera_nr}) ; + +$print_box_content_rows .= &common_min_box_foot ; + +if ($db{$table}{$id}{replacement}) { + $trigger_jquery_raw .= qq~ + \$("#checkboxReplacement").prop('checked',true) ; + ~ ; +} + +} #---------------------------------------------------------------------------------------- + +sub select_opts { + +my ($id) = @_ ; + +&db_min_ro($table,'*',"`id`='$id'",'','') if $id ; + +$select{camera_system_id} = 1 ; +$select{customer_id} = 1 ; + +&common_min_select_opts('camera_system_id','camera_systems','name','','','description','','','','','name') ; +&common_min_select_opts('customer_id','customers','name','','','','','','',"id,name",'name') ; +&common_min_select_opts('rma_status_id','rma_status','status','','','','','','','','status') ; + +$trigger_jquery_raw .= qq~ + \$("#savebutt").click(function() { + \$('#rma-form').submit() ; + }); +~ ; + +# $required{based_in} = 1 ; +# $select{based_in} = 1 ; +# $opts{based_in} = qq~~ ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + +# $print_thead = qq~IDNAMEDESCRIPTION ~ ; + +&common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'list' ; +our $lcpage = 'rma' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; +our $table = 'rma' ; +$s{no} = 1 ; ### ???????????????????????????????????????????????????????????? +&common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/school_managers.pl b/scripts/_FromProd/v1.0/school_managers.pl new file mode 100644 index 0000000..e8e269b --- /dev/null +++ b/scripts/_FromProd/v1.0/school_managers.pl @@ -0,0 +1,124 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Crypt::PasswdMD5; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +# unless ($username eq 'rory') { print ">>>> DEVELOPMENT IN PROGRESS <<<<" ; exit ; } + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + + &users_validate; + +} #------------------------------------------------------------------------------------------ + +sub insert { + + &users_insert ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + &users_update ; + +} #------------------------------------------------------------------------------------------ + +sub process_multi_select { + + &users_process_multi_select ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + &users_list_screen ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + &users_sort_fields ; + +} #------------------------------------------------------------------------------- + +sub add_db_fields { + + &users_add_db_fields ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &users_edit_db_fields ; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + + # called from common_add_screen + &users_add_screen ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + &users_edit_screen ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &users_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'user' ; + our $lcpage = 'school-manager' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'users' ; + our $user_type = 'schools_manager' ; + + &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; +use users ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/set_up_groups_report.pl b/scripts/_FromProd/v1.0/set_up_groups_report.pl new file mode 100644 index 0000000..a080bef --- /dev/null +++ b/scripts/_FromProd/v1.0/set_up_groups_report.pl @@ -0,0 +1,653 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +# unless ($useropts{it}{$username}) { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; +use Time::Piece ; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; +# our $testing = 1 ; + +# if ($username ne 'handre') { + # print "<< MAINTENANCE IN PROGRESS >>" ; exit ; +# } + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $srchscr = 1 ; + +if ($iaction eq 'save') { + &db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &common_min_load_params ; + &report_ifields; + &update ; + # &list_screen ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + exit if $testing ; + # &screen3; + &redirect_screen; +} + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &report_screen if $iaction eq '' ; + + if ($iaction eq 'report') { + &common_min_load_params ; + &report_ifields; + &list_screen ; + &screen3; + } + + &common_min_action; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { } + +sub insert { } + +sub update { + + my %seen_event_id = () ; + + foreach (keys %i) { + next if $_ !~ /^update_/ || ($_ =~ /^update_/ && !$i{$_}) ; + local @abc = split("_",$_) ; + $seen_event_id{$abc[-3]} = 1 ; + } + + local $e_q_sql = join (" OR ",map { "id='$_'" } keys %seen_event_id) ; + + &db_min_ro($table,'id,event_system_id_multiple,date_from,date_to,set_up_groups_head_operator_ids,set_up_groups_status_ids',"$e_q_sql",'','') ; + + my %ii = () ; my %iii = %i ; + + foreach my $event_id (keys %seen_event_id) { + + my @event_system_ids = split(/\;/,$db{$table}{$event_id}{event_system_id_multiple}) ; + + my @set_up_head_operator_ids = split(/\;/,$db{$table}{$event_id}{set_up_groups_head_operator_ids}) ; + my @set_up_status = split(/\;/,$db{$table}{$event_id}{set_up_groups_status_ids}) ; + + my $system_cnt = 0 ; + + foreach (@event_system_ids) { + $system_cnt++ ; + $head_operator_hash{cnt}{$event_id}{$_} = $system_cnt ; + $status_hash{cnt}{$event_id}{$_} = $system_cnt ; + } + + $system_cnt = 0 ; + + foreach my $system_data (@set_up_head_operator_ids) { + $system_cnt++ ; + next unless $system_data ; + if ($system_data =~ /~/) { + ($system_id,$system_data) = split(/\~/,$system_data) ; + } else { + $system_id = $event_system_ids[$system_cnt - 1] ; + } + next unless $head_operator_hash{cnt}{$event_id}{$system_id} ; + my $day_cnt = 0 ; + foreach my $daily_data (split(/\-/,$system_data)) { + $day_cnt++ ; + $ii{$event_id}{$system_id}{$day_cnt}{head_operator} = $daily_data ; + } + } + + $system_cnt = 0 ; + + foreach my $system_data (@set_up_status) { + $system_cnt++ ; + next unless $system_data ; + if ($system_data =~ /~/) { + ($system_id,$system_data) = split(/\~/,$system_data) ; + } else { + $system_id = $event_system_ids[$system_cnt - 1] ; + } + next unless $status_hash{cnt}{$event_id}{$system_id}; + my $day_cnt = 0 ; + foreach my $daily_data (split(/\-/,$system_data)) { + $day_cnt++ ; + $ii{$event_id}{$system_id}{$day_cnt}{calibration_status} = $daily_data ; + } + } + } + + foreach my $field (keys %i) { + + local @a = split("_",$field) ; + + my $upd_field = "update_$a[-3]\_$a[-2]\_$a[-1]" ; + + next unless $i{$upd_field} ; + + if (substr($field,0,19) eq 'calibration_status_') { + $ii{$a[-3]}{$a[-2]}{$a[-1]}{calibration_status} = $i{$field} ; + + } elsif (substr($field,0,14) eq 'head_operator_') { + $ii{$a[-3]}{$a[-2]}{$a[-1]}{head_operator} = $i{$field} ; + } + + } + + # my $calid_field = 'event_system_calibration_ids' ; + my $calstatus_field = 'set_up_groups_status_ids' ; + my $headops_field = 'set_up_groups_head_operator_ids' ; + + foreach my $event_id (keys %ii) { + + %i = () ; + + # &common_debug("1. +++ event_id[$event_id] date_from[$db{$table}{$event_id}{date_from}] date_to[$db{$table}{$event_id}{date_to}] event_system_calibration_ids[$db{$table}{$event_id}{event_system_calibration_ids}] set_up_groups_status_ids[$db{$table}{$event_id}{set_up_groups_status_ids}] event_system_id_multiple[$db{$table}{$event_id}{event_system_id_multiple}]") ; + + my @event_system_calibration_status = split(/\;/,$db{$table}{$event_id}{set_up_groups_status_ids}) ; + my @event_system_ids = split(/\;/,$db{$table}{$event_id}{event_system_id_multiple}) ; + # my @calibration_ids = split(";",$db{$table}{$event_id}{event_system_calibration_ids}) ; + my @op_head_id = split(/\;/,$db{$table}{$event_id}{set_up_groups_head_operator_ids}) ; + + my @ed_from = &common_split_sql_time($db{$table}{$event_id}{date_from}) ; + my @ed_to = &common_split_sql_time($db{$table}{$event_id}{date_to}) ; + + &common_date_array("$ed_from[0]$ed_from[1]$ed_from[2]","$ed_to[0]$ed_to[1]$ed_to[2]") ; + + $sys_cnt = 0; + + foreach my $system_id (sort { $status_hash{cnt}{$event_id}{$a} <=> $status_hash{cnt}{$event_id}{$b} } keys %{$status_hash{cnt}{$event_id}}) { + $sys_cnt++; + my (@calibrator_statuses_per_event_day) = split(/\-/,$event_system_calibration_status[$sys_cnt-1]); + my $sys_day=0; + + my $line = qq~~ ; + + foreach my $_date (@common_date_array) { + $sys_day++; + $line .= "$ii{$event_id}{$system_id}{$sys_day}{calibration_status}-" ; + } + $line =~ s/-+$// ; + $i{$calstatus_field} .= qq~$system_id\~$line~ if $line ; + $i{$calstatus_field} .= qq~;~ ; + } + $i{$calstatus_field} =~ s/;+$// ; + + $sys_cnt = 0; + foreach my $system_id (sort { $head_operator_hash{cnt}{$event_id}{$a} <=> $head_operator_hash{cnt}{$event_id}{$b} } keys %{$head_operator_hash{cnt}{$event_id}}) { + $sys_cnt++ ; + my (@head_op_id_per_event_day) = split(/\-/,$op_head_id[$sys_cnt-1]) ; + my $sys_day = 0 ; + + my $line = qq~~ ; + + foreach my $_date (@common_date_array) { + $sys_day++; + $line .= "$ii{$event_id}{$system_id}{$sys_day}{head_operator}-" ; + } + + $line =~ s/-+$// ; + $i{$headops_field} .= qq~$system_id\~$line~ if $line ; + $i{$headops_field} .= ";" ; + } + $i{$headops_field} =~ s/;+$// ; + + $ignore{$calstatus_field} = (($i{$calstatus_field} eq $db{$table}{$event_id}{$calstatus_field}) || (!$i{$calstatus_field} && !$db{$table}{$event_id}{$calstatus_field})) ? 1 : 0 ; + $ignore{$headops_field} = (($i{$headops_field} eq $db{$table}{$event_id}{$headops_field}) || (!$i{$headops_field} && !$db{$table}{$event_id}{$headops_field})) ? 1 : 0 ; + + # print "\n $event_id : $calstatus_field ($ignore{$calstatus_field}) : $i{$calstatus_field} , $db{$table}{$event_id}{$calstatus_field}" ; + # print "\n $event_id : $headops_field ($ignore{$headops_field}) : $i{$headops_field} , $db{$table}{$event_id}{$headops_field}" ; + + &db_min_upd($table,"`id`='$event_id'") if !$ignore{$calstatus_field} || !$ignore{$headops_field} ; + + } + + %i = %iii ; + + # exit ; + +} #------------------------------------------------------------------------------------------ + +sub report_ifields { + + &load_search_vars ; + + if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { + $error = qq~'$i{date_from}' > '$i{date_to}'~ ; &report_screen ; + } + # push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` <= '$i{date_to} 23:59:59' AND `date_to` >= '$i{date_from} 00:00:00'))" ; + # push @report_sql, "(('$i{date_from} 23:59:59' >= `date_from` AND '$i{date_from} 00:00:00' <= `date_to`) OR ('$i{date_to} 23:59:59' >= `date_from` AND '$i{date_to} 00:00:00' <= `date_to`))" ; + # push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` >= '$i{date_from} 00:00:00' AND `date_to` <= '$i{date_to} 23:59:59'))" ; + my @srch_ed_from = &common_split_sql_time($i{date_from}) ; + my @srch_ed_to = &common_split_sql_time($i{date_to}) ; + + &common_date_array("$srch_ed_from[0]$srch_ed_from[1]$srch_ed_from[2]","$srch_ed_to[0]$srch_ed_to[1]$srch_ed_to[2]") ; + + @report_sql_or = () ; + + foreach my $_srch_date (@common_date_array) { + my $srch_ccyy_mm_dd = substr($_srch_date,0,4) . '-' . substr($_srch_date,4,2) . '-' . substr($_srch_date,6,2) ; + push @report_sql_or, "('$srch_ccyy_mm_dd 23:59:59' >= date_from AND '$srch_ccyy_mm_dd 00:00:00' <= date_to)" + } + + my $sql_or = join(' OR ',@report_sql_or) ; + push @report_sql, "($sql_or)" if $sql_or ; + + # push @report_sql, "((`date_from` >= '$i{date_from} 00:00:00' AND `date_from` <= '$i{date_to} 23:59:59') OR (`date_to` >= '$i{date_from} 00:00:00' AND `date_to` <= '$i{date_to} 23:59:59'))" ; + push @report_results, "(BETWEEN '$i{date_from}' AND '$i{date_to}')" ; + } elsif (not $i{date_from}) { + $error = qq~PLEASE ENTER A START DATE!~ ; + &report_screen; + } elsif (not $i{date_to}) { + $error = qq~PLEASE ENTER AN END DATE!~ ; + &report_screen; + } + + # if ($i{calibrator_id} and $i{calibrator_id} ne 'all') { + # push @report_results,"`CALIBRATOR` = '$db{users}{1}{name}'" ; + # push @report_sql, " + # ( + # `event_system_calibration_ids` LIKE '%;$i{calibrator_id};%' OR + # `event_system_calibration_ids` LIKE '%;$i{calibrator_id}' OR + # `event_system_calibration_ids` LIKE '$i{calibrator_id};%' OR + # `event_system_calibration_ids` LIKE '%-$i{calibrator_id};%' OR + # `event_system_calibration_ids` LIKE '%;$i{calibrator_id}-%' OR + # `event_system_calibration_ids` LIKE '%-$i{calibrator_id}-%' OR + # `event_system_calibration_ids` LIKE '$i{calibrator_id}-%' OR + # `event_system_calibration_ids` LIKE '%-$i{calibrator_id}' + # ) + # " ; + # } elsif ($i{calibrator_id} and $i{calibrator_id} eq 'all') { + # push @report_results,"`CALIBRATORS` = 'ALL'" ; + # } else { + # # push @report_sql, "(`user_id` = '')" ; + # } + + if ($i{calibration_status} and $i{calibration_status} ne 'all') { + push @report_sql, " + ( + `set_up_groups_status_ids` LIKE '%;$i{calibration_status};%' OR + `set_up_groups_status_ids` LIKE '%;$i{calibration_status}' OR + `set_up_groups_status_ids` LIKE '$i{calibration_status};%' OR + `set_up_groups_status_ids` LIKE '%-$i{calibration_status};%' OR + `set_up_groups_status_ids` LIKE '%;$i{calibration_status}-%' OR + `set_up_groups_status_ids` LIKE '%-$i{calibration_status}-%' OR + `set_up_groups_status_ids` LIKE '$i{calibration_status}-%' OR + `set_up_groups_status_ids` LIKE '%-$i{calibration_status}' OR + `set_up_groups_status_ids` LIKE '%~$i{calibration_status};%' OR + `set_up_groups_status_ids` LIKE '%~$i{calibration_status}' OR + `set_up_groups_status_ids` LIKE '%~$i{calibration_status}-%' + ) + " ; + push @report_results,"`STATUS` = '$db{calibration_status}{$i{calibration_status}}{status}'" ; + } + + if ($i{client_id}) { + push @report_sql,"quote_to='$i{client_id}'" ; + &db_min_ro('customers','id,name',"id='$i{client_id}'",'','') ; + push @report_results,"CLIENT = '$db{customers}{$i{client_id}}{name}'" ; + } + + $report_results_msg = uc join(', ', @report_results) ; + + if (not $report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); + &report_screen; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + + our $srch_where_sql = join(' AND ',@report_sql) ; + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + # if ($i{calibrator_id} and $i{calibrator_id} ne 'all') { + # &db_min_ro('users','1,name',"`id` = '$i{calibrator_id}'",'','') ; + # } + + &db_min_ro('calibration_status','id,status','','','') ; + + our $calibration_status = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + $print_box_content_rows .= &common_min_forms_start("$lcpage") ; + + our $set_up_groups = 1 ; + + &calibration_load_list_vars("$srch_where_sql") ; + + # $box_icon .= qq~
    ~ ; + + # $trigger_jquery_raw .= qq~ + + # function selectAll() { + + # let jsObject = { + # $quote_and_ops_ids + # }; + + # for (let key in jsObject) { + # let op_id = jsObject[key]; + + # let parts = key.split("_") ; + # let event_id = parts[1] ; + + # \$(\$("#itv-table").dataTable().fnGetNodes()).find(\$("input[name=update_"+event_id+"_"+op_id+"]")).each(function () { + + # console.log("input[name=paid_"+event_id+"_"+op_id+"]") ; + # if(\$(this).is(':checked')) { + # \$(this).prop('checked',false); + # } else { + # \$(this).prop('checked',true); + # } + # }) ; + # } + # } + # ~; + # $fcol = 2 ; + + # $print_box_content_rows .= qq~
    ~ ; + # $print_box_content_rows .= &common_min_form_input_col("date_from",$i{date_from}) ; #date_from_i_field + # $print_box_content_rows .= &common_min_form_input_col("date_to",$i{date_to}) ; #date_to_i_field + # $print_box_content_rows .= &common_min_form_input_col("calibrator_id",$i{calibrator_id}) ; #operator_id_i_field + # # $print_box_content_rows .= &common_min_form_input_col("event_quote_id",$i{event_quote_id}) ; + # $print_box_content_rows .= &common_min_form_input_col("calibration_status",$i{calibration_status}) ; + # $print_box_content_rows .= qq~
    ~ ; + + $fcol = 12 ; + + my $report = 1 ; + + our $xlsxdir = "set_up_groups_report" ; + + our $xlsxreportname = "Set_Up_Groups_Report" ; + + my $date = &common_write_date_interval($i{date_from},$i{date_to}) ; + + our $xlsx_title_heading = "Set Up Groups Report $date" ; + + my $found_after_date = 0 ; + my $today_val = int("$now_year$now_mm$now_dd") ; + + my @date_from_inp = split(/ /,$i{date_from}) ; + my ($year_inp1,$month_inp1,$day_inp1) = split(/\-/,$date_from_inp[0]) ; + my $date_inp_val1 = int("$year_inp1$month_inp1$day_inp1") ; + + my @date_to_inp = split(/ /,$i{date_to}) ; + my ($year_inp2,$month_inp2,$day_inp2) = split(/\-/,$date_to_inp[0]) ; + my $date_inp_val2 = int("$year_inp2$month_inp2$day_inp2") ; + + foreach (keys %{$db{$table}}) { + my @date_from = split(/ /,$db{$table}{$_}{date_from}) ; + my ($year_1,$month_1,$day_1) = split(/\-/,$date_from[0]) ; + my $date_val1 = int("$year_1$month_1$day_1") ; + my @date_to = split(/ /,$db{$table}{$_}{date_to}) ; + my ($year_2,$month_2,$day_2) = split(/\-/,$date_to[0]) ; + my $date_val2 = int("$year_2$month_2$day_2") ; + $found_after_date = 1 if ($today_val <= $date_val1 && $today_val <= $date_inp_val1) || ($today_val <= $date_val2 && $today_val <= $date_inp_val2) ; + } + + # if ($found_after_date) { + # $trigger_jquery_raw .= qq~ + # \$("#itv-table tr th:nth-last-child(3)").css("width", "12.5%") ; + # \$("#itv-table tr th:nth-last-child(2)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(4)").css("width", "12.5%") ; + # ~ ; + # } else { + # $trigger_jquery_raw .= qq~ + # \$("#itv-table tr th:nth-last-child(3)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(2)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(4)").css("width", "7.5%") ; + # ~ ; + # } + + + + &calibration_build_table_and_or_excel(1) ; + + $fnsortorder = 'asc' ; + + &common_min_extra_crumb("$lcpage","Search Screen") ; + + $trigger_jquery_raw .= qq~ + \$("#savebutt").click(function() { + \$("#$lcpage-form").submit() ; + }) ; + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub set_tick { + + my ($color,$tooltip) = @_ ; + + $tick{green} = qq~2~ ; + $tick{orange} = qq~1~ ; + $tick{red} = qq~0~ ; + + return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub set_cross { + + my ($color,$tooltip) = @_ ; + + $tick{green} = qq~2~ ; + $tick{orange} = qq~1~ ; + $tick{red} = qq~0~ ; + + return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + our $lcpage = 'set-up-groups-report' ; + + &common_page_name ; + + our $table = 'event_quotes' ; + $page_title = 'Set Up Groups Report' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + # &common_min_select_opts('client_id','customers','name','','','',"events='1'") ; + my $def = ($i{client_id}) ? $i{client_id} : 5 ; + $allow_deselect{client_id} = 1 ; + &common_min_select_opts('client_id','customers','name',$def,'','',"") ; + + $print_box_content_rows .= &common_min_form_select('client_id','') ; + + my ($sql_next_day) = &common_add_delta_days(1) ; + my ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$next_year-$next_month-$next_day") ; #unless $i{date_from} ; + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$next_year-$next_month-$next_day") ; + + $selected{calibration_status}{all} = 'SELECTED' ; + if ($i{calibration_status}) { + $selected{calibration_status}{$i{calibration_status}} = 'SELECTED' ; + $selected{calibration_status}{all} = '' ; + } + + &db_min_ro('calibration_status','id,status','','','') ; + + # $opts{calibration_status} .= qq~~ ; + foreach (keys %{$db{calibration_status}}) { + $opts{calibration_status} .= qq~~ ; + } + $opts{calibration_status} .= qq~~ ; + + $preferred_title{calibration_status} = "Status" ; + + # $preferred_title{calibrator_id} = "Calibrator" ; + + # # &db_min_ro('users',"id,name","`user_type` = 'support' OR `user_type` = 'casual_calibrator'",'','') ; + # &db_min_ro('users',"id,name,username","(user_type = 'support' OR user_type = 'manager' OR user_type = 'casual_calibrator') AND name NOT LIKE 'Rory%' AND name NOT LIKE 'Handre%'",'','') ; + + # $selected{calibrator_id}{all} = 'SELECTED' ; + + # if ($i{calibrator_id}) { + # $selected{calibrator_id}{$i{calibrator_id}} = 'SELECTED' ; + # $selected{calibrator_id}{all} = '' ; + # } + + # # $opts{calibrator_id} .= qq~~ ; + # foreach (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + # next if $useropts{it}{$db{users}{$_}{username}} ; + # $opts{calibrator_id} .= qq~~ ; + # } + # $opts{calibrator_id} .= qq~~ ; + + # if ($i{event_quote_id}) { + # $selected{event_quote_id}{$i{event_quote_id}} = 'SELECTED' ; + # } else { + # $selected{event_quote_id}{all} = 'SELECTED' ; + # } + + # $opts{event_quote_id} .= qq~~ ; + + # $print_box_content_rows .= &common_min_form_select('operator_id','') ; + # $print_box_content_rows .= &common_min_form_select('event_quote_id','') ; + $print_box_content_rows .= &common_min_form_select('calibration_status','') ; + # $print_box_content_rows .= &common_min_form_select('calibrator_id','') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub screen3 { + + &thead; + + if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + + # my $page = "$lcpage\s" ; + + my $page = "event-quotes" ; + + if ($s{no}) { $page = $lcpage ; } + + &common_min_table('id',$page,'list') ; + + our $savjqy = 1 ; + + # &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ; + + $extra_form_fields .= qq~ + + + + ~; + + $print_box_content_rows .= &common_min_forms_end('','','save') ; + + require _blank ; + + exit ; + +} #------------------------------------------------------------------------------------------ + +sub redirect_screen { + + &common_min_alert_type ; + + print < + + + + $useropts{title} + + + + + + +
    + + + + + + +
    + + +ENDOFTEXT +# + + exit ; + +} #------------------------------------------------------------------------------------------ + +use common ; +use report ; +use xlsxcreator ; +use today ; +use calibration ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/sport_types.pl b/scripts/_FromProd/v1.0/sport_types.pl new file mode 100644 index 0000000..50b524d --- /dev/null +++ b/scripts/_FromProd/v1.0/sport_types.pl @@ -0,0 +1,211 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + + my $exists = '' ; + + $i{name} = &common_fix_str($i{name}) ; + + &db_min_ro($table,'id,name',"",'name','') ; + + foreach my $id (keys %{$db{$table}}) { + if (lc $db{$table}{$id}{name} eq lc $i{name}) { + $exists = 1 ; + } + } + + if ($exists) { + $alert = &common_min_alert('warning',"'$i{name}' AS A SPORT TYPE NAME ALREADY EXISTS!",'ok') ; + %col_name = (); + &common_min_add_screen; + &common_min_screen1; + } + +} #------------------------------------------------------------------------------------------ + +sub insert { + + &add_db_fields ; + + $i{id} = &db_min_get_max($table,'id') ; + + &db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + unless ($i{id}) { $error = qq(NO ID) ; return ; } + + &edit_db_fields ; + + &db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + &db_min_ro('cameras','id,sport_type_ids',"sport_type_ids IS NOT NULL",'','') ; + + foreach my $_id (keys %{$db{cameras}}) { + my @sport_type_ids = split(/\,/,$db{cameras}{$_id}{sport_type_ids}); + foreach (@sport_type_ids) { + $type_id_used{$_} = 1 ; + } + } + + &db_min_ro('event_quotes','id,sport_type_ids',"sport_type_ids IS NOT NULL",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + my @sport_type_ids = split(/\,/,$db{event_quotes}{$_id}{sport_type_ids}); + foreach (@sport_type_ids) { + $type_id_used{$_} = 1 ; + } + } + + &db_min_ro($table,'*','','name','') ; + + foreach my $id (keys %{$db{$table}}) { + + my $edit_butt = '' ; my $del_butt = '' ; + + if ($useropts{super}{$username}) { + $edit_butt = qq~ ~ ; + } + + if ($useropts{boss}{$username} || $useropts{it}{$username}) { + $del_butt = qq~ ~ ; + } + + if ($type_id_used{$id}) { + $edit_butt = qq~ ~ ; + $del_butt = qq~ ~ ; + } + + $print_tbody .= qq~ + + $id + $db{$table}{$id}{name} + + $edit_butt + $del_butt + + + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + &sort_fields; + + &hidden_db_fields; + + # $ignore{id} = 1 ; + + } #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &sort_fields; + + &hidden_db_fields; + + $hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + + $ignore{iaction} = 1 ; + $required{name} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + %sort_field = () ; + + $sort_field{1} = 'name' ; + +} #------------------------------------------------------------------------------- + +sub add_screen { + + # called from common_add_screen + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + +# $required{based_in} = 1 ; +# $select{based_in} = 1 ; +# $opts{based_in} = qq~~ ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + $print_thead = qq~IDNAME ~ ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'facetime-video' ; + our $lcpage = 'sport-type' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'sport_types' ; + + &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/stock_report.pl b/scripts/_FromProd/v1.0/stock_report.pl new file mode 100644 index 0000000..f71f6b3 --- /dev/null +++ b/scripts/_FromProd/v1.0/stock_report.pl @@ -0,0 +1,307 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our $srchscr = 1 ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + if ($iaction eq ''){ &report_screen ; } + &common_min_action; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub report_ifields { + +&load_search_vars ; + +# if ($i{camera_id}) { + # push @report_sql, "(`id`='$i{camera_id}')" ; + # push @report_results, "camera = $camera_name{$i{camera_id}}" ; + # $xlsreportname .= '-' . $i{camera_id} ; + # # our $acc_id_sql_where = "`camera_id`='$i{camera_id}'" + # } + +# if ($i{camera_system_id}) { + # push @report_sql, "(`camera_system_id`='$i{camera_system_id}')" ; + # push @report_results, "camera_system = $camera_system{$i{camera_id}}" ; + # $xlsreportname .= '-' . $i{camera_system_id} ; + # } + +# if ($i{camera_system_id}) { +if ($i{camera_system_id} and $i{camera_system_id} ne 'main' and $i{camera_system_id} ne 'other' and $i{camera_system_id} ne 'all') { + push @report_sql, "(`camera_system_id`='$i{camera_system_id}')" ; + push @report_results, "camera_system = $camera_system{$i{camera_system_id}}" ; + $xlsreportname .= '-' . $i{camera_id} ; + # our $acc_id_sql_where = "`camera_id`='$i{camera_id}'" +} elsif ($i{camera_system_id} eq 'main' or $i{camera_system_id} eq 'other' or $i{camera_system_id} eq 'all') { + push @report_results, "camera_system = $i{camera_system_id}" ; +} + +if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { $error = qq(CAMERAS FROM ($i{date_from}) > CAMERAS TO ($i{date_to})); &report_screen; } + } + +if ($i{date_from}) { + # push @report_sql, "(`date_active` >= '$i{date_from}')" ; + # push @report_results, "date_active >= $i{date_from}" ; + push @report_sql, "(`date_time` >= '$i{date_from}')" ; + push @report_results, "date_time >= $i{date_from}" ; + } + +if ($i{date_to}) { + # push @report_sql, "(`date_active` <= '$i{date_to}')" ; + # push @report_results, "date_active <= $i{date_to}" ; + push @report_sql, "(`date_time` <= '$i{date_to}')" ; + push @report_results, "date_time <= $i{date_to}" ; + } + +if ($i{client_id}) { + # push @report_sql, "(`client_id` = '$i{client_id}')" ; + push @report_results, "Client = $client{$i{client_id}}" ; + } + +if ($i{stock}) { + push @report_results, "Stock = $i{stock}" ; + } + +$report_results_msg = uc join(', ', @report_results) ; + +unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); &report_screen; } else { $isaved = qq(SELECT WHERE $report_results_msg) ; } + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + # my $cameras_sql_where = "`id`='$i{camera_id}'" ; + # &db_min_ro('cameras','id,camera_nr',$cameras_sql_where,'','') ; + # foreach my $id (keys %{$db{cameras}}) { $camera_name{$id} = $db{cameras}{$id}{camera_nr} ; } + + my $camera_systems_sql_where = "`id`='$i{camera_system_id}'" if $i{camera_system_id} ; + &db_min_ro('camera_systems','id,name',$camera_systems_sql_where,'','') ; + foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + + # my $price_list_sql_where = " AND `id`='$i{camera_system_id}'" if $i{camera_system_id} ; + # &db_min_ro('price_list','id,description',"`excl`<>'1' AND `type`='systems'$price_list_sql_where",'','') ; + # foreach my $id (keys %{$db{price_list}}) { $camera_system{$id} = $db{price_list}{$id}{name} ; } + + # my $customers_sql_where = "`id`='$i{client_id}'" if $i{client_id} ; + # &db_min_ro('customers','*',$customers_sql_where,'','') ; + # foreach my $id (keys %{$db{customers}}) { $client{$id} = $db{customers}{$id}{name} ; } + + if ($i{client_id}) { + my $customers_sql_where = "`id`='$i{client_id}'" ; + &db_min_ro('customers','*',$customers_sql_where,'','') ; + foreach my $id (keys %{$db{customers}}) { $client{$id} = $db{customers}{$id}{name} ; } + } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +my $srch_where_sql = join(' AND ', @report_sql) ; + +my $add_sql_where = '' ; + +# our @sql_col_display = ("id","camera_nr","camera_serial_nr","date_received","amount_usd","amount_zar","in_stock") ; +our @sql_col_display = ("camera_nr","camera_system_id","camera_serial_nr","vpu_serial_nr","date_received","amount_usd","amount_zar","type","date_delivered","in_stock") ; + +&report_xls_export_header("Camera_Stock_Report$xlsreportname",'stockreport') ; + +&load_list_vars("$srch_where_sql$add_sql_where") ; + +foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) { + if ($linked_sn{$db{$table}{$id}{serial_nr}}) { $vpu_is_linked{$linked_sn{$db{$table}{$id}{serial_nr}}} = 1 ; } +} + +foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) { + + # if ($i{stock} eq 'stock') { if ($db{$table}{$id}{quote_nr} or $db{$table}{$id}{demo_recipient}) { next ; } } + + # if ($i{stock} eq 'purchased') { unless ($db{$table}{$id}{quote_nr}) { next ; } } + # if ($i{stock} eq 'demo') { unless ($db{$table}{$id}{demo_recipient} ) { next ; } } + # if ($i{stock} eq 'rental') { unless ($db{$table}{$id}{camera_system_id}<7 and lc $quote_type{$id} eq 'rental') { next ; } } + + # if ($i{camera_system_id} eq 'main') { unless ($db{$table}{$id}{camera_system_id}<7) { next ; } } + # if ($i{camera_system_id} eq 'other') { unless ($db{$table}{$id}{camera_system_id}>7) { next ; } } + + next if (&common_camera_system_filter($table,$id)) ; + + if ($i{client_id}) { next unless $client{$i{client_id}} eq $quote_customer{$id} ; } + # if ($i{stock}) { next unless $i{stock} eq lc $quote_type{$id} ; } + + next if $vpu_is_linked{$db{$table}{$id}{serial_nr}} ; + + $print_tbody .= qq~~ ; + + $xlscol=0; + + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$table}{$id}{$_} ; + my $align = '' ; + + my $center = qq~ class="dt-center"~ ; + + if ($_ eq 'date_delivered') { $val = $db{$table}{$id}{quote_delivery_date} ; $align = $center ; } + if ($_ eq 'date_received') { $align = $center ; } + if ($_ eq 'amount_zar') { $val = $db{$table}{$id}{cur_amount} ; } + if ($_ eq 'amount_usd') { $val = $db{$table}{$id}{usd_amount} ; } + if ($_ eq 'camera_serial_nr') { $val = $db{$table}{$id}{serial_nr} ; } + if ($_ eq 'camera_system_id') { $val = $camera_system{$val} ; } + if ($_ eq 'type') { $val = $quote_type{$id} ; } + # if ($_ eq 'in_stock') { if ($db{$table}{$id}{quote_nr}) { $val = 0 ; } else { $val = 1 ; } } + if ($_ eq 'in_stock') { if ($db{$table}{$id}{quote_nr} or $db{$table}{$id}{demo_recipient} or $db{$table}{$id}{replacement_date} or $db{$table}{$id}{event_system_id}) { $val = 0 ; } else { $val = 1 ; } } + if ($_ eq 'vpu_serial_nr') { $val = $linked_sn{$db{$table}{$id}{serial_nr}} ; } # $val .= ' [' . $linked_cn{$db{$table}{$id}{serial_nr}} . ']' if $linked_cn{$db{$table}{$id}{serial_nr}} ; + + &report_xls_export_process_cell('','',$val) ; # ------------------------------------------------------------------------- HTML AFTER + $xlscol++; + + $val = &common_camera_links($table,$id,$val) if $_ eq 'camera_nr' or $_ eq 'ref_nr' ; + + if ($_ eq 'in_stock') { if ($val==1) { $val = &set_tick('green', '') ; } else { $val = &set_tick('red', '') ; } $align = $center ; } + + $print_tbody .= qq~$val~ ; + } + + $print_tbody .= qq~~ ; + $xlsrow++ ; + } + +&report_xls_export_footer('L',15,'stockreport') ; + +$fnsortcol = 3 ; +$fnsortorder = 'asc' ; + +$print_more_boxes .= qq~


    ~ ; + +&common_min_extra_crumb("$lcpage-report","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub set_tick { + +my ($color,$tooltip) = @_ ; + +$tick{green} = qq~2~ ; +$tick{orange} = qq~1~ ; +$tick{red} = qq~0~ ; + +return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub load_list_vars { + +my ($where) = @_ ; + +&db_min_ro('camera_systems','id,name','','','') ; +foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + +&db_min_ro('customers','id,name','','','') ; +foreach my $id (keys %{$db{customers}}) { $customer{$id} = $db{customers}{$id}{name} ; } + +# &common_load_quote_vars('>0'); +&common_load_quote_vars("cameras.quote_nr>0 AND cameras.quote_nr=quotes.quote_nr"); + +&db_min_ro($table,'*',$where,'','') ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + +&common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'list' ; +our $lcpage = 'stock' ; + +&common_page_name ; + +our $table = 'cameras' ; +$page_title = 'Stock' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + +our $lcol = 3 ; +our $fcol = 5 ; + +$print_box_content_rows .= &common_min_forms_start('report') ; + +&common_camera_opts ; + +&common_min_select_opts('camera_system_id','camera_systems','code',$i{camera_system_id},'') ; +# &common_min_select_opts('camera_system_id','price_list','description','','') ; +&common_min_select_opts('client_id','customers','name',$i{client_id},'') ; + +my @datefrom = &common_add_delta_ymd(-2,0,0) ; + +$print_box_content_rows .= &common_min_form_datepicker('date_from',"$datefrom[0]-01-01") ; +$print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$now_dd") ; +$print_box_content_rows .= &common_min_form_select('camera_system_id','') ; +# $opts{stock} = qq~ +# +# +# +# ~ ; +$print_box_content_rows .= &common_min_form_select('stock','','',1,'') ; +$print_box_content_rows .= &common_min_form_select('client_id','') ; +$print_box_content_rows .= &common_min_forms_end('','','report') ; + +&common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +use common ; +use report ; +use xlsxcreator ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/storage.pl b/scripts/_FromProd/v1.0/storage.pl new file mode 100644 index 0000000..a20cb3d --- /dev/null +++ b/scripts/_FromProd/v1.0/storage.pl @@ -0,0 +1,417 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use DBI; +use CGI; +use POSIX; + +# unless ($username eq 'rory') { print "<<<<<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our ($q) = CGI -> new() ; +$iaction = $q -> param('iaction') || '' ; +$iall = $q -> param('iall') || '' ; +$iboth = $q -> param('iboth') || '' ; +$isaved = $q -> param('isaved') || '' ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +&today; + +if ($iaction eq ''){ + &base_screen ; + } + +if ($iaction eq 'edit'){ + &common_load_params ; + &get_storage_list ; + &edit_screen ; + &screen1; + } + +if ($iaction eq 'save'){ + &common_load_params ; + &process_storage_for_save ; + $savetype = "SAVED" ; + $viewsaved = 0 ; + &screen2; + } + +if ($iaction eq 'update'){ + &common_load_params ; + &check_update_storage ; + &update_storage(1) ; + $savetype = "UPDATED" ; + &screen2; + } + +if ($iaction eq 'delete'){ + &common_load_params ; + &delete_storage ; + $savetype = "DELETED" ; + $viewsaved = 1 ; + &screen2; + } + +exit; + +#------------------------------------------------------------------------------------------ + +sub process_storage_for_save { + +@input_array = $q -> param('input_array'); + +our $batchno = &db_get_max_storage_batch_no ; + +foreach (@input_array) { + $at_least_one_input = 1 ; + if ($i{storageid}{$_}){ + &update_storage($_) ; + } + else + { + &insert_storage ; + } + } + +unless ($at_least_one_input) { $error = qq(NOTHING SELECTED); &base_screen ; } + +} #------------------------------------------------------------------------------------------ + +sub delete_storage { + +unless ($i{storageid}) { return ; } + +&db_open_upd ; + +$sql = qq(DELETE FROM storage WHERE ID = "$i{storageid}" AND HAWB = "$i{hawb}") ; + +&common_debug($sql) ; + +$sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +&db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +sub check_update_storage { + +$input = $q -> param('input_array'); + +unless ($input) { $error = qq(NOTHING SELECTED); &base_screen ; return ; } + +$viewsaved = 0 ; + +if (($i{dateout}{1}) and ($i{storageid}{1}) and ($i{waybillno}{1})) { $viewsaved = 1 ; } + +} #------------------------------------------------------------------------------------------ + +sub update_storage { + +my ($field) = @_ ; + +unless ($i{storageid}{$field}) { return ; } + +&db_open_upd ; + +$sql = qq(UPDATE storage SET +DateOut = "$i{dateout}{$field}", +Remarks = "$i{remarks}{$field}" +WHERE ID = "$i{storageid}{$field}" AND HAWB = "$i{waybillno}{$field}") ; + +&common_debug($sql) ; + +$sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +&db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +sub insert_storage { + +&db_open_upd ; + +$sql = qq(INSERT INTO storage (ID,BatchNo,DateCreated,HAWB,DateOut,Remarks) +VALUES ("","$batchno","$now_ccyy_mm_dd","$i{waybillno}{$_}","$i{dateout}{$_}","$i{remarks}{$_}");) ; + +&common_debug($sql) ; + +$sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +&db_close_conn ; + +} #------------------------------------------------------------------------------------------ + +sub db_get_max_storage_batch_no { + +&db_open_ro ; + +my $sql = qq(SELECT BatchNo FROM storage ORDER BY BatchNo DESC LIMIT 1) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $max_batch_no_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +my $new_batchno = 1 ; + +foreach $row (@$max_batch_no_array_ref) { + $batchno = @$row[0] ; + $new_batchno = $batchno ; + $new_batchno++ ; + } + +return ($new_batchno) ; + +} #------------------------------------------------------------------------------------------ + +sub get_storage_list { + +if ($iall) { + &db_load_all_parcels ; + &get_db_storage_list(1) ; + } +elsif ($iboth) { + &db_load_all_parcels ; + &get_db_storage_list(3) ; + &get_db_waybill_storage_list ; + } +else + { + &db_load_all_parcels ; + &get_db_storage_list(2) ; + &get_db_waybill_storage_list ; + } + +} #------------------------------------------------------------------------------------------ + +sub get_db_waybill_storage_list { + +&db_open_ro ; + +my $sql = qq(SELECT * FROM waybills WHERE OthSvc1 = 'Storage') ; +# my $sql = qq(SELECT * FROM waybills WHERE OthSvc1 = 'Packaging') ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $id_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +foreach $row (@$id_array_ref) { + &db_waybills_fields ; + + if ($storage{$wb{waybillno}}{$wb{storageno}}) { next ; } + + my $checked = '' ; + + if ($i{hawb}) { unless ($i{hawb} eq $wb{waybillno}) { next ; } $checked = 'CHECKED' ; } + + $r++ ; + + if ($i{id}{$wb{waybillno}}) { $hidden_fields_edit = qq() ; } else { $hidden_fields_edit = '' ; } + + my $invno = sprintf("%.0f",($wb{'invno'})) ; + + $print_contents = '' ; + + if ($contents{$wb{waybillno}}){ &db_package_parcels($wb{waybillno}) ; } + if ($wb{volmass} > $wb{actmass}) { $chgmass = ceil($wb{volmass}); } else { $chgmass = ceil($wb{actmass}); } + + my $view_wb_link = qq(dlgMdl('$useropts{scripts}/dialog/view_waybill.pl?$wb{waybillno}','HAWB $wb{waybillno} : $wb{client} : $wb{coldate}','','max-dialog');) ; + $tbody .= qq($wb{coldate}$wb{waybillno}$wb{origin}$wb{client}$print_contents$wb{pcs}$chgmass) ; + my $dateout = qq(
    ) ; + $tbody .= qq($dateout$invno$hidden_fields_edit) ; + } + +} #------------------------------------------------------------------------------------------ + +sub get_db_storage_list { + +my ($type) = @_ ; + +&db_open_ro ; + +my $sql = qq(SELECT storage.*,waybills.client,waybills.invno,waybills.coldate,waybills.origin,waybills.pcs,waybills.volmass,waybills.actmass,waybills.othsvc1 FROM storage,waybills WHERE waybills.waybillno = storage.hawb LIMIT 1000) ; + +my $sth = $dbh->prepare($sql) ; + +$sth -> execute() or die "Could not execute SQL statement $sql ... maybe invalid? $!"; +my $id_array_ref = $sth->fetchall_arrayref(); + +$sth->finish(); + +&db_close_conn ; + +foreach $row (@$id_array_ref) { + &db_storage_fields ; + + $wb{client} = @$row[6] ; + $wb{invno} = @$row[7] ; + $wb{coldate} = @$row[8] ; + $wb{origin} = @$row[9] ; + $wb{pcs} = @$row[10] ; + $wb{volmass} = @$row[11] ; + $wb{actmass} = @$row[12] ; + $wb{othsvc1} = @$row[13] ; + + if (&edit_ifields($st{hawb})) { next ; } + if (($i{hawb}) and ($iaction eq 'edit')) { next ; } + + if ($type == 2) { $storage{$st{hawb}}{$st{othsvc1}} = 1 ; next ; } + if ($type == 3) { next ; } + + my $invno = sprintf("%.0f",($wb{invno})) ; + + $print_contents = '' ; + + if ($contents{$wb{waybillno}}){ &db_package_parcels($wb{waybillno}) ; } + if ($wb{volmass} > $wb{actmass}) { $chgmass = ceil($wb{volmass}); } else { $chgmass = ceil($wb{actmass}); } + + my $view_wb_link = qq(dlgMdl('$useropts{scripts}/dialog/view_waybill.pl?$st{hawb}','HAWB $st{hawb} : $wb{client} : $wb{coldate}','','max-dialog');) ; + $tbody .= qq($wb{coldate}$st{hawb}$wb{origin}$wb{client}$print_contents$wb{pcs}$chgmass) ; + $tbody .= qq($st{dateout}$invno$st{remarks}) ; + + #   + } + +} #------------------------------------------------------------------------------------------ + +sub edit_ifields { + +my ($hawb) = @_ ; + +$i{id}{$hawb} = $st{id} ; +$i{batchno}{$hawb} = $st{batchno} ; +$i{dateout}{$hawb} = $st{dateout} ; +$i{remarks}{$hawb} = $st{remarks} ; ; + +my $incomplete = '' ; + +foreach my $p (keys %i) { + $i{$p}{$hawb} =~ s/0000-00-00//g ; + unless ($i{$p}{$hawb}) { $incomplete = 1 ;} + } + +return($incomplete) ; + +} #------------------------------------------------------------------------------------------ + +sub base_screen { + +&get_storage_list; +&save_screen; +&screen1; + +} #------------------------------------------------------------------------------------------ + +sub save_screen { + +$hidden_action = 'save' ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + +$hidden_action = 'update' ; + +} #------------------------------------------------------------------------------------------ + +sub screen1 { + +if ($error) { $alert = qq() ; } +if ($isaved) { $alert = qq() ; } + +my $allbutt = qq( All) ; +my $incbutt = qq( Incomplete) ; +my $combutt = qq( Completed) ; + +if ($iall) { + $table_title = qq(: Complete) ; + $view_butt = qq($incbutt $allbutt); + } +elsif ($iboth) { + $table_title = qq(: All) ; + $view_butt = qq($combutt $incbutt); + } +elsif ($iaction eq 'edit') { + $table_title = qq(: Edit) ; + $view_butt = qq($combutt $incbutt); + } +else + { + $table_title = qq(: Incomplete); + $view_butt = qq($combutt $allbutt); + } + +$print_buttons = qq(
     
     
    ) ; + +$trigger_jquery_raw .= qq(\$('#storagelist').dataTable({ + "iDisplayLength": -1, + "aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]], + "sDom": "<'row'<'col-md-6'l><'col-md-6'f>r>t<'row'<'col-md-12'i><'col-md-12 center-block'p>>", + "sPaginationType": "bootstrap", + "oLanguage": { + "sLengthMenu": "_MENU_ records per page" + } + }); + ) ; + +require st_list ; +exit ; + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + +print < + + + + Film Freight Admin + + + + + + +
    + + + +
    + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +use db ; +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/supplier_contacts.pl b/scripts/_FromProd/v1.0/supplier_contacts.pl new file mode 100644 index 0000000..fd43e2b --- /dev/null +++ b/scripts/_FromProd/v1.0/supplier_contacts.pl @@ -0,0 +1,325 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Crypt::PasswdMD5; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +# unless (($iaction eq 'view') or ($iaction eq 'list')) { unless ($useropts{super}{$username}) { print "UNAUTHORISED" ; exit ; } } + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + +my $exists = '' ; + +# $i{SupplierName} = ucfirst $i{SupplierName} ; +# $i{name} =~ s/ //gi ; + +&db_min_ro($table,'*',"`SupplierName`='$i{SupplierName}'",'SupplierName','') ; + +foreach my $id (keys %{$db{$table}}) { if ($db{$table}{$id}{SupplierName} eq $i{SupplierName}) { $exists = 1 ; } } + +if ($exists) { + $alert = &common_min_alert('warning',"SUPPLIERNAME ALREADY EXISTS!",'ok') ; + %col_name = (); + &common_min_add_screen; + &common_min_screen1; + } + +} #------------------------------------------------------------------------------------------ + +sub insert { + +&add_db_fields ; + +$i{SupplierID} = &db_get_max_supplier_id ; +$i{AccNo} = &db_get_max_supplier_acc_no ; + +&db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + +unless ($i{SupplierID}) { $error = qq(NO ID) ; return ; } + +&edit_db_fields ; + +unless ($i{Active}) { $i{Active} = '0' ; } + +# $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&db_min_upd($table,"`SupplierID`='$i{SupplierID}'") ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +&db_min_ro('waybills','WaybillNo,MainAccNo,Client','','','') ; +foreach my $id (keys %{$db{waybills}}) { + # $client_accno_on_waybill{$db{waybills}{$id}{MainAccNo}} = $db{waybills}{$id}{Client} ; + $client_accno_on_waybill{$db{waybills}{$id}{MainAccNo}} .= $db{waybills}{$id}{WaybillNo} . ', ' ; + } + +&db_min_ro('manifests','ManifestDetailID,Supplier,ManifestID','','','') ; +foreach my $id (keys %{$db{manifests}}) { + $supplier_on_manifest{$db{manifests}{$id}{Supplier}} = $db{manifests}{$id}{ManifestID} . ', ' ; + } + +&db_min_ro($table,'*','','SupplierName','') ; + +foreach my $id (keys %{$db{$table}}) { + + my $del_butt = qq( ) ; + my $edit_butt = qq( ) ; + my $view_butt = qq( ) ; + + # if ((lc $username eq 'vivian') or (lc $username eq 'rory')) { + # $del_butt = qq( ) ; + # } + + if ($iaction eq 'display'){ + # unless ($useropts{super}{$username}) { + $del_butt = '' ; $edit_butt = '' ; + if ($db{$table}{$id}{Active}) { next ; } + } + elsif ($client_accno_on_waybill{$db{$table}{$id}{AccNo}}){ + my $ttw = $client_accno_on_waybill{$db{$table}{$id}{AccNo}} ; $ttw = substr($ttw,0,-2); + $del_butt = qq( ) ; + } + elsif ($supplier_on_manifest{$db{$table}{$id}{SupplierName}}){ + my $ttw = $supplier_on_manifest{$db{$table}{$id}{SupplierName}} ; $ttw = substr($ttw,0,-2); + $del_butt = qq( ) ; + } + + my $disp_active = qq(); if ($db{$table}{$id}{Active}) { $disp_active = qq(); } + my $disp_email = '' ; if ($db{$table}{$id}{Email}) { $disp_email = qq($db{$table}{$id}{Email}); } + + $print_tbody .= qq( + $id + $db{$table}{$id}{SupplierName} + $db{$table}{$id}{Country} + $db{$table}{$id}{City} + $db{$table}{$id}{AirportCode} + $db{$table}{$id}{ContactName} + $disp_email + $db{$table}{$id}{PhoneNo} + $disp_active + + $edit_butt + $view_butt + $del_butt + + ) ; + } + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + +&hidden_db_fields; + +$hidden{SupplierID} = 2 ; +$hidden{AccNo} = 2 ; +# $required{name} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + +&hidden_db_fields; + +$hidden{SupplierID} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub view_db_fields { + +&hidden_db_fields; + +$ignore{SupplierID} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + +$ignore{iaction} = 1 ; +$ignore{FaxNo} = 1 ; +$ignore{Website} = 1 ; +$ignore{PostalAddr1} = 1 ; +$ignore{PostalAddr2} = 1 ; +$ignore{PostalAddr3} = 1 ; +$ignore{PostalAddr4} = 1 ; +$ignore{DocCharge} = 1 ; +$ignore{InsPerc} = 1 ; +$ignore{InsMin} = 1 ; +$ignore{FuelPerc} = 1 ; +$ignore{FuelFlatRate} = 1 ; +$ignore{FuelMin} = 1 ; +$ignore{FuelMax} = 1 ; +$ignore{Terms} = 1 ; +# $ignore{AccNo} = 1 ; +$ignore{RegNo} = 1 ; +$ignore{VatNo} = 1 ; +$ignore{PhyPC} = 1 ; +$ignore{PostalPC} = 1 ; +# $ignore{PhoneNo} = 1 ; + +$checkbox{Active} = 1 ; +$textarea{Notes} = 1 ; +$textarea_height{Notes} = 80 ; + +$required{SupplierName} = 1 ; +$required{ContactName} = 1 ; +$required{CellNo} = 1 ; +$required{Country} = 1 ; +$required{Email} = 6 ; # only email format allowed +$required{City} = 1 ; + +&sort_fields; + +# SupplierID SupplierName ContactName CellNo Email PhyAddr1 PhyAddr2 PhyAddr3 PhyAddr4 Country City AirportCode + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + +$sort_field{1} = 'SupplierName' ; $preferred_title{SupplierName} = 'Supplier Name' ; +$sort_field{2} = 'Country' ; +$sort_field{3} = 'City' ; +$sort_field{4} = 'AirportCode' ; $preferred_title{AirportCode} = 'Airport' ; +$sort_field{5} = 'PhoneNo' ; $preferred_title{PhoneNo} = 'Tel No' ; +$sort_field{6} = 'ContactName' ; $preferred_title{ContactName} = 'Contact Name 1' ; +$sort_field{7} = 'Email' ; $preferred_title{Email} = 'Email 1' ; +$sort_field{8} = 'CellNo' ; $preferred_title{CellNo} = 'CellNo 1' ; +$sort_field{9} = 'ContactName2' ; $preferred_title{ContactName2} = 'Contact Name 2' ; +$sort_field{10} = 'Email2' ; $preferred_title{Email2} = 'Email 2' ; +$sort_field{11} = 'CellNo2' ; $preferred_title{CellNo2} = 'CellNo 2' ; +$sort_field{12} = 'ContactName3' ; $preferred_title{ContactName3} = 'Contact Name 3' ; +$sort_field{13} = 'Email3' ; $preferred_title{Email3} = 'Email 3' ; +$sort_field{14} = 'CellNo3' ; $preferred_title{CellNo3} = 'CellNo 3' ; +$sort_field{15} = 'PhyAddr1' ; $preferred_title{PhyAddr1} = 'Addr 1' ; +$sort_field{16} = 'PhyAddr2' ; $preferred_title{PhyAddr2} = 'Addr 2' ; +$sort_field{17} = 'PhyAddr3' ; $preferred_title{PhyAddr3} = 'Addr 3' ; +$sort_field{18} = 'PhyAddr4' ; $preferred_title{PhyAddr4} = 'Addr 4' ; +$sort_field{19} = 'Active' ; $preferred_title{Active} = 'Inactive' ; +$sort_field{20} = 'Notes' ; + +} #------------------------------------------------------------------------------- + +sub add_screen { + +# called from common_add_screen + +&select_opts_airport('AirportCode','airport_codes','name','',1,'iata_code',''); + +} #------------------------------------------------------------------------------------------ + +sub select_opts_airport { + +my ($field,$table,$valfield,$fid,$required,$addfield,$where) = @_ ; + +$select{$field} = 1 ; + +if ($required) { $required{$field} = 1 ; } + +&db_min_ro($table,'`iata_code`,`name`',$where,'','') ; + +foreach my $id (keys %{$db{$table}}) { + if ($fid eq $id) { $selected = 'selected="selected"'; } else { $selected = ''; } + if ($db{$table}{$id}{$addfield}) { $disp_addfield = " [$db{$table}{$id}{$addfield}]" ; } else { $disp_addfield = '' ; } + $opts{$field} .= qq() ; + } + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +# &common_debug("edit_screen: id[$i{SupplierID}] AirportCode[$db{$table}{$i{SupplierID}}{AirportCode}]"); + +&select_opts_airport('AirportCode','airport_codes','name',$db{$table}{$i{SupplierID}}{AirportCode},1,'iata_code',''); + +# $extra_form_fields .= &common_min_form_input('new_password','','password') ; + +} #------------------------------------------------------------------------------------------ + +sub view_screen { + +my ($iid) = @_ ; + +our ($lcol,$fcol) = &common_min_columns($label_col,$field_col) ; + +foreach my $cnt (sort {$a <=> $b} keys %sort_field) { + my $col = $sort_field{$cnt} ; + if ($ignore{$col}) { next ; } + my $val = $db{$table}{$iid}{$col} ; + $print_box_content_rows .= &common_min_form_view($col,$val) ; + } + +} #------------------------------------------------------------------------------------------ + +sub thead { + +$print_thead = qq(SupplierIDCompanyNameCountryCityAirportCodeContactEmailTelNoActive ) ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'plane' ; +our $lcpage = 'supplier-contact' ; # $ucpage = uc $lcpage ; # $ucfirstpage = ucfirst $lcpage ; + +my @splitlcpage = split(/\-/,$lcpage) ; +my @ucfirstpage = map(ucfirst, map(lc,@splitlcpage)); +$ucfirstpage = join(' ', @ucfirstpage); +$ucpage = uc $ucfirstpage ; + +our $table = 'agents' ; +our $uniq_id = 'SupplierID' ; + +$page_title = 'Supplier Contacts' ; + +our $glob_sort_col = 1 ; +our $glob_sort_asc_desc = 'asc' ; + +&common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/teams.pl b/scripts/_FromProd/v1.0/teams.pl new file mode 100644 index 0000000..84c6ff2 --- /dev/null +++ b/scripts/_FromProd/v1.0/teams.pl @@ -0,0 +1,391 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +&db_switch_conn('sss') ; + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + + my $exists = '' ; + + $i{name} = &common_fix_str($i{name}) ; + + if (length($i{name}) > 75) { $alert = &common_min_alert('danger',"YOUR TEAM NAME CONTAINS TOO MANY CHARACTERS!",'warning-sign') ; %col_name = () ; &load_vars ; &common_min_add_screen ; &common_min_screen1 ; exit ; } + + &db_min_ro($table,'*',"name = '$i{name}'",'name','') ; + + foreach my $id (keys %{$db{$table}}) { + if (lc $db{$table}{$id}{name} eq lc $i{name}) { + $exists = 1 ; + last ; + } + } + + if ($exists) { $alert = &common_min_alert('danger',"'$i{name}' AS A TEAM NAME ALREADY EXISTS!",'warning-sign') ; %col_name = () ; &load_vars ; &common_min_add_screen ; &common_min_screen1 ; exit ; } + +} #------------------------------------------------------------------------------------------ + +sub insert { + + &add_db_fields ; + + $i{id} = &db_min_get_max($table,'id') ; + + $ignore{name} = 1 ; + $ignore{region_id} = 1 ; + + &db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + unless ($i{id}) { $error = qq(NO ID) ; return ; } + + &edit_db_fields ; + + $ignore{name} = 1 ; + $ignore{region_id} = 1 ; + + &db_min_upd($table,"id='$i{id}'") ; + + $ignore{name} = '' ; + $ignore{region_id} = '' ; + +} #------------------------------------------------------------------------------------------ + +sub load_vars { + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + &db_switch_conn('aisa'); + + &db_min_ro('customers','id,name','','','') ; + + &db_min_ro('regions','*','','','') ; + + &db_min_ro('analytics_event_bookings',"id,fixtures_saved_values,client_id","fixtures_saved_values IS NOT NULL",'','') ; + + foreach my $analytics_id (keys %{$db{analytics_event_bookings}}) { + + # 1;2025-06-03 08:00:00;5;open;a;3404;1;3404;s;r;s;r|2;2025-06-03 08:00:00;6;u19;a;6046;1;6046;p;s;p;s + + my @row_split_1 = split(/\|/,$db{analytics_event_bookings}{$analytics_id}{fixtures_saved_values}) ; + + foreach (@row_split_1) { + my @row_split_2 = split(/\;/,$_) ; + $venue_id_used{$row_split_2[5]} = 1 if $row_split_2[5] ; + $venue_id_used{$row_split_2[7]} = 1 if $row_split_2[7] ; + $client_team_combo_used{$db{analytics_event_bookings}{$analytics_id}{client_id}}{$row_split_2[5]} = 1 if $db{analytics_event_bookings}{$analytics_id}{client_id} && $row_split_2[5] ; + } + } + + &db_switch_conn('sss'); + + &db_min_ro('event_quotes',"DISTINCT team_ids AS 'team_ids'","team_ids <> 0",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + if ($_id =~ /;/) { ## 13,32 + foreach (split(/\;/,$_id)) { + $venue_id_used{$_} = 1 ; + } + } else { + $venue_id_used{$_id} = 1 ; + } + } + + &db_min_ro($table,'*','','','') ; + + foreach my $id (sort {$db{$table}{$a}{name} cmp $db{$table}{$b}{name}} keys %{$db{$table}}) { + + my $edit_butt = qq~ ~ ; + my $del_butt = qq~ ~ ; + + if ($glod_user_level >= 3) { + $edit_butt = qq~ ~ ; + if ($client_team_combo_used{$db{$table}{$id}{aisa_client_id}}{$id}) { + $edit_butt = qq~ ~ ; + } + } + + if ($glod_user_level >= 3) { + $del_butt = qq~ ~ ; + } + + if ($venue_id_used{$id}) { + # $edit_butt = qq~ ~ ; + $del_butt = qq~ ~ ; + } + + my $region_name = ($db{$table}{$id}{region_id}) ? "$db{regions}{$db{$table}{$id}{region_id}}{name} [$db{regions}{$db{$table}{$id}{region_id}}{code}]" : "" ; + my $matched_region_name = ($db{$table}{$id}{matched_region_id}) ? "$db{regions}{$db{$table}{$id}{matched_region_id}}{name} [$db{regions}{$db{$table}{$id}{matched_region_id}}{code}]" : "" ; + my $customer_name = $db{customers}{$db{$table}{$id}{aisa_client_id}}{name} ; + + $print_tbody .= qq~ + + $id + $db{$table}{$id}{name} + $region_name + $matched_region_name + $customer_name + + $edit_butt + + + ~ ; + } + &db_switch_conn('aisa'); + # $extra_edit_hidden_inputs .= qq~~ ; + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + &sort_fields; + + &hidden_db_fields; + + # $ignore{id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &hidden_db_fields; + + &sort_fields; + + $hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + + $ignore{iaction} = 1 ; + # $required{region_code} = 1 ; + # $required{address_line_1} = 1 ; + # $required{address_line_2} = 1 ; + # $required{address_line_3} = 1 ; + # $required{address_line_4} = 1 ; + # $required{suburb} = 1 ; + # $required{postal_code} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + if ($i{id}) { + + &db_min_ro('event_quotes',"DISTINCT team_ids AS 'team_ids'","`team_ids` <> 0 AND `team_ids` LIKE '%$i{id}%'",'','') ; + + our %venue_id_used = () ; + + foreach my $_id (keys %{$db{event_quotes}}) { + + next if $venue_id_used{$db{event_quotes}{$_id}{team_ids}} ; + my @split = split(/\;/,$db{event_quotes}{$_id}{team_ids}) ; + foreach (@split) { + $venue_id_used{$_} = 1 ; + } + } + + &db_switch_conn('aisa'); + + &db_min_ro('analytics_event_bookings',"id,fixtures_saved_values","fixtures_saved_values IS NOT NULL AND fixtures_saved_values LIKE '%;$i{id};%'",'','') ; + + # &db_min_ro('regions',"id,name,code","",'','') ; + &common_min_select_opts('region_id','regions','name',$db{$table}{$i{id}}{region_id},'','','','','','','name') ; + + &db_switch_conn('sss'); + + foreach my $analytics_id (keys %{$db{analytics_event_bookings}}) { + + my @row_split_1 = split(/\|/,$db{analytics_event_bookings}{$analytics_id}{fixtures_saved_values}) ; + + foreach (@row_split_1) { + my @row_split_2 = split(/\;/,$_) ; + $venue_id_used{$row_split_2[5]} = 1 ; + $venue_id_used{$row_split_2[7]} = 1 ; + } + } + } + + %sort_field = () ; + + # $sort_field{1} = 'region_code' ; $preferred_title{region_code} = 'Region Code' ; + $sort_field{1} = 'region_id' ; # $preferred_title{region_id} = 'Region' ; + $sort_field{2} = 'name' ; $preferred_title{name} = 'Name' ; + $sort_field{3} = 'aisa_client_id' ; + # $sort_field{4} = 'address_line_2' ; + # $sort_field{5} = 'address_line_3' ; + # $sort_field{6} = 'address_line_4' ; + # $sort_field{7} = 'suburb' ; + # $sort_field{8} = 'postal_code' ; + + if ($venue_id_used{$i{id}}) { + # &db_min_ro('regions',"code,name","",'','') ; + + if ($db{$table}{$i{id}}{region_id}) { + $db{$table}{$i{id}}{region_id} = "$db{regions}{$db{$table}{$i{id}}{region_id}}{name} [$db{regions}{$db{$table}{$i{id}}{region_id}}{code}]" ; + $required{region_id} = 0 ; + $input{region_id} = 1 ; + $readonly{region_id} = "READONLY" ; + } elsif ($db{$table}{$i{id}}{matched_region_id}) { + $opts{region_id} =~ s/value="$db{$table}{$i{id}}{matched_region_id}"/value="$db{$table}{$i{id}}{matched_region_id}" SELECTED/g ; + $select{region_id} = 1 ; + } + + $required{name} = 0 ; + $readonly{name} = "READONLY" ; + } else { + if ($db{$table}{$i{id}}{matched_region_id}) { + $opts{region_id} =~ s/value="$db{$table}{$i{id}}{matched_region_id}"/value="$db{$table}{$i{id}}{matched_region_id}" SELECTED/g ; + } + $select{region_id} = 1 ; + } + + $select{region_id} = '' ; + $select{aisa_client_id} = 1 ; + $input{region_id} = 1 ; + + $readonly{region_id} = "READONLY" ; + $readonly{name} = "READONLY" ; + $required{region_id} = "" ; + $required{name} = "" ; + + # $i{region_id} = "123123123" ; + + if ($db{$table}{$i{id}}{region_id}) { + $db{$table}{$i{id}}{region_id} = ($db{regions}{$db{$table}{$i{id}}{region_id}}{code}) ? "$db{regions}{$db{$table}{$i{id}}{region_id}}{name} [$db{regions}{$db{$table}{$i{id}}{region_id}}{code}]" : $db{regions}{$db{$table}{$i{id}}{region_id}}{name} ; + } elsif ($db{$table}{$i{id}}{matched_region_id}) { + $db{$table}{$i{id}}{region_id} = ($db{regions}{$db{$table}{$i{id}}{matched_region_id}}{code}) ? "$db{regions}{$db{$table}{$i{id}}{matched_region_id}}{name} [$db{regions}{$db{$table}{$i{id}}{matched_region_id}}{code}]" : $db{regions}{$db{$table}{$i{id}}{matched_region_id}}{name} ; + } else { + $db{$table}{$i{id}}{region_id} = "N/A" ; + } + +} #------------------------------------------------------------------------------- + +sub add_screen { + + # called from common_add_screen + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + + # $required{based_in} = 1 ; + # $select{based_in} = 1 ; + # $opts{based_in} = qq~~ ; + + # return if $venue_id_used{$i{id}} ; + + my $sql_or = '' ; + + if ($is_schools_manager || $is_operator) { + @report_sql_or = () ; + foreach $_reg_id (keys %{$glob_regids{$userid}}) { + push @report_sql_or, "id = '$_reg_id'" + } + $sql_or = join(' OR ',@report_sql_or) ; + } + + # &common_min_select_opts('region_code','regions','name',$db{$table}{$i{id}}{region_code},'','code','','code','','','name') ; + + &db_switch_conn('aisa'); + + &common_min_select_opts('aisa_client_id','customers','name','','','','','','','','name') ; + + &db_min_ro('regions','id,name,code','','','') ; + + if ($db{$table}{$i{id}}{aisa_client_id}) { + # $opts{aisa_client_id} =~ s/\"/\'/g ; + # $opts{aisa_client_id} =~ s/value='$db{$table}{$i{id}}{aisa_client_id}'/value='$db{$table}{$i{id}}{aisa_client_id}' SELECTED/g ; + $trigger_jquery_raw .= qq~ + \$("#selectAisa_client_id").val($db{$table}{$i{id}}{aisa_client_id}).trigger("chosen:updated") ; + ~ ; + } + + $trigger_jquery_raw .= qq~ + \$("#selectAisa_client_id").chosen({ allow_single_deselect:true }); + ~ ; + + &db_switch_conn('sss'); + +} #------------------------------------------------------------------------------------------ + +sub thead { + + if ($venue_id_used{$i{id}}) { + # $ignore{region_code} = 1 ; + $ignore{region_id} = 1 ; + $ignore{name} = 1 ; + } + + $print_thead = qq~IDNameRegionRegion (est.)Client Name~ ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'map-marker' ; + our $lcpage = 'teams' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'teams' ; + + $s{no} = 1 ; + + &common_min_add_extras ; + + $box_icon = '' ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/teams_test.pl b/scripts/_FromProd/v1.0/teams_test.pl new file mode 100644 index 0000000..30041a4 --- /dev/null +++ b/scripts/_FromProd/v1.0/teams_test.pl @@ -0,0 +1,667 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $debug = 1 ; +our $testing = 1 ; + +our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +&db_switch_conn('sss') ; + +# &db_open_ro ; + # $db_ignore_open_close = 1 ; + &common_min_action; + $db_ignore_open_close = 0 ; +&db_close_conn ; + + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + + my $exists = '' ; + + $i{name} = &common_fix_str($i{name}) ; + + if (length($i{name}) > 75) { $alert = &common_min_alert('danger',"YOUR TEAM NAME CONTAINS TOO MANY CHARACTERS!",'warning-sign') ; %col_name = () ; &load_vars ; &common_min_add_screen ; &common_min_screen1 ; exit ; } + + &db_min_ro($table,'*',"name = '$i{name}'",'name','') ; + + foreach my $id (keys %{$db{$table}}) { + if (lc $db{$table}{$id}{name} eq lc $i{name}) { + $exists = 1 ; + last ; + } + } + + if ($exists) { $alert = &common_min_alert('danger',"'$i{name}' AS A TEAM NAME ALREADY EXISTS!",'warning-sign') ; %col_name = () ; &load_vars ; &common_min_add_screen ; &common_min_screen1 ; exit ; } + +} #------------------------------------------------------------------------------------------ + +sub insert { + + &add_db_fields ; + + $i{id} = &db_min_get_max($table,'id') ; + + $ignore{name} = 1 ; + $ignore{region_id} = 1 ; + $ignore{country_id} = 1 ; + + &db_min_insert($table) ; + + $ignore{name} = "" ; + $ignore{region_id} = "" ; + $ignore{country_id} = "" ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + unless ($i{id}) { $error = qq(NO ID) ; return ; } + + &edit_db_fields ; + + # &db_min_ro('teams','1,region_id,aisa_client_id',"id='$i{id}'",'','') ; + + $ignore{name} = 1 ; + $ignore{region_id} = 1 ; + $ignore{country_id} = 1 ; + + &db_min_upd($table,"id='$i{id}'") ; + + $ignore{name} = '' ; + $ignore{region_id} = '' ; + $ignore{country_id} = '' ; + +} #------------------------------------------------------------------------------------------ + +sub load_vars { + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + &db_switch_conn('aisa'); + + &db_min_ro('customers','id,name','','','') ; + + &db_min_ro('regions','*','','','') ; + + &db_min_ro('countries','id,name','','','') ; + + &db_min_ro('analytics_event_bookings',"id,fixtures_saved_values,client_id","fixtures_saved_values IS NOT NULL",'','') ; + + foreach my $analytics_id (keys %{$db{analytics_event_bookings}}) { + + # 1;2025-06-03 08:00:00;5;open;a;3404;1;3404;s;r;s;r|2;2025-06-03 08:00:00;6;u19;a;6046;1;6046;p;s;p;s + + my @row_split_1 = split(/\|/,$db{analytics_event_bookings}{$analytics_id}{fixtures_saved_values}) ; + + foreach (@row_split_1) { + my @row_split_2 = split(/\;/,$_) ; + $venue_id_used{$row_split_2[5]} = 1 if $row_split_2[5] ; + $venue_id_used{$row_split_2[7]} = 1 if $row_split_2[7] ; + $client_team_combo_used{$db{analytics_event_bookings}{$analytics_id}{client_id}}{$row_split_2[5]} = 1 if $db{analytics_event_bookings}{$analytics_id}{client_id} && $row_split_2[5] ; + } + } + + &db_switch_conn('sss'); + + &db_min_ro('event_quotes',"DISTINCT team_ids AS 'team_ids'","team_ids <> 0",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + if ($_id =~ /;/) { ## 13,32 + foreach (split(/\;/,$_id)) { + $venue_id_used{$_} = 1 ; + } + } else { + $venue_id_used{$_id} = 1 ; + } + } + + &db_min_ro($table,'*','','','') ; + + foreach my $id (sort {$db{$table}{$a}{name} cmp $db{$table}{$b}{name}} keys %{$db{$table}}) { + + my $edit_butt = qq~ ~ ; + my $del_butt = qq~ ~ ; + + if ($glod_user_level >= 3) { + $edit_butt = qq~ ~ ; + if ($client_team_combo_used{$db{$table}{$id}{aisa_client_id}}{$id}) { + $edit_butt = qq~ ~ ; + } + } + + if ($glod_user_level >= 3) { + $del_butt = qq~ ~ ; + } + + if ($venue_id_used{$id}) { + # $edit_butt = qq~ ~ ; + $del_butt = qq~ ~ ; + } + + my $region_name = ($db{$table}{$id}{region_id}) ? "$db{regions}{$db{$table}{$id}{region_id}}{name} [$db{regions}{$db{$table}{$id}{region_id}}{code}]" : "" ; + my $matched_region_name = ($db{$table}{$id}{matched_region_id}) ? "$db{regions}{$db{$table}{$id}{matched_region_id}}{name} [$db{regions}{$db{$table}{$id}{matched_region_id}}{code}]" : "" ; + my $customer_name = $db{customers}{$db{$table}{$id}{aisa_client_id}}{name} ; + + my $country_name = ($db{$table}{$id}{region_id}) ? $db{countries}{$db{regions}{$db{$table}{$id}{region_id}}{country_id}}{name} : ($db{$table}{$id}{matched_region_id}) ? $db{countries}{$db{regions}{$db{$table}{$id}{matched_region_id}}{country_id}}{name} : "" ; + + $print_tbody .= qq~ + + $id + $db{$table}{$id}{name} + $customer_name + $region_name + $matched_region_name + $country_name + + $edit_butt + + + ~ ; + } + &db_switch_conn('aisa'); + # $extra_edit_hidden_inputs .= qq~~ ; + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + &sort_fields; + + &hidden_db_fields; + + # $ignore{id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &hidden_db_fields; + + &sort_fields; + + $hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + + $ignore{iaction} = 1 ; + # $required{region_code} = 1 ; + # $required{address_line_1} = 1 ; + # $required{address_line_2} = 1 ; + # $required{address_line_3} = 1 ; + # $required{address_line_4} = 1 ; + # $required{suburb} = 1 ; + # $required{postal_code} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + %sort_field = () ; + + # $sort_field{1} = 'region_code' ; $preferred_title{region_code} = 'Region Code' ; + + $sort_field{2} = 'name' ; $preferred_title{name} = 'Name' ; + $sort_field{3} = 'aisa_client_id' ; + $sort_field{4} = 'region_id' ; # $preferred_title{region_id} = 'Region' ; + $sort_field{5} = 'country_id' ; # $preferred_title{region_id} = 'Region' ; + + # $sort_field{4} = 'address_line_2' ; + # $sort_field{5} = 'address_line_3' ; + # $sort_field{6} = 'address_line_4' ; + # $sort_field{7} = 'suburb' ; + # $sort_field{8} = 'postal_code' ; + +} #------------------------------------------------------------------------------- + +sub add_screen { + + # called from common_add_screen + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + + our %venue_id_used = () ; + + if ($i{id}) { + + &db_min_ro('event_quotes',"DISTINCT team_ids AS 'team_ids'","`team_ids` <> 0 AND `team_ids` LIKE '%$i{id}%'",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + + next if $venue_id_used{$db{event_quotes}{$_id}{team_ids}} ; + my @split = split(/\;/,$db{event_quotes}{$_id}{team_ids}) ; + foreach (@split) { + $venue_id_used{$_} = 1 ; + } + } + + &db_switch_conn('aisa'); + + &db_min_ro('analytics_event_bookings',"id,fixtures_saved_values","fixtures_saved_values IS NOT NULL AND fixtures_saved_values LIKE '%;$i{id};%'",'','') ; + + # &db_min_ro('regions',"id,name,code","",'','') ; + &common_min_select_opts('region_id','regions','name',$db{$table}{$i{id}}{region_id},'','','','','','','name') ; + + $default_country = ($db{$table}{$i{id}}{region_id}) ? $db{regions}{$db{$table}{$i{id}}{region_id}}{country_id} : ($db{$table}{$i{id}}{matched_region_id}) ? $db{regions}{$db{$table}{$i{id}}{matched_region_id}}{country_id} : "" ; + + &common_min_select_opts('country_id','countries','name',$default_country,'','','','','','','name') ; + + &db_switch_conn('sss'); + + foreach my $analytics_id (keys %{$db{analytics_event_bookings}}) { + + my @row_split_1 = split(/\|/,$db{analytics_event_bookings}{$analytics_id}{fixtures_saved_values}) ; + + foreach (@row_split_1) { + my @row_split_2 = split(/\;/,$_) ; + $venue_id_used{$row_split_2[5]} = 1 ; + $venue_id_used{$row_split_2[7]} = 1 ; + } + } + } + + if ($venue_id_used{$i{id}}) { + + if ($db{$table}{$i{id}}{aisa_client_id}) { + &db_switch_conn('aisa'); + &db_min_ro("customers","1,name","id='$db{$table}{$i{id}}{aisa_client_id}'",'','') ; + &db_switch_conn('sss'); + $db{$table}{$i{id}}{aisa_client_id} = $db{customers}{1}{name} ; + } else { + $db{$table}{$i{id}}{aisa_client_id} = "N/A" ; + } + + if ($db{$table}{$i{id}}{region_id}) { + + $db{$table}{$i{id}}{country_id} = "$db{countries}{$db{regions}{$db{$table}{$i{id}}{region_id}}{country_id}}{name}" ; + $db{$table}{$i{id}}{region_id} = "$db{regions}{$db{$table}{$i{id}}{region_id}}{name} [$db{regions}{$db{$table}{$i{id}}{region_id}}{code}]" ; + + $required{region_id} = 0 ; + $select{region_id} = '' ; $select{country_id} = '' ; + $input{region_id} = 1 ; $input{country_id} = 1 ; + $readonly{region_id} = "READONLY" ; + $readonly{country_id} = "READONLY" ; + + } elsif ($db{$table}{$i{id}}{matched_region_id} && !$db{$table}{$i{id}}{region_id}) { + + $db{$table}{$i{id}}{country_id} = "$db{countries}{$db{regions}{$db{$table}{$i{id}}{matched_region_id}}{country_id}}{name}" ; + $db{$table}{$i{id}}{region_id} = "$db{regions}{$db{$table}{$i{id}}{region_id}}{name} [$db{regions}{$db{$table}{$i{id}}{matched_region_id}}{code}]" ; + + $required{region_id} = 0 ; + $select{region_id} = '' ; $select{country_id} = '' ; + $input{region_id} = 1 ; $input{country_id} = 1 ; + $readonly{region_id} = "READONLY" ; + $readonly{country_id} = "READONLY" ; + + # # $opts{region_id} =~ s/value="$db{$table}{$i{id}}{matched_region_id}"/value="$db{$table}{$i{id}}{matched_region_id}" SELECTED/g ; + + # # if ($is_schools_manager || $is_operator) { + # # @report_sql_or = () ; + # # foreach $_reg_id (keys %{$glob_regids{$userid}}) { + # # push @report_sql_or, "$_reg_id" + # # } + # # if (grep { $_ eq "$db{$table}{$i{id}}{matched_region_id}" } @report_sql_or) { + + # # } else { + # # $select{region_id} = '' ; + # # $select{country_id} = '' ; + # # $required{region_id} = 0 ; + # # $readonly{region_id} = "READONLY" ; + # # $readonly{country_id} = "READONLY" ; + # # $input{region_id} = 1 ; + # # $input{country_id} = 1 ; + # # $db{$table}{$i{id}}{region_id} = "N/A" ; + # # $db{$table}{$i{id}}{country_id} = "N/A" ; + # # } + # # } + + # # if (!$readonly{region_id}) { + + # # my $country_id = 0 ; + # # foreach (keys %{$db{regions}}) { + # # if ($_ eq $db{$table}{$i{id}}{matched_region_id}) { + # # $country_id = $db{regions}{$_}{country_id} ; + # # } + # # } + # # $opts{region_id} = qq~~ ; + # # $opts{country_id} = qq~~ ; + # # $select{region_id} = 1 ; $select{country_id} = 1 ; $required{region_id} = 1 ; + # # } + + } else { + $select{region_id} = '' ; + $select{country_id} = '' ; + $input{region_id} = 1 ; + $input{country_id} = 1 ; + $readonly{region_id} = "READONLY" ; + $readonly{country_id} = "READONLY" ; + $required{region_id} = "" ; + $db{$table}{$i{id}}{region_id} = "N/A" ; + $db{$table}{$i{id}}{country_id} = "N/A" ; + } + + $required{name} = 0 ; + $readonly{name} = "READONLY" ; + + $select{aisa_client_id} = '' ; + $input{aisa_client_id} = 1 ; + $readonly{aisa_client_id} = "READONLY" ; + + } else { + + # # my $regions_limit = '' ; + + # # if ($is_schools_manager || $is_operator) { + # # @report_sql_or = () ; + # # foreach $_reg_id (keys %{$glob_regids{$userid}}) { + # # push @report_sql_or, "id = '$_reg_id'" + # # } + # # $regions_limit = join(' OR ',@report_sql_or) ; + # # } + + # # my $default_region_id = ($db{$table}{$i{id}}{region_id}) ? $db{$table}{$i{id}}{region_id} : $db{$table}{$i{id}}{matched_region_id} ; + + # # if ($default_region_id) { + # # $opts{region_id} =~ s/value="$default_region_id"/value="$default_region_id" SELECTED/g ; + # # $opts{country_id} =~ s/value="$db{regions}{$default_region_id}{country_id}"/value="$db{regions}{$default_region_id}{country_id}" SELECTED/g ; + # # } + + # # $select{region_id} = 1 ; + # # $select{country_id} = 1 ; + # # $required{region_id} = 1 ; + # # $required{name} = 1 ; + + # # $trigger_jquery_raw .= qq~ + # # \$("#selectCountry_id").chosen({ allow_single_deselect:true }); + # # ~ ; + + $required{name} = 0 ; + $readonly{name} = "READONLY" ; + + my $default_region_id = ($db{$table}{$i{id}}{region_id}) ? $db{$table}{$i{id}}{region_id} : $db{$table}{$i{id}}{matched_region_id} ; + + $select{region_id} = '' ; + $select{country_id} = '' ; + $input{region_id} = 1 ; + $input{country_id} = 1 ; + $readonly{region_id} = "READONLY" ; + $readonly{country_id} = "READONLY" ; + $required{region_id} = "" ; + $db{$table}{$i{id}}{region_id} = ($default_region_id) ? "$db{regions}{$default_region_id}{name}" : "N/A" ; + $db{$table}{$i{id}}{country_id} = ($default_region_id) ? "$db{countries}{$db{regions}{$default_region_id}{country_id}}{name}" : "N/A" ; + + $select{aisa_client_id} = 1 ; + + &db_switch_conn('aisa'); + &common_min_select_opts('aisa_client_id','customers','name','','','','','','','','name') ; + &db_switch_conn('sss'); + + if ($db{$table}{$i{id}}{aisa_client_id}) { + $trigger_jquery_raw .= qq~ + \$("#selectAisa_client_id").val($db{$table}{$i{id}}{aisa_client_id}).trigger("chosen:updated") ; + ~ ; + } + + $trigger_jquery_raw .= qq~ + \$("#selectAisa_client_id").chosen({ allow_single_deselect:true }); + ~ ; + + + } + + # $trigger_jquery_raw .= qq~ + # \$("#selectCountry_id").val($db{$table}{$i{id}}{aisa_client_id}).trigger("chosen:updated") ; + # ~ ; + + # $select{region_id} = '' ; + # $select{aisa_client_id} = 1 ; + # $input{region_id} = 1 ; + # $input{country_id} = 1 ; + # $select{country_id} = '' ; + + # $readonly{region_id} = "READONLY" ; + # $readonly{country_id} = "READONLY" ; + # $readonly{name} = "READONLY" ; + # $required{region_id} = "" ; + # $required{name} = "" ; + + # $i{region_id} = "123123123" ; + + # if ($db{$table}{$i{id}}{region_id}) { + # $db{$table}{$i{id}}{region_id} = ($db{regions}{$db{$table}{$i{id}}{region_id}}{code}) ? "$db{regions}{$db{$table}{$i{id}}{region_id}}{name} [$db{regions}{$db{$table}{$i{id}}{region_id}}{code}]" : $db{regions}{$db{$table}{$i{id}}{region_id}}{name} ; + # } elsif ($db{$table}{$i{id}}{matched_region_id}) { + # $db{$table}{$i{id}}{region_id} = ($db{regions}{$db{$table}{$i{id}}{matched_region_id}}{code}) ? "$db{regions}{$db{$table}{$i{id}}{matched_region_id}}{name} [$db{regions}{$db{$table}{$i{id}}{matched_region_id}}{code}]" : $db{regions}{$db{$table}{$i{id}}{matched_region_id}}{name} ; + # } else { + # $db{$table}{$i{id}}{region_id} = "N/A" ; + # } + + # if ($default_country) { + # $db{$table}{$i{id}}{country_id} = $db{countries}{$default_country}{name} ; + # } else { + # $db{$table}{$i{id}}{country_id} = "N/A" ; + # } + + if (!$readonly{region_id}) { + + $trigger_jquery_raw .= qq~ + + let map_region_to_country = {} ; + + const \$countrySelect = \$("#selectCountry_id") ; + const \$regionSelect = \$("#selectRegion_id") ; + + const updateChosen = \$el => \$el.trigger("chosen:updated"); + + const fetchJSON = async url => { + try { + const res = await fetch(url); + if (!res.ok) throw new Error(`Request failed: \${res.status}`); + return await res.json(); + } catch (err) { + console.error("Fetch error:", err); + return []; + } + }; + + const populateSelect = (\$field, json_list, getLabel, defaultSelected = () => "") => { + + let isSelected ; + + // Determine how to handle selected logic + if (typeof defaultSelected === "function") { + isSelected = defaultSelected ; + } else if (Array.isArray(defaultSelected)) { + isSelected = data => defaultSelected.includes(data.id) ? "selected" : "" ; + } else { + isSelected = data => data.id == defaultSelected ? "selected" : "" ; + } + + // Auto-select the only item if none explicitly selected + const autoSelectOnly = json_list.length === 1 && typeof defaultSelected === "string" && defaultSelected === "" ; + + json_list.forEach(data => { + const selected = autoSelectOnly || isSelected(data) ? "selected" : "" ; + \$field.append(``) ; + }); + + updateChosen(\$field) ; + return json_list.length ; + }; + + const getInputValue = name => \$(`input[name='\${name}']`).val(); + + const clearSelect = (\$el) => { + \$el.empty(); + \$el.append(``).trigger("chosen:updated"); + }; + + // _______________________________________________ + + \$countrySelect.change( async function() { + \$("input[name='custom_selected_country']").val("1") ; + await update_region_drop_down_from_country(\$countrySelect.val()) ; + }) ; + + async function update_region_drop_down_from_country (countryId) { + + clearSelect(\$regionSelect) ; + + const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}` ; + const regions = await fetchJSON(regionUrl); + + for (const data of regions) { + map_region_to_country[data.id] = countryId ; + } + + const regionCount = populateSelect(\$regionSelect, regions, r => r.code ? `\${r.name} [\${r.code}]` : r.name , "") ; + + if (regionCount === 0 && \$countrySelect.val()) { + \$regionSelect.append(``).trigger("chosen:updated") ; + } + + } + + // _______________________________________________ + + \$regionSelect.change( async function() { + \$("input[name='custom_selected_region']").val("1") ; + \$("input[name='custom_selected_country']").val("1") ; + const regionId = \$regionSelect.val() ; + await update_country_from_region(regionId,1) ; + }); + + async function update_country_from_region (regionId,update_country=0) { + if (map_region_to_country[regionId] || regionId == '13') { + \$countrySelect.val(map_region_to_country[regionId]).trigger("chosen:updated") ; + } else if (!\$("input[name='custom_selected_country']").val() || update_country) { + const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=®ion_id=\${regionId}`; + const regionMeta = await fetchJSON(lookupUrl); + const { country_id } = regionMeta[0] ?? {} ; + if (country_id) { + map_region_to_country[regionId] = country_id; + \$countrySelect.val(country_id).trigger("chosen:updated"); + } + } + } + + // _______________________________________________ + + ~ ; + + } + + # $required{based_in} = 1 ; + # $select{based_in} = 1 ; + # $opts{based_in} = qq~~ ; + + # return if $venue_id_used{$i{id}} ; + + # my $regions_limit = '' ; + + # if ($is_schools_manager || $is_operator) { + # @report_sql_or = () ; + # foreach $_reg_id (keys %{$glob_regids{$userid}}) { + # push @report_sql_or, "id = '$_reg_id'" + # } + # $regions_limit = join(' OR ',@report_sql_or) ; + # } + + # &common_min_select_opts('region_code','regions','name',$db{$table}{$i{id}}{region_code},'','code','','code','','','name') ; + + # &db_switch_conn('aisa'); + + # &common_min_select_opts('aisa_client_id','customers','name','','','','','','','','name') ; + + # &db_min_ro('regions','id,name,code','','','') ; + + # if ($db{$table}{$i{id}}{aisa_client_id}) { + # # $opts{aisa_client_id} =~ s/\"/\'/g ; + # # $opts{aisa_client_id} =~ s/value='$db{$table}{$i{id}}{aisa_client_id}'/value='$db{$table}{$i{id}}{aisa_client_id}' SELECTED/g ; + # $trigger_jquery_raw .= qq~ + # \$("#selectAisa_client_id").val($db{$table}{$i{id}}{aisa_client_id}).trigger("chosen:updated") ; + # ~ ; + # } + + # $trigger_jquery_raw .= qq~ + # \$("#selectAisa_client_id").chosen({ allow_single_deselect:true }); + # ~ ; + + &db_switch_conn('sss'); + +} #------------------------------------------------------------------------------------------ + +sub thead { + + if ($venue_id_used{$i{id}}) { + # $ignore{region_code} = 1 ; + $ignore{region_id} = 1 ; + $ignore{name} = 1 ; + } + + $print_thead = qq~IDNameClient NameRegionRegion (est.)Country ~ ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'map-marker' ; + our $lcpage = 'teams' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'teams' ; + + $s{no} = 1 ; + + &common_min_add_extras ; + + $box_icon = '' ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/temp_calibrator_payments_report.pl b/scripts/_FromProd/v1.0/temp_calibrator_payments_report.pl new file mode 100644 index 0000000..39e322f --- /dev/null +++ b/scripts/_FromProd/v1.0/temp_calibrator_payments_report.pl @@ -0,0 +1,211 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +# unless ($useropts{it}{$username}) { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $srchscr = 1 ; + +# our $testing = 1 ; +# our $debug = 1 ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &report_screen if $iaction eq '' ; + + if ($iaction eq 'report') { + &common_min_load_params ; + &report_ifields; + &list_screen ; + &screen3; + } + + if ($iaction eq 'save') { + &common_min_load_params ; + &update ; + &report_ifields; + &list_screen ; + &screen3; + } + + &common_min_action; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub update { + + &schedule_payments_update("temp_calibrator") ; + +} #------------------------------------------------------------------------------------------ + +sub report_ifields { + + &schedule_payments_report_ifields("temp_calibrator") ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + our $count_outstanding = 0 ; + our $temp_calibrator_payments_report = 1 ; + + my $field3 = 'temp_calibrator' ; + + $field3 =~ s/\_/ /g ; + + &db_min_ro('event_cost_items','id,name,rates,full_half_day',"`name` LIKE '$field3%' OR `name` LIKE 'temp support%'",'','') ; + + foreach my $id (keys %{$db{event_cost_items}}) { + my @full_half_day = split(/\;/,$db{event_cost_items}{$id}{full_half_day}) ; + my @rates = split(/\;/,$db{event_cost_items}{$id}{rates}) ; + my $cnt = 0 ; + foreach (@full_half_day) { + $temp_support_rates{full_day} = $rates[$cnt] if $full_half_day[$cnt] eq '1' ; + $temp_support_rates{half_day} = $rates[$cnt] if $full_half_day[$cnt] eq '2' ; + $cnt++ ; + } + if ($db{event_cost_items}{$id}{name} eq 'Temp Calibrator Allocations') { + $db{event_cost_items}{1}{rates} = $db{event_cost_items}{$id}{rates} ; + } + } + + &schedule_payments_list_screen("temp_calibrator") ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + our $lcpage = 'temp-calibrator-payment' ; + + &common_page_name ; + + our $table = 'shift_operator_ids' ; + $page_title = 'Temp Operator Payments' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + &schedule_payments_report_screen("temp_calibrator") ; + +} #------------------------------------------------------------------------------- + +sub screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# my $page = "$lcpage\s" ; + +my $page = "event-quotes" ; + +if ($s{no}) { $page = $lcpage ; } + +&common_min_table('id',$page,'list') ; + +our $savjqy = 1 ; + +# &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ; + +$extra_form_fields .= qq~ + + + +~; + +$print_box_content_rows .= &common_min_forms_end('','','save') if $count_outstanding ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +# sub screen4 { + +# &common_min_alert_type ; + +# print < +# +# + # + # $useropts{title} + # +# +# +# +# + +#
    +# +# +# +# +# +# +#
    + +# +# ENDOFTEXT +# # + +# exit ; + +# } #------------------------------------------------------------------------------------------ + +use common ; +use report ; +use xlsxcreator ; +use today ; +use schedule ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/temp_calibrator_report.pl b/scripts/_FromProd/v1.0/temp_calibrator_report.pl new file mode 100644 index 0000000..178ebdb --- /dev/null +++ b/scripts/_FromProd/v1.0/temp_calibrator_report.pl @@ -0,0 +1,498 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +# unless ($useropts{it}{$username}) { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; +use Time::Piece ; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $temp_calibrator_report = 1 ; + +# our $debug = 1 ; +# our $testing = 1 ; +# our $testing = ($username eq 'handre') ? 1 : 0 ; + +# if ($username ne 'handre') { + # print "<< MAINTENANCE IN PROGRESS >>" ; exit ; +# } + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $srchscr = 1 ; + +if ($iaction eq 'save') { + &db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &common_min_load_params ; + &report_ifields; + &update ; + &list_screen ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + exit if $username eq 'handre' && $testing ; + &screen3; + # &redirect_screen; +} + +# if ($iaction eq 'delete') { + # &db_open_upd ; + # our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + # &common_min_load_params ; + # &report_ifields; + # &list_screen ; + # &delete ; + # $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + # &db_close_conn ; + # exit if $username eq 'handre' && $testing ; + # &screen3; + # # &redirect_screen; +# } + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &report_screen if $iaction eq '' ; + + if ($iaction eq 'report') { + &common_min_load_params ; + &report_ifields; + &list_screen ; + &screen3; + } + + &common_min_action; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub hidden_fields { + + # $ignore{id} = 1 ; + $ignore{iaction} = 1 ; + $ignore{date} = 1 ; + $ignore{temp_calibrator_id} = 1 ; + for my $date_cnt (1 .. $date_counter) { + for (1 .. 4) { + $ignore{"shifttempcalibratorid_$_\_$date_cnt"} = 1 ; + $ignore{"shift_temp_calibrator_$_\_$date_cnt"} = 1 ; + } + } + # $ignore{temp_calibrator_ids} = 1 if $date_inp_val < $today_val ; + $ignore{update} = 1 ; + $ignore{update_table_1} = 1 ; + $ignore{"itv-table_length"} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + &schedule_update("shift_operator_ids","temp_calibrator_ids","shifttempcalibratorid","") ; + +} #------------------------------------------------------------------------------------------ + +# sub delete { + + # my %ii = %i ; + # %i = () ; + # foreach my $support_to_shift (split(/\|/,$db{$table_}{$ii{date}}{temp_calibrator_support_shifts})) { + # my @abc = split(/\:/,$support_to_shift) ; + # if ($abc[0] ne $ii{id}) { + # $i{temp_calibrator_support_shifts} .= qq~$support_to_shift|~ ; + # } + # } + # chop $i{temp_calibrator_support_shifts} if $i{temp_calibrator_support_shifts} ; + # &db_min_upd("$table_","`date`='$ii{date}'") ; + +# } #------------------------------------------------------------------------------------------ + +sub report_ifields { + + &load_search_vars ; + + # if ($i{date}) { # check dates + # push @report_sql, " `date_from` <= '$i{date} 23:59:59' AND '$i{date} 00:00:00' <= `date_to` " ; + # push @report_results, "DATE IS '$i{date}'" ; + # } else { + # $error = qq~PLEASE ENTER A DATE!~ ; + # &report_screen; + # } + + my $date_from_val = $i{date_from} ; my $date_to_val = $i{date_to} ; + + $date_from_val =~ s/\-//g ; $date_to_val =~ s/\-//g ; + + if ($i{date_from} && $i{date_to} && $date_from_val > $date_to_val) { + $error = qq~THE START MUST BE BEFORE THE END DATE!!!~ ; + &report_screen; + } elsif ($i{date_from} && $i{date_to}) { # check dates + push @report_sql, "(('$i{date_from} 00:00:00' <= `date_from` AND `date_from` <= '$i{date_to} 23:59:59') OR ('$i{date_from} 00:00:00' <= `date_to` AND `date_to` <= '$i{date_to} 23:59:59') OR (`date_from` <= '$i{date_from} 00:00:00' AND '$i{date_to} 23:59:59' <= `date_to`))" ; ############################################### > OR >= + push @report_results, "(EVENT BETWEEN '$i{date_from}' AND '$i{date_to}')" ; + } else { + $error = qq~PLEASE ENTER A START AND END DATE!!!~ ; + &report_screen; + } + + if ($i{temp_calibrator_id} and $i{temp_calibrator_id} ne 'all') { + push @report_results,"`TEMP CALIBRATOR` = '$db{users}{1}{name}'" ; + push @report_sql, " `temp_calibrator_ids` LIKE '%$i{temp_calibrator_id}%' " ; + } elsif ($i{temp_calibrator_id} and $i{temp_calibrator_id} eq 'all') { + push @report_results,"`TEMP CALIBRATORS` = 'ALL'" ; + } else { + # push @report_sql, "(`user_id` = '')" ; + } + + $report_results_msg = uc join(', ', @report_results) ; + + if ($iaction eq 'save') { + $isaved = qq(SUCCESSFULLY SAVED) ; + } elsif ($iaction eq 'delete') { + $isaved = qq(SUCCESSFULLY DELETED SUPPORT TEMP) ; + } elsif (not $report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); + &report_screen; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + + our $srch_where_sql = join(' AND ',@report_sql) ; + + # my @date = split(/ /,$i{date}) ; + + # my ($year_inp,$month_inp,$day_inp) = split(/\-/,$date[0]) ; + + # our $date_inp_val = int("$year_inp$month_inp$day_inp") ; + # our $today_val = int("$now_year$now_mm$now_dd") ; + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + if ($i{temp_calibrator_id} and $i{temp_calibrator_id} ne 'all') { + &db_min_ro('users','1,name',"`id` = '$i{temp_calibrator_id}'",'','') ; + } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + # $print_box_content_rows .= &common_min_forms_start("$lcpage") if $date_inp_val >= $today_val ; + + $print_box_content_rows .= &common_min_forms_start("$lcpage") ; + + &schedule_load_list_vars("$srch_where_sql") ; + + $fcol = 12 ; + + my $report = 1 ; + + our $xlsxdir = "temp_calibrator_report" ; + + our $xlsxreportname = "Temp_Calibrator_Allocations" ; + + my $date = &common_write_date_interval($i{date_from},$i{date_to}) ; + + our $xlsx_title_heading = "Temp Calibrator Allocations $date" ; + + # my $field_name = "shift_monitor" ; + # my $uc_field_name = ucfirst $field_name ; + + our $print_tbody_extra = qq~~ ; + + our @sql_col_display_extra = ("date","shift_1_(07:00-10:00)","shift_2_(10:00-13:00)","shift_3_(13:00-16:00)","shift_4_(16:00-19:00)") ; + # our @sql_col_display_extra = ("date","shift_1_(08:00-11:00)","shift_2_(11:00-14:00)","shift_3_(14:00-17:00)","shift_4_(17:00-21:00)") ; + push @sql_col_display_extra,"update" ; + # if $date_inp_val >= $today_val ; + + our @sql_col_display = ("count","event","date","day","start_date","start_time","end_time","venue","region","type","system","sport","operator") ; + + # push @sql_col_display,"update" if ($monitoring_report || $temp_calibrator_report) && $date_inp_val >= $today_val ; + + &report_xlsx_export_header("$xlsxreportname",$xlsxdir,'',$xlsx_title_heading) ; + + &schedule_build_extra_table("shift_temp_calibrator","shift_operator_ids","temp_calibrator_ids",'',"select_temp_calibrators") ; + + our @sql_col_display_2 = ("date","name","shift","update","") ; + + &schedule_build_extra_second_table("temp_support","shift_operator_ids","temp_calibrator_support_shifts") ; + + my $table_col_name = "temp_calibrator_ids" ; + + $xlsxrow-- ; + + &schedule_build_table("temp_calibrator_ids") ; + + # if ($date_inp_val >= $today_val) { + # $trigger_jquery_raw .= qq~ + # \$("#itv-table tr th:nth-last-child(5)").css("width","10%") ; + # \$("#itv-table tr th:nth-last-child(4)").css("width","10%") ; + # \$("#itv-table tr th:nth-last-child(3)").css("width","10%") ; + # \$("#itv-table tr th:nth-last-child(2)").css("width","10%") ; + # ~ ; + + # } else { + # $trigger_jquery_raw .= qq~ + # \$("#select_temp_calibrators tr th:nth-last-child(1)").css("width","23%") ; + # \$("#select_temp_calibrators tr th:nth-last-child(4)").css("width","23%") ; + # \$("#select_temp_calibrators tr th:nth-last-child(3)").css("width","23%") ; + # \$("#select_temp_calibrators tr th:nth-last-child(2)").css("width","23%") ; + # ~ ; + # } + + # &calibration_build_table_and_or_excel(1) ; + + # if ($found_after_date) { + + + + # } else { + # $trigger_jquery_raw .= qq~ + # \$("#itv-table tr th:nth-last-child(2)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(3)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(4)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(5)").css("width", "7.5%") ; + + # ~ ; + # } + + $fnsortorder = 'asc' ; + + &common_min_extra_crumb("$lcpage","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + # &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + our $lcpage = 'temp-calibrator-allocations' ; + + &common_page_name ; + + our $table = 'event_quotes' ; + $page_title = 'Temp Calibrator Allocations' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + my ($sql_next_day) = &common_add_delta_days(1) ; + my ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-$now_mm-$now_dd") ; #unless $i{date_from} ; + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$next_year-$next_month-$next_day") ; #unless $i{date_from} ; + + push @date_value_ids,"input[name='date_from']" ; + push @date_value_ids,"input[name='date_to']" ; + + &common_min_table_validate_date_inputs_jquery ; + + $preferred_title{temp_calibrator_id} = "Temp Calibrator" ; + + # &db_min_ro('users',"id,name","`user_type` = 'support' OR `user_type` = 'casual_calibrator'",'','') ; + # &db_min_ro('users',"id,name,username","`name` NOT LIKE 'Rory%'",'','') ; + + $selected{temp_calibrator_id}{all} = 'SELECTED' ; + + # if ($i{temp_calibrator_id}) { + # $selected{temp_calibrator_id}{$i{temp_calibrator_id}} = 'SELECTED' ; + # $selected{temp_calibrator_id}{all} = '' ; + # } + + # foreach (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + # next if $useropts{it}{$db{users}{$_}{username}} ; + # $opts{temp_calibrator_id} .= qq~~ ; + # } + $opts{temp_calibrator_id} .= qq~~ ; + + $print_box_content_rows .= &common_min_form_select('temp_calibrator_id','') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# my $page = "$lcpage\s" ; + +my $page = "temp-calibratortest-report" ; + +if ($s{no}) { $page = $lcpage ; } + +# &db_min_ro('daily_monitor_ids','date,monitor_ids') ; + +my @sql_col_display_22 = @sql_col_display ; + +@sql_col_display = @sql_col_display_extra ; + +&common_min_thead ; + +# &common_min_thead_2 ; + +# $db{shift_operator_ids}{$i{date}}{temp_calibrator_support_shifts} .= "||" ; + + +# style="padding-bottom:10px;margin-left:10px;" + +# alter table `shift_operator_ids` add column `temp_calibrator_support_shifts` varchar(255) default null +$print_box_content_rows .= qq~ + + $print_thead + + + $print_tbody_extra + + +
    + $print_tbody_extra_2 + ~ ; + + # + # $print_thead_2 + # + # $print_tbody_extra_2 + # + #
    + # $plus_button + + +@sql_col_display = @sql_col_display_22 ; + +&common_min_thead ; + +&common_min_table('id',$page,'list') ; + +our $savjqy = 1 ; + +$extra_form_fields .= qq~ + + + +~; + +for (1 .. $date_cnt) { + + $extra_form_fields .= qq~ + + + + + ~; + +} + +# $print_box_content_rows .= &common_min_forms_end('','','save') if $date_inp_val >= $today_val ; +$print_box_content_rows .= &common_min_forms_end('','','save') ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_thead_2 { + + my $colspan = scalar @sql_col_display_2 ; + + $print_thead_2 = qq(TEMP SUPPORT) ; # + + foreach (@sql_col_display_2) { + my $coltitle = $_ ; $coltitle =~ s/\_id//g ; $coltitle =~ s/\_/ /g ; $coltitle = uc $coltitle ; $coltitle = $replace_blank_table_top_right if $coltitle eq '' and $replace_blank_table_top_right ; + $print_thead_2 .= qq($coltitle); + } + + # if ($add_th_row) { $print_thead_2 .= $add_th_row ; } # used in agent_commission_report.pl and cruiseline_commission_report.pl + + $print_thead_2 .= qq() ; + +} #------------------------------------------------------------------------------- + + +sub redirect_screen { + +&common_min_alert_type ; + +print < + + + + $useropts{title} + + + + + + +
    + + + + + +
    + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +use common ; +use report ; +use xlsxcreator ; +use today ; +# use calibration_test ; +use schedule ; +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/tickets.pl b/scripts/_FromProd/v1.0/tickets.pl new file mode 100644 index 0000000..8aa31c5 --- /dev/null +++ b/scripts/_FromProd/v1.0/tickets.pl @@ -0,0 +1,784 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); +use Date::Calc qw(:all); + +require cfg ; + +print header; # CGI.pm method + +# unless ($useropts{admin}{$userid} eq $username) { require '401.pm' ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +&common_min_debug ("action [$action]") ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + if ($action eq 'assign'){ + &common_min_load_params ; + &update ; + %i = () ; # clear so the list loads + # exit; + &common_min_screen2; + } + + &common_min_action; + + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + + # my $exists = '' ; + + # $i{ref} = uc $i{ref} ; + + # &db_min_ro($table,'*',"`ref`='$i{ref}'",'ref','') ; + + # foreach my $id (keys %{$db{$table}}) { if ($db{$table}{$id}{ref} eq $i{ref}) { $exists = 1 ; } } + + # if ($exists) { $alert = &common_min_alert('warning',"$ucpage ALREADY EXISTS!",'ok') ; %col_name = (); &common_add_screen; &common_screen1; } + +} #------------------------------------------------------------------------------------------ + +# sub insert { + + # &add_db_fields ; + + # # $i{date_created} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + + # &db_min_insert($table) ; + +# } #------------------------------------------------------------------------------------------ + +sub update { + + &common_min_debug ("update [$i{completed}] id=$i{id}") ; + + unless ($i{id}) { $error = qq(NO ID) ; return ; } + + &edit_db_fields ; + + # unless ($i{camera_id}) { $i{camera_id} = '0' ; } + unless ($i{completed}) { $i{completed} = '0' ; } + if ($i{staff_id}) { $i{assign_date} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; } else { $ignore{assign_date} = 1 ; } + unless ($i{completed}) { $ignore{action_time} = 1 ; } + + &process_camera_ids; + + # if ($i{completed} == 1) { + if ($iaction eq 'completed') { + &update_open_closed ; + } else { + &db_min_upd($table,"id='$i{id}'") ; + } + +} #------------------------------------------------------------------------------------------ + +sub process_camera_ids { + +local @cameraids = split(/\,/,$i{cameraids}) ; + +my $cameraids = join(",",@cameraids) ; + +$cameraids =~ s/\s//g; # remove white space + +$ignore{cameraids} = 1 ; +$i{camera_ids} = $cameraids ; + +} #------------------------------------------------------------------------------------------ + +sub update_open_closed { + + my $upd_id = $i{id} ; + my $upd_uid = $i{unique_id} ; + my $upd_suid = $i{suid} ; + my $from = $i{sent_from} ; + my $completed = $i{completed} ; + + %i = () ; + $i{id} = $upd_id ; + + if ($completed == 1) { + $i{completed} = 1 ; + $i{action_time} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + } else { + $success = qq~`$upd_uid` OPENED~ ; + $i{completed} = '0' ; + } + + &db_min_upd($table,"id='$i{id}' OR suid='$upd_uid' OR unique_id='$upd_uid' OR suid='$upd_suid' OR unique_id='$upd_suid'") ; + + if ($completed == 1) { + &auto_send_close_email if $from ; + $success = qq~`$upd_uid` CLOSED~ ; + $success .= qq~ and email sent to $from~ if $from ; + } else { + $success = qq~`$upd_uid` OPENED~ ; + } + + # exit; + +} #------------------------------------------------------------------------------------------ + +sub auto_send_close_email { + +my $remsg = qq~Hello, + +Your ticket $i{unique_id} has now been closed. + +Do not hesitate to contact us should you need additional assistance. + +Best regards, + +The ITV Africa Team~ ; + +&common_send_mail("$i{sent_from}",'','','','',"$remsg","$i{subject}") ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + local $surl = qq~javascript:dlgMdl('$useropts{scripts}/dialog/read_ticket.pl~; + + &load_db_vars ; + + # our @sql_col_display = ("ref","unique_id","sent_date","subject","sent_from","priority_id","staff_id","client_id","camera_id","camera_system_id","serial_nr","part_nr","") ; + our @sql_col_display = ("ref","unique_id","sent_date","subject","sent_from","priority_id","staff_id","client_id","camera_nr","quote_nr","") ; + + my $sql_where = $iaction eq 'closed' ? "completed = '1'" : "completed = '0'" ; + + $sql_where .= (!$useropts{super}{$username} && !$useropts{boss}{$username} && !$useropts{it}{$username} && !$useropts{tickets}{$username}) ? " AND staff_id = '$userid'" : '' ; + + &db_min_ro($table,'*',$sql_where,'','') ; + + foreach my $id (sort {$a <=> $b} keys %{$db{$table}}) { + + my $uid = $db{$table}{$id}{unique_id} ; + my $responded = $db{$table}{$id}{responded} ; + + my $date_time = $db{$table}{$id}{date_time} ; + my $subject = $db{$table}{$id}{subject} ; + my $camera_ids = $db{$table}{$id}{camera_ids} ; + my $priority_id = $db{$table}{$id}{priority_id} ; + my $staff_id = $db{$table}{$id}{staff_id} ; + my $client_id = $db{$table}{$id}{client_id} ; + my $sent_from = $db{$table}{$id}{sent_from} ; + + my @hash_split = split /\#\#/, $subject ; + my @subj_uid = split / /, $hash_split[1] ; + # my $suid = ($subj_uid[0]) ? $subj_uid[0] : $uid ; + my $suid = $subj_uid[0] ; + + $open_ticket{$suid} = $has_responce{$suid} ; + $open_cameras{$suid} = $has_camera_ids{$suid} ; + $open_client{$suid} = $has_client_id{$suid} ; + $open_staff{$suid} = $has_staff_id{$suid} ; + $open_priority{$suid} = $has_priority_id{$suid} ; + $open_sent_from{$suid} = $has_sent_from{$suid} ; + + $has_sent_from{$uid} = &get_from($sent_from) ; + $has_responce{$uid} = $responded ; + $has_camera_ids{$uid} = $camera_ids ; + $has_client_id{$uid} = $client_id ; + $has_staff_id{$uid} = $staff_id ; + $has_priority_id{$uid} = $priority_id ; + + &common_min_debug ("[open=$open_ticket{$suid}] [$uid] [$suid] [$subject]") ; + + if ($responded && $client_id && !$suid) { $suid = $uid ; } + + $cnt{$suid}++ ; + + next unless $responded ; + + $link_previous{$suid} .= qq~ [$cnt{$suid}]~ ; + + } + + # &common_min_debug ("action [$action]") ; + + foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) { + + my $uid = $db{$table}{$id}{unique_id} ; + my $completed = $db{$table}{$id}{completed} ; + my $responded = $db{$table}{$id}{responded} ; + my $sent_from = $db{$table}{$id}{sent_from} ; + my $date_time = $db{$table}{$id}{date_time} ; + my $client_id = $db{$table}{$id}{client_id} ; + my $staff_id = $db{$table}{$id}{staff_id} ; + my $priority_id = $db{$table}{$id}{priority_id} ; + my $s_uid = $db{$table}{$id}{suid} ; + + next if $responded && ($iaction eq 'list' || $iaction eq 'active') ; + # next if $s_uid && $iaction eq 'open' ; + next if $got_open_ticket{$s_uid} && $iaction eq 'open' && $s_uid ne '0' ; $got_open_ticket{$s_uid} = 1 ; $got_open_ticket{$uid} = 1 ; + next if $got_closed_ticket{$s_uid} && $iaction eq 'closed' && $s_uid ne '0' ; $got_closed_ticket{$s_uid} = 1 ; $got_closed_ticket{$uid} = 1 ; + + # &common_min_debug ("got_open_ticket [$s_uid] $uid [$iaction]") ; + + my $subject = $db{$table}{$id}{subject} ; + + # my @hash_split = split /\#/, $subject ; + # my $sub_uid = ($hash_split[1]) ? $hash_split[1] : $uid ; + + my @hash_split = split /\#\#/, $subject ; + my @subj_uid = split / /, $hash_split[1] ; + my $suid = ($subj_uid[0]) ? $subj_uid[0] : $uid ; $got_open_ticket{$suid} = 1 ; $got_closed_ticket{$suid} = 1 ; + + $sent_from{$uid} = &get_from($sent_from) ; + + # my @from_array = split /\//g; $sent_from{$uid} = $from_email ; + + # &common_min_debug ("$id. sub_uid=$sub_uid [$uid]") ; + + # if ($responded) { + # $link_previous{$sub_uid} .= qq~ $surl?uniqueid=$uid&subject=$subject&from=$sent_from{$uid}','$val [$uid] $clientname{$client_id}','','max-dialog');" data-toggle="tooltip" data-placement="top" data-title="Read ticket">[$sub_uid]~ ; + # next ; + # } + + $print_tbody .= qq~~ ; + + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$table}{$id}{$_} ; + # if ($_ eq 'rate_id') { $val = $rate{$db{$table}{$id}{$_}} ; } + + $align = qq~class="dt-center"~ ; + + if ($_ eq 'staff_id') { $val = ($val > 0) ? "$staffname{$val}" : ($open_staff{$suid}) ? "$staffname{$open_staff{$suid}}" : ($completed) ? '' : &load_links('staff',$id,$suid) ; } + if ($_ eq 'client_id') { $val = ($val > 0) ? "$clientname{$val}" : ($open_client{$suid}) ? "$clientname{$open_client{$suid}}" : ($completed) ? '' : &load_links('customers',$id,$suid) ; } + if ($_ eq 'priority_id') { $val = ($val > 0) ? "$priorityname{$val}" : ($open_priority{$suid}) ? "$priorityname{$open_priority{$suid}}" : ($completed) ? '' : &load_links('priority',$id,$suid) ; } + + if ($_ eq 'camera_nr' || $_ eq 'quote_nr') { + my @camera_ids = ($db{$table}{$id}{camera_ids}) ? split(/\,/,$db{$table}{$id}{camera_ids}) : ($open_cameras{$suid}) ? split(/\,/,$open_cameras{$suid}) : () ; + $val = '' ; + + foreach my $cam_id (@camera_ids) { + &common_debug("$_ : cam_id [$cam_id] : $camera_quote_nr{$cam_id}") ; + if ($_ eq 'quote_nr') { + $val = &common_camera_links($tables,$cam_id,$camera_quote_nr{$cam_id}) if $pixellot_limit{$username}!=1 and $events_limit{$username}!=1 ; + next if $done_quote{$camera_quote_nr{$cam_id}} ; $done_quote{$camera_quote_nr{$cam_id}} ; + } elsif ($_ eq 'camera_nr') { + # my $tt_txt = qq~Camera System:$camera_system_id{$cam_id}
    Serial Nr:$camera_serial_nr{$cam_id}
    ~ ; + my $tt_txt = qq~Camera System:$camera_system_id{$cam_id}
    Camera Nr:$camera_nr{$cam_id}
    ~ ; + $tt_txt .= ($camera_part_nr{$cam_id}) ? qq~Part Nr:$camera_part_nr{$cam_id}
    ~ : qq~Part Nr: n/a
    ~ ; + $tt_txt .= ($camera_sport_type{$cam_id}) ? qq~Sport Type:$camera_sport_type{$cam_id}
    ~ : qq~Sport Type: n/a
    ~ ; + our $tooltip = qq~data-toggle="tooltip" data-placement="top" data-title="$tt_txt"~ ; + $val .= &common_camera_links($tables,$cam_id,$camera_serial_nr{$cam_id}) . ' ' if $pixellot_limit{$username}!=1 and $events_limit{$username}!=1 ; + $tooltip = '' ; + # $val .= ($cam_id > 0) ? "$camera_nr{$cam_id} " : '' ; + } # elsif ($_ eq 'sport_type_id') { + # $val .= $camera_sport_type{$cam_id} ; + # } + } + # $val = ($val > 0) ? "$camera_nr{$val}" : ($open_cameras{$suid}) ? "$camera_nr{$open_cameras{$suid}}" : '' ; + } + + # if ($_ eq 'camera_system_id') { $val = ($val > 0) ? "$camera_system_id{$val}" : ($open_cameras{$suid}) ? "$camera_system_id{$open_cameras{$suid}}" : '' ; } + # if ($_ eq 'serial_nr') { $val = ($val > 0) ? "$camera_serial_nr{$val}" : ($open_cameras{$suid}) ? "$camera_serial_nr{$open_cameras{$suid}}" : '' ; } + # if ($_ eq 'part_nr') { $val = ($val > 0) ? "$camera_part_nr{$val}" : ($open_cameras{$suid}) ? "$camera_part_nr{$open_cameras{$suid}}" : '' ; } + if ($_ eq 'sent_from') { $val = ($open_sent_from{$suid}) ? $open_sent_from{$suid} : $sent_from{$uid} ; } # strip off the > character + # if ($_ eq 'subject') { $val = qq~$val~; $align = '' ; } + # if ($_ eq 'subject') { $val = '$val $link_previous{$suid}~; $align = '' ; } + if ($_ eq 'subject') { $val = (!$completed && ($client_id || $open_client{$suid}) && ($staff_id || $open_staff{$suid}) && ($priority_id || $open_priority{$suid})) ? '$val ~ : '$val ~ ; $align = '' ; } + if ($_ eq 'ref') { $val = $id ; } + + + + + $print_tbody .= qq~$val~ ; + } + + $print_tbody .= qq~ ~; + + my $tooltip_start = qq~data-toggle="tooltip" data-placement="top"~ ; + + if (!$completed && ($client_id || $open_client{$suid}) && ($staff_id || $open_staff{$suid}) && ($priority_id || $open_priority{$suid})) { + $print_tbody .= qq~ ~; + } + + unless ($completed || $link_previous{$suid}) { + $print_tbody .= qq~ +   + ~; + } + + $print_tbody .= &load_links('completed',$id,$suid) ; + + if (!$completed && !$link_previous{$suid} && ($useropts{it}{$username} || $useropts{boss}{$username})) { + $print_tbody .= qq~ +   + ~; + } + + # $print_tbody .= qq~ ~; + + #   + + $print_tbody .= qq~~ ; + + $print_tbody .= qq~~ ; + } + + &build_jquery ; + + $box_icon .= qq~~ if $opentickets > 0 ; + + # &common_min_extra_crumb("closed-$table","Closed $page_title") unless $iaction eq 'closed' ; + # &common_min_extra_crumb("open-$table","Open $page_title") unless $iaction eq 'open' ; + &common_min_extra_crumb("active-$table","Active $page_title") unless $iaction eq 'list' || $iaction eq 'active' ; + +} #------------------------------------------------------------------------------------------ + +sub get_from { + + my ($sfrom) = @_ ; + + @from_array = split /\//g; + + return ($from_email) ; + +} #------------------------------------------------------------------------------------------ + +sub load_db_vars { + + # local $last_year = $now_year - 1 ; + + my ($sql_back_ccyy_mm_dd) = &common_add_delta_days(-90) ; + + # &db_min_ro('quotes','DISTINCT quote_to',"quote_date >= '$last_year-06-01'",'','') ; + &db_min_ro('quotes','DISTINCT quote_to',"quote_date >= '$sql_back_ccyy_mm_dd' AND quote_to <> 1",'','') ; + # &db_min_ro('quotes','DISTINCT quote_to','','quote_date DESC',10) ; + + foreach my $clid (keys %{$db{quotes}}) { + $display_client{$clid} = 1 ; + } + + &db_min_ro('quotes','DISTINCT user_id',"quote_date >= '$sql_back_ccyy_mm_dd'",'','') ; + # &db_min_ro('quotes','DISTINCT user_id','','quote_date DESC',10) ; + + foreach my $uid (keys %{$db{quotes}}) { + $display_user{$uid} = 1 ; + } + + # &db_min_ro('quotes','DISTINCT user_id',"quote_date >= '$sql_back_ccyy_mm_dd'",'','') ; + + # foreach my $uid (keys %{$db{quotes}}) { + # $display_user{$uid} = 1 ; + # } + + &db_min_ro('users','id,username','','','') ; + foreach my $id (keys %{$db{users}}) { + $staffname{$id} = $db{users}{$id}{username} ; + } + + &db_min_ro('customers','id,name',"active = '1'",'','') ; + foreach my $id (keys %{$db{customers}}) { + # &common_min_debug ("load_db_vars customers [clientid=$id] display_client=$db{customers}{$id}{name}") ; + $clientname{$id} = $db{customers}{$id}{name} ; + } + + &db_min_ro('priority','id,name,colour','','','') ; + foreach my $id (keys %{$db{priority}}) { + $priorityname{$id} = $db{priority}{$id}{name} ; + $prioritycolour{$id} = $db{priority}{$id}{colour} ; + } + + &db_min_ro('sport_types','*','','','') ; + foreach my $id (keys %{$db{sport_types}}) { + $sport_type_name{$id} = $db{sport_types}{$id}{name} ; + } + + my $t1 = 'cameras' ; + my $t2 = 'camera_systems' ; + our $tables = "$t1,$t2" ; + + &db_min_ro($tables,"$t1.id,$t1.camera_nr,$t1.serial_nr,$t1.part_number,$t1.camera_system_id,$t1.quote_nr,$t1.sport_type_ids,$t2.name AS 'camera_system_name',$t2.description AS 'camera_system_desc'","$t1.camera_system_id = $t2.id",'','') ; + + foreach my $id (keys %{$db{$tables}}) { + # $camera_nr{$id} = "$db{cameras}{$id}{camera_nr} [$db{cameras}{$id}{serial_nr}]" ; + $camera_nr{$id} = $db{$tables}{$id}{camera_nr} ; + $camera_serial_nr{$id} = $db{$tables}{$id}{serial_nr} ; + $camera_part_nr{$id} = $db{$tables}{$id}{part_number} ; + $camera_system_id{$id} = $db{$tables}{$id}{camera_system_desc} ; + $camera_quote_nr{$id} = $db{$tables}{$id}{quote_nr} ; + # $camera_sport_type{$id} = $sport_type_name{$db{$tables}{$id}{sport_type_id}} ; + + my @sport_type_ids = split(/\,/,$db{$tables}{$id}{sport_type_ids}); + + foreach (@sport_type_ids) { + $camera_sport_type{$id} .= ($camera_sport_type{$id}) ? ", $sport_type_name{$_}" : $sport_type_name{$_} ; + } + } + + my $xtra_sql_where = (!$useropts{super}{$username} && !$useropts{boss}{$username} && !$useropts{it}{$username} && !$useropts{tickets}{$username}) ? " AND staff_id = '$userid'" : '' ; + # my $xtra_sql_where = " AND staff_id = '$userid'" ; + + # &db_min_ro('tickets','DISTINCT suid',"completed = '0'",'','') ; + &db_min_ro($table,'*',"completed = '0'",'','') ; + + our $opentickets = 0 ; + + foreach (keys %{$db{$table}}) { + my @hash_split = split /\#\#/, $db{$table}{$_}{subject} ; + my @subj_uid = split / /, $hash_split[1] ; + my $suid = ($subj_uid[0]) ? $subj_uid[0] : ($db{$table}{$_}{suid}) ? $db{$table}{$_}{suid} : $db{$table}{$_}{unique_id} ; + + next if $check_open_ticket{$suid} ; + $opentickets++ ; + $check_open_ticket{$suid} = 1 ; + } + + &common_load_quote_vars("cameras.quote_nr>0 AND cameras.quote_nr=quotes.quote_nr"); + +} #------------------------------------------------------------------------------------------ + +sub load_links { + + local ($type,$id,$suid) = @_ ; + + local $links = '' ; + + # return('') unless $useropts{admin}{$userid} ; + + # &common_min_debug ("load_links [$type,$id]") ; + + local $cnt = 0 ; + + if ($type eq 'staff') { + foreach my $staffid (keys %{$db{users}}) { + next if $useropts{it}{$staffname{$staffid}} ; + next unless $display_user{$staffid} ; + my $department_id = $db{users}{$staffid}{department_id} ; + my $initial = uc substr($staffname{$staffid},0,1) ; + next if $department_id==2 || $department_id==2 ; # accounts + $cnt++ ; + $links .= qq~[$initial] ~ ; + last if $cnt>=5 ; + } + } + + if ($type eq 'customers') { + foreach my $clientid (keys %{$db{customers}}) { + # &common_min_debug ("load_links customers [clientid=$clientid] display_client=$display_client{$clientid}") ; + next unless $display_client{$clientid} ; + # my $ref_init = uc substr($db{customers}{$clientid}{ref},0,3) ; + my $ref_init = uc substr($clientname{$clientid},0,3) ; + + # &common_min_debug ("load_links customers [clientid=$clientid] display_client=$display_client{$clientid}") ; + + $cnt++ ; + $links .= qq~[$ref_init] ~ ; + last if $cnt>=5 ; + } + } + + if ($type eq 'priority') { + foreach my $priorityid (sort keys %{$db{priority}}) { + my $priority_init = uc substr($db{priority}{$priorityid}{name},0,1) ; + $links .= qq~[$priority_init] ~ ; + } + } + + if ($type eq 'completed') { + my $completed = $db{$table}{$id}{completed} ; + my $openclose = ($completed) ? 0 : 1 ; + # my $color = ($completed) ? 'green' : 'red' ; + # my $color = ($completed) ? 'success' : 'danger' ; + my $color = ($completed) ? 'success' : 'warning' ; + my $text = ($completed) ? 'Open' : 'Close' ; + # my $glyph = ($completed) ? 'ok-circle' : 'remove-circle' ; + # my $glyph = ($completed) ? 'eye-open' : 'eye-close' ; + # my $glyph = ($completed) ? 'tags' : 'tags' ; + # $links .= qq~[$text] ~ ; + $links .= qq~ ~ ; + } + + return ($links) ; + +} #------------------------------------------------------------------------------------------ + +sub build_jquery { + + $trigger_jquery_raw .= qq~ + function saveStaff(uniqueid,staffid,id) + { + document.staffform.unique_id.value = uniqueid ; + document.staffform.staff_id.value = staffid ; + document.staffform.id.value = id ; + \$('#staff-form').submit(); + } + function saveClient(uniqueid,clientid,id) + { + document.clientform.unique_id.value = uniqueid ; + document.clientform.client_id.value = clientid ; + document.clientform.id.value = id ; + \$('#client-form').submit(); + } + function savePriority(uniqueid,priorityid,id) + { + document.priorityform.unique_id.value = uniqueid ; + document.priorityform.priority_id.value = priorityid ; + document.priorityform.id.value = id ; + \$('#priority-form').submit(); + } + function setOpenClose(uniqueid,openclose,id,sent_from,suid) + { + document.completedform.unique_id.value = uniqueid ; + document.completedform.completed.value = openclose ; + document.completedform.sent_from.value = sent_from ; + document.completedform.suid.value = suid ; + document.completedform.id.value = id ; + \$('#completed-form').submit(); + } + ~; + + $print_footer_forms .= qq~ +
    + + + + +
    +
    + + + + +
    +
    + + + + +
    +
    + + + + + + +
    + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + +&common_min_thead ; + +} #------------------------------------------------------------------------------- + +# sub add_db_fields { + +# &hidden_fields ; + +# $ignore{id} = 1 ; + +# } #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + +&sort_fields; + +&hidden_fields ; + +} #------------------------------------------------------------------------------------------ + +sub hidden_fields { + +$ignore{iaction} = 1 ; +$ignore{date_time} = 1 ; +$ignore{mailtype} = 1 ; +$ignore{doctype} = 1 ; +$ignore{cc} = 1 ; +$ignore{bcc} = 1 ; +$ignore{responded} = 1 ; + +$hidden{id} = 1 ; +$hidden{unique_id} = 1 ; +$hidden{suid} = 2 ; +$hidden{assign_date} = 2 ; +$hidden{completed} = 2 ; +$hidden{action_time} = 2 ; + +$preferred_title{id} = 'Ref' ; + +$readonly{sent_from} = 'READONLY' ; +$readonly{sent_to} = 'READONLY' ; +$readonly{reply_to} = 'READONLY' ; +$readonly{subject} = 'READONLY' ; +$readonly{unique_id} = 'READONLY' ; +$readonly{sent_date} = 'READONLY' ; +$readonly{assign_date} = 'READONLY' ; +$readonly{id} = 'READONLY' ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + +%sort_field = () ; + +$sort_field{1} = 'client_id' ; +$sort_field{2} = 'camera_ids' ; $preferred_title{camera_ids} = 'Cameras' ; +$sort_field{3} = 'priority_id' ; +$sort_field{4} = 'staff_id' ; +$sort_field{5} = 'sent_date' ; +$sort_field{6} = 'sent_from' ; +$sort_field{7} = 'reply_to' ; +$sort_field{8} = 'sent_to' ; +$sort_field{9} = 'subject' ; + +} #------------------------------------------------------------------------------- + +# sub add_screen { + +# # called from common_add_screen + +# &select_opts('') ; + +# } #------------------------------------------------------------------------------------------ + +sub edit_screen { + +# called from common_edit_screen + +&select_opts($i{id}) ; + +$custom_back_button = qq~ ~ ; + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + + my ($id) = @_ ; + + # $selected{contact_title}{$db{$table}{$id}{contact_title}} = 'SELECTED' ; + # $select{contact_title} = 1 ; + # $opts{contact_title} = qq() ; + + $opts{staff_id} = qq~~ ; + $opts{client_id} = qq~~ ; + # $opts{camera_ids} = qq~~ ; + + # &common_min_select_opts('staff_id','users','username',$db{$table}{$id}{staff_id},1) ; + &common_min_select_opts('staff_id','users','username',$db{$table}{$id}{staff_id},1,,'',"user_type NOT LIKE 'casual%' AND block <> 1 AND inactive <> 1") ; + &common_min_select_opts('client_id','customers','name',$db{$table}{$id}{client_id},1) ; + &common_min_select_opts('priority_id','priority','name',$db{$table}{$id}{priority_id},1) ; + + &common_load_quote_vars("quotes.quote_to='$db{$table}{$id}{client_id}'"); + + $select{camera_ids} = 1 ; + $multiple{camera_ids} = 1; + # $setmultiple = 'multiple' ; + + my @camera_ids = split(/\,/,$db{$table}{$id}{camera_ids}); + + foreach (@camera_ids) { + $selected_multi{$_} = 'SELECTED' ; + &common_debug("SELECTED camera_ids [$_] : [selected=$selected_multi{$_}]") ; + } + + foreach my $cam_id (keys %quote_customer) { + next if $gotit{$cam_id} ; + # $selected = ($cam_id eq $db{$table}{$id}{camera_ids}) ? 'SELECTED' : '' ; + $selected = ($selected_multi{$cam_id}) ? 'SELECTED' : '' ; + my $cam_txt = qq~$quote_camera_camera_nr{$cam_id} [$quote_camera_serial_nr{$cam_id}]~ ; $cam_txt =~ s/\-/ /g ; # $cam_txt =~ s/ //g ; + $cam_txt .= qq~ $quote_nr{$cam_id}~ if $quote_nr{$cam_id} ; + $opts{camera_ids} .= qq~~ ; + $gotit{$cam_id} = 1 ; + } + + # &common_min_select_opts('camera_ids','cameras','camera_nr',$i{camera_ids},1,'serial_nr',"quote_nr>0") ; + + $extra_form_fields .= qq~~; + + $trigger_jquery_raw .= qq( + \$("#selectClient_id").change(function() { + var cid = \$("#selectCamera_ids") ; + cid.empty(); // remove old options + cid.trigger("chosen:updated"); + var url = "$useropts{scripts}/get/get_db_cameras.pl?clientid=" + \$("#selectClient_id").val() ; + \$.get(url, function(json) { + \$.each(json, function(key, data) { + let txt = '' ; + if (data.camera_nr) { txt = data.camera_nr ; } + if (data.serial_nr) { txt = txt + " [" + data.serial_nr + "]" ; } + txt = txt.replace(/-/g, " "); + cid.append(""); + cid.trigger("chosen:updated"); + }); + }, + 'json'); + }); + ); + + $trigger_jquery_raw .= qq~ + \$("#savebutt").click(function() { + let msg_x = '' ; + let sc_val = \$("#selectCamera_ids").chosen().val() ; + \$('#camera-ids').val(sc_val); + \$('#tickets-form').submit(); + });~; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'envelope' ; +our $lcpage = 'ticket' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; our $page_title = $ucfirstpage . 's' ; +our $table = 'tickets' ; + +our $redirsave = 'active' ; +our $savjqy = 1 ; # incorporate jquery into the save event to accommodate the multiple chosen options + +$alert = qq~
    ~ ; + +$box_icon .= qq~
    ~ ; +# $box_icon .= qq~
    ~ ; +# $box_icon .= qq~
    ~ ; +$box_icon .= qq~
    ~ ; +$box_icon .= qq~
    ~ ; + +# &common_add_box_icon ; + +# $useropts{'common'}{'css'} .= qq~.top-block i {font-size: 12px;}~ ; +# $useropts{'common'}{'css'} .= qq~.box-icon .glyphicons::before { padding: 0px; }~ ; + +} #------------------------------------------------------------------------------- + +use db ; +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/towns.pl b/scripts/_FromProd/v1.0/towns.pl new file mode 100644 index 0000000..7dc39e5 --- /dev/null +++ b/scripts/_FromProd/v1.0/towns.pl @@ -0,0 +1,255 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use DBI; +use CGI; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +$iaction = $q -> param('iaction') || $action ; +$itownid = $q -> param('itownid') || '' ; +$isaved = $q -> param('isaved') || '' ; +$itype = $q -> param("itype") || '' ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +&today; + +if ($iaction eq ''){ + &db_get_town_opts ; + &screen4; + } + +if ($iaction eq 'add'){ + &add_screen; + &screen1; + } + +if ($iaction eq 'list'){ + &list_screen ; + &screen3; + } + +if ($iaction eq 'edit'){ + &load_screen ; + &edit_screen; + &screen1; + } + +if ($iaction eq 'save'){ + &common_load_params ; + &check_towns ; + &insert_town ; + &screen2; + } + +if ($iaction eq 'update'){ + &common_load_params ; + &update_town ; + &load_screen ; + &edit_screen; + &screen2; + } + +exit; + +#------------------------------------------------------------------------------------------ + +sub check_towns { + +my $exists = &db_check_town($i{town}) ; + +if ($exists) { + $alert = qq() ; + &edit_screen; + &screen1; + } + +} #------------------------------------------------------------------------------------------ + +sub insert_town { + +&db_insert_town ; + +$itownid = $new_town_id ; + +} #------------------------------------------------------------------------------------------ + +sub update_town { + +unless ($itownid) { return ; } + +&db_open_upd ; + +# $sql = qq(UPDATE towns SET +# town = "$i{town}", +# hub = "$i{hub}", +# acchubcode = "$i{acchubcode}", +# opshubcode = "$i{opshubcode}", +# airportcode = "$i{airportcode}" +# WHERE townid = "$itownid") ; + +$sql = qq(UPDATE towns SET +town = "$i{town}", +airportcode = "$i{airportcode}" +WHERE townid = "$itownid") ; + +&common_debug($sql) ; + +$sth = $dbh -> do ($sql) or die "could not execute :
    $sql
    $!" ; + +&db_close_conn ; + +$success = qq(SUCCESSFULLY SAVED) ; + +} #------------------------------------------------------------------------------------------ + +sub get_opts { + +&db_get_airport_opts ; +# &db_load_town_hubs ; +# &db_load_town_acchubcode ; +# &db_load_town_opshubcode ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +&db_get_airport_opts ; +&db_town_list ; +&extra_crumb ; + +$trigger_jquery = qq(var oTable = \$('#tnlist').dataTable(); oTable.fnSort( [ [1,'asc'] ] );) ; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + +&get_opts ; +$box_header_title = 'Add Town' ; +$hidden_action = 'save' ; +$head_col_width = 1 ; +&extra_crumb ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + +$box_header_title = 'Edit Town : ' . $tn_town ; +$hidden_action = 'update' ; +$head_col_width = 1 ; +&extra_crumb ; + +} #------------------------------------------------------------------------------------------ + +sub extra_crumb { + +$insert_crumbs = qq(
  • Manage Towns
  • ) ; + +&config_set_breadcrumbs ; + +} #------------------------------------------------------------------------------------------ + +sub load_screen { + +unless ($itownid) { $warning = qq(NO TOWN ID) ; return ; } + +&db_load_town($itownid) ; +&get_opts ; + +$trigger_jquery_raw .= qq(\$("#selectAirPort").val("$tn_airportcode").trigger('change');) ; +# $trigger_jquery_raw .= qq(\$("#selectHUB").val("$tn_hub").trigger('change');) ; +# $trigger_jquery_raw .= qq(\$("#selectAccHubCode").val("$tn_acchubcode").trigger('change');) ; +# $trigger_jquery_raw .= qq(\$("#selectOpsHubCode").val("$tn_opshubcode").trigger('change');) ; + +} #------------------------------------------------------------------------------------------ + +sub screen1 { + +$screen_buttons = qq(
     
     
    ) ; + +&common_town_html ; + +if ($error) { + $alert = qq() ; + } +elsif ($warning) { + $alert = qq() ; + } +elsif ($success) { + $alert = qq() ; + } + +unless ($print_town) { $trigger_jquery .= qq(\$("#towntable").hide();) ; } + +require tn_edit ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + +print < + + + + Film Freight Admin + + + + + + +
    + + + +
    + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub screen3 { + +if ($isaved) { $alert = qq() ; } + +require tn_list ; +exit ; + +} #------------------------------------------------------------------------------------------ + +sub screen4 { + +require tn_main ; +exit ; + +} #------------------------------------------------------------------------------------------ + +use db ; +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/troubleshoot_monitor_payments_report.pl b/scripts/_FromProd/v1.0/troubleshoot_monitor_payments_report.pl new file mode 100644 index 0000000..f8626d3 --- /dev/null +++ b/scripts/_FromProd/v1.0/troubleshoot_monitor_payments_report.pl @@ -0,0 +1,189 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +# unless ($useropts{it}{$username}) { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $srchscr = 1 ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &report_screen if $iaction eq '' ; + + if ($iaction eq 'report') { + &common_min_load_params ; + &report_ifields; + &list_screen ; + &screen3; + } + + if ($iaction eq 'save') { + &common_min_load_params ; + &update ; + &report_ifields; + &list_screen ; + &screen3; + } + + &common_min_action; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub update { + + &schedule_payments_update("troubleshoot_monitor") ; + +} #------------------------------------------------------------------------------------------ + +sub report_ifields { + + &schedule_payments_report_ifields("troubleshoot_monitor") ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + our $count_outstanding = 0 ; + + &schedule_payments_list_screen("troubleshoot_monitor") ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + our $lcpage = 'troubleshoot-monitor-payment' ; + + &common_page_name ; + + our $table = 'shift_operator_ids' ; + $page_title = 'Troubleshoot Monitor Payments' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + &schedule_payments_report_screen("troubleshoot_monitor") ; + +} #------------------------------------------------------------------------------- + +sub screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# my $page = "$lcpage\s" ; + +my $page = "event-quotes" ; + +if ($s{no}) { $page = $lcpage ; } + +&common_min_table('id',$page,'list') ; + +our $savjqy = 1 ; + +# &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ; + +$extra_form_fields .= qq~ + + + +~; + +$print_box_content_rows .= &common_min_forms_end('','','save') if $count_outstanding ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +# sub screen4 { + +# &common_min_alert_type ; + +# print < +# +# + # + # $useropts{title} + # +# +# +# +# + +#
    +# +# +# +# +# +# +#
    + +# +# ENDOFTEXT +# # + +# exit ; + +# } #------------------------------------------------------------------------------------------ + +use common ; +use report ; +use xlsxcreator ; +use today ; +use schedule ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/troubleshoot_monitoring_report.pl b/scripts/_FromProd/v1.0/troubleshoot_monitoring_report.pl new file mode 100644 index 0000000..6b70654 --- /dev/null +++ b/scripts/_FromProd/v1.0/troubleshoot_monitoring_report.pl @@ -0,0 +1,624 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +# unless ($useropts{it}{$username}) { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; +use Time::Piece ; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $no_dates_in_table = 1 ; + +# our $debug = 1 ; +# our $testing = 1 ; + +# if ($username ne 'handre') { + # print "<< MAINTENANCE IN PROGRESS >>" ; exit ; +# } + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $srchscr = 1 ; + +if ($iaction eq 'save') { + &db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &common_min_load_params ; + &report_ifields ; + &update ; + &list_screen ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + # exit if $username eq 'handre' && $testing ; + &screen3 ; + # &redirect_screen; +} + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + &report_screen if $iaction eq '' ; + + if ($iaction eq 'report') { + &common_min_load_params ; + &report_ifields ; + &list_screen ; + &screen3 ; + } + + &common_min_action ; + + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub hidden_fields { + + # $ignore{id} = 1 ; + $ignore{iaction} = 1 ; + $ignore{date} = 1 ; + $ignore{troubleshoot_monitor_id} = 1 ; + + for my $d_cnt (1 .. $date_counter) { + for my $shift_cnt (1 .. 4) { + $ignore{"shifttroubleshootmonitorid_$shift_cnt\_$d_cnt"} = 1 ; + $ignore{"shift_troubleshoot_monitor_$shift_cnt\_$d_cnt"} = 1 ; + } + } + # $ignore{monitor_ids} = 1 ; + $ignore{update_table_1} = 1 ; + $ignore{update} = 1 ; + $ignore{"itv-table_length"} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + &schedule_update("shift_operator_ids","troubleshoot_monitor_ids","shifttroubleshootmonitorid","troubleshoot_monitor_notes") ; +# 12=f:;s:|s:1;t:1|f:2;s:2-13=|f:3;s:3|f:4;s:4 + + my @table_sql_where = () ; + + if ($i{client_id}) { + push @table_sql_where, "`quote_to`='$i{client_id}'" ; + } + if ($i{date_from} && $i{date_to}) { # check dates + push @table_sql_where, "(('$i{date_from} 00:00:00' <= `date_from` AND `date_from` <= '$i{date_to} 23:59:59') OR ('$i{date_from} 00:00:00' <= `date_to` AND `date_to` <= '$i{date_to} 23:59:59') OR (`date_from` <= '$i{date_from} 00:00:00' AND '$i{date_to} 23:59:59' <= `date_to`))" ; ############################################### > OR >= + + } + + if ($i{monitor_id} and $i{monitor_id} ne 'all') { + push @table_sql_where,"`TROUBLESHOOT MONITOR` = '$db{users}{1}{name}'" ; + } + + my $table_sql_where_str = join(" AND ",@table_sql_where) ; + + &db_min_ro($table,"id,monitor_report_saved_data","$table_sql_where_str",'','') ; + + my %saved_field_hash = () ; + + foreach my $id (keys %{$db{$table}}) { + + my @saved_data_split_1 = split(/\-/,$db{$table}{$id}{monitor_report_saved_data}) ; + + foreach my $a (@saved_data_split_1) { + my @saved_data_split_2 = split(/\=/,$a) ; + my $event_sys_id = $saved_data_split_2[0] ; + my @saved_data_split_3 = split(/\|/,$saved_data_split_2[1]) ; + my $day_cnt = 0 ; + foreach my $b (@saved_data_split_3) { + $day_cnt++ ; + next unless $b =~ /(\d+)/g ; + $saved_field_hash{$id}{$event_sys_id}{$day_cnt} = $b ; + } + } + } + + foreach my $field_name (keys %i) { + + next if ($field_name =~ /update_event/ && !$i{$field_name}) || $field_name !~ /update_event/ ; + + my @fields = split(/\_/,$field_name) ; + + my $system_id = substr($fields[-3],5) ; + my $day_cnt = $fields[-2] ; + my $event_id = $fields[-1] ; + + my $fixture_field = "fixture_check_event$system_id\_$day_cnt\_$event_id" ; + my $status_field = "status_event$system_id\_$day_cnt\_$event_id" ; + + $saved_field_hash{$event_id}{$system_id}{$day_cnt} = qq~~ ; + $saved_field_hash{$event_id}{$system_id}{$day_cnt} = qq~f:$i{$fixture_field};~ if $i{$fixture_field} ; + $saved_field_hash{$event_id}{$system_id}{$day_cnt} .= qq~s:$i{$status_field}~ if $i{$status_field} ; + + } + + %ii = %i ; + %i = () ; + + foreach my $event_id (keys %saved_field_hash) { + + $i{monitor_report_saved_data} = qq~~ ; + + foreach my $system_id (sort { $a <=> $b } keys %{$saved_field_hash{$event_id}}) { + + # $i{monitor_report_saved_data} .= qq~$system_id\=~ ; + my $saved_by_system = qq~~ ; + + foreach my $day_max (sort { $b <=> $a } keys %{$saved_field_hash{$event_id}{$system_id}}) { + for my $day_cnt (1 .. $day_max) { + $saved_by_system .= qq~$saved_field_hash{$event_id}{$system_id}{$day_cnt}|~ ; + } + chop $saved_by_system if $day_max ; + last ; + } + $i{monitor_report_saved_data} .= qq~$system_id\=$saved_by_system\-~ if $saved_by_system =~ /(\d+)/g ; + } + + chop $i{monitor_report_saved_data} if $i{monitor_report_saved_data} ; + + next if ($i{monitor_report_saved_data} eq $db{$table}{$event_id}{monitor_report_saved_data}) || (!$i{monitor_report_saved_data} && !$db{$table}{$event_id}{monitor_report_saved_data}) ; + + &db_min_upd($table,"id='$event_id'") ; + + } + + %i = %ii ; + +} #------------------------------------------------------------------------------------------ + +sub report_ifields { + + &load_search_vars ; + + # if ($i{date}) { # check dates + # push @report_sql, " `date_from` <= '$i{date} 23:59:59' AND '$i{date} 00:00:00' <= `date_to` " ; + # push @report_results, "DATE IS '$i{date}'" ; + # } else { + # $error = qq~PLEASE ENTER A DATE!~ ; + # &report_screen; + # } + + if ($i{client_id}) { + push @report_sql, "`quote_to`='$i{client_id}'" ; + &db_min_ro('customers','id,name',"`id`='$i{client_id}'") ; + push @report_results,"`CLIENT` = '$db{customers}{$i{client_id}}{name}'" ; + } + + my $date_from_val = $i{date_from} ; my $date_to_val = $i{date_to} ; + + $date_from_val =~ s/\-//g ; $date_to_val =~ s/\-//g ; + + if ($i{date_from} && $i{date_to} && $date_from_val > $date_to_val) { + $error = qq~THE START MUST BE BEFORE THE END DATE!!!~ ; + &report_screen ; + } elsif ($i{date_from} && $i{date_to}) { # check dates + push @report_sql, "(('$i{date_from} 00:00:00' <= `date_from` AND `date_from` <= '$i{date_to} 23:59:59') OR ('$i{date_from} 00:00:00' <= `date_to` AND `date_to` <= '$i{date_to} 23:59:59') OR (`date_from` <= '$i{date_from} 00:00:00' AND '$i{date_to} 23:59:59' <= `date_to`))" ; ############################################### > OR >= + push @report_results, "(EVENT BETWEEN '$i{date_from}' AND '$i{date_to}')" ; + } else { + $error = qq~PLEASE ENTER A START AND END DATE!!!~ ; + &report_screen; + } + + if ($i{monitor_id} and $i{monitor_id} ne 'all') { + push @report_results,"`TROUBLESHOOT MONITOR` = '$db{users}{1}{name}'" ; + push @report_sql, " `troubleshoot_monitor_ids` LIKE '%$i{troubleshoot_monitor_id}%' " ; + } elsif ($i{monitor_id} and $i{monitor_id} eq 'all') { + push @report_results,"`TROUBLESHOOT MONITORS` = 'ALL'" ; + } else { + # push @report_sql, "(`user_id` = '')" ; + } + + $report_results_msg = uc join(', ', @report_results) ; + + if ($iaction eq 'save') { + $isaved = qq(SUCCESSFULLY SAVED!) ; + } elsif (not $report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER) ; + &report_screen; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + + our $srch_where_sql = join(' AND ',@report_sql) ; + + my @date = split(/ /,$i{date}) ; + + my ($year_inp,$month_inp,$day_inp) = split(/\-/,$date[0]) ; + + our $date_inp_val = int("$year_inp$month_inp$day_inp") ; + our $today_val = int("$now_year$now_mm$now_dd") ; + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + if ($i{monitor_id} and $i{monitor_id} ne 'all') { + &db_min_ro('users','1,name',"`id` = '$i{troubleshoot_monitor_id}'",'','') ; + } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + $print_box_content_rows .= &common_min_forms_start("$lcpage") ; + + # our $monitoring_report = 1 ; + + our $troubleshoot_monitoring_report = 1 ; + + our $extra_column = ",monitor_report_saved_data" ; + + &schedule_load_list_vars("$srch_where_sql") ; + + $fcol = 12 ; + + my $report = 1 ; + + our $xlsxdir = "troubleshoot_monitoring_report" ; + + our $xlsxreportname = "Troubleshoot_Monitors" ; + + my $date = &common_write_date_interval($i{date_from},$i{date_to}) ; + + our $xlsx_title_heading = "Troubleshoot Monitor Allocations $date" ; + + my $field_name = "troubleshoot_shift_monitor" ; + + my $uc_field_name = ucfirst $field_name ; + + our $print_tbody_extra = qq~~ ; + + # our @sql_col_display_extra = ("date","shift_1_(07:00-10:00)","shift_2_(10:00-13:00)","shift_3_(13:00-16:00)","shift_4_(16:00-19:00)") ; + our @sql_col_display_extra = ("date","shift_1_(08:00-11:00)","shift_2_(11:00-14:00)","shift_3_(14:00-17:00)","shift_4_(17:00-21:00)","notes") ; + push @sql_col_display_extra,"update" ; + # if $date_inp_val >= $today_val ; + + our @sql_col_display = ("count","event","date","day","start_date","start_time","end_time","region","sport","system","club_name","operator","fixture_check","status") ; + + # push @sql_col_display,"update" if ($monitoring_report || $temp_calibrator_report) && $date_inp_val >= $today_val ; + + &report_xlsx_export_header("$xlsxreportname",$xlsxdir,'',$xlsx_title_heading) ; + # troubleshoot_monitoring_report + + &schedule_build_extra_table("shift_troubleshoot_monitor","shift_operator_ids","troubleshoot_monitor_ids","troubleshoot_monitor_notes","select_troubleshoot_monitors") ; + + # &common_min_table_update_checkbox_col("3") ; + + push @sql_col_display,"update" ; + + my $table_col_name = "troubleshoot_monitor_ids" ; + + $xlsxrow-- ; + + my @rev_sql_col_display = reverse @sql_col_display ; + + foreach (@rev_sql_col_display) { $lastchild++ ; $last_child{$_} = $lastchild ; } + + our %default_values = () ; + # 12=f:;s:|s:1;t:1|f:2;s:2-13=|f:3;s:3|f:4;s:4 + foreach my $id (keys %{$db{$table}}) { + + my @saved_data_split_1 = split(/\-/,$db{$table}{$id}{monitor_report_saved_data}) ; + # $sql_col_display[-2] + # $default_vals{}{$event_sys_id}{$sys_day_cnt}{$id} + + foreach my $a (@saved_data_split_1) { + my @saved_data_split_2 = split(/\=/,$a) ; + my $event_sys_id = $saved_data_split_2[0] ; + my @saved_data_split_3 = split(/\|/,$saved_data_split_2[1]) ; + my $day_cnt = 0 ; + foreach my $b (@saved_data_split_3) { + $day_cnt++ ; + next unless $b =~ /(\d+)/g ; + my @saved_data_split_3 = split(/\;/,$b) ; + my @saved_data_split_4 = split(/\:/,$saved_data_split_3[0]) ; + my @saved_data_split_5 = split(/\:/,$saved_data_split_3[1]) ; + + if ($saved_data_split_4[0] =~ /f/) { + $default_values{$sql_col_display[-3]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_4[1] ; + } + if ($saved_data_split_5[0] =~ /s/) { + $default_values{$sql_col_display[-2]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_5[1] ; + } elsif ($saved_data_split_4[0] =~ /s/) { + $default_values{$sql_col_display[-2]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_4[1] ; + } + } + } + } + + &common_min_select_opts("status","monitor_status","status") ; + + our @default_javascript_by_id_2 = () ; + + &schedule_build_table("troubleshoot_monitor_ids") ; + + # if ($date_inp_val >= $today_val) { + # $trigger_jquery_raw .= qq~ + # \$("#itv-table tr th:nth-last-child(5)").css("width","10%") ; + # \$("#itv-table tr th:nth-last-child(4)").css("width","10%") ; + # \$("#itv-table tr th:nth-last-child(3)").css("width","10%") ; + # \$("#itv-table tr th:nth-last-child(2)").css("width","10%") ; + # ~ ; + + # } else { + # $trigger_jquery_raw .= qq~ + # \$("#select_monitors tr th:nth-last-child(1)").css("width","23%") ; + # \$("#select_monitors tr th:nth-last-child(4)").css("width","23%") ; + # \$("#select_monitors tr th:nth-last-child(3)").css("width","23%") ; + # \$("#select_monitors tr th:nth-last-child(2)").css("width","23%") ; + # ~ ; + # } + + # &calibration_build_table_and_or_excel(1) ; + + # if ($found_after_date) { + + + + # } else { + # $trigger_jquery_raw .= qq~ + # \$("#itv-table tr th:nth-last-child(2)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(3)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(4)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(5)").css("width", "7.5%") ; + + # ~ ; + # } + + + # my $first_table_multi_select_table_cells_str = join(",",@first_table_multi_select_table_cells) ; + + # &common_min_table_select_fixed_width_jquery($first_table_multi_select_table_cells_str ) ; + + # &common_min_table_select_default_values_jquery ; + + # &common_min_table_update_checkbox_col("3") ; + + + my $first_table_multi_select_table_cells_str = join(",",@first_table_multi_select_table_cells) ; + # $useropts{table_id} + &common_min_table_select_fixed_width_jquery($first_table_multi_select_table_cells_str) ; + + &common_min_table_select_prevent_dropdown_overlap_jquery ; + + &common_min_table_select_default_values_jquery ; + + &common_min_table_update_checkbox_col("3","content","[id^='selectFixture_check_'],[id^='selectStatus_'],[id^='selectShift_troubleshoot_monitor_1_'],[id^='selectShift_troubleshoot_monitor_2_'],[id^='selectShift_troubleshoot_monitor_3_'],[id^='selectShift_troubleshoot_monitor_4_'],[id^='textareaShift_troubleshoot_monitor_notes_1_'],[id^='textareaShift_troubleshoot_monitor_notes_2_'],[id^='textareaShift_troubleshoot_monitor_notes_3_'],[id^='textareaShift_troubleshoot_monitor_notes_4_']") ; + + # my $default_javascript_by_id_str = join (",",@default_javascript_by_id) ; + + # print "\n default_javascript_by_id_str : $default_javascript_by_id_str" ; + + # $trigger_jquery_raw .= qq~ + + # all_def_vals = {$default_javascript_by_id_str} ; + + # \$("#$useropts{table_id}").on("change","[id^='selectFixture_check_'],[id^='selectStatus_']", function (event) { + # event.preventDefault(); + # console.log("2 update : "+this.id) ; + # check_whether_to_update(this.id); + # }); + + # ~ ; + + # &common_min_table_update_checkbox_col("3") ; + + $fnsortorder = 'asc' ; + + &common_min_extra_crumb("$lcpage","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + # &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + # our $lcpage = 'monitor-allocations' ; + our $lcpage = 'troubleshoot-monitoring-report' ; + + &common_page_name ; + + our $table = 'event_quotes' ; + $page_title = 'Troubleshoot Monitor Allocations' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + &common_min_select_opts('client_id','customers','name','','','',"events='1'") ; + + $allow_deselect{client_id} = 1 ; + $opts{client_id} =~ s/value="$i{client_id}"/value="$i{client_id}" SELECTED/g if $i{client_id} ; + $print_box_content_rows .= &common_min_form_select('client_id','') ; + + my ($sql_next_day) = &common_add_delta_days(1) ; + my ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-$now_mm-$now_dd") ; #unless $i{date_from} ; + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$next_year-$next_month-$next_day") ; #unless $i{date_from} ; + + push @date_value_ids,"input[name='date_from']" ; + push @date_value_ids,"input[name='date_to']" ; + + &common_min_table_validate_date_inputs_jquery ; + + $preferred_title{troubleshoot_monitor_id} = "Troubleshoot Monitor" ; + + # &db_min_ro('users',"id,name","`user_type` = 'support' OR `user_type` = 'casual_calibrator'",'','') ; + # &db_min_ro('users',"id,name,username","`name` NOT LIKE 'Rory%'",'','') ; + + $selected{troubleshoot_monitor_id}{all} = 'SELECTED' ; + + # if ($i{monitor_id}) { + # $selected{monitor_id}{$i{monitor_id}} = 'SELECTED' ; + # $selected{monitor_id}{all} = '' ; + # } + + # foreach (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + # next if $useropts{it}{$db{users}{$_}{username}} ; + # $opts{monitor_id} .= qq~~ ; + # } + $opts{troubleshoot_monitor_id} .= qq~~ ; + + $print_box_content_rows .= &common_min_form_select('troubleshoot_monitor_id','') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# my $page = "$lcpage\s" ; + +my $page = "event-quotes" ; + +if ($s{no}) { $page = $lcpage ; } + +# &db_min_ro('daily_monitor_ids','date,monitor_ids') ; + +my @sql_col_display_2 = @sql_col_display ; + +@sql_col_display = @sql_col_display_extra ; + +our %custom_column_styles = () ; + +$custom_column_styles{fixture_check} = qq~style="width:7%;min-width:150px;"~ ; +$custom_column_styles{status} = qq~style="width:7%;min-width:150px;"~ ; + +&common_min_thead ; + +$print_box_content_rows .= qq~ + + $print_thead + + + $print_tbody_extra + + +
    ~ ; + +@sql_col_display = @sql_col_display_2 ; + +&common_min_thead ; + +&common_min_table('id',$page,'list') ; + +our $savjqy = 1 ; + +$extra_form_fields .= qq~ + + + + + +~; + +for (1 .. $date_cnt) { + + $extra_form_fields .= qq~ + + + + + ~ ; + +} + + +# $print_box_content_rows .= &common_min_forms_end('','','save') if $date_inp_val >= $today_val ; +$print_box_content_rows .= &common_min_forms_end('','','save') ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub redirect_screen { + +&common_min_alert_type ; + +print < + + + + $useropts{title} + + + + + + +
    + + + + + +
    + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +use common ; +use report ; +use xlsxcreator ; +use today ; +# use calibration_test ; +use schedule ; +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/users.pl b/scripts/_FromProd/v1.0/users.pl new file mode 100644 index 0000000..ce58a19 --- /dev/null +++ b/scripts/_FromProd/v1.0/users.pl @@ -0,0 +1,115 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Crypt::PasswdMD5; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + + &users_validate; + +} #------------------------------------------------------------------------------------------ + +sub insert { + + &users_insert ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + &users_update ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + &users_list_screen ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + &users_sort_fields ; + +} #------------------------------------------------------------------------------- + +sub add_db_fields { + + &users_add_db_fields ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &users_edit_db_fields ; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + + # called from common_add_screen + &users_add_screen ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + &users_edit_screen ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &users_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'user' ; + our $lcpage = 'user' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'users' ; + + &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; +use users ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/venue.pl b/scripts/_FromProd/v1.0/venue.pl new file mode 100644 index 0000000..5574557 --- /dev/null +++ b/scripts/_FromProd/v1.0/venue.pl @@ -0,0 +1,429 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +&db_open_ro ; + $db_ignore_open_close = 1 ; + &common_min_action; + $db_ignore_open_close = 0 ; +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + + my $exists = '' ; + + $i{name} = &common_fix_str($i{name}) ; + + &db_min_ro($table,'*',"name='$i{name}'",'name','') ; + + foreach my $id (keys %{$db{$table}}) { if (lc $db{$table}{$id}{name} eq lc $i{name}) { $exists = 1 ; } } + + if ($exists) { + $alert = &common_min_alert('warning',"VENUE NAME ALREADY EXISTS!",'ok') ; + %col_name = () ; + &common_min_add_screen ; + &common_min_screen1 ; + } + +# REMOVE LATER ----------------- + + &db_min_ro('regions','id,code',"id='$i{region_id}'",'','') if $i{region_id} ; + + $i{region_code} = $db{regions}{$i{region_id}}{code} if $i{region_id} ; + +# REMOVE LATER ----------------- + +} #------------------------------------------------------------------------------------------ + +sub insert { + + &add_db_fields ; + + $i{id} = &db_min_get_max($table,'id') ; + + $ignore{country_id} = 1 ; + + &db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + unless ($i{id}) { $error = qq(NO ID) ; return ; } + + &edit_db_fields ; + + $ignore{country_id} = 1 ; + + &db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + &db_min_ro('regions','id,name,code,country_id','','','') ; + + &db_min_ro('countries','id,name','','','') ; + + &db_min_ro('event_quotes',"DISTINCT organisation_ids AS 'organisation_ids'","organisation_ids <> '0'",'','') ; + + foreach my $_id (keys %{$db{event_quotes}}) { + if ($_id =~ /,/) { ## 13,32 + foreach (split(/\,/,$_id)) { + $venue_id_used{$_} = 1 ; + } + } else { + $venue_id_used{$_id} = 1 ; + } + } + + &db_min_ro($table,'*','','','') ; + + foreach my $id (keys %{$db{$table}}) { + + my $edit_butt = qq~ ~ ; + my $del_butt = qq~ ~ ; + + if ($glod_user_level >= 3) { + $edit_butt = qq~ ~ ; + } + + if ($glod_user_level >= 3) { + $del_butt = qq~ ~ ; + } + + if ($venue_id_used{$id}) { + # $edit_butt = qq~ ~ ; + $del_butt = qq~ ~ ; + } + + my $region = ($db{regions}{$db{$table}{$id}{region_id}}{code}) ? qq~$db{regions}{$db{$table}{$id}{region_id}}{name} [$db{regions}{$db{$table}{$id}{region_id}}{code}]~ : qq~$db{regions}{$db{$table}{$id}{region_id}}{name}~ ; + + $print_tbody .= qq~ + + $id + $db{$table}{$id}{name} + $db{$table}{$id}{address_line_1} + $db{$table}{$id}{address_line_2} + $db{$table}{$id}{address_line_3} + $db{$table}{$id}{address_line_4} + $db{$table}{$id}{suburb} + $db{$table}{$id}{postal_code} + $region + $db{countries}{$db{regions}{$db{$table}{$id}{region_id}}{country_id}}{name} + + $edit_butt + $del_butt + + + ~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + &sort_fields; + + &hidden_db_fields; + + # $ignore{id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &hidden_db_fields; + + &sort_fields; + + $hidden{id} = 1 ; # 1 = bypass for db update + +} #------------------------------------------------------------------------------------------ + +sub hidden_db_fields { + + $ignore{iaction} = 1 ; + $required{name} = 1 ; + $required{region_id} = 1 ; + $required{address_line_1} = 1 ; + $required{address_line_2} = 1 ; + $required{address_line_3} = 1 ; + $required{address_line_4} = 1 ; + $required{suburb} = 1 ; + $required{postal_code} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + &db_min_ro('event_quotes',"DISTINCT organisation_ids AS 'organisation_ids'","`organisation_ids` <> 0 AND `organisation_ids` LIKE '%$i{id}%'",'','') ; + + our %venue_id_used = () ; + + foreach my $_id (keys %{$db{event_quotes}}) { + if ($_id =~ /,/) { ## 13,32 + foreach (split(/,/,$_id)) { + $venue_id_used{$_} = 1 ; + } + } else { + $venue_id_used{$_id} = 1 ; + } + } + + %sort_field = () ; + + + $sort_field{3} = 'name' ; $preferred_title{name} = 'Name' ; + $sort_field{4} = 'address_line_1' ; + $sort_field{5} = 'address_line_2' ; + $sort_field{6} = 'address_line_3' ; + $sort_field{7} = 'address_line_4' ; + $sort_field{8} = 'suburb' ; + $sort_field{9} = 'postal_code' ; + $sort_field{10} = 'region_id' ; $preferred_title{region_id} = 'Region' ; + $sort_field{11} = 'country_id' ; + + if ($venue_id_used{$i{id}}) { + # &db_min_ro('regions',"code,name","",'','') ; + $required{name} = 0 ; + $required{region_id} = 0 ; + $input{region_id} = 1 ; + $readonly{region_id} = "READONLY" ; + $readonly{name} = "READONLY" ; + &db_min_ro('regions','id,code',"id='$db{$table}{$i{id}}{region_id}'",'','') if $i{id} ; + + $db{$table}{$i{id}}{region_id} = $db{regions}{$db{$table}{$i{id}}{region_id}}{code} if $i{id} ; + + $preferred_title{region_id} = 'Region Code' ; + + } else { + $select{region_id} = 1 ; + } + +} #------------------------------------------------------------------------------- + +sub add_screen { + + # called from common_add_screen + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + &select_opts ; + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + + # $required{based_in} = 1 ; + # $select{based_in} = 1 ; + # $opts{based_in} = qq~~ ; + + return if $venue_id_used{$i{id}} ; + + my $sql_or = ($is_schools_manager || $is_operator) ? join(' OR ', map { "id = '$_'" } keys %{$glob_regids{$userid}}) : '' ; + + # if ($is_schools_manager || $is_operator) { + # @report_sql_or = () ; + # foreach $_reg_id (keys %{$glob_regids{$userid}}) { + # push @report_sql_or, "id = '$_reg_id'" + # }{ + # } + + if ($db{$table}{$i{id}}{country_id}) { + $sql_or = ($sql_or) ? "`country_id` = '$db{$table}{$i{id}}{country_id}' AND ($sql_or)" : "`country_id` = '$db{$table}{$i{id}}{country_id}'" ; + } + + $allow_deselect{country_id} = 1 ; + + &common_min_select_opts('region_id','regions','name',$db{$table}{$i{id}}{region_id},'','code',$sql_or,'','','','name') ; + &common_min_select_opts('country_id','countries','name',$db{regions}{$db{$table}{$i{id}}{region_id}}{country_id},'','','','','','','name') ; + + $trigger_jquery_raw .= qq~ + + let map_region_to_country = {} ; + + const \$countrySelect = \$("#selectCountry_id") ; + const \$regionSelect = \$("#selectRegion_id") ; + + const updateChosen = \$el => \$el.trigger("chosen:updated"); + + const fetchJSON = async url => { + try { + const res = await fetch(url); + if (!res.ok) throw new Error(`Request failed: \${res.status}`); + return await res.json(); + } catch (err) { + console.error("Fetch error:", err); + return []; + } + }; + + const populateSelect = (\$field, json_list, getLabel, defaultSelected = () => "") => { + + let isSelected ; + + // Determine how to handle selected logic + if (typeof defaultSelected === "function") { + isSelected = defaultSelected ; + } else if (Array.isArray(defaultSelected)) { + isSelected = data => defaultSelected.includes(data.id) ? "selected" : "" ; + } else { + isSelected = data => data.id == defaultSelected ? "selected" : "" ; + } + + // Auto-select the only item if none explicitly selected + const autoSelectOnly = json_list.length === 1 && typeof defaultSelected === "string" && defaultSelected === "" ; + + json_list.forEach(data => { + const selected = autoSelectOnly || isSelected(data) ? "selected" : "" ; + \$field.append(``) ; + }); + + updateChosen(\$field) ; + return json_list.length ; + }; + + const getInputValue = name => \$(`input[name='\${name}']`).val(); + + const clearSelect = (\$el) => { + \$el.empty(); + \$el.append(``).trigger("chosen:updated"); + }; + + // _______________________________________________ + + \$countrySelect.change( async function() { + \$("input[name='custom_selected_country']").val("1") ; + await update_region_drop_down_from_country(\$countrySelect.val()) ; + }) ; + + async function update_region_drop_down_from_country (countryId) { + + clearSelect(\$regionSelect) ; + + const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}` ; + const regions = await fetchJSON(regionUrl); + + for (const data of regions) { + map_region_to_country[data.id] = countryId ; + } + + const regionCount = populateSelect(\$regionSelect, regions, r => r.code ? `\${r.name} [\${r.code}]` : r.name , "") ; + + if (regionCount === 0 && \$countrySelect.val()) { + \$regionSelect.append(``).trigger("chosen:updated") ; + } + + } + + // _______________________________________________ + + \$regionSelect.change( async function() { + \$("input[name='custom_selected_region']").val("1") ; + \$("input[name='custom_selected_country']").val("1") ; + const regionId = \$regionSelect.val() ; + await update_country_from_region(regionId,1) ; + }); + + async function update_country_from_region (regionId,update_country=0) { + if (map_region_to_country[regionId] || regionId == '13') { + \$countrySelect.val(map_region_to_country[regionId]).trigger("chosen:updated") ; + } else if (!\$("input[name='custom_selected_country']").val() || update_country) { + const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=®ion_id=\${regionId}`; + const regionMeta = await fetchJSON(lookupUrl); + const { country_id } = regionMeta[0] ?? {} ; + if (country_id) { + map_region_to_country[regionId] = country_id; + \$countrySelect.val(country_id).trigger("chosen:updated"); + } + } + } + + // _______________________________________________ + + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + if ($venue_id_used{$i{id}}) { + $ignore{region_id} = 1 ; + $ignore{name} = 1 ; + } + + $print_thead = qq~ + + + ID + Name + Address Line 1 + Address Line 2 + Address Line 3 + Address Line 4 + Suburb + Postal Code + Region + Country +   + + + ~ ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'map-marker' ; + our $lcpage = 'venue' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'organisations' ; + + $s{no} = 1 ; + + &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/warranty_report.pl b/scripts/_FromProd/v1.0/warranty_report.pl new file mode 100644 index 0000000..f7f42dd --- /dev/null +++ b/scripts/_FromProd/v1.0/warranty_report.pl @@ -0,0 +1,293 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +our $srchscr = 1 ; + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + if ($iaction eq ''){ &report_screen ; } + &common_min_action; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub report_ifields { + +&load_search_vars ; + +# if ($i{camera_id}) { + # push @report_sql, "(`id`='$i{camera_id}')" ; + # push @report_results, "camera = $camera_name{$i{camera_id}}" ; + # $xlsreportname .= '-' . $i{camera_id} ; + # # our $acc_id_sql_where = "`camera_id`='$i{camera_id}'" + # } + +# if ($i{camera_system_id}) { + # push @report_sql, "(`camera_system_id`='$i{camera_system_id}')" ; + # push @report_results, "camera_system = $camera_system{$i{camera_id}}" ; + # $xlsreportname .= '-' . $i{camera_system_id} ; + # } + +if ($i{camera_system_id} and $i{camera_system_id} ne 'main' and $i{camera_system_id} ne 'other' and $i{camera_system_id} ne 'all') { + push @report_sql, "(`camera_system_id`='$i{camera_system_id}')" ; + push @report_results, "camera_system = $camera_system{$i{camera_system_id}}" ; + $xlsreportname .= '-' . $i{camera_id} ; + # our $acc_id_sql_where = "`camera_id`='$i{camera_id}'" +} elsif ($i{camera_system_id} eq 'main' or $i{camera_system_id} eq 'other' or $i{camera_system_id} eq 'all') { + push @report_results, "camera_system = $i{camera_system_id}" ; +} + +if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { $error = qq(CAMERAS FROM ($i{date_from}) > CAMERAS TO ($i{date_to})); &report_screen; } + } + +if ($i{date_from}) { + # push @report_sql, "(`date_active` >= '$i{date_from}')" ; + # push @report_results, "date_active >= $i{date_from}" ; + push @report_sql, "(`date_time` >= '$i{date_from}')" ; + push @report_results, "date_time >= $i{date_from}" ; + } + +if ($i{date_to}) { + # push @report_sql, "(`date_active` <= '$i{date_to}')" ; + # push @report_results, "date_active <= $i{date_to}" ; + push @report_sql, "(`date_time` <= '$i{date_to}')" ; + push @report_results, "date_time <= $i{date_to}" ; + } + +if ($i{client_id}) { + # push @report_sql, "(`client_id` = '$i{client_id}')" ; + push @report_results, "Client = $client{$i{client_id}}" ; + } + +$report_results_msg = uc join(', ', @report_results) ; + +unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER); &report_screen; } else { $isaved = qq(SELECT WHERE $report_results_msg) ; } + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + # my $cameras_sql_where = "`id`='$i{camera_id}'" ; + # &db_min_ro('cameras','id,camera_nr',$cameras_sql_where,'','') ; + # foreach my $id (keys %{$db{cameras}}) { $camera_name{$id} = $db{cameras}{$id}{camera_nr} ; } + + my $camera_systems_sql_where = "`id`='$i{camera_system_id}'" if $i{camera_system_id} ; + &db_min_ro('camera_systems','id,name',$camera_systems_sql_where,'','') ; + foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + + # my $price_list_sql_where = " AND `id`='$i{camera_system_id}'" if $i{camera_system_id} ; + # &db_min_ro('price_list','id,description',"`excl`<>'1' AND `type`='systems'$price_list_sql_where",'','') ; + # foreach my $id (keys %{$db{price_list}}) { $camera_system{$id} = $db{price_list}{$id}{name} ; } + + # my $customers_sql_where = "`id`='$i{client_id}'" if $i{client_id} ; + # &db_min_ro('customers','*',$customers_sql_where,'','') ; + # foreach my $id (keys %{$db{customers}}) { $client{$id} = $db{customers}{$id}{name} ; } + + if ($i{client_id}) { + my $customers_sql_where = "`id`='$i{client_id}'" ; + &db_min_ro('customers','*',$customers_sql_where,'','') ; + foreach my $id (keys %{$db{customers}}) { $client{$id} = $db{customers}{$id}{name} ; } + } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +my $srch_where_sql = join(' AND ', @report_sql) ; + +my $add_sql_where = '' ; + +# our @sql_col_display = ("id","camera_nr","camera_serial_nr","date_received","client_id","ref_nr","ref","date_delivered","extended_warranty") ; +our @sql_col_display = ("camera_nr","camera_system_id","camera_serial_nr","vpu_serial_nr","date_received","client_id","ref_nr","ref","date_delivered","extended_warranty") ; + +&report_xls_export_header("Extended_Warranty_Report$xlsreportname",'warrantyreport') ; + +&load_list_vars("$srch_where_sql$add_sql_where") ; + +foreach my $id (sort {$b <=> $a} keys %{$db{$table}}) { + + next unless $db{$table}{$id}{quote_ew_date_from} or $db{$table}{$id}{quote_ew_date_to} ; + + next if (&common_camera_system_filter($table,$id)) ; + + if ($i{client_id}) { + next unless $client{$i{client_id}} eq $quote_customer{$id} ; + } + + $print_tbody .= qq~~ ; + + $xlscol=0; + + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$table}{$id}{$_} ; + my $align = '' ; + + my $center = qq~ class="dt-center"~ ; + + if ($_ eq 'date_received') { $align = $center ; } + if ($_ eq 'date_delivered') { $val = $db{$table}{$id}{quote_delivery_date} ; $align = $center ; } + if ($_ eq 'client_id') { $val = $quote_customer{$id} ; } + if ($_ eq 'ref_nr') { $val = $db{$table}{$id}{quote_nr} ; $align = $center ; } + # if ($_ eq 'ref') { $val = $db{$table}{$id}{quote_ref} ? "$db{$table}{$id}{quote_ref}" : $quote_ref{$id} ; } + if ($_ eq 'ref') { $val = $db{$table}{$id}{quote_ref} ? $db{$table}{$id}{quote_ref} : $quote_ref{$id} ; } + if ($_ eq 'camera_system_id') { $val = $camera_system{$val} ; } + if ($_ eq 'camera_serial_nr') { $val = $db{$table}{$id}{serial_nr} ; } + + if ($_ eq 'extended_warranty') { + $val = $db{$table}{$id}{quote_ew_date_from} if $db{$table}{$id}{quote_ew_date_from} ; + $val .= "/$db{$table}{$id}{quote_ew_date_to}" if $db{$table}{$id}{quote_ew_date_to} ; + $align = $center ; + } + + # if ($_ eq 'vpu_serial_nr') { $val = &common_check_for_linked_vpu($db{$table}{$id}{camera_nr},$quote_nr{$id},$id,'SN') ; } + if ($_ eq 'vpu_serial_nr') { $val = $linked_sn{$db{$table}{$id}{serial_nr}} ; } + + &report_xls_export_process_cell('','',$val) ; # ------------------------------------------------------------------------- HTML AFTER + $xlscol++; + + $val = &common_camera_links($table,$id,$val) if $_ eq 'camera_nr' or $_ eq 'ref_nr' ; + + $print_tbody .= qq~$val~ ; + } + + $print_tbody .= qq~~ ; + $xlsrow++ ; + } + +&report_xls_export_footer('L',15,'warrantyreport') ; + +$fnsortcol = 3 ; +$fnsortorder = 'asc' ; + +$print_more_boxes .= qq~


    ~ ; + +&common_min_extra_crumb("$lcpage-report","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub set_tick { + +my ($color,$tooltip) = @_ ; + +$tick{green} = qq~2~ ; +$tick{orange} = qq~1~ ; +$tick{red} = qq~0~ ; + +return ($tick{$color}) ; + +} #------------------------------------------------------------------------------------------ + +sub load_list_vars { + +my ($where) = @_ ; + +&db_min_ro('camera_systems','id,name','','','') ; +foreach my $id (keys %{$db{camera_systems}}) { $camera_system{$id} = $db{camera_systems}{$id}{name} ; } + +&db_min_ro('customers','id,name','','','') ; +foreach my $id (keys %{$db{customers}}) { $customer{$id} = $db{customers}{$id}{name} ; } + +# &common_load_quote_vars('>0'); +&common_load_quote_vars("cameras.quote_nr>0 AND cameras.quote_nr=quotes.quote_nr"); + +&db_min_ro($table,'*',$where,'','') ; + +# foreach my $id (keys %{$db{$table}}) { + # $cam_nr{$id} = $db{$table}{$id}{camera_nr} ; + # $serial_nr{$id} = $db{$table}{$id}{serial_nr} ; +# } + +} #------------------------------------------------------------------------------------------ + +sub thead { + +&common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'list' ; +our $lcpage = 'extended' ; + +&common_page_name ; + +our $table = 'cameras' ; +$page_title = 'Extended Warranty' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + +our $lcol = 3 ; +our $fcol = 5 ; + +$print_box_content_rows .= &common_min_forms_start('report') ; + +&common_camera_opts ; +&common_min_select_opts('camera_system_id','camera_systems','code',$i{camera_system_id},'') ; +&common_min_select_opts('client_id','customers','name',$i{client_id},'') ; + + +my @datefrom = &common_add_delta_ymd(-2,0,0) ; + +$print_box_content_rows .= &common_min_form_datepicker('date_from',"$datefrom[0]-01-01") ; +$print_box_content_rows .= &common_min_form_datepicker('date_to',"$now_year-$now_mm-$now_dd") ; +$print_box_content_rows .= &common_min_form_select('camera_system_id','') ; +$print_box_content_rows .= &common_min_form_select('client_id','') ; +$print_box_content_rows .= &common_min_forms_end('','','report') ; + +&common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +use common ; +use report ; +use xlsxcreator ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/weekend.pl b/scripts/_FromProd/v1.0/weekend.pl new file mode 100644 index 0000000..54d4a93 --- /dev/null +++ b/scripts/_FromProd/v1.0/weekend.pl @@ -0,0 +1,252 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; + +require cfg ; + +print header; # CGI.pm method + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +# unless ($username eq 'rory') { print ">>>>>> APOLOGIES, DOING MAINTENANCE <<<<<<"; exit; } + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +# &common_min_restriction_super ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + +# my $exists = '' ; + +# &db_min_ro($table,'*',"name = '$i{name}'",'name','') ; + +# foreach my $id (keys %{$db{$table}}) { if ($db{$table}{$id}{name} eq $i{name}) { $exists = 1 ; } } + +# if ($exists) { $alert = &common_min_alert('warning',"$ucpage ALREADY EXISTS!",'ok') ; %col_name = (); &common_min_add_screen; &common_min_screen1; } + +} #------------------------------------------------------------------------------------------ + +sub insert { + +&add_db_fields ; + +$i{id} = &db_min_get_max($table,'id') ; + +&common_min_upload_files("weekend_work/$i{id}") ; + +$i{date_time} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; +$i{category} = 'weekend_work' ; + +&db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub update { + +unless ($i{id}) { $error = qq(NO ID) ; return ; } + +&edit_db_fields ; + +&common_min_upload_files("weekend_work/$i{id}") ; + +# unless ($i{block}) { $i{block} = '0' ; } +# $i{lastupdate} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + +&db_min_upd($table,"id='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +&db_min_ro('users','*','','','') ; +foreach my $id (keys %{$db{users}}) { $user_name{$id} = $db{users}{$id}{name} ; } + +my $extra_sql = '' ; unless ($useropts{super}{lc $username}) { $extra_sql = " AND `user_id`='$userid'" ; } + +&db_min_ro($table,'*',"`category`='weekend_work'$extra_sql",'','') ; + +foreach my $id (keys %{$db{$table}}) { + # my $weekend_work_type = ucfirst $db{$table}{$id}{type} ; + + my $attach_butt = '' ; $attach_options = &common_min_get_uploads("weekend_work/$id",'all') ; if ($attach_options) { $attach_butt = qq( ) ; } + my $edit_butt = '' ; + my $del_butt = '' ; + + my $category = ucfirst $db{$table}{$id}{category} ; $category =~ s/\_/ /g ; + + if ($useropts{super}{lc $username}){ + $edit_butt = qq( ) ; + $del_butt = qq() ; + } + + $print_tbody .= qq( + $id + $db{$table}{$id}{date_time} + $user_name{$db{$table}{$id}{user_id}} + $db{$table}{$id}{startdate} + $db{$table}{$id}{enddate} + $db{$table}{$id}{notes} +   + $edit_butt + $del_butt + $attach_butt + + ) ; + } + +} #------------------------------------------------------------------------------------------ + +sub thead { + +$print_thead = qq(IDDATE ADDEDSTAFF NAMESTART DATEEND DATENOTES ) ; + +} #------------------------------------------------------------------------------- + +sub add_db_fields { + +&hidden_db_fields ; + +# $ignore{id} = 1 ; +$hidden{id} = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub sort_weekend_work_fields { + +$sort_field{1} = 'startdate' ; +$sort_field{2} = 'enddate' ; +$sort_field{3} = 'user_id' ; +$sort_field{4} = 'notes' ; + +} #------------------------------------------------------------------------------- + +sub hidden_db_fields { + +$ignore{iaction} = 1 ; +$textarea{notes} = 1 ; +# $required{title} = 1 ; +$required{category} = 1 ; +$required{days} = 9 ; +$datetimepicker{startdate} = 1 ; +$datetimepicker{enddate} = 1 ; +$ignore{completed} = 1 ; +$ignore{iattachwenw} = 1 ; +$ignore{title} = 1 ; +$ignore{type} = 1 ; +$ignore{days} = 1 ; + +# $hidden{user_id} = 2 ; +$hidden{date_time} = 2 ; +$hidden{category} = 2 ; + +&sort_weekend_work_fields ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + +&hidden_db_fields ; + +$hidden{id} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + +&select_opts('') ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + +# $selected{'type'}{$db{$table}{$i{id}}{type}} = 'SELECTED' ; + +$weekend_work_uploads = &common_min_get_uploads("weekend_work/$i{id}",'wenw') ; + +&select_opts($i{id}) ; + +} #------------------------------------------------------------------------------------------ + +sub select_opts { + +my ($id) = @_ ; + +# &common_min_select_opts('user_id','users','name',$db{$table}{$id}{user_id},1) ; + +@user_excl_sql = () ; + +foreach (keys %{$useropts{it}}) { + push @user_excl_sql, "username <> '$_'" ; +} + +my $user_excl_sql = join(" AND ", @user_excl_sql) ; + +&common_min_select_opts('user_id','users','name',$db{$table}{$id}{user_id},1,'',$user_excl_sql) ; + +# &common_min_opts('weekend_work_type','type',1) ; + +$extra_form_fields .= qq(
     
    +
    +
    +
    + + +

    Upload file from PC.

    +
    +
    +
    +
    +
    + $weekend_work_uploads +
    +
    + ) ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'calendar' ; +our $lcpage = 'weekend' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; +our $table = 'events' ; + +$s{no} = 1 ; + +&common_min_add_extras ; +&common_min_add_box_icon ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; + +1; \ No newline at end of file diff --git a/scripts/_FromProd/v1.0/weekend_report.pl b/scripts/_FromProd/v1.0/weekend_report.pl new file mode 100644 index 0000000..69781d4 --- /dev/null +++ b/scripts/_FromProd/v1.0/weekend_report.pl @@ -0,0 +1,210 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); +use Date::Calc qw(:all); + +use Spreadsheet::WriteExcel; +use Spreadsheet::WriteExcel::Utility; + +require cfg ; + +print header; # CGI.pm method + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || '' ; + +# our $debug = 1 ; + +&common_min_restriction_super ; + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +if ($iaction eq ''){ + &report_screen ; + # &common_min_screen1; + } +elsif ($iaction eq 'report'){ + &common_min_load_params ; + &report_ifields; + &list_screen ; + &report_screen ; + # &common_min_screen3; + } + +exit; + +#------------------------------------------------------------------------------------------ + +sub report_ifields { + +if ($i{date_from} and $i{date_to}) { # check dates + my $date_from_check = $i{date_from} ; + $date_from_check =~ s/\-//g ; + my $date_to_check = $i{date_to} ; + $date_to_check =~ s/\-//g ; + if ($date_from_check > $date_to_check) { $error = qq(DATE FROM ($i{date_from}) > DATE TO ($i{date_to})); &report_screen; } + } + +if ($i{date_from}) { + push @report_sql, "(`startdate` >= '$i{date_from}')" ; + push @report_results, "startdate >= $i{date_from}" ; + } + +if ($i{date_to}) { + push @report_sql, "(`startdate` <= '$i{date_to}')" ; + push @report_results, "startdate <= $i{date_to}" ; + } + +&db_min_ro('users','*',"`id`='$i{user_id}'",'','') ; +foreach my $id (keys %{$db{users}}) { $user{$id} = $db{users}{$id}{name} ; } + +push @report_sql, "(`user_id` = '$i{user_id}')" ; +push @report_results, "Consultant = $user{$i{user_id}}" ; + +$srch_where_sql = join(' AND ', @report_sql) ; + +$report_results_msg = uc join(', ', @report_results) ; + +unless ($i{user_id}) { $error = qq(PLEASE SELECT A CONSULTANT); &report_screen; } else { $success = qq(REPORT WHERE $report_results_msg) ; } +unless ($report_results_msg) { $error = qq(ENTER AT LEAST ONE REPORT PARAMETER); &report_screen; } else { $success = qq(REPORT WHERE $report_results_msg) ; } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + +# &db_min_ro('agency','*','','','') ; +# foreach my $id (keys %{$db{agency}}) { $agency{$id} = $db{agency}{$id}{name} ; } + +our @sql_col_display = ("date_time","user_id","startdate","enddate","notes","duration") ; + +# our %money_format = (agent_balance => 1); + +my $xlsfolder = 'weekendwork' ; + +&report_xls_export_header("$user{$i{user_id}}_Weekend_Work_Report",$xlsfolder) ; + +# &db_min_ro($table,'*','','','') ; +&db_min_ro($table,'*',"$srch_where_sql AND `category`='weekend_work'",'','') ; + +foreach my $id (keys %{$db{$table}}) { + + # unless ($db{$table}{$id}{category} eq 'weekend_work') { next ; } + + $print_tbody .= qq() ; + + $xlscol=0; + + foreach (@sql_col_display) { + my $val = $db{$table}{$id}{$_} ; + if ($_ eq 'user_id') { $val = $user{$db{$table}{$id}{$_}} ; } + + if ($_ eq 'duration') { # calculate time worked + my ($s_dy,$s_dm,$s_dd,$s_th,$s_tm,$s_ts) = &common_min_split_sql_date_time($db{$table}{$id}{startdate}) ; + my ($e_dy,$e_dm,$e_dd,$e_th,$e_tm,$e_ts) = &common_min_split_sql_date_time($db{$table}{$id}{enddate}) ; + my ($Dd,$Dh,$Dm,$Ds) = Delta_DHMS($s_dy,$s_dm,$s_dd, $s_th,$s_tm,$s_ts, $e_dy,$e_dm,$e_dd, $e_th,$e_tm,$e_ts); + $val = $Dd . ' days, ' . $Dh . ' hrs, ' . $Dm . ' min' ; + } + + &report_xls_export_process_cell('',$money_format{$_},$val) ; + $xlscol++; + if ($_ eq 'user_id') { $val = qq($user{$db{$table}{$id}{$_}}); } + $print_tbody .= qq($val) ; + } + + $print_tbody .= qq() ; + + $xlsrow++ ; + } + +# $print_ttl_agent_balance = &common_min_commify(sprintf("%0.2f",$ttl_agent_balance)) ; +# our $add_th_row = qq($print_ttl_agent_balance) ; # used in common_min_thead + +&report_xls_export_footer('F',30) ; + +} #------------------------------------------------------------------------------------------ + +sub report_screen { + +our $lcol = 3 ; +our $fcol = 5 ; + +# &db_min_ro($table,'*','','',1) ; + +@user_excl_sql = () ; + +foreach (keys %{$useropts{it}}) { + push @user_excl_sql, "username <> '$_'" ; +} + +my $sql_where = join(" AND ", @user_excl_sql) ; + +# my $sql_where = '' ; unless ($useropts{super}{lc $username}) { $sql_where = "`id`='$userid'" ; } +unless ($useropts{super}{lc $username}) { $sql_where = " AND `id`='$userid'" ; } + +&common_min_select_opts('user_id','users','name',$i{user_id},'','',"$sql_where") ; + +$print_box_content_rows .= &common_min_forms_start('report') ; +$print_box_content_rows .= &common_min_form_datepicker('date_from',$i{date_from}) ; +$print_box_content_rows .= &common_min_form_datepicker('date_to',$i{date_to}) ; +$print_box_content_rows .= &common_min_form_select('user_id','','',1,'','Consultant') ; +$print_box_content_rows .= &common_min_forms_end('','','report') ; + +my $page = "$lcpage\s" ; if ($s{no}) { $page = $lcpage ; } + +if ($print_tbody) { &thead; &common_min_table('id',$page,'list') ; } + +&screen1 ; + +} #------------------------------------------------------------------------------- + +sub thead { + +&common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub screen1 { + +&common_min_alert_type ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub page_opts { + + +our $glyphicon = 'global' ; +our $lcpage = 'weekend-report' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; +our $table = 'events' ; +our $srchscr = 1 ; + +# our $open_new_tab = qq(target="_blank") ; # opens booking page in a new tab +# our $fnsortorder = 'asc' ; + +} #------------------------------------------------------------------------------- + +use common ; +use today ; +use report ; +use xlscreator ; + +1; \ No newline at end of file diff --git a/scripts/admin/oneoff/find_saved_fixtures.pl b/scripts/admin/oneoff/find_saved_fixtures.pl new file mode 100644 index 0000000..5019b5a --- /dev/null +++ b/scripts/admin/oneoff/find_saved_fixtures.pl @@ -0,0 +1,59 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +use CGI::Carp qw(fatalsToBrowser) ; +# use Date::Calc qw(:all); +# use DBI; + +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/find_saved_fixtures.pl?1 +# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/build_poc_table.pl?1&recipient + +#------------------------------------------------------------------------------- + +my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +our $debug = $ARGV[0] ; +our $poc_or_recipient = $ARGV[1] ; +# our $username = 'rory' ; + +if ($debug) { print "Content-type: text/html\n\n"; } + +#------------------------------------------------------------------------------------------ + +&today ; + +&db_open_upd ; +# &db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &load_vars ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +if ($debug) { print "Done."; } + +exit; + +#------------------------------------------------------------------------------------------ + +sub load_vars { + + &db_min_ro('analytics_event_bookings','id,fixtures_saved_values','','','') ; + + foreach my $id (keys %{$db{analytics_event_bookings}}) { + if ($db{analytics_event_bookings}{$id}{fixtures_saved_values}) { + my @abc = split(/\|/,$db{analytics_event_bookings}{$id}{fixtures_saved_values}) ; + foreach my $fixture (@abc) { + my @abc2 = split(/\;/,$fixture) ; + print "\n $abc2[9],$abc2[10],$abc2[11]" if $abc2[9] || $abc2[10] || $abc2[11] ; + } + } + } + +} + +use db ; +use today ; +use common ; +use common_min ; diff --git a/scripts/admin/oneoff/sendmailv5.pl b/scripts/admin/oneoff/sendmailv5.pl new file mode 100644 index 0000000..7da1d3d --- /dev/null +++ b/scripts/admin/oneoff/sendmailv5.pl @@ -0,0 +1,78 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +use MIME::Lite; +use Mail::Sendmail; + +require cfg ; + +print "Content-type: text/html\n\n"; + +&today ; + +our $debug = 1 ; + +#------------------------------------------------------------------------------------------ + +# https://aisadmin.co.za/cgi-bin/aisa/scripts/admin/oneoff/sendmailv5.pl + +use CGI::Carp qw(fatalsToBrowser); + +# my $message = "Hi Kre8IT, +#

    +# Your match analysis is now complete and ready for review in your analytics channel. +#

    +# Match details:
    +# Date: 2026-02-02
    +# Event name: K8Test
    +# Sport: Rugby
    +# Age group: u15
    +# Coding type: Primary +#

    +# You can now log in and begin reviewing the analysis, clips, and insights with your team. +#

    +#
    AI Sport Africa Analytics
    +#

    +# If you have any questions or would like feedback adjusted or expanded, please don’t hesitate to get in touch. +#

    +# Kind regards,
    +# AI Sport Africa Analytics
    +# $email_analytics" ; + +$email{$event_id}{$row_cnt}{date} = '2026-02-02' ; +$event_name = 'K8TEST' ; +$sport = 'Rugby' ; +$age_group = 'u/15' ; +$coding_type = 'Primary' ; + +my $hmsg = qq~Hi Kre8IT,

    Your match analysis is now complete and ready for review in your analytics channel.~; +my $tmsg = qq~ Match details  + Date:  $email{$event_id}{$row_cnt}{date}  + Event name:  $event_name  + Sport:  $sport  + Age group:  $age_group  + Coding type:  $coding_type  +~ ; + +our $display_notif_msg = qq~You can now log in and begin reviewing the analysis, clips, and insights with your team. +

    +
    AI Sport Africa Analytics
    +

    +If you have any questions or would like feedback adjusted or expanded, please don’t hesitate to get in touch. +

    +AI Sport Africa Analytics +
    +$email_analytics +

    ~ ; + +&common_send_smtp_mail('',$email_it_1,'','',"Match Analysis Event 1001 Fixture 1",$hmsg,$tmsg,'html') ; + +exit ; + +#------------------------------------------------------------------------------------------ + +use today ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/aisa_event_feedback.pl b/scripts/aisa_event_feedback.pl new file mode 100644 index 0000000..2a5714d --- /dev/null +++ b/scripts/aisa_event_feedback.pl @@ -0,0 +1,629 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +# unless ($useropts{it}{$username}) { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; +use Time::Piece ; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $no_dates_in_table = 1 ; + +# our $debug = 1 ; +# our $testing = 1 ; + +# if ($username ne 'handre') { + # print "<< MAINTENANCE IN PROGRESS >>" ; exit ; +# } + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $srchscr = 1 ; + +if ($iaction eq 'save') { + &db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &common_min_load_params ; + &report_ifields ; + &update ; + &list_screen ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + # exit if $username eq 'handre' && $testing ; + &screen3 ; + # &redirect_screen; +} + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + &report_screen if $iaction eq '' ; + + if ($iaction eq 'report') { + &common_min_load_params ; + &report_ifields ; + &list_screen ; + &screen3 ; + } + + &common_min_action ; + + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub hidden_fields { + + # $ignore{id} = 1 ; + $ignore{iaction} = 1 ; + $ignore{date} = 1 ; + $ignore{troubleshoot_monitor_id} = 1 ; + + for my $d_cnt (1 .. $date_counter) { + for my $shift_cnt (1 .. 4) { + $ignore{"shifttroubleshootmonitorid_$shift_cnt\_$d_cnt"} = 1 ; + $ignore{"shift_troubleshoot_monitor_$shift_cnt\_$d_cnt"} = 1 ; + } + } + # $ignore{monitor_ids} = 1 ; + $ignore{update_table_1} = 1 ; + $ignore{update} = 1 ; + $ignore{"itv-table_length"} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + &schedule_update("shift_operator_ids","troubleshoot_monitor_ids","shifttroubleshootmonitorid","troubleshoot_monitor_notes") ; +# 12=f:;s:|s:1;t:1|f:2;s:2-13=|f:3;s:3|f:4;s:4 + + &schedule_update_monitor_reports ; + + # my @table_sql_where = () ; + + # if ($i{client_id}) { + # push @table_sql_where, "`quote_to`='$i{client_id}'" ; + # } + # if ($i{date_from} && $i{date_to}) { # check dates + # push @table_sql_where, "(('$i{date_from} 00:00:00' <= `date_from` AND `date_from` <= '$i{date_to} 23:59:59') OR ('$i{date_from} 00:00:00' <= `date_to` AND `date_to` <= '$i{date_to} 23:59:59') OR (`date_from` <= '$i{date_from} 00:00:00' AND '$i{date_to} 23:59:59' <= `date_to`))" ; ############################################### > OR >= + + # } + + # # if ($i{monitor_id} and $i{monitor_id} ne 'all') { + # # push @table_sql_where,"`TROUBLESHOOT MONITOR` = '$db{users}{1}{name}'" ; + # # } + + # my $table_sql_where_str = join(" AND ",@table_sql_where) ; + + # &db_min_ro($table,"id,monitor_report_saved_data","$table_sql_where_str",'','') ; + + # my %saved_field_hash = () ; + + # foreach my $id (keys %{$db{$table}}) { + + # my @saved_data_split_1 = split(/\-/,$db{$table}{$id}{monitor_report_saved_data}) ; + + # foreach my $a (@saved_data_split_1) { + # my @saved_data_split_2 = split(/\=/,$a) ; + # my $event_sys_id = $saved_data_split_2[0] ; + # my @saved_data_split_3 = split(/\|/,$saved_data_split_2[1]) ; + # my $day_cnt = 0 ; + # foreach my $b (@saved_data_split_3) { + # $day_cnt++ ; + # next unless $b =~ /(\d+)/g ; + # $saved_field_hash{$id}{$event_sys_id}{$day_cnt} = $b ; + # } + # } + # } + + # foreach my $field_name (keys %i) { + + # next if ($field_name =~ /update_event/ && !$i{$field_name}) || $field_name !~ /update_event/ ; + + # my @fields = split(/\_/,$field_name) ; + + # my $system_id = substr($fields[-3],5) ; + # my $day_cnt = $fields[-2] ; + # my $event_id = $fields[-1] ; + + # my $fixture_field = "fixture_check_event$system_id\_$day_cnt\_$event_id" ; + # my $status_field = "status_event$system_id\_$day_cnt\_$event_id" ; + + # $saved_field_hash{$event_id}{$system_id}{$day_cnt} = qq~~ ; + # $saved_field_hash{$event_id}{$system_id}{$day_cnt} = qq~f:$i{$fixture_field};~ if $i{$fixture_field} ; + # $saved_field_hash{$event_id}{$system_id}{$day_cnt} .= qq~s:$i{$status_field}~ if $i{$status_field} ; + + # } + + # %ii = %i ; + # %i = () ; + + # foreach my $event_id (keys %saved_field_hash) { + + # $i{monitor_report_saved_data} = qq~~ ; + + # foreach my $system_id (sort { $a <=> $b } keys %{$saved_field_hash{$event_id}}) { + + # # $i{monitor_report_saved_data} .= qq~$system_id\=~ ; + # my $saved_by_system = qq~~ ; + + # foreach my $day_max (sort { $b <=> $a } keys %{$saved_field_hash{$event_id}{$system_id}}) { + # for my $day_cnt (1 .. $day_max) { + # $saved_by_system .= qq~$saved_field_hash{$event_id}{$system_id}{$day_cnt}|~ ; + # } + # chop $saved_by_system if $day_max ; + # last ; + # } + # $i{monitor_report_saved_data} .= qq~$system_id\=$saved_by_system\-~ if $saved_by_system =~ /(\d+)/g ; + # } + + # chop $i{monitor_report_saved_data} if $i{monitor_report_saved_data} ; + + # next if ($i{monitor_report_saved_data} eq $db{$table}{$event_id}{monitor_report_saved_data}) || (!$i{monitor_report_saved_data} && !$db{$table}{$event_id}{monitor_report_saved_data}) ; + + # &db_min_upd($table,"id='$event_id'") ; + + # } + + # %i = %ii ; + +} #------------------------------------------------------------------------------------------ + +sub report_ifields { + + &load_search_vars ; + + # if ($i{date}) { # check dates + # push @report_sql, " `date_from` <= '$i{date} 23:59:59' AND '$i{date} 00:00:00' <= `date_to` " ; + # push @report_results, "DATE IS '$i{date}'" ; + # } else { + # $error = qq~PLEASE ENTER A DATE!~ ; + # &report_screen; + # } + + if ($i{client_id}) { + push @report_sql, "`quote_to`='$i{client_id}'" ; + &db_min_ro('customers','id,name',"`id`='$i{client_id}'") ; + push @report_results,"`CLIENT` = '$db{customers}{$i{client_id}}{name}'" ; + } + + my $date_from_val = $i{date_from} ; my $date_to_val = $i{date_to} ; + + $date_from_val =~ s/\-//g ; $date_to_val =~ s/\-//g ; + + if ($i{date_from} && $i{date_to} && $date_from_val > $date_to_val) { + $error = qq~THE START MUST BE BEFORE THE END DATE!!!~ ; + &report_screen ; + } elsif ($i{date_from} && $i{date_to}) { # check dates + push @report_sql, "(('$i{date_from} 00:00:00' <= `date_from` AND `date_from` <= '$i{date_to} 23:59:59') OR ('$i{date_from} 00:00:00' <= `date_to` AND `date_to` <= '$i{date_to} 23:59:59') OR (`date_from` <= '$i{date_from} 00:00:00' AND '$i{date_to} 23:59:59' <= `date_to`))" ; ############################################### > OR >= + push @report_results, "(EVENT BETWEEN '$i{date_from}' AND '$i{date_to}')" ; + } else { + $error = qq~PLEASE ENTER A START AND END DATE!!!~ ; + &report_screen; + } + + if ($i{monitor_id} and $i{monitor_id} ne 'all') { + push @report_results,"`TROUBLESHOOT MONITOR` = '$db{users}{1}{name}'" ; + push @report_sql, " `troubleshoot_monitor_ids` LIKE '%$i{troubleshoot_monitor_id}%' " ; + } elsif ($i{monitor_id} and $i{monitor_id} eq 'all') { + push @report_results,"`TROUBLESHOOT MONITORS` = 'ALL'" ; + } else { + # push @report_sql, "(`user_id` = '')" ; + } + + $report_results_msg = uc join(', ', @report_results) ; + + if ($iaction eq 'save') { + $isaved = qq(SUCCESSFULLY SAVED!) ; + } elsif (not $report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER) ; + &report_screen; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + + our $srch_where_sql = join(' AND ',@report_sql) ; + + my @date = split(/ /,$i{date}) ; + + my ($year_inp,$month_inp,$day_inp) = split(/\-/,$date[0]) ; + + our $date_inp_val = int("$year_inp$month_inp$day_inp") ; + our $today_val = int("$now_year$now_mm$now_dd") ; + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + if ($i{monitor_id} and $i{monitor_id} ne 'all') { + &db_min_ro('users','1,name',"`id` = '$i{troubleshoot_monitor_id}'",'','') ; + } + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + $print_box_content_rows .= &common_min_forms_start("$lcpage") ; + + # our $monitoring_report = 1 ; + + our $troubleshoot_monitoring_report = 1 ; + + our $extra_column = ",monitor_report_saved_data" ; + + &schedule_load_list_vars("$srch_where_sql") ; + + $fcol = 12 ; + + my $report = 1 ; + + our $xlsxdir = "troubleshoot_report" ; + + our $xlsxreportname = "Troubleshoot_Report" ; + + my $date = &common_write_date_interval($i{date_from},$i{date_to}) ; + + our $xlsx_title_heading = "Troubleshoot Allocations $date" ; + + my $field_name = "troubleshoot_shift_monitor" ; + + my $uc_field_name = ucfirst $field_name ; + + our $print_tbody_extra = qq~~ ; + + # our @sql_col_display_extra = ("date","shift_1_(07:00-10:00)","shift_2_(10:00-13:00)","shift_3_(13:00-16:00)","shift_4_(16:00-19:00)") ; + our @sql_col_display_extra = ("date","shift_1_(08:00-11:00)","shift_2_(11:00-14:00)","shift_3_(14:00-17:00)","shift_4_(17:00-21:00)","notes") ; + push @sql_col_display_extra,"update" ; + # if $date_inp_val >= $today_val ; + + our @sql_col_display = ("count","event","date","day","start_date","start_time","end_time","region","sport","system","club_name","operator","fixture_check","status","comments") ; + + # push @sql_col_display,"update" if ($monitoring_report || $temp_calibrator_report) && $date_inp_val >= $today_val ; + + &report_xlsx_export_header("$xlsxreportname",$xlsxdir,'',$xlsx_title_heading) ; + # troubleshoot_monitoring_report + + &schedule_build_extra_table("shift_troubleshoot_monitor","shift_operator_ids","troubleshoot_monitor_ids","troubleshoot_monitor_notes","select_troubleshoot_monitors") ; + + # &common_min_table_update_checkbox_col("3") ; + + push @sql_col_display,"update" ; + + my $table_col_name = "troubleshoot_monitor_ids" ; + + $xlsxrow-- ; + + my @rev_sql_col_display = reverse @sql_col_display ; + + foreach (@rev_sql_col_display) { $lastchild++ ; $last_child{$_} = $lastchild ; } + + &schedule_get_monitor_reports_default_values ; + + # our %default_values = () ; + # # 12=f:;s:|s:1;t:1|f:2;s:2-13=|f:3;s:3|f:4;s:4 + # foreach my $id (keys %{$db{$table}}) { + + # my @saved_data_split_1 = split(/\-/,$db{$table}{$id}{monitor_report_saved_data}) ; + # # $sql_col_display[-2] + # # $default_vals{}{$event_sys_id}{$sys_day_cnt}{$id} + + # foreach my $a (@saved_data_split_1) { + # my @saved_data_split_2 = split(/\=/,$a) ; + # my $event_sys_id = $saved_data_split_2[0] ; + # my @saved_data_split_3 = split(/\|/,$saved_data_split_2[1]) ; + # my $day_cnt = 0 ; + # foreach my $b (@saved_data_split_3) { + # $day_cnt++ ; + # next unless $b =~ /(\d+)/g ; + # my @saved_data_split_3 = split(/\;/,$b) ; + # my @saved_data_split_4 = split(/\:/,$saved_data_split_3[0]) ; + # my @saved_data_split_5 = split(/\:/,$saved_data_split_3[1]) ; + + # if ($saved_data_split_4[0] =~ /f/) { + # $default_values{$sql_col_display[-3]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_4[1] ; + # } + # if ($saved_data_split_5[0] =~ /s/) { + # $default_values{$sql_col_display[-2]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_5[1] ; + # } elsif ($saved_data_split_4[0] =~ /s/) { + # $default_values{$sql_col_display[-2]}{$event_sys_id}{$day_cnt}{$id} = $saved_data_split_4[1] ; + # } + # } + # } + # } + + &common_min_select_opts("status","monitor_status","status") ; + + our @default_javascript_by_id_2 = () ; + + &schedule_build_table("troubleshoot_monitor_ids") ; + + # if ($date_inp_val >= $today_val) { + # $trigger_jquery_raw .= qq~ + # \$("#itv-table tr th:nth-last-child(5)").css("width","10%") ; + # \$("#itv-table tr th:nth-last-child(4)").css("width","10%") ; + # \$("#itv-table tr th:nth-last-child(3)").css("width","10%") ; + # \$("#itv-table tr th:nth-last-child(2)").css("width","10%") ; + # ~ ; + + # } else { + # $trigger_jquery_raw .= qq~ + # \$("#select_monitors tr th:nth-last-child(1)").css("width","23%") ; + # \$("#select_monitors tr th:nth-last-child(4)").css("width","23%") ; + # \$("#select_monitors tr th:nth-last-child(3)").css("width","23%") ; + # \$("#select_monitors tr th:nth-last-child(2)").css("width","23%") ; + # ~ ; + # } + + # &calibration_build_table_and_or_excel(1) ; + + # if ($found_after_date) { + + + + # } else { + # $trigger_jquery_raw .= qq~ + # \$("#itv-table tr th:nth-last-child(2)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(3)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(4)").css("width", "7.5%") ; + # \$("#itv-table tr th:nth-last-child(5)").css("width", "7.5%") ; + + # ~ ; + # } + + + # my $first_table_multi_select_table_cells_str = join(",",@first_table_multi_select_table_cells) ; + + # &common_min_table_select_fixed_width_jquery($first_table_multi_select_table_cells_str ) ; + + # &common_min_table_select_default_values_jquery ; + + # &common_min_table_update_checkbox_col("3") ; + + + my $first_table_multi_select_table_cells_str = join(",",@first_table_multi_select_table_cells) ; + # $useropts{table_id} + &common_min_table_select_fixed_width_jquery($first_table_multi_select_table_cells_str) ; + + &common_min_table_select_prevent_dropdown_overlap_jquery ; + + &common_min_table_select_default_values_jquery ; + + &common_min_table_update_checkbox_col("3","content","[id^='textareaComments_'],[id^='selectFixture_check_'],[id^='selectStatus_'],[id^='selectShift_troubleshoot_monitor_1_'],[id^='selectShift_troubleshoot_monitor_2_'],[id^='selectShift_troubleshoot_monitor_3_'],[id^='selectShift_troubleshoot_monitor_4_'],[id^='textareaShift_troubleshoot_monitor_notes_1_'],[id^='textareaShift_troubleshoot_monitor_notes_2_'],[id^='textareaShift_troubleshoot_monitor_notes_3_'],[id^='textareaShift_troubleshoot_monitor_notes_4_']") ; + + # my $default_javascript_by_id_str = join (",",@default_javascript_by_id) ; + + # print "\n default_javascript_by_id_str : $default_javascript_by_id_str" ; + + # $trigger_jquery_raw .= qq~ + + # all_def_vals = {$default_javascript_by_id_str} ; + + # \$("#$useropts{table_id}").on("change","[id^='selectFixture_check_'],[id^='selectStatus_']", function (event) { + # event.preventDefault(); + # console.log("2 update : "+this.id) ; + # check_whether_to_update(this.id); + # }); + + # ~ ; + + # &common_min_table_update_checkbox_col("3") ; + + $fnsortorder = 'asc' ; + + &common_min_extra_crumb("$lcpage","Search Screen") ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + # &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + # our $lcpage = 'monitor-allocations' ; + # our $lcpage = 'troubleshoot-report' ; + our $lcpage = 'aisa-event-feedback' ; + + &common_page_name ; + + our $table = 'event_quotes' ; + $page_title = 'AISA Event Feedback' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + our $lcol = 3 ; + our $fcol = 5 ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + &common_min_select_opts('client_id','customers','name','','','',"events='1'") ; + + $allow_deselect{client_id} = 1 ; + $opts{client_id} =~ s/value="$i{client_id}"/value="$i{client_id}" SELECTED/g if $i{client_id} ; + $print_box_content_rows .= &common_min_form_select('client_id','') ; + + my ($sql_next_day) = &common_add_delta_days(1) ; + my ($next_year,$next_month,$next_day) = split(/\-/,$sql_next_day) ; + $print_box_content_rows .= &common_min_form_datepicker('date_from',"$now_year-$now_mm-$now_dd") ; #unless $i{date_from} ; + $print_box_content_rows .= &common_min_form_datepicker('date_to',"$next_year-$next_month-$next_day") ; #unless $i{date_from} ; + + push @date_value_ids,"input[name='date_from']" ; + push @date_value_ids,"input[name='date_to']" ; + + &common_min_table_validate_date_inputs_jquery ; + + $preferred_title{troubleshoot_monitor_id} = "Troubleshoot Monitor" ; + + # &db_min_ro('users',"id,name","`user_type` = 'support' OR `user_type` = 'casual_calibrator'",'','') ; + # &db_min_ro('users',"id,name,username","`name` NOT LIKE 'Rory%'",'','') ; + + $selected{troubleshoot_monitor_id}{all} = 'SELECTED' ; + + # if ($i{monitor_id}) { + # $selected{monitor_id}{$i{monitor_id}} = 'SELECTED' ; + # $selected{monitor_id}{all} = '' ; + # } + + # foreach (sort {$db{users}{$a}{name} cmp $db{users}{$b}{name}} keys %{$db{users}}) { + # next if $useropts{it}{$db{users}{$_}{username}} ; + # $opts{monitor_id} .= qq~~ ; + # } + $opts{troubleshoot_monitor_id} .= qq~~ ; + + $print_box_content_rows .= &common_min_form_select('troubleshoot_monitor_id','') ; + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +# my $page = "$lcpage\s" ; + +my $page = "event-quotes" ; + +if ($s{no}) { $page = $lcpage ; } + +# &db_min_ro('daily_monitor_ids','date,monitor_ids') ; + +my @sql_col_display_2 = @sql_col_display ; + +@sql_col_display = @sql_col_display_extra ; + +our %custom_column_styles = () ; + +$custom_column_styles{fixture_check} = qq~style="width:7%;min-width:150px;"~ ; +$custom_column_styles{status} = qq~style="width:7%;min-width:150px;"~ ; + +&common_min_thead ; + +$print_box_content_rows .= qq~ + + $print_thead + + + $print_tbody_extra + + +
    ~ ; + +@sql_col_display = @sql_col_display_2 ; + +&common_min_thead ; + +&common_min_table('id',$page,'list') ; + +our $savjqy = 1 ; + +$extra_form_fields .= qq~ + + + + + +~; + +for (1 .. $date_cnt) { + + $extra_form_fields .= qq~ + + + + + ~ ; + +} + + +# $print_box_content_rows .= &common_min_forms_end('','','save') if $date_inp_val >= $today_val ; +$print_box_content_rows .= &common_min_forms_end('','','save') ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub redirect_screen { + +&common_min_alert_type ; + +print < + + + + $useropts{title} + + + + + + +

    + + + + + +
    + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +use common ; +use report ; +use xlsxcreator ; +use today ; +# use calibration_test ; +use schedule ; +1; \ No newline at end of file diff --git a/scripts/all_fixtures_report.pl b/scripts/all_fixtures_report.pl new file mode 100644 index 0000000..7a7e393 --- /dev/null +++ b/scripts/all_fixtures_report.pl @@ -0,0 +1,1284 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +# unless ($useropts{it}{$username}) { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Mail::Sendmail; +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; +use Time::Piece ; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}) ; +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +# our $debug = 1 ; +# our $testing = 1 ; + +# if ($username ne 'handre') { + # print "<< MAINTENANCE IN PROGRESS >>" ; exit ; +# } + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +our %fixtures_status = (1 => 'Coding',2 => 'Ready',3 => 'Complete') ; +# our %coding_provider = (1 => 'SportVot',2 => 'iSport') ; +our %footage_type = ("s" => "Pixellot","r" => "YouTube") ; +our %service_types = (1 => "Live Coding",2 => "Individual 48 hrs",3 => "Post Coding 24 hrs") ; +our %coding_type = ("s" => "Standard","p" => "Premium","i" => "Individual") ; +our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +our $srchscr = 1 ; + +# $usertype = 'coding_provider' ; + +# if ($username ne 'handre' && $username ne 'rory') { +if ($glod_user_level < 5 && $usertype ne 'coding_provider') { + print "Please Log in as a Level 5 or Coding Provider User Type!" ; + exit ; +} + +if ($iaction eq 'save') { + &db_open_upd ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &common_min_load_params ; + &update ; + &report_ifields; + $isaved = qq~SUCCESSFULLY SAVED!~ ; + &list_screen ; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it + &db_close_conn ; + exit if $testing ; + &screen3; + # &redirect_screen; +} + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + &report_screen if $iaction eq '' ; + + if ($iaction eq 'report') { + &common_min_load_params ; + &report_ifields ; + &list_screen ; + &screen3 ; + } + + &common_min_action; + $db_ignore_open_close = 0 ; # do one open and one close instead of repeating it +&db_close_conn ; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + +} #------------------------------------------------------------------------------------------ + +sub insert { + + +} #------------------------------------------------------------------------------------------ + +sub update { + + my @analytics_field_keys = ("stream_forwarding","stream_key","stream_URL") ; + + &db_min_ro($table,"id,start_date_time,client_id,fixtures_saved_values,analytics_saved_values,cant_charge_client_fixtures,sport_type_ids,total_fixtures,event_accepted,event_name,created_by","",'','') ; + + my %seen_event_id = () ; my %ii = %i ; %i = () ; my %email = () ; + + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + foreach my $_ (keys %ii) { + + # next if $_ !~ /update_/ || ($_ =~ /update_/ && !$ii{$_}) ; + next if $_ !~ /update_/ ; + + my @abc = split(/\_/,$_) ; + + my $event_id = $abc[-1] ; # or -2? + + next if $seen_event_id{$event_id} ; + + $seen_event_id{$event_id} = 1 ; + + $i{fixtures_saved_values} = qq~~ ; + $i{analytics_saved_values} = qq~~ ; + + our @fixtures_saved_values_split = split(/\|/,$db{$table}{$event_id}{fixtures_saved_values}) ; + my @cant_charge_client_split = split(/\;/,$db{$table}{$event_id}{cant_charge_client_fixtures}) ; + + my $nr_of_rows = $db{$table}{$event_id}{total_fixtures} ; + $nr_of_rows = scalar @fixtures_saved_values_split if scalar @fixtures_saved_values_split > $nr_of_rows ; + + # my $cant_charge_field = "cant_charge_client_reasons_$event_id" ; + # $ignore{$cant_charge_field} = 1 ; + + my %iii = () ; + + for my $row_nr (1 .. 100) { + + last if $row_nr > $nr_of_rows ; + + my $input_vals = qq~~ ; + + my $upd_field = "update_$row_nr\_$event_id" ; + my $coding_provider_field = "coding_provider_$row_nr\_$event_id" ; + my $status_field = "status_$row_nr\_$event_id" ; + my $moderated_field = "moderated_$row_nr\_$event_id" ; + my $analyst_field = "analyst_$row_nr\_$event_id" ; + my $cant_charge_field = "cant_charge_client_$row_nr\_$event_id" ; + + my @parts = split(/\;/,$fixtures_saved_values_split[$row_nr - 1]); + + $i{cant_charge_client_fixtures} .= ($ii{$upd_field}) ? qq~$ii{$cant_charge_field};~ : qq~$cant_charge_client_split[$row_nr-1];~ ; + + # $cant_charge_field + + # splice(@parts, -2) if @parts >= 2; + + $i{fixtures_saved_values} .= ($ii{$upd_field}) ? join(";",@parts[0..9]) . ';' . qq~$ii{$coding_provider_field};$ii{$status_field};$ii{$moderated_field};$ii{$analyst_field}~ : qq~$fixtures_saved_values_split[$row_nr - 1]~ ; + + $i{fixtures_saved_values} =~ s/;+$//g ; + $i{fixtures_saved_values} .= qq~|~ ; + + $ignore{$upd_field} = 1 ; + $ignore{$coding_provider_field} = 1 ; + $ignore{$status_field} = 1 ; + $ignore{$moderated_field} = 1 ; + $ignore{$analyst_field} = 1 ; + + foreach (@analytics_field_keys) { + my $field_key = "$_\_$row_nr\_$event_id" ; + $i{$field_key} =~ s/\;/\_semi_colon_character_/g ; + $i{$field_key} =~ s/\|/\_pipe_character_/g ; + $i{analytics_saved_values} .= qq~$ii{$field_key};~ ; + $ignore{$field_key} = 1 ; + } + $i{analytics_saved_values} =~ s/;+$//g ; + $i{analytics_saved_values} .= qq~|~ ; + + if ((!$parts[12] || $parts[12] eq "2") && $ii{$moderated_field} eq "1" && $ii{$upd_field}) { + $email{$event_id}{$row_nr}{date} = ($parts[0]) ? $parts[0] : $db{$table}{$event_id}{start_date_time} ; + $email{$event_id}{$row_nr}{date} = &common_min_date_as_string($email{$event_id}{$row_nr}{date}) ; + $email{$event_id}{$row_nr}{sport} = ($parts[1]) ? $parts[1] : ($db{$table}{$event_id}{sport_type_ids} !~ /;/) ? $db{$table}{$event_id}{sport_type_ids} : "" ; + $email{$event_id}{$row_nr}{age_group} = ucfirst $parts[2] ; + $email{$event_id}{$row_nr}{coding_type} = $coding_type{$parts[7]} ; + } + + } + + $i{cant_charge_client_fixtures} =~ s/;+$//g ; + $i{analytics_saved_values} =~ s/\|+$//g ; + $i{fixtures_saved_values} =~ s/\|+$//g ; + + # $i{fixtures_saved_values} =~ s/([a-zA-Z0-9;])\|+\z/$1/; + + $i{fixtures_saved_values} =~ s/([a-zA-Z0-9]);+(\|)/$1$2/g; + $i{fixtures_saved_values} =~ s/([a-zA-Z0-9])\|+$/$1/; + + $ignore{fixtures_saved_values} = (($i{fixtures_saved_values} && $db{$table}{$event_id}{fixtures_saved_values} && $i{fixtures_saved_values} eq $db{$table}{$event_id}{fixtures_saved_values} ) || (!$i{fixtures_saved_values} && !$db{$table}{$event_id}{fixtures_saved_values})) ? 1 : 0 ; + $ignore{analytics_saved_values} = (($i{analytics_saved_values} && $db{$table}{$event_id}{analytics_saved_values} && $i{analytics_saved_values} eq $db{$table}{$event_id}{analytics_saved_values}) || (!$i{analytics_saved_values} && !$db{$table}{$event_id}{analytics_saved_values})) ? 1 : 0 ; + $ignore{cant_charge_client_fixtures} = (($i{cant_charge_client_fixtures} && $db{$table}{$event_id}{cant_charge_client_fixtures} && $i{cant_charge_client_fixtures} eq $db{$table}{$event_id}{cant_charge_client_fixtures}) || (!$i{cant_charge_client_fixtures} && !$db{$table}{$event_id}{cant_charge_client_fixtures})) ? 1 : 0 ; + + $i{client_id} = $db{$table}{$event_id}{client_id} ; + $ignore{client_id} = 1 ; + + $i{total_fixtures} = $db{$table}{$event_id}{total_fixtures} ; + $ignore{total_fixtures} = 1 ; + + $i{sport_type_ids} = $db{$table}{$event_id}{sport_type_ids} ; + $ignore{sport_type_ids} = 1 ; + + $i{event_accepted} = $db{$table}{$event_id}{event_accepted} ; + $ignore{event_accepted} = 1 ; + + if (!$ignore{cant_charge_client_fixtures} && $i{event_accepted} && $i{client_id} && $i{sport_type_ids}) { + &analytics_event_booking_tabs_update_credits_used($event_id,'') ; + } + + &db_min_upd($table,"id='$event_id'") ; + + } + + %i = %ii ; + + my $client_sql = join(" OR ", map { "id='$db{$table}{$_}{client_id}'"} keys %{$db{$table}}) ; + + if ($client_sql) { + + &db_min_ro('customers','id,name',$client_sql,'','') ; + + &db_min_ro('sport_types','id,name','','','') ; + + my $users_sql = join(" OR ", map { "id='$db{$table}{$_}{created_by}'"} keys %{$db{$table}}) ; + + &db_min_ro('users','id,email',$users_sql,'','') ; + + } + + foreach my $event_id (sort {$a cmp $b} keys %email) { + foreach my $row_cnt (sort {$a cmp $b} keys %{$email{$event_id}}) { + + my $event_name = ($db{$table}{$event_id}{event_name}) ? $db{$table}{$event_id}{event_name} : "N/A" ; + my $sport = ($db{sport_types}{$email{$event_id}{$row_cnt}{sport}}{name}) ? $db{sport_types}{$email{$event_id}{$row_cnt}{sport}}{name} : "N/A" ; + my $age_group = ($email{$event_id}{$row_cnt}{age_group}) ? $email{$event_id}{$row_cnt}{age_group} : "N/A" ; + my $coding_type = ($email{$event_id}{$row_cnt}{coding_type}) ? $email{$event_id}{$row_cnt}{coding_type} : "N/A" ; + + # my $subj = "" ; + # my $message = "Hi $db{customers}{$db{$table}{$event_id}{client_id}}{name}, + + # Your match analysis is now complete and ready for review in your analytics channel. + + # Match details: + # Date: $email{$event_id}{$row_cnt}{date} + # Event name: $event_name + # Sport: $sport + # Age group: $age_group + # Coding type: $coding_type + + # You can now log in and begin reviewing the analysis, clips, and insights with your team. + + # If you have any questions or would like feedback adjusted or expanded, please don’t hesitate to get in touch. + + # Kind regards, + # AI Sport Africa Analytics + # $email_analytics" ; + + my $hmsg = qq~Hi Kre8IT,

    Your match analysis is now complete and ready for review in your analytics channel.~; + my $tmsg = qq~ Match Details  +  Date:  $email{$event_id}{$row_cnt}{date}  +  Event name:  $event_name  +  Sport:  $sport  +  Age group:  $age_group  +  Coding type:  $coding_type  + ~ ; + + our $display_notif_msg = qq~You can now log in and begin reviewing the analysis, clips, and insights with your team. +

    + AI Sport Africa Analytics +

    + If you have any questions or would like feedback adjusted or expanded, please don’t hesitate to get in touch. +

    + AI Sport Africa Analytics +
    + $email_analytics +

    ~ ; + + #
    AI Sport Africa Analytics
    + + # &db_min_ro('users','id,email',"id='25'",'','') if $event_id eq '1001' ; + + # &common_send_smtp_mail('',$db{users}{$db{$table}{$event_id}{created_by}}{email},'','',"Match Analysis Event $event_id Fixture $row_cnt",$message) if $event_id eq '1001' ; + # &common_send_smtp_mail('',$db{users}{$db{$table}{$event_id}{created_by}}{email},$email_analytics,'',"Match Analysis Event $event_id Fixture $row_cnt",$message) if $event_id ne '1001' ; + &common_send_smtp_mail('',$db{users}{$db{$table}{$event_id}{created_by}}{email},$email_analytics,'',"Match Analysis Event $event_id Fixture $row_cnt",$hmsg,$tmsg,'html') ; + } + } + +# &common_send_smtp_mail('','handre@kre8it.co.za','','',"Hello OWrld",'Hello World!') ; + + # exit ; + +} #------------------------------------------------------------------------------------------ + +# sub analytics_event_booking_tabs_update_credits_used { + + # my ($id,$id2) = @_ ; + + # my %credits_used = () ; my $row_cnt = 0 ; + + # my @cnt_charge = split(/\;/,$db{$table}{$id}{cant_charge_client_fixtures}) ; + + # if ($db{$table}{$id}{client_id}) { + # foreach my $fixture_row (@fixtures_saved_values_split) { + # $row_cnt++ ; + # last if $row_cnt > $db{$table}{$id}{total_fixtures} ; + # my @fixtures_saved_values_split_2 = split(/\;/,$fixture_row) ; + # my $sport_id = ($db{$table}{$id}{sport_type_ids} !~ /;/) ? $db{$table}{$id}{sport_type_ids} : $fixtures_saved_values_split_2[1] ; + + # next unless $sport_id ; + + # $credits_used{previous}{premium}{$db{$table}{$id}{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 'p' && !$cnt_charge[$row_cnt-1] ; + # $credits_used{previous}{standard}{$db{$table}{$id}{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 's' && !$cnt_charge[$row_cnt-1] ; + # $credits_used{previous}{individual}{$db{$table}{$id}{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 'i' && !$cnt_charge[$row_cnt-1] ; + # } + # } + + # if ($i{client_id}) { + + # @fixtures_saved_values_split = split(/\|/,$i{fixtures_saved_values}) ; + # $row_cnt = 0 ; + # @cnt_charge = split(/\;/,$i{cant_charge_client_fixtures}) ; + + # foreach my $fixture_row (@fixtures_saved_values_split) { + + # $row_cnt++ ; + # last if $row_cnt > $i{total_fixtures} ; + # my @fixtures_saved_values_split_2 = split(/\;/,$fixture_row) ; + + # my $sport_id = ($i{sport_type_ids} !~ /;/) ? $db{$table}{$id}{sport_type_ids} : $fixtures_saved_values_split_2[1] ; + + # next unless $sport_id ; + + # $credits_used{new}{premium}{$i{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 'p' && !$cnt_charge[$row_cnt-1] ; + # $credits_used{new}{standard}{$i{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 's' && !$cnt_charge[$row_cnt-1] ; + # $credits_used{new}{individual}{$i{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 'i' && !$cnt_charge[$row_cnt-1] ; + + # } + + # my %seen = () ; + + # } + + # $seen{client}{$i{client_id}} = 1 if $i{client_id} ; + # $seen{client}{$db{$table}{$id}{client_id}} = 1 if $db{$table}{$id}{client_id} ; + + # foreach (split(/\;/,$db{$table}{$id}{sport_type_ids})) { + # $seen{sport}{$_} = 1 if $_ ; + # } + + # if ($i{sport_type_ids}) { + # foreach (split(/\;/,$i{sport_type_ids})) { + # $seen{sport}{$_} = 1 if $_ ; + # } + # } + + # my $sport_sql = join(" OR ",map{"sport_type_id='$_'"} keys %{$seen{sport}}) ; + # my $client_sql = join(" OR ",map{"client_id='$_'"} keys %{$seen{client}}) ; + # my $id_sql = ($id2) ? "analytics_event_id='$id2'" : ($id) ? "analytics_event_id='$id'" : "" ; + + # my @sql_where_arr = () ; + # push @sql_where_arr,"($sport_sql)" if $sport_sql ; + # push @sql_where_arr,"($client_sql)" if $client_sql ; + # push @sql_where_arr,$id_sql if $id_sql ; + + # my $sql_where = join(" AND ",@sql_where_arr) ; + + # &db_min_ro('credits_used','*',$sql_where,'','') ; my %exists = () ; + + # my %db_credits_used = %db ; + + # foreach my $_id (keys %{$db{credits_used}}) { + # $exists{$db{credits_used}{$_id}{sport_type_id}}{$db{credits_used}{$_id}{client_id}} = 1 ; + # } + + # my $new_id = 0 ; + + # foreach my $client_id (sort {$a <=> $b} keys %{$seen{client}}) { + # foreach my $sport_id (sort {$a <=> $b} keys %{$seen{sport}}) { + # unless ($exists{$sport_id}{$client_id}) { + # if ($new_id) { + # $new_id++ ; + # } else { + # $new_id = &db_min_get_max('credits_used','id') ; + # } + + # $db_credits_used{credits_used}{$new_id}{sport_type_id} = $sport_id ; + # $db_credits_used{credits_used}{$new_id}{client_id} = $client_id ; + + # } + # } + # } + + # my %hidden_old = %hidden ; + # %hidden = () ; + # my %ignore_old = %ignore ; + # %ignore = () ; + # my %ij = %i ; + + # # cant_charge_client_fixtures_1 + # foreach my $_id (keys %{$db_credits_used{credits_used}}) { + + # my $premium_credits = ($db_credits_used{credits_used}{$_id}{premium_credits_used}) ? $db_credits_used{credits_used}{$_id}{premium_credits_used} : 0 ; + # my $standard_credits = ($db_credits_used{credits_used}{$_id}{standard_credits_used}) ? $db_credits_used{credits_used}{$_id}{standard_credits_used} : 0 ; + # my $individual_credits = ($db_credits_used{credits_used}{$_id}{individual_credits_used}) ? $db_credits_used{credits_used}{$_id}{individual_credits_used} : 0 ; + + # my $sport_id = $db_credits_used{credits_used}{$_id}{sport_type_id} ; + # my $client_id = $db_credits_used{credits_used}{$_id}{client_id} ; + + # %i = () ; + + # $i{premium_credits_used} = $credits_used{new}{premium}{$client_id}{$sport_id} ; + # $i{standard_credits_used} = $credits_used{new}{standard}{$client_id}{$sport_id} ; + # $i{individual_credits_used} = $credits_used{new}{individual}{$client_id}{$sport_id} ; + + # $i{premium_credits_used} = 0 unless $i{premium_credits_used} ; + # $i{standard_credits_used} = 0 unless $i{standard_credits_used} ; + # $i{individual_credits_used} = 0 unless $i{individual_credits_used} ; + + # $ignore{premium_credits_used} = ($credits_used{new}{premium}{$client_id}{$sport_id} ne $premium_credits) ? 0 : 1 ; + # $ignore{standard_credits_used} = ($credits_used{new}{standard}{$client_id}{$sport_id} ne $standard_credits) ? 0 : 1 ; + # $ignore{individual_credits_used} = ($credits_used{new}{individual}{$client_id}{$sport_id} ne $individual_credits) ? 0 : 1 ; + + # if (!$exists{$sport_id}{$client_id} && ($i{premium_credits_used} || $i{standard_credits_used} || $i{individual_credits_used}) && $ij{event_accepted}) { + # $i{id} = "$_id" ; + # $i{sport_type_id} = "$sport_id" ; + # $i{client_id} = "$client_id" ; + # $i{analytics_event_id} = ($id2) ? "$id2" : ($id) ? "$id" : "0" ; + # &db_min_insert('credits_used') ; + # } elsif ($exists{$sport_id}{$client_id} && ($i{premium_credits_used} || $i{standard_credits_used} || $i{individual_credits_used}) && $ij{event_accepted}) { + # &db_min_upd('credits_used',"id='$_id'") ; + # } elsif ($exists{$sport_id}{$client_id} && ((!$i{premium_credits_used} && !$i{standard_credits_used} && !$i{individual_credits_used}) || !$ij{event_accepted})) { + # &db_min_delete('credits_used',"id='$_id'") ; + # } + # } + + # %ignore = %ignore_old ; + # %hidden = %hidden ; + # %i = %ij ; + +# } + +sub report_ifields { + + if ($i{start_date_from} && $i{start_date_to}) { + push @report_sql, " (('$i{start_date_from}' <= q.start_date_time AND q.start_date_time <= '$i{start_date_to}') OR ('$i{start_date_from}' <= q.end_date_time AND q.end_date_time <= '$i{start_date_to}' AND q.end_date_time IS NOT NULL) OR (q.start_date_time <= '$i{start_date_from}' AND '$i{start_date_to}' <= q.end_date_time AND q.end_date_time IS NOT NULL) OR (q.start_date_time <= '$i{start_date_from}' AND q.end_date_time IS NULL)) " ; # + our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + my $start_date_from = &common_min_date_as_string($i{start_date_from}) ; + my $start_date_to = &common_min_date_as_string($i{start_date_to}) ; + push @report_results, " (DATE BETWEEN '$start_date_from' AND '$start_date_to') " ; + } + + if ($i{country}) { + push @report_sql, "(q.country_id = '$i{country}')" ; + push @report_results, "country_id = `$i{country}`" ; + } + + if ($i{customer_name} && $i{customer_name} ne 'all') { + push @report_sql, "(q.client_id = '$i{customer_name}')" ; + &db_min_ro('customers','id,name',"`id`='$i{customer_name}'",'','') ; + push @report_results, "customer = `$db{customers}{$i{customer_name}}{name}`" ; + } + + # if ($i{accepted} || $i{options} eq 'accepted') { + # push @report_sql, "(q.event_accepted='1' AND q.event_completed<>'1')" ; + # push @report_results, "event_accepted = `Yes`" ; + # } + + if ($i{options} eq 'accepted') { + push @report_sql, "(q.event_accepted='1')" ; + push @report_results, "Event is Accepted" ; + } elsif ($i{options} eq 'completed') { + push @report_sql, "(q.event_completed='1')" ; + push @report_results, "Event is Completing" ; + } elsif ($i{options} eq 'pending') { + push @report_sql, "(q.event_pending='1')" ; + push @report_results, "Event is Pending" ; + } elsif ($i{options} eq 'cancelled') { + push @report_sql, "(q.event_cancelled='1' OR (q.event_expiry IS NOT NULL AND q.event_expiry<'$now_year-$now_mm-$now_dd' AND q.event_accepted<>'1'))" ; + push @report_results, "Event is Cancelled" ; + } elsif ($i{options} eq 'rejected') { + push @report_sql, "(q.event_rejected='1')" ; + push @report_results, "Event is Rejecting" ; + } + + $preferred_title{region_id} = "Region" ; + $preferred_title{city_id} = "City" ; + $preferred_title{organisation_ids} = "Venue" ; + $preferred_title{sport_type_ids} = "Sport Type" ; + + if ($i{sport_type_ids} && $i{sport_type_ids} ne 'all') { + &db_min_ro('sport_types',"id,name","id='$i{sport_type_ids}'",'','') ; + push @report_sql, "FIND_IN_SET($i{sport_type_ids},REPLACE(q.sport_type_ids,';',','))" ; + push @report_results, "sport_types INCLUDE `$db{sport_types}{$i{sport_type_ids}}{name}`" ; + } + + if ($i{service_type_id} && $i{service_type_id} ne 'all') { + # push @report_sql, "(service_type_id = '$i{service_type_id}')" ; + push @report_results, "Service Type is `$service_types{$i{service_type_id}}`" ; + } + + if ($i{coding_provider_id} && $i{coding_provider_id} ne 'all') { + # push @report_sql, "(fixtures_saved_values REGEXP ';$i{coding_provider_id};[0-9a-z]+\\|' OR fixtures_saved_values REGEXP ';$i{coding_provider_id};[0-9a-z]+\$')" ; + # fixtures_saved_values REGEXP '(^|\\|)([0-9a-z]+;){9}$i{coding_provider_id}(;[0-9]+;[0-9]+|;;[0-9]+|;[0-9]+)(\\||\$)' + # push @report_sql, " + # (fixtures_saved_values REGEXP '(^|\\|)([0-9a-z]+;|;){9}') + # " ; + + push @report_results, "Coding Provider is `$coding_type{$i{coding_provider_id}}`" ; + } + + if ($usertype eq 'analytics_client') { + push @report_sql, "(q.client_id='$userid')" ; + } + + our $srch_where_sql = join(" AND ",@report_sql) ; + + $report_results_msg = uc join(', ', @report_results) ; + + unless ($report_results_msg) { + $error = qq(ENTER AT LEAST ONE SEARCH PARAMETER) ; + &report_screen ; + } else { + $isaved = qq(SELECT WHERE $report_results_msg) ; + } + +} #------------------------------------------------------------------------------------------ + +sub load_search_vars { + + + +} #------------------------------------------------------------------------------------------ + +sub list_screen { + + $print_box_content_rows .= &common_min_forms_start("$lcpage") ; + + our $set_up_groups = 1 ; + + &load_list_vars("$srch_where_sql") ; + + $fcol = 12 ; + + my $report = 1 ; + + our $xlsxdir = "fixtures_report" ; + + our $xlsxreportname = "Fixtures_Report" ; + + my $date = &common_write_date_interval($i{date_from},$i{date_to}) ; + + our $xlsx_title_heading = "Fixtures Report $date" ; + + &build_table_and_or_excel(1) ; + + $fnsortorder = 'asc' ; + + &common_min_extra_crumb("$lcpage","Search Screen") ; + + $trigger_jquery_raw .= qq~ + \$("#savebutt").click(function() { + \$("#$lcpage-form").submit() ; + }) ; + ~ ; + +} #------------------------------------------------------------------------------------------ + +sub build_table_and_or_excel { + + my ($report) = @_ ; + # $custom_header{$headers[13]} .= qq~~ ; + + our @sql_col_display = ("nr","start_date_time","sport","age_group","team","home_team","ht_colour","away_team","coding_type","footage_type","service_type","stream_forwarding","stream_key","stream_URL","coding_provider","status","moderated") ; + + # push @sql_col_display,"analyst" if $usertype eq 'coding_provider' ; + push @sql_col_display,"analyst" ; + + $custom_header{"analyst"} = qq~ANALYST  ~ ; + + $custom_header{"cant_charge_client"} = qq~~ ; + + &report_xlsx_export_header("$xlsxreportname",$xlsxdir,'',$xlsx_title_heading) ; + + push @sql_col_display,"cant_charge_client" ; + + push @sql_col_display,"update" ; + + my $nr_of_cols = scalar @sql_col_display ; + + my @rev_sql_col_display = reverse @sql_col_display ; + + foreach (@rev_sql_col_display) { $lastchild++ ; $last_child{$_} = $lastchild ; } # &common_debug("last-child : $_ [$last_child{$_}]"); + + $xlsxrow-- ; + + my $cali_cnt = 0 ; my $found_editable = 0 ; my @all_select_ids = () ; + + $format84 -> set_align("center") ; + + my $start_date_input = $i{start_date_from} ; + + $start_date_input =~ s/://g ; + $start_date_input =~ s/-//g ; + $start_date_input =~ s/ //g ; + + my $end_date_input = $i{start_date_to} ; + + $end_date_input =~ s/://g ; + $end_date_input =~ s/-//g ; + $end_date_input =~ s/ //g ; + + my %seen_analytics_id = () ; + + # foreach my $id (sort {$db{$table}{$a}{date_from} cmp $db{$table}{$b}{date_from}} keys %{$db{$table}}) { + use URI::Escape; + + foreach my $id (sort { $b <=> $a } keys %{$db{$table}}) { + + my @fixtures_split = split(/\|/,$db{$table}{$id}{fixtures_saved_values}) ; + + my @analytics_split = split(/\|/,$db{$table}{$id}{analytics_saved_values}) ; + + my @sport_type_ids = split(/\;/,$db{$table}{$id}{sport_type_ids}) ; + + my @cant_charge_client_fixtures_arr = split(/\;/,$db{$table}{$id}{cant_charge_client_fixtures}) ; + + my @cant_charge_client_reasons_arr = split(/\:\|;/,$db{$table}{$id}{cant_charge_client_reasons}) ; + + my $row_cnt = - 1 ; + + # foreach my $row (@fixtures_split) { + foreach my $row_nr (1 .. $db{$table}{$id}{total_fixtures}) { + + my @fixtures_split_2 = split(/\;/,$fixtures_split[$row_nr - 1]) ; + + my @analytics_split_2 = split(/\;/,$analytics_split[$row_nr - 1]) ; + + $row_cnt++ ; + + next if $i{coding_provider_id} && $i{coding_provider_id} ne 'all' && $fixtures_split_2[10] ne $i{coding_provider_id} ; + next if $i{service_type_id} && $i{service_type_id} ne 'all' && (($fixtures_split_2[9] && $fixtures_split_2[9] ne $i{service_type_id}) || (!$fixtures_split_2[9] && $db{$table}{$id}{service_type_id} ne $i{service_type_id})) ; + + my $date_val = ($fixtures_split_2[0]) ? $fixtures_split_2[0] : $db{$table}{$id}{start_date_time} ; + + $date_val =~ s/://g ; + $date_val =~ s/-//g ; + $date_val =~ s/ //g ; + + next if $date_val < $start_date_input || $date_val > $end_date_input ; + + $cali_cnt++ ; + + my $col_cnt = -2 ; + + # last if $db{$table}{$id}{total_fixtures} eq $row_cnt ; + + $xlsxcol = 0 ; + + our $default_javascript = qq~~ ; + + $seen_analytics_id{$id} = 1 ; + + foreach (@sql_col_display) { + + # &common_debug("1. XLSX >>> $_") if !$report ; + + $nr_of_cols_cnt-- ; + + next unless $_ ; # blank for the buttons column + + my $formatting = $format84 ; + my $val = $db{$table}{$id}{$_} ; + my $val_xlsx = 'MUSTBEBLANK' ; + my $align = qq~ class="dt-center"~ ; + my $nowrap = '' ; + my $cell_id = '' ; + + # &common_debug("2. XLSX >>> val_min=$val_min") if !$report ; + + my $sys_day_cnt = $cnt{$event_sys_id}{$id} ; + + $col_cnt++ ; + + my $field = "" ; my $default_val = ($_ eq 'stream_forwarding') ? $analytics_split_2[0] : ($_ eq 'stream_key') ? $analytics_split_2[1] : ($_ eq 'stream_URL') ? $analytics_split_2[2] : $fixtures_split_2[$col_cnt] ; my $only_display_val = 0 ; my $background_color = "#424949" ; my $default_val_is_saved = ($default_val) ? 1 : 0 ; + +# our %fixtures_status = (1 => 'Pending',2 => 'Booked',3 => 'Completed') ; +# our %coding_provider = (1 => 'SportVot',2 => 'iSport') ; +# our %footage_type = ("s" => "SSS","r" => "Raw") ; +# our %service_types = (1 => "Live Coding",2 => "Post Coding 12 hrs",3 => "Post Coding 24 hrs") ; +# our %coding_type = ("s" => "Standard","p" => "Premium") ; +# our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + + if ($_ eq 'nr') { + $val = &common_min_get_event_quote_button($id,$table,'analytics-event-bookings') ; + $val .= qq~~ if $db{$table}{$id}{event_quote_id} > 0 && $db{$table}{$id}{event_quote_id} ; + $val_xlsx = $id ; + $nowrap = 'nowrap' ; + } elsif ($_ eq "start_date_time") { + $val = ($fixtures_split_2[0]) ? &common_min_date_as_string($fixtures_split_2[0]) : &common_min_date_as_string($db{$table}{$id}{start_date_time}) ; + $nowrap = 'nowrap' ; + } elsif ($_ eq "sport") { + $val = ($fixtures_split_2[1] && $db{$table}{$id}{sport_type_ids} =~ /\b$fixtures_split_2[1]\b/) ? $db{sport_types}{$fixtures_split_2[1]}{name} : ($db{$table}{$id}{sport_type_ids} !~ /;/ && !$fixtures_split_2[1]) ? $db{sport_types}{$db{$table}{$id}{sport_type_ids}}{name} : "" ; + } elsif ($_ eq "age_group") { + $val = ucfirst $fixtures_split_2[2] ; + } elsif ($_ eq "team") { + $val = uc $fixtures_split_2[3] ; + } elsif ($_ eq "home_team") { + $val = $db{teams}{$fixtures_split_2[4]}{name} ; + } elsif ($_ eq "ht_colour") { + $val = $db{analytics_ht_colors}{$fixtures_split_2[5]}{name} ; + } elsif ($_ eq "away_team") { + $val = $db{teams}{$fixtures_split_2[6]}{name} ; + } elsif ($_ eq "coding_type") { + $val = $coding_type{$fixtures_split_2[7]} ; + } elsif ($_ eq "footage_type") { + $val = $footage_type{$fixtures_split_2[8]} ; + } elsif ($_ eq "service_type") { + $val = ($fixtures_split_2[9]) ? $service_types{$fixtures_split_2[9]} : $service_types{$db{$table}{$id}{service_type_id}} ; + $nowrap = 'nowrap' ; + } elsif ($_ eq 'stream_forwarding') { + $col_cnt-- ; + $background_color = ($default_val eq '1') ? "rgb(46,204,113)" : ($default_val eq '2') ? "rgb(249,13,13)" : "" ; + $opts{"stream_forwarding_$row_nr\_$id"} = qq~~ ; + $val = &common_min_table_select("stream_forwarding_$row_nr\_$id",$default_val,$only_display_val,$cali_cnt,$last_child{$_},$background_color,$default_val,$_) ; + $val_xlsx = ($default_val eq '1') ? 'Yes' : ($default_val eq '2') ? 'No' : '' ; + $val = qq~Do not edit this hidden input below!~ . $val_xlsx if $usertype eq 'coding_provider' ; + } elsif ($_ eq 'stream_key') { + $col_cnt-- ; + my $hide_text = ($analytics_split_2[0] eq '2') ? 1 : 0 ; + $default_val =~ s/\_semi_colon_character_/\;/g ; + $default_val =~ s/\_pipe_character_/\|/g ; + my $default_is_saved = ($default_val && $analytics_split_2[0] ne '2') ? 1 : 0 ; + $readonly{"stream_key_$row_nr\_$id"} = "READONLY" if $usertype eq 'coding_provider' ; + $val = qq~Do not edit this teaxtarea below if readonly!~ . &common_min_table_textarea("stream_key_$row_nr\_$id",$default_val,'',$cali_cnt,$last_child{$_},$background_color,$default_is_saved,'','',$hide_text) ; + $val_xlsx = $default_val ; + } elsif ($_ eq 'stream_URL') { + $col_cnt-- ; + my $hide_text = ($analytics_split_2[0] eq '2') ? 1 : 0 ; + $default_val =~ s/\_semi_colon_character_/\;/g ; + $default_val =~ s/\_pipe_character_/\|/g ; + my $default_is_saved = ($default_val && $analytics_split_2[0] ne '2') ? 1 : 0 ; + $readonly{"stream_URL_$row_nr\_$id"} = "READONLY" if $usertype eq 'coding_provider' ; + $val = qq~Do not edit this teaxtarea below if readonly!~ . &common_min_table_textarea("stream_URL_$row_nr\_$id",$default_val,'',$cali_cnt,$last_child{$_},$background_color,$default_is_saved,'','',$hide_text) ; + $val_xlsx = $default_val ; + } elsif ($_ eq 'coding_provider') { + $field = "coding_provider_$row_nr\_$id" ; + $opts{$field} = ($default_val) ? qq~~ : $opts{coding_provider_id} ; + $dont_allow_deselect_in_table{$field} = 1 if $usertype eq 'coding_provider' || $default_val ; + $val = &common_min_table_select($field,$default_val,$only_display_val,$cali_cnt,$last_child{$_},$background_color,$default_val) ; + $val_xlsx = "$db{users}{$default_val}{name} [$db{users}{$default_val}{username}]" ; + } elsif ($_ eq 'status') { + + # if ($default_val eq '1') { #calibrating + # $background_color = "#FFA500" ; orange + # $formatting = $format89 ; + # } elsif ($default_val eq '2') { #cancelled + # $background_color = "#AD0502" ; red + # $formatting = $format90 ; + # } elsif ($default_val eq '3') { #done + # $background_color = "#2ECC71" ; greeen + # $formatting = $format88 ; + # } elsif ($default_val eq '4') { + # $background_color = "#424949" ; + # } + + # rgb(81, 203, 242) blue + + if ($default_val eq '1') { + $background_color = "#FFA500" ; + } elsif ($default_val eq '2') { # + $background_color = "rgb(81, 203, 242)" ; + } elsif ($default_val eq '3') { + $background_color = "#2ECC71" ; + } + $field = "status_$row_nr\_$id" ; + $opts{$field} = $opts{status_id} ; + + # 1;;;open;a;7495;1;6684;s;s;s;s|2;;;u19;b;845;1;778;p;r;p;r|3;2025-06-18 06:00:00;8;u17;c;54;1;3975;s;s;s;s + $val = &common_min_table_select($field,$default_val,$only_display_val,$cali_cnt,$last_child{$_},$background_color,$default_val,$_) ; + $val_xlsx = $fixtures_status{$default_val} ; + } elsif ($_ eq 'analyst') { + + # $opts{"analyst_$row_nr\_$id"} = $opts{analyst} ; + # if ($usertype ne 'coding_provider') { + + if ($fixtures_split_2[10]) { + $opts{"analyst_$row_nr\_$id"} = $opts{$fixtures_split_2[10]}{analyst} ; + } else { + $opts{"analyst_$row_nr\_$id"} = qq~~ ; + } + + $opts{"analyst_$row_nr\_$id"} =~ s/value='$default_val'/value='$default_val' SELECTED/g if $default_val ; + + my $ab = "analyst_$row_nr\_$id" ; + + $val = &common_min_table_select("analyst_$row_nr\_$id",$default_val,$only_display_val,$cali_cnt,$last_child{$_},$background_color,$default_val) ; + $val_xlsx = $db{all_fixtures_analysts}{$default_val}{name} ; + + } elsif ($_ eq 'moderated') { + + # $background_color = (($_ eq 'status' || $_ eq 'equipment_checked') && $default_vals[$col_cnt] eq '1') ? "rgb(46,204,113)" : (($_ eq 'status' || $_ eq 'equipment_checked') && $default_vals[$col_cnt] eq '2') ? "rgb(249,13,13)" : ($_ eq 'status' && $default_vals[$col_cnt] eq '3') ? "rgb(255,153,0)" : '' ; + $background_color = ($default_val eq '1') ? "rgb(46,204,113)" : ($default_val eq '2') ? "rgb(249,13,13)" : "" ; + $opts{"moderated_$row_nr\_$id"} = $opts{moderated} ; + $val = &common_min_table_select("moderated_$row_nr\_$id",$default_val,$only_display_val,$cali_cnt,$last_child{$_},$background_color,$default_val,$_) ; + $val_xlsx = ($default_val eq '1') ? "Yes" : ($default_val eq '2') ? "No" : "" ; + } elsif ($_ eq 'cant_charge_client') { + # $val = &common_min_table_checkbox("cant_charge_client_$row_nr\_$id") ; + $nowrap = 'nowrap' ; + # $align = "class='dt-left'" ; + my $checked = ($cant_charge_client_fixtures_arr[$row_cnt]) ? 'CHECKED' : '' ; + $val = qq~~ ; + my $reason_url = $cant_charge_client_reasons_arr[$row_cnt] ; + $reason_url =~ s/\R/\_new_line_character_/g ; + $reason_url =~ s/ /\ /g ; + + $disp_reason = ($cant_charge_client_fixtures_arr[$row_cnt]) ? "" : "display:none;" ; + $val .= qq~  ~ if $cant_charge_client_reasons_arr[$row_cnt] ; + $default_javascript .= ($cant_charge_client_fixtures_arr[$row_cnt]) ? qq~"checkboxCant_charge_client_$row_nr\_$id":"true",~ : qq~"checkboxCant_charge_client_$row_nr\_$id":"false",~ ; + $cell_id = "id='c_cant_charge_client_$row_nr\_$id'" ; + } elsif ($_ eq 'update') { + $val = &common_min_table_checkbox("update_$row_nr\_$id") ; + $default_javascript =~ s/,+$//g ; + if ($default_javascript) { + push @default_javascript_by_id, qq~"$row_nr\_$id":{$default_javascript}~ ; + my $update_ids_str = "#selectStatus_$row_nr\_$id,#selectCoding_provider_$row_nr\_$id,#selectModerated_$row_nr\_$id,#selectStream_forwarding_$row_nr\_$id,#textareaStream_key_$row_nr\_$id,#textareaStream_URL_$row_nr\_$id,#checkboxCant_charge_client_$row_nr\_$id" ; + # $update_ids_str .= ",#selectAnalyst_$row_nr\_$id" if $usertype eq 'coding_provider' ; + $update_ids_str .= ",#selectAnalyst_$row_nr\_$id" ; + push @all_update_field_ids,$update_ids_str ; + } + + } + + $print_tbody .= qq~$val~ if $report ; + + $val_xlsx = $val if $val_xlsx eq 'MUSTBEBLANK' ; + + &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$formatting) if $val_xlsx && $_ ne 'update' ; + $xlsxcol++ ; + } + + $print_tbody .= qq~~ if $report ; + + $xlsxrow++ ; + + } + } + + &common_shared_build_select_primary_jquery ; + + foreach my $id (%seen_analytics_id) { + next if $id eq '1' ; + $db{$table}{$id}{cant_charge_client_reasons} =~ s/\R/\_new_line_character_/g ; + $db{$table}{$id}{cant_charge_client_reasons} =~ s/ /\ /g ; + $print_box_content_rows .= qq~~ ; + } + + $trigger_jquery_raw .= qq~ + + \$("#$useropts{table_id}").on("change","[id^='selectCoding_provider_']", async function (event) { + + let row_nr = get_row_nr (this.id,2) ; + let analysts = "[]" ; + console.log("row_nr : "+row_nr) ; + + if (!\$("#selectCoding_provider_"+row_nr).val()) { + \$("#selectAnalyst_"+row_nr).val('').trigger("chosen:updated") ; + clearSelect(\$("#selectAnalyst_"+row_nr)); + } else { + let url_get_analysts = "$useropts{scripts}/get/get_analyst_from_coding_provider.pl?coding_provider_id="+\$("#selectCoding_provider_"+row_nr).val() ; + console.log("url_get_analysts : "+url_get_analysts) ; + analysts = await fetchJSON(url_get_analysts) ; + clearSelect(\$("#selectAnalyst_"+row_nr)); + populateSelect(\$("#selectAnalyst_"+row_nr),analysts,r => r.name); + } + + }) ; + + \$("#$useropts{table_id}").on("click","[id^='checkboxCant_charge_client']", function () { + let analytics_id = get_row_nr(this.id,1) ; + let row_nr = get_row_nr(this.id,2) ; + row_nr = row_nr.split('_')[0]; + if (\$("#"+this.id).is(":checked")) { + if (\$("#reason_icon_"+row_nr+"_"+analytics_id).html()) { + \$("#reason_icon_"+row_nr+"_"+analytics_id).css("display","") ; + } else { + dlgMdl("$useropts{scripts}/dialog/add_fixtures_charge_free_table_reason.pl?add&&"+analytics_id+"&"+row_nr+"&&1","Add Reason",'','medium-dialog') ; + } + } else { + \$("#reason_icon_"+row_nr+"_"+analytics_id).hide() ; + } + }) ; + + ~ ; + + # \$("#itv-table tr th:nth-last-child(1)").css("width","0%") ; + # \$("#itv-table tr th:nth-last-child(1)").css("display","none") ; + + my $all_select_ids_string = join(",",@all_select_ids) ; + + # $trigger_jquery_raw .= qq~\$('[data-toggle="tooltip"]').tooltip({ container: 'body' });~ ; + + $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({allow_single_deselect:true});~ ; + # if ($usertype eq 'coding_provider') { + &common_min_table_select_jquery("#$useropts{table_id} td:nth-last-child($last_child{stream_forwarding}),#$useropts{table_id} td:nth-last-child($last_child{analyst}),#$useropts{table_id} td:nth-last-child($last_child{status}),#$useropts{table_id} td:nth-last-child($last_child{moderated}),#$useropts{table_id} td:nth-last-child($last_child{coding_provider})") ; + # } else { + # &common_min_table_select_jquery("#$useropts{table_id} td:nth-last-child(7),#$useropts{table_id} td:nth-last-child(4),#$useropts{table_id} td:nth-last-child(3),#$useropts{table_id} td:nth-last-child(2)") ; + # } + + &common_min_table_update_checkbox_col("2") ; + + $worksheet{$ws}->set_column(0,0,10) ; + $worksheet{$ws}->set_column(1,17,20) ; + + &report_xlsx_export_footer('L',15,$xlsxdir) ; +# "#$useropts{table_id} tr:eq(???) td:nth-last-child(6)" ; + + # my $key_col = ($usertype ne 'coding_provider') ? 6 : 7 ; + # my $url_col = ($usertype ne 'coding_provider') ? 5 : 6 ; + my $key_col = 7 ; + my $url_col = 6 ; + + $trigger_jquery_raw .= qq~ + + \$("#$useropts{table_id}").on("change","[id^='selectStream_forwarding_']", function () { + + let row_nr = get_row_nr (this.id,2) ; + + let \$tr = \$(this).closest("tr"); + + if ((\$(this).val() == '1' || !\$(this).val()) && \$("#textareaStream_key_"+row_nr).is(":hidden")) { + \$("#textareaStream_key_"+row_nr).show() ; + if (\$("#textareaStream_key_"+row_nr).val()) { + \$tr.find("td:nth-last-child($key_col)").css("background-color","rgb(66,73,73)") ; + } + \$("#textareaStream_URL_"+row_nr).show() ; + if (\$("#textareaStream_URL_"+row_nr).val()) { + \$tr.find("td:nth-last-child($url_col)").css("background-color","rgb(66,73,73)") ; + } + } else if (\$(this).val() == '2' && !\$("#textareaStream_key_"+row_nr).is(":hidden")) { + \$("#textareaStream_key_"+row_nr).hide() ; + if (\$("#textareaStream_key_"+row_nr).val()) { + \$tr.find("td:nth-last-child($key_col)").css("background-color","") ; + } + \$("#textareaStream_URL_"+row_nr).hide() ; + if (\$("#textareaStream_URL_"+row_nr).val()) { + \$tr.find("td:nth-last-child($url_col)").css("background-color","") ; + } + } + + }) ; + + \$("#$useropts{table_id}").on("change","[id^='textareaStream_key_'],[id^='textareaStream_URL_']", function () { + + let row_nr = get_row_nr (this.id,2) ; + if (!\$("#selectStream_forwarding_"+row_nr).val()) { + \$("#selectStream_forwarding_"+row_nr).val("1").trigger("chosen:updated") ; + } + + }) ; + + ~ ; + +} #------------------------------------------------------------------------------- + +sub thead { + + # # # # # # &common_min_thead ; + + $print_thead = qq~~ ; + + foreach (@sql_col_display) { + + my $coltitle = "" ; + if ($custom_header{$_}) { + $coltitle = $custom_header{$_} ; + } else { + $coltitle = $_ ; $coltitle =~ s/\_id//g ; $coltitle =~ s/\_/ /g ; $coltitle = uc $coltitle ; $coltitle = $replace_blank_table_top_right if $coltitle eq '' and $replace_blank_table_top_right ; + } + + # $custom_column_styles{$_} = qq~style="min-width:120px;"~ unless $custom_column_styles{$_} ; + $print_thead .= qq~$coltitle~ ; + } + + if ($add_th_row) { $print_thead .= $add_th_row ; } # used in agent_commission_report.pl and cruiseline_commission_report.pl + + $print_thead .= qq~~ ; + +} #------------------------------------------------------------------------------- + +sub page_opts { + + our $glyphicon = 'list' ; + our $lcpage = 'all-fixtures-report' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + + &common_page_name ; + + our $table = 'analytics_event_bookings q' ; + $page_title = 'All Fixtures Report' ; + +} #------------------------------------------------------------------------------- + +sub report_screen { + + our $lcol = 2 ; + our $fcol = 5 ; + + my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-42) ; # 6 weeks back + + $set_month = sprintf("%02s", $set_month) ; + $set_day = sprintf("%02s", $set_day) ; + + my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ; + + $print_box_content_rows .= &common_min_forms_start('report') ; + + # $allow_deselect{customer_name} = 1 ; + $allow_deselect{options} = 1 ; + $allow_deselect{sport_type_ids} = 1 ; + + my $defualt_customer = 0 ; $defualt_customer = 5 if $usertype ne 'school_manager' ; + # &common_min_select_opts('customer_name','customers','name',$defualt_customer,'','',"events='1'") ; + &common_min_select_opts('customer_name','customers','name','','','',"analytics='1'") ; + $opts{customer_name} .= qq~~ ; + my $def_val = ($i{customer_name}) ? $i{customer_name} : "all" ; + $opts{customer_name} =~ s/value='$def_val'/value='$def_val' SELECTED/g ; + $print_box_content_rows .= &common_min_form_select('customer_name','') ; + + $preferred_title{event_from} = 'Event Date From' ; + + my $day_of_week = Day_of_Week($now_year,$now_mm,$now_dd) ; + + my ($def_s_year,$def_s_mm,$def_s_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,1-$day_of_week) ; + my ($def_e_year,$def_e_mm,$def_e_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,7-$day_of_week) ; + + $def_s_mm = sprintf("%02d",$def_s_mm) ; + $def_s_day = sprintf("%02d",$def_s_day) ; + $def_e_mm = sprintf("%02d",$def_e_mm) ; + $def_e_day = sprintf("%02d",$def_e_day) ; + + $i{start_date_from} = qq~$def_s_year-$def_s_mm-$def_s_day 00:00:00~ unless $i{start_date_from} ; + $i{start_date_to} = qq~$def_e_year-$def_e_mm-$def_e_day 23:59:59~ unless $i{start_date_to} ; + + $preferred_title{start_date_from} = "Date Time From" ; + $preferred_title{start_date_to} = "Date Time To" ; + + $print_box_content_rows .= &common_min_form_datetimepicker('start_date_from',$i{start_date_from},720) ; + $print_box_content_rows .= &common_min_form_datetimepicker('start_date_to',$i{start_date_to},720) ; + + $opts{options} = qq~ + + + + + + + ~ ; + + $allow_deselect{options} = 0 ; + + $print_box_content_rows .= &common_min_form_select('options','') ; + + &common_min_select_opts('sport_type_ids','sport_types','name','','','','') ; + + $preferred_title{sport_type_ids} = "Sport Type" ; + + $allow_deselect{sport_type_ids} = 0 ; + + $opts{sport_type_ids} .= qq~~ ; + + $print_box_content_rows .= &common_min_form_select('sport_type_ids','') ; + + if ($usertype ne 'coding_provider') { + + &common_min_select_opts('coding_provider_id','users','name','','','username',"user_type='coding_provider'") ; + + $opts{coding_provider_id} .= qq~~ ; + + $i{coding_provider_id} = 'all' unless $i{coding_provider_id}; + + $opts{coding_provider_id} =~ s/value="$i{coding_provider_id}"/value="$i{coding_provider_id}" SELECTED/g ; + + } elsif ($usertype eq 'coding_provider') { + &db_min_ro('users','1,name,username',"id='$userid'",'','') ; + $opts{coding_provider_id} = qq~~ ; + + } + + $print_box_content_rows .= &common_min_form_select('coding_provider_id','') ; + + our %service_types = (1 => "Live Coding",2 => "Individual 48 hrs",3 => "Post Coding 24 hrs") ; + + foreach (keys %service_types) { + $opts{service_type_id} .= qq~~ ; + } + $opts{service_type_id} .= qq~~ ; + + $i{service_type_id} = 'all' unless $i{service_type_id}; + + $opts{service_type_id} =~ s/value="$i{service_type_id}"/value="$i{service_type_id}" SELECTED/g ; + + $print_box_content_rows .= &common_min_form_select('service_type_id','') ; + + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + local $all_select_ids_string = join(",",@all_select_ids) ; + $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true });~ ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub screen3 { + + $custom_column_styles{coding_provider} = qq~style="width:7.5%;min-width:120px;"~ ; + $custom_column_styles{status} = qq~style="width:7.5%;min-width:120px;"~ ; + $custom_column_styles{moderated} = qq~style="width:7.5%;min-width:120px;"~ ; + $custom_column_styles{stream_forwarding} = qq~style="width:7.5%;min-width:120px;"~ ; + $custom_column_styles{stream_key} = qq~style="width:7.5%;min-width:120px;"~ ; + $custom_column_styles{stream_URL} = qq~style="width:7.5%;min-width:120px;"~ ; + $custom_column_styles{analyst} = qq~style="width:7.5%;min-width:120px;position:relative;"~ ; + # stream_forwarding","stream_key","stream_URL + &thead; + + if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + + # my $page = "$lcpage\s" ; + + my $page = "analytics-event-bookings" ; + + if ($s{no}) { $page = $lcpage ; } + + &common_min_table('id',$page,'list') ; + + our $savjqy = 1 ; + + # &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ; + + $extra_form_fields .= qq~ + + + + + + + + ~; + + # $skip_save_btn = 1 if $usertype eq 'coding_provider' ; + + $print_box_content_rows .= &common_min_forms_end('','','save') ; + + # $trigger_jquery_raw .= qq~\$("#selectCoding_provider_1_1020_chosen").~ ; + + require _blank ; + + exit ; + +} #------------------------------------------------------------------------------------------ + +sub redirect_screen { + +&common_min_alert_type ; + +print < + + + + $useropts{title} + + + + + + +

    + + + + + + + + +
    + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub load_list_vars { + + my ($where) = @_ ; + + &db_min_ro($table,'id,event_quote_id,fixtures_saved_values,analytics_saved_values,event_completed,event_accepted,event_pending,event_cancelled,event_rejected,sport_type_ids,start_date_time,region_id,client_id,total_fixtures,service_type_id,cant_charge_client_fixtures,cant_charge_client_reasons',$where,'','') ; + my %seen_region = () ; my %seen_client = () ; my $cnt_client = 0 ; + foreach (keys %{$db{$table}}) { + $seen_region{$db{$table}{$_}{region_id}} = 1 ; + $seen_client{$db{$table}{$_}{client_id}} = 1 ; + $cnt_client++ ; + } + &db_min_ro('sport_types','id,name','','','') ; + &db_min_ro('analytics_ht_colors','id,name','','','') ; + + + if ($usertype eq 'coding_provider') { + + &db_min_ro('users','id,name,username',"id='$userid'",'','') ; + + &db_min_ro('all_fixtures_analysts','id,name',"coding_provider_id='$userid'",'','') ; + + foreach (sort {$db{all_fixtures_analysts}{$a}{name} cmp $db{all_fixtures_analysts}{$b}{name}} keys %{$db{all_fixtures_analysts}}) { + $opts{$userid}{analyst} .= qq~~ ; + } + + } else { + + &db_min_ro('users','id,name,username',"user_type='coding_provider'",'','') ; + + &db_min_ro('all_fixtures_analysts','id,name,coding_provider_id',"",'','') ; + + foreach (sort {$db{all_fixtures_analysts}{$a}{name} cmp $db{all_fixtures_analysts}{$b}{name}} keys %{$db{all_fixtures_analysts}}) { + $opts{$db{all_fixtures_analysts}{$_}{coding_provider_id}}{analyst} .= qq~~ ; + } + + } + + # my $teams_sql_where = join (" OR ", map { "region_id='$_' OR (region_id='0' AND matched_region_id ='$_')" } keys %seen_region) ; + # $teams_sql_where .= qq~ OR ~ if $cnt_client && $teams_sql_where ; + # my $teams_sql_where .= join (" OR ", map { "aisa_client_id='$_'" } keys %seen_client) ; + + &db_switch_conn('sss') ; + &db_min_ro('teams','id,name',"",'','') ; + &db_switch_conn('aisa') ; + + foreach (keys %{$db{users}}) { + $opts{coding_provider_id} .= qq~~ ; + } + + # # our %coding_provider = (1 => 'SportVot',2 => 'iSport') ; + + # foreach (keys %coding_provider) { + + foreach (keys %fixtures_status) { + $opts{status_id} .= qq~~ ; + } + + $opts{moderated} = qq~~ ; + +} #------------------------------------------------------------------------------------------ + +use common ; +use common_shared ; +use report ; +use xlsxcreator ; +use today ; +use analytics_event_booking_tabs ; + +1; \ No newline at end of file diff --git a/scripts/allocate_credits.pl b/scripts/allocate_credits.pl index 56e6079..0107f37 100644 --- a/scripts/allocate_credits.pl +++ b/scripts/allocate_credits.pl @@ -3,7 +3,7 @@ BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } require cfg ; - +# unless ($username eq 'handre') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } #--------------------------------------------------------------------------------------------------------------------------------------------------------------------- use CGI::Carp qw(fatalsToBrowser); @@ -19,359 +19,365 @@ $action = $ARGV[0] ; our ($q) = CGI -> new() ; our $iaction = $q -> param('iaction') || $action ; our $isaved = $q -> param('isaved') || '' ; - -our $debug = 1 ; +# our $debug = 1 ; # our $testing = 1 ; +our $double_box_layout = 1 ; + +# our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + #-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- -&page_opts ; +&page_opts ; #--------------------------------------------------------------------------------------------------------------------------------------------------------------------- -print "Content-type: text/html\n\n"; - -our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab - -if ($username ne 'handre') { +# unless ($useropts{it}{$username}) { +unless ($glod_user_level >= 5) { print "Development in Progress!!!" ; exit ; } -&db_open_ro ; - $db_ignore_open_close = 1 ; - &common_min_action; - $db_ignore_open_close = 0 ; -&db_close_conn ; +print "Content-type: text/html\n\n"; -exit; +if ($iaction eq 'update') { + &common_min_load_params ; + &validate ; + &update ; + &common_min_screen2 ; + exit ; +} + +&common_min_action ; + +exit ; #------------------------------------------------------------------------------------------ sub validate { - my $exists = '' ; + my $exists = '' ; + &db_min_ro($table,'*','','','') ; - $i{name} = &common_fix_str($i{name}) ; + foreach my $id (keys %{$db{$table}}) { + next if $i{id} && $i{id} eq $id ; + if ($db{$table}{$id}{credit_type} eq $i{credit_type} && $db{$table}{$id}{client_id} eq $i{client_id} && ($db{$table}{$id}{sport_type_id} eq 'all' || $db{$table}{$id}{sport_type_id} eq $i{sport_type_id} || $i{sport_type_id} eq 'all')) { + $exists = 1 ; + } + } - ## REMOVE LATER --------------------------------- + my $credits_out_of_range = (length $i{credits} > 10) ? 1 : 0 ; - $i{city} = $i{name} ; - - ## REMOVE LATER --------------------------------- - - &db_min_ro($table,'*',"name='$i{name}'",'name','') ; - - foreach my $id (keys %{$db{$table}}) { if ($db{$table}{$id}{name} eq $i{name}) { $exists = 1 ; } } - - if ($exists) { - $alert = &common_min_alert('warning',"CITY NAME ALREADY EXISTS!",'ok') ; + if ($credits_out_of_range) { + $i{id} = $i{orig_id} if $i{orig_id} ; + $alert = &common_min_alert('warning',"THE CREDITS NUMBER CONTAIN TOO MANY CHARACTERS!",'ok') ; %col_name = (); - &common_min_add_screen; + &common_min_error_screen; &common_min_screen1; - } - + exit ; + } + + if ($exists) { + $i{id} = $i{orig_id} if $i{orig_id} ; + $alert = &common_min_alert('warning',"CREDITS ALREADY EXIST FOR THIS CLIENT, SPORT AND CREDIT TYPE!",'ok') ; + %col_name = (); + &common_min_error_screen; + # $i{id} = $i{orig_id} if $i{orig_id} ; + &common_min_screen1; + exit ; + } + } #------------------------------------------------------------------------------------------ sub insert { &add_db_fields ; - - &set_default_vals ; - - $i{id} = &db_min_get_max($table,'id') ; - - $ignore{country_id} = 1 ; + + $i{id} = &db_min_get_max($table,'id') ; &db_min_insert($table) ; + + # exit ; } #------------------------------------------------------------------------------------------ sub update { - unless ($i{id}) { $error = qq(NO ID) ; return ; } + unless ($i{id}) { + $error = qq(NO ID) ; + return ; + } &edit_db_fields ; - &set_default_vals ; - - $ignore{country_id} = 1 ; + $ignore{id} = 1 ; &db_min_upd($table,"id='$i{id}'") ; } #------------------------------------------------------------------------------------------ -sub set_default_vals { +sub build_rates_fields { - &db_min_ro('regions','id,name',"id = $i{region_id}",'','') ; - $i{province} = $db{regions}{$i{region_id}}{name}; + my ($field_name,$row_cnt) = @_ ; + + # $ii{$field_name} = qq~$db{$table}{1}{$field_name}~ ; + $ii{$field_name} .= ';' if $ii{$field_name} ; + $ii{$field_name} .= qq~$i{"$field_name\_$row_cnt"}~ ; + $i{$field_name} = $ii{$field_name} ; } #------------------------------------------------------------------------------------------ sub list_screen { - &db_min_ro('regions','id,name,country_id',"",'','') ; + &db_min_ro('sport_types','*','','','') ; - &db_min_ro('countries','id,name',"",'','') ; + &db_min_ro('customers','id,name','','','') ; - &db_min_ro('event_quotes','id,city_id',"city_id <> 0",'','') ; - - foreach my $_id (keys %{$db{event_quotes}}) { - $type_id_used{$_} = 1 ; - my @city_ids = split(/\,/,$db{event_quotes}{$_id}{city_id}); - foreach my $_cid (@city_ids) { - $type_id_used{$_cid} = 1 ; - } - } - - &db_min_ro($table,'*','','','') ; - - foreach my $id (keys %{$db{$table}}) { + &db_min_ro($table,'*','','id','') ; + + my $excl = "" ; + + our @sql_col_display = ("id","client","sport","credit_type","credits","") ; + + my %credit_types = (1 => "Standard", 2 => "Premium", 3 => "Individual") ; + + my $row_cnt = 0 ; + + foreach my $id (sort { $db{customers}{$db{$table}{$a}{client_id}}{name} cmp $db{customers}{$db{$table}{$b}{client_id}}{name} || $db{sport_types}{$db{$table}{$a}{sport_type_id}}{name} cmp $db{sport_types}{$db{$table}{$b}{sport_type_id}}{name} || $db{$table}{$a}{credit_type} <=> $db{$table}{$b}{credit_type} } keys %{$db{$table}}) { - my $edit_butt = qq~ ~ ; - my $del_butt = qq~ ~ ; + $print_tbody .= qq~~ ; - if ($glod_user_level >= 3) { - $edit_butt = qq~ ~ ; - } + $row_cnt++ ; - if ($glod_user_level >= 3) { - $del_butt = qq~ ~ ; - } + foreach my $col (@sql_col_display) { - if ($type_id_used{$id}) { - $edit_butt = qq~ ~ ; - $del_butt = qq~ ~ ; + $val = $db{$table}{$id}{$col} ; + my $nowrap = "" ; + my $align = qq~ class="dt-center"~ ; + + if ($col eq "id") { + + my $row_val = sprintf("%09d",$row_cnt) ; + $val = qq~$row_val$id~ ; + $align = qq~ class="dt-left"~ ; + } elsif ($col eq "client") { + $val = $db{customers}{$db{$table}{$id}{client_id}}{name} ; + } elsif ($col eq "sport") { + $val = $db{sport_types}{$db{$table}{$id}{sport_type_id}}{name} ; + $val = "All" if $db{$table}{$id}{sport_type_id} eq 'all' ; + } elsif ($col eq "credit_type") { + $val = $credit_types{$db{$table}{$id}{credit_type}} ; + } elsif ($col eq "credits") { + $val = &common_commify($val); + } elsif ($col eq '') { + $align = qq~ class="dt-left"~ ; + my $edit_butt = '' ; + my $del_butt = '' ; + # if ($useropts{super}{$username}) { + # $edit_butt = qq~ ~ ; + # } + # if ($useropts{boss}{$username} or $useropts{super}{$username}) { + # $del_butt = qq~ ~ if not $seen_event_item_costing{$id}; + # $del_butt = qq~ ~ if $seen_event_item_costing{$id}; + # } + $edit_butt = qq~ ~ ; + $del_butt = qq~ ~ ; + + $val = qq~$edit_butt$del_butt~ ; + } + $print_tbody .= qq~$val~ ; } - - $print_tbody .= qq~ - $id - $db{$table}{$id}{name} - $db{$table}{$id}{city_short} - $db{$table}{$id}{lat} - $db{$table}{$id}{lng} - $db{regions}{$db{$table}{$id}{region_id}}{name} - $db{countries}{$db{regions}{$db{$table}{$id}{region_id}}{country_id}}{name} - - $edit_butt - $del_butt - - ~ ; + $print_tbody .= qq~~ ; } } #------------------------------------------------------------------------------------------ sub add_db_fields { - - &sort_fields; + # &sort_fields; &hidden_db_fields; - # $ignore{id} = 1 ; } #------------------------------------------------------------------------------------------ sub edit_db_fields { - - &sort_fields; + # &sort_fields; &hidden_db_fields; - $hidden{id} = 1 ; # 1 = bypass for db update } #------------------------------------------------------------------------------------------ sub hidden_db_fields { - $ignore{iaction} = 1 ; - $required{name} = 1 ; - # $required{province} = 1 ; - $required{region_id} = 1 ; - - # $ignore{country_id} = 1 ; + $ignore{selected_add_credit_types} = 1 ; + $ignore{iaction} = 1 ; + $ignore{orig_id} = 1 ; + &sort_fields ; + } #------------------------------------------------------------------------------------------ sub sort_fields { - %sort_field = () ; - - # $ignore{country_id} = '' ; - - - $sort_field{3} = 'name' ; $preferred_title{city_short} = "City Name" ; - $sort_field{4} = 'city_short' ; $preferred_title{city_short} = "City Acronym" ; - # $sort_field{3} = 'province' ; $preferred_title{province} = 'Region' ; - $sort_field{5} = 'lat' ; $preferred_title{lat} = 'Latitude' ; - $sort_field{6} = 'lng' ; $preferred_title{lng} = 'Longitude' ; - $sort_field{7} = 'region_id' ; - $sort_field{8} = 'country_id' ; - } #------------------------------------------------------------------------------- sub add_screen { - # called from common_add_screen + &sort_fields ; &select_opts ; - + + &build_boxes ; + } #------------------------------------------------------------------------------------------ sub edit_screen { - + &select_opts ; + &build_boxes ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes { + + our ($lcol,$fcol) = &common_min_columns() ; + + $add_form_fields = '' ; + + $print_box_content_rows .= &common_min_forms_start($table,$skip) ; + + $print_box_content_rows .= qq~~ if $i{id} ; + + $add_form_fields .= qq~ +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + ~ ; + # align='center' + $add_form_fields .= qq~
    ~ ; + $fcol = 2 ; + $add_form_fields .= &common_min_form_select_col("client_id") ; + + $fcol = 1 ; + $add_form_fields .= &common_min_form_select_col("sport_type_id") ; + $fcol = 1 ; + $lcol = 3 ; + + # $i{credit_type} = $db{$table}{$i{id}}{credit_type} if $db{$table}{$i{id}}{credit_type} ; + + $add_form_fields .= &common_min_form_select_col("credit_type") ; + $fcol = 1 ; + # $add_form_fields .= qq~
    ~ ; + + # $i{credits} = $db{$table}{$i{id}}{credits} if $db{$table}{$i{id}}{credits} ; + + $required{credits} = 'data-validation="length number" data-validation-length="0-10"' ; + + $add_form_fields .= &common_min_form_input_col("credits",$i{credits}) ; + $add_form_fields .= qq~
    ~ ; + + my $save_action = ($i{id}) ? 'update' : 'save' ; + + my $custom_class = ($invoice_exists && !$useropts{super}{$username} && !$useropts{it}{$username}) ? "custom" : "primary" ; + our $custom_back_button = ($save_action eq 'update') ? qq~  ~ : qq~~ ; + our $addbkb = ($save_action eq 'update') ? 1 : 0 ; + $add_form_fields .= &common_min_forms_end($iid,$table,$save_action,$skip) ; + + my $add_edit = ucfirst $iaction ; + + my $orig_id = $i{id} ; + + $orig_id = "New" unless $orig_id; + + if ($save_action eq 'update') { + $add_form_fields .= qq~~ ; + $i{id} = &db_min_get_max($table,'id') ; + } + + $print_box_content_rows .= &common_min_box_top(''," $add_edit : $orig_id",$box_right_bg) ; + $print_box_content_rows .= $add_form_fields ; + $print_box_content_rows .= &common_min_box_foot ; + + $trigger_jquery_raw .= qq~ + \$("#credits_allocated-form [id^='savebutt']").on("click", function (e) { + if (this.id.includes("_new")) { + \$("input[name='iaction']").val("save") ; + \$("input[name='id']").val("$i{id}") ; + } + if (!\$("#selectClient_id").val() || !\$("#selectSport_type_id").val() || !\$("#selectCredit_type").val() || !\$("input[name='credits']").val()) { + noty({text:'Please select all of the input!',layout:"center",type:"error",timeout:10000}) ; + return ; + } + \$("#credits_allocated-form").submit() ; + }) ; + ~ ; + + $i{id} = $orig_id if $orig_id ne 'new' ; + } #------------------------------------------------------------------------------------------ sub select_opts { - - # $required{based_in} = 1 ; - # $select{based_in} = 1 ; - # $opts{based_in} = qq~~ ; - # my $sql_or = '' ; + &common_min_select_opts('sport_type_id','sport_types','name','',0,'','') ; - # if ($is_schools_manager || $is_operator) { - # @report_sql_or = () ; - # foreach $_reg_id (keys %{$glob_regids{$userid}}) { - # push @report_sql_or, "id = '$_reg_id'" - # } - # $sql_or = join(' OR ',@report_sql_or) ; - # } + $i{client_id} = ($i{client_id}) ? $i{client_id} : $db{$table}{$i{id}}{client_id} ; + $i{sport_type_id} = ($i{sport_type_id}) ? $i{sport_type_id} : $db{$table}{$i{id}}{sport_type_id} ; + $i{credit_type} = ($i{credit_type}) ? $i{credit_type} : $db{$table}{$i{id}}{credit_type} ; + $i{credits} = ($i{credits}) ? $i{credits} : $db{$table}{$i{id}}{credits} ; - my $sql_or = ($is_schools_manager || $is_operator) ? join(' OR ', map { "id = '$_'" } keys %{$glob_regids{$userid}}) : '' ; + # $i{sport_type_id} = $db{$table}{$i{id}}{sport_type_id} if $db{$table}{$i{id}}{sport_type_id} ; - $allow_deselect{country_id} = 1 ; + $opts{sport_type_id} .= qq~~ ; + + $opts{sport_type_id} =~ s/value="\Q$i{sport_type_id}\E"/value="$i{sport_type_id}" SELECTED/g if $i{sport_type_id} ; - # &common_min_select_opts('province','regions','name',$db{$table}{$i{id}}{province},'','',$sql_or,'name'); + &common_min_select_opts('client_id','customers','name','',0,'',"analytics='1'") ; + + # $i{client_id} = ($i{client_id}) ? $i{client_id} : $db{$table}{$i{id}}{client_id} ; + + $opts{client_id} =~ s/value="\Q$i{client_id}\E"/value="$i{client_id}" SELECTED/g if $i{client_id} ; + + my %radio_opts_hash = (1 => "standard",2 => "premium",3 => "individuals") ; + + $opts{credit_type} = "`) ; - }); - - updateChosen(\$field) ; - return json_list.length ; - }; - - const getInputValue = name => \$(`input[name='\${name}']`).val(); - - const clearSelect = (\$el) => { - \$el.empty(); - \$el.append(``).trigger("chosen:updated"); - }; - - // _______________________________________________ - - \$countrySelect.change( async function() { - \$("input[name='custom_selected_country']").val("1") ; - await update_region_drop_down_from_country(\$countrySelect.val()) ; - }) ; - - async function update_region_drop_down_from_country (countryId) { - - clearSelect(\$regionSelect) ; - - const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}` ; - const regions = await fetchJSON(regionUrl); - - for (const data of regions) { - map_region_to_country[data.id] = countryId ; - } - - const regionCount = populateSelect(\$regionSelect, regions, r => r.code ? `\${r.name} [\${r.code}]` : r.name , "") ; - - if (regionCount === 0 && \$countrySelect.val()) { - \$regionSelect.append(``).trigger("chosen:updated") ; - } - - } - - // _______________________________________________ - - \$regionSelect.change( async function() { - \$("input[name='custom_selected_region']").val("1") ; - \$("input[name='custom_selected_country']").val("1") ; - const regionId = \$regionSelect.val() ; - await update_country_from_region(regionId,1) ; - }); - - async function update_country_from_region (regionId,update_country=0) { - if (map_region_to_country[regionId] || regionId == '13') { - \$countrySelect.val(map_region_to_country[regionId]).trigger("chosen:updated") ; - } else if (!\$("input[name='custom_selected_country']").val() || update_country) { - const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=®ion_id=\${regionId}`; - const regionMeta = await fetchJSON(lookupUrl); - const { country_id } = regionMeta[0] ?? {} ; - if (country_id) { - map_region_to_country[regionId] = country_id; - \$countrySelect.val(country_id).trigger("chosen:updated"); - } - } - } - - // _______________________________________________ - - ~ ; - } #------------------------------------------------------------------------------------------ sub thead { - - $print_thead = qq~IDCITY NAMECITY ACRONYMLATLNGREGIONCOUNTRY ~ ; - + + &common_min_thead ; + # $print_thead = qq(IDNAMEEXCLUDED FROM EXPENSES ) ; + } #------------------------------------------------------------------------------- sub page_opts { - our $glyphicon = 'map-marker' ; - our $lcpage = 'cities' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; - our $table = 'cities' ; + our $glyphicon = 'facetime-video' ; + our $lcpage = 'allocate-credit + ' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'credits_allocated' ; - $s{no} = 1 ; - &common_min_add_extras ; + our $savjqy = 1 ; + } #------------------------------------------------------------------------------- use common ; diff --git a/scripts/analytics_event_bookings.pl b/scripts/analytics_event_bookings.pl index 90bd328..778ff6b 100644 --- a/scripts/analytics_event_bookings.pl +++ b/scripts/analytics_event_bookings.pl @@ -65,11 +65,11 @@ our $nr_of_system_names_and_clubs = 15 ; our @all_select_ids = () ; our $minify_ #------------------------------------------------------------------------------------------------------------------------------------------------------------------ - our @fixture_headers = ("Fixture Date/Time From","Sport","Age Group","Team","Home Team","HT Colour","Away Team","Coding Type","Footage Type"); + our @fixture_headers = ("Fixture Date/Time From","Sport","Age Group","Team","Home Team","HT Colour","Away Team","Coding Type","Footage Type","Service Type"); our @analytics_headers = ("Fixture Date/Time From","Sport","Age Group","Team","Home Team","HT Colour","Away Team","Coding Type","Footage Type","Service Type"); - our %service_types = (1 => "Live Coding",2 => "Post Coding 12 hrs",3 => "Post Coding 24 hrs") ; + our %service_types = (1 => "Live Coding",2 => "Individual 48 hrs",3 => "Post Coding 24 hrs") ; our %coding_type = ("s" => "Standard","p" => "Premium") ; - our %footage_type = ("s" => "SSS","r" => "Raw") ; + our %footage_type = ("s" => "Pixellot","r" => "YouTube") ; if ($iaction eq 'add') { &add_screen ; @@ -120,15 +120,15 @@ sub edit_or_list { sub process_fixtures_tab { - my ($id) = @_ ; + my ($id,$id2) = @_ ; - &db_min_ro($table,"id,fixtures_saved_values,analytics_saved_values","id='$id'",'','') if $id ; + &db_min_ro($table,"*","id='$id'",'','') if $id ; $i{fixtures_saved_values} = qq~~ ; my $suffix = "fixtures" ; - my @changed_field_keys = ("age_group","team","home_team","ht_colour","away_team","coding_type","footage_type") ; + my @changed_field_keys = ("age_group","team","home_team","ht_colour","away_team","coding_type","footage_type","service_type") ; my @fixtures_saved_values_split = ($id) ? split(/\|/,$db{$table}{$id}{fixtures_saved_values}) : () ; @@ -144,7 +144,7 @@ sub process_fixtures_tab { $input_vals .= qq~;$i{"$_\_$suffix\_$row_nr"}~ ; $ignore{"$_\_$suffix\_$row_nr"} = 1 ; } - $input_vals .= qq~;$fixtures_saved_values_split_2[9];$fixtures_saved_values_split_2[10]~ ; + $input_vals .= qq~;$fixtures_saved_values_split_2[10];$fixtures_saved_values_split_2[11];$fixtures_saved_values_split_2[12];$fixtures_saved_values_split_2[13]~ ; my $changed_fixtures_date_field = "changed_fixtures_date_$row_nr" ; @@ -157,28 +157,180 @@ sub process_fixtures_tab { $i{fixtures_saved_values} .= qq~$input_vals~ ; } + $i{fixtures_saved_values} =~ s/;+$//g ; $i{fixtures_saved_values} .= qq~|~ ; + $ignore{"typeahead_home_team_$suffix\_$row_nr"} = 1 ; + $ignore{"typeahead_away_team_$suffix\_$row_nr"} = 1 ; $ignore{"start_date_time_$suffix\_$row_nr"} = 1 ; $ignore{"readonly_sport_$suffix\_$row_nr"} = 1 ; $ignore{"sport_$suffix\_$row_nr"} = 1 ; + my $cant_charge_client_field = qq~cant_charge_client_$suffix\_$row_nr~ ; + $ignore{$cant_charge_client_field} = 1 ; + $i{cant_charge_client_fixtures} .= ($i{$cant_charge_client_field}) ? qq~1;~ : qq~;~ ; + } - # 1;;;u14;a;;1;;s;s|2;;;u14;a;;1;;s;s|3;;2;u15;a;;1;;s;s|4;;1;u15;a;;1;;s;s|5;;2;u16;a;;1;;s;s|6;;1;u16;a;;1;;s;s|7;;2;open;b;;1;;s;s|8;;1;open;b;;1;;s;s|9;;2;open;a;;1;;p;s|10;;1;open;a;;1;;p;s - # 1;;;u14;a;;1;;s;s;;|2;;;u14;a;;1;;s;s;;|3;;2;u15;a;;1;;s;s;;|4;;1;u15;a;;1;;s;s;;|5;;2;u16;a;;1;;s;s;;|6;;1;u16;a;;1;;s;s;;|7;;2;open;b;;1;;s;s;;|8;;1;open;b;;1;;s;s;;|9;;2;open;a;;1;;p;s;;|10;;1;open;a;;1;;p;s;; 1005 + $i{fixtures_saved_values} =~ s/\|+$//g ; + + my $prev_field = "" ; + + $i{cant_charge_client_fixtures} =~ s/\;+$//g ; - # 1;;;open;a;7495;1;6684;s;s;;|2;;;u19;b;845;1;778;p;r;;|3;2025-06-18 06:00:00;8;u17;c;54;1;3975;s;s;; 1000 - - # 1;;;u14;a;;1;;s;s;;|2;;1;u15;a;;1;;s;s;;|3;;1;u16;a;;1;;s;s;;|4;;1;u17;a;;1;;s;s;;|5;;1;open;a;;1;;p;s;; - # 1;;;u14;a;;1;;s;s|2;;1;u15;a;;1;;s;s|3;;1;u16;a;;1;;s;s|4;;1;u17;a;;1;;s;s|5;;1;open;a;;1;;p;s - - chop $i{fixtures_saved_values} if $i{fixtures_saved_values} ; + # chop $i{fixtures_saved_values} if $i{fixtures_saved_values} ; $i{fixtures_saved_values} =~ s/([a-zA-Z0-9]);+(\|)/$1$2/g; $i{fixtures_saved_values} =~ s/([a-zA-Z0-9])\|+$/$1/; $ignore{fixtures_saved_values} = (($id && $i{fixtures_saved_values} eq $db{$table}{$id}{fixtures_saved_values}) || (!$i{fixtures_saved_values} && !$db{$table}{$id}{fixtures_saved_values})) ? 1 : 0 ; + $ignore{cant_charge_client_fixtures} = (($id && $i{cant_charge_client_fixtures} eq $db{$table}{$id}{cant_charge_client_fixtures}) || (!$i{cant_charge_client_fixtures} && !$db{$table}{$id}{cant_charge_client_fixtures})) ? 1 : 0 ; + $ignore{sport_type_ids} = (($id && $i{sport_type_ids} eq $db{$table}{$id}{sport_type_ids}) || (!$i{sport_type_ids} && !$db{$table}{$id}{sport_type_ids})) ? 1 : 0 ; + $ignore{total_fixtures} = ($id && $i{total_fixtures} eq $db{$table}{$id}{total_fixtures}) ? 1 : 0 ; + $ignore{client_id} = ($id && $i{client_id} eq $db{$table}{$id}{client_id}) ? 1 : 0 ; + # $ignore{total_fixtures} = ($id && $i{total_fixtures} eq $db{$table}{$id}{total_fixtures}) ? 1 : 0 ; + + if (!$ignore{cant_charge_client_fixtures} || !$ignore{sport_type_ids} || !$ignore{total_fixtures} || !$ignore{client_id} || 1) { ## ignore credit type outstanding + + &analytics_event_booking_tabs_update_credits_used($id,$id2) ; + + # my %credits_used = () ; my $row_cnt = 0 ; + # my @cnt_charge = split(/\;/,$db{$table}{$id}{cant_charge_client_fixtures}) ; + + # if ($db{$table}{$id}{client_id}) { + # foreach my $fixture_row (@fixtures_saved_values_split) { + # $row_cnt++ ; + # last if $row_cnt > $db{$table}{$id}{total_fixtures} ; + # my @fixtures_saved_values_split_2 = split(/\;/,$fixture_row) ; + # my $sport_id = ($db{$table}{$id}{sport_type_ids} !~ /;/) ? $db{$table}{$id}{sport_type_ids} : $fixtures_saved_values_split_2[1] ; + + # next unless $sport_id ; + + # $credits_used{previous}{premium}{$db{$table}{$id}{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 'p' && !$cnt_charge[$row_cnt-1] ; + # $credits_used{previous}{standard}{$db{$table}{$id}{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 's' && !$cnt_charge[$row_cnt-1] ; + # $credits_used{previous}{individual}{$db{$table}{$id}{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 'i' && !$cnt_charge[$row_cnt-1] ; + # } + # } + + # if ($i{client_id}) { + + # @fixtures_saved_values_split = split(/\|/,$i{fixtures_saved_values}) ; + # $row_cnt = 0 ; + # @cnt_charge = split(/\;/,$i{cant_charge_client_fixtures}) ; + + # foreach my $fixture_row (@fixtures_saved_values_split) { + + # $row_cnt++ ; + # last if $row_cnt > $i{total_fixtures} ; + # my @fixtures_saved_values_split_2 = split(/\;/,$fixture_row) ; + + # my $sport_id = ($i{sport_type_ids} !~ /;/) ? $db{$table}{$id}{sport_type_ids} : $fixtures_saved_values_split_2[1] ; + + # next unless $sport_id ; + + # $credits_used{new}{premium}{$i{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 'p' && !$cnt_charge[$row_cnt-1] ; + # $credits_used{new}{standard}{$i{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 's' && !$cnt_charge[$row_cnt-1] ; + # $credits_used{new}{individual}{$i{client_id}}{$sport_id} += 1 if $fixtures_saved_values_split_2[7] eq 'i' && !$cnt_charge[$row_cnt-1] ; + + # } + + # my %seen = () ; + + # } + + # $seen{client}{$i{client_id}} = 1 if $i{client_id} ; + # $seen{client}{$db{$table}{$id}{client_id}} = 1 if $db{$table}{$id}{client_id} ; + + # foreach (split(/\;/,$db{$table}{$id}{sport_type_ids})) { + # $seen{sport}{$_} = 1 if $_ ; + # } + # foreach (split(/\;/,$i{sport_type_ids})) { + # $seen{sport}{$_} = 1 if $_ ; + # } + + # my $sport_sql = join(" OR ",map{"sport_type_id='$_'"} keys %{$seen{sport}}) ; + # my $client_sql = join(" OR ",map{"client_id='$_'"} keys %{$seen{client}}) ; + # my $id_sql = ($id2) ? "analytics_event_id='$id2'" : ($id) ? "analytics_event_id='$id'" : "" ; + + # my @sql_where_arr = () ; + # push @sql_where_arr,"($sport_sql)" if $sport_sql ; + # push @sql_where_arr,"($client_sql)" if $client_sql ; + # push @sql_where_arr,$id_sql if $id_sql ; + + # my $sql_where = join(" AND ",@sql_where_arr) ; + + # &db_min_ro('credits_used','*',$sql_where,'','') ; my %exists = () ; + + # my %db_credits_used = %db ; + + # foreach my $_id (keys %{$db{credits_used}}) { + # $exists{$db{credits_used}{$_id}{sport_type_id}}{$db{credits_used}{$_id}{client_id}} = 1 ; + # } + + # my $new_id = 0 ; + + # foreach my $client_id (sort {$a <=> $b} keys %{$seen{client}}) { + # foreach my $sport_id (sort {$a <=> $b} keys %{$seen{sport}}) { + # unless ($exists{$sport_id}{$client_id}) { + # if ($new_id) { + # $new_id++ ; + # } else { + # $new_id = &db_min_get_max('credits_used','id') ; + # } + + # $db_credits_used{credits_used}{$new_id}{sport_type_id} = $sport_id ; + # $db_credits_used{credits_used}{$new_id}{client_id} = $client_id ; + + # } + # } + # } + + # my %hidden_old = %hidden ; + # %hidden = () ; + # my %ignore_old = %ignore ; + # %ignore = () ; + # my %ii = %i ; + # # cant_charge_client_fixtures_1 + # foreach my $_id (keys %{$db_credits_used{credits_used}}) { + + # my $premium_credits = ($db_credits_used{credits_used}{$_id}{premium_credits_used}) ? $db_credits_used{credits_used}{$_id}{premium_credits_used} : 0 ; + # my $standard_credits = ($db_credits_used{credits_used}{$_id}{standard_credits_used}) ? $db_credits_used{credits_used}{$_id}{standard_credits_used} : 0 ; + # my $individual_credits = ($db_credits_used{credits_used}{$_id}{individual_credits_used}) ? $db_credits_used{credits_used}{$_id}{individual_credits_used} : 0 ; + + # my $sport_id = $db_credits_used{credits_used}{$_id}{sport_type_id} ; + # my $client_id = $db_credits_used{credits_used}{$_id}{client_id} ; + + # %i = () ; + + # $i{premium_credits_used} = $credits_used{new}{premium}{$client_id}{$sport_id} ; + # $i{standard_credits_used} = $credits_used{new}{standard}{$client_id}{$sport_id} ; + # $i{individual_credits_used} = $credits_used{new}{individual}{$client_id}{$sport_id} ; + + # $i{premium_credits_used} = 0 unless $i{premium_credits_used} ; + # $i{standard_credits_used} = 0 unless $i{standard_credits_used} ; + # $i{individual_credits_used} = 0 unless $i{individual_credits_used} ; + + # $ignore{premium_credits_used} = ($credits_used{new}{premium}{$client_id}{$sport_id} ne $premium_credits) ? 0 : 1 ; + # $ignore{standard_credits_used} = ($credits_used{new}{standard}{$client_id}{$sport_id} ne $standard_credits) ? 0 : 1 ; + # $ignore{individual_credits_used} = ($credits_used{new}{individual}{$client_id}{$sport_id} ne $individual_credits) ? 0 : 1 ; + + # if (!$exists{$sport_id}{$client_id} && ($i{premium_credits_used} || $i{standard_credits_used} || $i{individual_credits_used}) && $ii{event_accepted}) { + # $i{id} = "$_id" ; + # $i{sport_type_id} = "$sport_id" ; + # $i{client_id} = "$client_id" ; + # $i{analytics_event_id} = ($id2) ? "$id2" : ($id) ? "$id" : "0" ; + # &db_min_insert('credits_used') ; + # } elsif ($exists{$sport_id}{$client_id} && ($i{premium_credits_used} || $i{standard_credits_used} || $i{individual_credits_used}) && $ii{event_accepted}) { + # &db_min_upd('credits_used',"id='$_id'") ; + # } elsif ($exists{$sport_id}{$client_id} && ((!$i{premium_credits_used} && !$i{standard_credits_used} && !$i{individual_credits_used}) || !$ii{event_accepted})) { + # &db_min_delete('credits_used',"id='$_id'") ; + # } + # } + + # %ignore = %ignore_old ; + # %hidden = %hidden ; + # %i = %ii ; + } } #------------------------------------------------------------------------------------------ @@ -192,6 +344,12 @@ sub process_analytics_tab { for my $row_nr (1 .. 100) { + $i{"stream_key_$suffix\_$row_nr"} =~ s/\;/\_semi_colon_character_/g ; + $i{"stream_URL_$suffix\_$row_nr"} =~ s/\;/\_semi_colon_character_/g ; + + $i{"stream_key_$suffix\_$row_nr"} =~ s/\|/\_pipe_character_/g ; + $i{"stream_URL_$suffix\_$row_nr"} =~ s/\|/\_pipe_character_/g ; + foreach (@changed_field_keys) { $i{analytics_saved_values} .= ($i{"$_\_$suffix\_$row_nr"}) ? qq~$i{"$_\_$suffix\_$row_nr"};~ : ($i{"$_\_fixtures_$row_nr"}) ? qq~$i{"$_\_fixtures_$row_nr"};~ : qq~;~ ; $ignore{"$_\_$suffix\_$row_nr"} = 1 ; @@ -223,16 +381,16 @@ sub insert { $i{id} = &db_min_get_max($table,'id') ; $i{id} = 1000 if !$i{id} || $i{id} < 1000 ; - &process_fixtures_tab('') ; + &process_client_id ; + + &process_multi_select ; + + &process_fixtures_tab('',$i{id}) ; &process_analytics_tab('') ; &set_default_i_vals ; - - &process_multi_select ; - - &process_client_id ; - + $ignore{country_id} = 1 ; &db_min_insert($table) ; @@ -253,14 +411,14 @@ sub update { &set_default_i_vals ; + &process_client_id ; + + &process_multi_select ; + &process_fixtures_tab($i{id}) ; &process_analytics_tab($i{id}) ; - &process_multi_select ; - - &process_client_id ; - # &log_changes($i{id}) ; # &db_min_upd($table,"id='$i{id}'") ; @@ -268,8 +426,12 @@ sub update { our $line = qq~~ ; $ignore{country_id} = 1 ; - - &common_shared_log_update_changes($table,"analytics_changes","changes_analytics") ; + + # foreach (keys %i) { + # print "\n $_ : $i{$_} , $ignore{$_}" ; + # } + + &common_shared_log_update_changes($table,"analytics_changes","changes_analytics") ; } #------------------------------------------------------------------------------------------ @@ -335,7 +497,22 @@ sub duplicate { return ; } + my %ii = %i ; &db_min_copy($table,$i{id}) ; + my $new_id = $i{id} ; + &db_min_ro('credits_used','id',"analytics_event_id='$ii{id}'") ; + my %copy_ids = () ; + foreach (keys %{$db{credits_used}}) { + &db_min_copy('credits_used',$_) ; + $copy_ids{$i{id}} = 1 ; + } + %i = () ; + my $copy_sql = join(" OR ",map{"id='$_'"} keys %copy_ids) ; + $i{analytics_event_id} = "$new_id" ; + &db_min_upd('credits_used',$copy_sql) ; + %i = %ii ; + $i{id} = $new_id ; + $success = qq($ii{id} SUCCESSFULLY COPIED TO $i{id}) ; } #------------------------------------------------------------------------------------------ @@ -343,8 +520,13 @@ sub delete { unless ($i{id}) { $error = uc "NO ID" ; return ; } - &db_min_delete($table,"`id`='$i{id}'") ; + my $delete_id = $i{id} ; + &db_min_delete($table,"id='$delete_id'") ; + &db_min_delete('credits_used',"analytics_event_id='$delete_id'") ; + $i{id} = $delete_id ; + $success = qq($delete_id SUCCESSFULLY DELETED) ; + } #------------------------------------------------------------------------------------------ sub set_default_i_vals { @@ -425,35 +607,39 @@ sub list_screen { my $srch_where_sql = join(' AND ', @report_sql) ; my $sql_where = ($srch_where_sql) ? "WHERE $srch_where_sql" : '' ; - &db_min_raw("SELECT q.id AS 'quote_id', - q.sport_type_ids, - q.start_date_time, - q.event_name, - q.event_expiry, - q.client_id, - q.event_date, - q.date_created, - q.country_id, - q.event_cancelled, - q.event_accepted, - q.event_completed, - q.event_pending, - q.event_created, - q.event_rejected, - q.created_by, - q.additional_notes, - q.total_fixtures, - q.service_type_id, - q.event_quote_id, - q.fixtures_saved_values, - q.analytics_saved_values, - c.name AS 'country', - t.name AS 'customer', - eq.event_system_id_multiple - FROM $t1 q LEFT JOIN $t2 c ON q.country_id = c.id - LEFT JOIN $t3 t ON q.client_id = t.id - LEFT JOIN $t4 eq ON q.event_quote_id = eq.id - $sql_where;"); + &db_min_raw(" + SELECT + q.id AS 'quote_id', + q.sport_type_ids, + q.start_date_time, + q.event_name, + q.event_expiry, + q.client_id, + q.event_date, + q.date_created, + q.country_id, + q.event_cancelled, + q.event_accepted, + q.event_completed, + q.event_pending, + q.event_created, + q.event_rejected, + q.created_by, + q.additional_notes, + q.total_fixtures, + q.service_type_id, + q.event_quote_id, + q.fixtures_saved_values, + q.analytics_saved_values, + c.name AS 'country', + t.name AS 'customer', + eq.event_system_id_multiple + FROM $t1 q + LEFT JOIN $t2 c ON q.country_id = c.id + LEFT JOIN $t3 t ON q.client_id = t.id + LEFT JOIN $t4 eq ON q.event_quote_id = eq.id + $sql_where ; + "); foreach $row (@$rows_array_ref) { for (0 .. $col_cnt){ @@ -557,7 +743,10 @@ sub quote_list { my @analytics_saved_values = split(/\|/,$db{$tables}{$id}{analytics_saved_values}) ; my $row_cnt = 0 ; - foreach (@fixtures_saved_values) { + foreach (@fixtures_saved_values) { + + next unless $_ ; + # my $date = (substr($_,0,1) eq ';' || !$_) ? substr($db{$tables}{$id}{start_date_time},0,10) : substr($_,0,10) ; my $date = (substr($_,0,1) eq ';') ? substr($db{$tables}{$id}{start_date_time},0,10) : substr($_,0,10) ; my $time = (substr($_,0,1) eq ';') ? substr($db{$tables}{$id}{start_date_time},11,5) : substr($_,11,5) ; $individual_games{$date}{$time}{$id}{fixtures} .= qq~$_\|~ ; @@ -579,7 +768,7 @@ sub quote_list { $sort_val = sprintf("%06d",$id) ; $sort_val = ($quote_accepted) ? qq~5~ . $sort_val : ($quote_completed) ? qq~4~ . $sort_val : ($quote_pending) ? qq~3~ . $sort_val : ($quote_rejected) ? qq~2~ . $sort_val : ($quote_cancelled) ? qq~1~ . $sort_val : qq~0~ . $sort_val ; $val = qq~$sort_val~ . &common_min_get_event_quote_button($id,$tables,"analytics-event-bookings") ; - $val .= qq~~ if $db{$tables}{$id}{event_quote_id} ; + $val .= qq~~ if $db{$tables}{$id}{event_quote_id} && $db{$tables}{$id}{event_quote_id} > 0 ; $val_xlsx = $id ; # javascript:editMinItem('10922','event-quotes'); if ($quote_completed) { @@ -665,10 +854,16 @@ sub quote_list { my $quote_nr = $quote_nr ; $quote_nr =~ s/'//iog; unless ($quote_nr) { $quote_nr = $id ; } - my $edit_butt = qq~~ ; - my $delete_butt = qq~~ ; - # ($glod_user_level < 3 || $quote_accepted || $quote_completed || $quote_rejected || $quote_pending) ? '' : + my $edit_butt = qq~~ ; + my $delete_butt = qq~~ ; + + # ($glod_user_level < 3 || $quote_accepted || $quote_completed || $quote_rejected || $quote_pending) ? '' : my $copy_butt = qq~~ ; + + if ($usertype eq 'analytics_client') { + $delete_butt = qq~~ ; + $copy_butt = qq~~ ; + } $edit_butt = qq~$edit_butt ~ if $edit_butt ; $copy_butt = qq~$copy_butt ~ if $copy_butt ; @@ -1141,7 +1336,7 @@ sub build_boxes { #-------------------------------------------------------------------------- - our $skip_save_btn = ($quote_completed && $glod_user_level <= 3) ? 1 : 0 ; + our $skip_save_btn = (($quote_completed && $glod_user_level <= 3) || $usertype eq 'analytics_client') ? 1 : 0 ; $print_box_content_rows .= &common_min_forms_end($id,$table,$action,$skip) ; @@ -1573,7 +1768,7 @@ sub select_opts { } } - if (\$("#selectEvent_quote_id").val() && we_can_save_form) { + if (\$("#selectEvent_quote_id").val() && \$("#selectEvent_quote_id").val() != '-1' && we_can_save_form) { let date_url = "$useropts{scripts}/get/get_dates_from_event_quote.pl?event_quote_id="+\$("#selectEvent_quote_id").val()+"&start_date_time="+\$("input[name='start_date_time']").val()+"&end_date_time="+\$("input[name='end_date_time']").val() ; @@ -1581,8 +1776,8 @@ sub select_opts { for (const key in dates_json) { const data = dates_json[key]; - noty({text:'The Start and End date of this Event is from '+data.start_date_time+' to '+data.end_date_time+' Compared to '+data.date_from+' to '+data.date_to+' for the Event Quote.
    Please Ensure the Dates Correspond!',layout:"center",type:"warning",timeout:7500}) ; - await sleep(7500); + // noty({text:'The Start and End date of this Event is from '+data.start_date_time+' to '+data.end_date_time+' Compared to '+data.date_from+' to '+data.date_to+' for the Event Quote.
    Please Ensure the Dates Correspond!',layout:"center",type:"warning",timeout:7500}) ; + // await sleep(5000); } // await \$.get(date_url, function(json) { @@ -1666,7 +1861,7 @@ sub page_opts { our $savjqy = 1 ; our $max_cams = 10 ; - &common_min_add_box_icon ; + &common_min_add_box_icon if $usertype ne 'analytics_client' ; our %casuals = (); @@ -1675,11 +1870,11 @@ sub page_opts { sub report_ifields { if ($i{start_date_from} && $i{start_date_to}) { - push @report_sql, " (('$i{start_date_from}' <= start_date_time AND start_date_time <= '$i{start_date_to}') OR ('$i{start_date_from}' <= end_date_time AND end_date_time <= '$i{start_date_to}' AND end_date_time IS NOT NULL)) " ; + push @report_sql, " (('$i{start_date_from}' <= q.start_date_time AND q.start_date_time <= '$i{start_date_to}') OR ('$i{start_date_from}' <= q.end_date_time AND q.end_date_time <= '$i{start_date_to}' AND q.end_date_time IS NOT NULL) OR (q.start_date_time <= '$i{start_date_from}' AND '$i{start_date_to}' <= q.end_date_time AND q.end_date_time IS NOT NULL)) " ; our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; my $start_date_from = &common_min_date_as_string($i{start_date_from}) ; my $start_date_to = &common_min_date_as_string($i{start_date_to}) ; - push @report_results, " (START DATE BETWEEN '$start_date_from' AND '$start_date_to') OR (END DATE BETWEEN '$start_date_from' AND '$start_date_to')" ; + push @report_results, " EVENT STARTS AND/OR ENDS FROM '$start_date_from' TO '$start_date_to'" ; } if ($i{country}) { @@ -1723,11 +1918,11 @@ sub report_ifields { if ($i{sport_type_ids} && $i{sport_type_ids} ne 'all') { &db_min_ro('sport_types',"id,name","id='$i{sport_type_ids}'",'','') ; push @report_sql, "FIND_IN_SET($i{sport_type_ids},REPLACE(q.sport_type_ids,';',','))" ; - push @report_results, "sport_types INCLUDE `$db{sport_types}{$i{sport_type_ids}}{name}`" ; + push @report_results, "SPORT TYPES INCLUDE `$db{sport_types}{$i{sport_type_ids}}{name}`" ; } if ($usertype eq 'analytics_client') { - push @report_sql, "(q.client_id='$userid')" ; + # push @report_sql, "(q.client_id='$userid')" ; } $report_results_msg = uc join(', ', @report_results) ; @@ -1795,8 +1990,8 @@ sub filter_screen { $print_box_content_rows .= &common_min_form_datetimepicker('start_date_to',$i{start_date_to},720) ; $opts{options} = qq~ - - + + diff --git a/scripts/analytics_event_credits.pl b/scripts/analytics_event_credits.pl index 6ce90ab..b3f6011 100644 --- a/scripts/analytics_event_credits.pl +++ b/scripts/analytics_event_credits.pl @@ -53,7 +53,7 @@ if ($is_operator && $glod_user_level == 2) { $glod_user_level = 3 ; } # upgrade our $nr_of_system_names_and_clubs = 15 ; our @all_select_ids = () ; our $minify_jquery = 1 ; -if ($username ne 'handre') { +unless ($glod_user_level >= 5) { print "Development in Progress!!!" ; exit ; } @@ -127,90 +127,90 @@ sub process_fixtures_tab { my ($id) = @_ ; - &db_min_ro($table,"id,fixtures_saved_values,analytics_saved_values","id='$id'",'','') if $id ; + # &db_min_ro($table,"id,fixtures_saved_values,analytics_saved_values","id='$id'",'','') if $id ; - $i{fixtures_saved_values} = qq~~ ; + # $i{fixtures_saved_values} = qq~~ ; - my $suffix = "fixtures" ; + # my $suffix = "fixtures" ; - my @changed_field_keys = ("age_group","team","home_team","ht_colour","away_team","coding_type","footage_type") ; + # my @changed_field_keys = ("age_group","team","home_team","ht_colour","away_team","coding_type","footage_type") ; - my @fixtures_saved_values_split = ($id) ? split(/\|/,$db{$table}{$id}{fixtures_saved_values}) : () ; + # my @fixtures_saved_values_split = ($id) ? split(/\|/,$db{$table}{$id}{fixtures_saved_values}) : () ; - for my $row_nr (1 .. 100) { + # for my $row_nr (1 .. 100) { - # last if $row_nr > $i{total_fixtures} ; + # # last if $row_nr > $i{total_fixtures} ; - my $input_vals = qq~~ ; + # my $input_vals = qq~~ ; - my @fixtures_saved_values_split_2 = ($id) ? split(/\;/,$fixtures_saved_values_split[$row_nr - 1]) : () ; + # my @fixtures_saved_values_split_2 = ($id) ? split(/\;/,$fixtures_saved_values_split[$row_nr - 1]) : () ; - foreach (@changed_field_keys) { - $input_vals .= qq~;$i{"$_\_$suffix\_$row_nr"}~ ; - $ignore{"$_\_$suffix\_$row_nr"} = 1 ; - } - $input_vals .= qq~;$fixtures_saved_values_split_2[9];$fixtures_saved_values_split_2[10]~ ; + # foreach (@changed_field_keys) { + # $input_vals .= qq~;$i{"$_\_$suffix\_$row_nr"}~ ; + # $ignore{"$_\_$suffix\_$row_nr"} = 1 ; + # } + # $input_vals .= qq~;$fixtures_saved_values_split_2[9];$fixtures_saved_values_split_2[10]~ ; - my $changed_fixtures_date_field = "changed_fixtures_date_$row_nr" ; + # my $changed_fixtures_date_field = "changed_fixtures_date_$row_nr" ; - my $date_field = "start_date_time_$suffix\_$row_nr" ; + # my $date_field = "start_date_time_$suffix\_$row_nr" ; - my $changed_sport_field = "sport_fixtures_$row_nr" ; + # my $changed_sport_field = "sport_fixtures_$row_nr" ; - if ($input_vals =~ /[a-zA-Z]/ || $input_vals =~ /(\d+)/g || $i{$changed_sport_field} || $i{$changed_fixtures_date_field}) { - $i{fixtures_saved_values} .= ($i{$changed_fixtures_date_field}) ? qq~$i{$date_field};$i{$changed_sport_field}~ : qq~;$i{$changed_sport_field}~ ; - $i{fixtures_saved_values} .= qq~$input_vals~ ; - } + # if ($input_vals =~ /[a-zA-Z]/ || $input_vals =~ /(\d+)/g || $i{$changed_sport_field} || $i{$changed_fixtures_date_field}) { + # $i{fixtures_saved_values} .= ($i{$changed_fixtures_date_field}) ? qq~$i{$date_field};$i{$changed_sport_field}~ : qq~;$i{$changed_sport_field}~ ; + # $i{fixtures_saved_values} .= qq~$input_vals~ ; + # } - $i{fixtures_saved_values} .= qq~|~ ; + # $i{fixtures_saved_values} .= qq~|~ ; - $ignore{"start_date_time_$suffix\_$row_nr"} = 1 ; - $ignore{"readonly_sport_$suffix\_$row_nr"} = 1 ; - $ignore{"sport_$suffix\_$row_nr"} = 1 ; + # $ignore{"start_date_time_$suffix\_$row_nr"} = 1 ; + # $ignore{"readonly_sport_$suffix\_$row_nr"} = 1 ; + # $ignore{"sport_$suffix\_$row_nr"} = 1 ; - } - # 1;;;u14;a;;1;;s;s|2;;;u14;a;;1;;s;s|3;;2;u15;a;;1;;s;s|4;;1;u15;a;;1;;s;s|5;;2;u16;a;;1;;s;s|6;;1;u16;a;;1;;s;s|7;;2;open;b;;1;;s;s|8;;1;open;b;;1;;s;s|9;;2;open;a;;1;;p;s|10;;1;open;a;;1;;p;s - # 1;;;u14;a;;1;;s;s;;|2;;;u14;a;;1;;s;s;;|3;;2;u15;a;;1;;s;s;;|4;;1;u15;a;;1;;s;s;;|5;;2;u16;a;;1;;s;s;;|6;;1;u16;a;;1;;s;s;;|7;;2;open;b;;1;;s;s;;|8;;1;open;b;;1;;s;s;;|9;;2;open;a;;1;;p;s;;|10;;1;open;a;;1;;p;s;; 1005 + # } + # # 1;;;u14;a;;1;;s;s|2;;;u14;a;;1;;s;s|3;;2;u15;a;;1;;s;s|4;;1;u15;a;;1;;s;s|5;;2;u16;a;;1;;s;s|6;;1;u16;a;;1;;s;s|7;;2;open;b;;1;;s;s|8;;1;open;b;;1;;s;s|9;;2;open;a;;1;;p;s|10;;1;open;a;;1;;p;s + # # 1;;;u14;a;;1;;s;s;;|2;;;u14;a;;1;;s;s;;|3;;2;u15;a;;1;;s;s;;|4;;1;u15;a;;1;;s;s;;|5;;2;u16;a;;1;;s;s;;|6;;1;u16;a;;1;;s;s;;|7;;2;open;b;;1;;s;s;;|8;;1;open;b;;1;;s;s;;|9;;2;open;a;;1;;p;s;;|10;;1;open;a;;1;;p;s;; 1005 - # 1;;;open;a;7495;1;6684;s;s;;|2;;;u19;b;845;1;778;p;r;;|3;2025-06-18 06:00:00;8;u17;c;54;1;3975;s;s;; 1000 + # # 1;;;open;a;7495;1;6684;s;s;;|2;;;u19;b;845;1;778;p;r;;|3;2025-06-18 06:00:00;8;u17;c;54;1;3975;s;s;; 1000 - # 1;;;u14;a;;1;;s;s;;|2;;1;u15;a;;1;;s;s;;|3;;1;u16;a;;1;;s;s;;|4;;1;u17;a;;1;;s;s;;|5;;1;open;a;;1;;p;s;; - # 1;;;u14;a;;1;;s;s|2;;1;u15;a;;1;;s;s|3;;1;u16;a;;1;;s;s|4;;1;u17;a;;1;;s;s|5;;1;open;a;;1;;p;s + # # 1;;;u14;a;;1;;s;s;;|2;;1;u15;a;;1;;s;s;;|3;;1;u16;a;;1;;s;s;;|4;;1;u17;a;;1;;s;s;;|5;;1;open;a;;1;;p;s;; + # # 1;;;u14;a;;1;;s;s|2;;1;u15;a;;1;;s;s|3;;1;u16;a;;1;;s;s|4;;1;u17;a;;1;;s;s|5;;1;open;a;;1;;p;s - chop $i{fixtures_saved_values} if $i{fixtures_saved_values} ; + # chop $i{fixtures_saved_values} if $i{fixtures_saved_values} ; - $i{fixtures_saved_values} =~ s/([a-zA-Z0-9]);+(\|)/$1$2/g; - $i{fixtures_saved_values} =~ s/([a-zA-Z0-9])\|+$/$1/; + # $i{fixtures_saved_values} =~ s/([a-zA-Z0-9]);+(\|)/$1$2/g; + # $i{fixtures_saved_values} =~ s/([a-zA-Z0-9])\|+$/$1/; - $ignore{fixtures_saved_values} = (($id && $i{fixtures_saved_values} eq $db{$table}{$id}{fixtures_saved_values}) || (!$i{fixtures_saved_values} && !$db{$table}{$id}{fixtures_saved_values})) ? 1 : 0 ; + # $ignore{fixtures_saved_values} = (($id && $i{fixtures_saved_values} eq $db{$table}{$id}{fixtures_saved_values}) || (!$i{fixtures_saved_values} && !$db{$table}{$id}{fixtures_saved_values})) ? 1 : 0 ; } #------------------------------------------------------------------------------------------ sub process_analytics_tab { - $i{analytics_saved_values} = qq~~ ; + # $i{analytics_saved_values} = qq~~ ; - my $suffix = "analytics" ; + # my $suffix = "analytics" ; - my @changed_field_keys = ("stream_forwarding","stream_key","stream_URL") ; + # my @changed_field_keys = ("stream_forwarding","stream_key","stream_URL") ; - for my $row_nr (1 .. 100) { + # for my $row_nr (1 .. 100) { - foreach (@changed_field_keys) { - $i{analytics_saved_values} .= ($i{"$_\_$suffix\_$row_nr"}) ? qq~$i{"$_\_$suffix\_$row_nr"};~ : ($i{"$_\_fixtures_$row_nr"}) ? qq~$i{"$_\_fixtures_$row_nr"};~ : qq~;~ ; - $ignore{"$_\_$suffix\_$row_nr"} = 1 ; - $ignore{"$_\_fixtures_$row_nr"} = 1 ; - } + # foreach (@changed_field_keys) { + # $i{analytics_saved_values} .= ($i{"$_\_$suffix\_$row_nr"}) ? qq~$i{"$_\_$suffix\_$row_nr"};~ : ($i{"$_\_fixtures_$row_nr"}) ? qq~$i{"$_\_fixtures_$row_nr"};~ : qq~;~ ; + # $ignore{"$_\_$suffix\_$row_nr"} = 1 ; + # $ignore{"$_\_fixtures_$row_nr"} = 1 ; + # } - $i{analytics_saved_values} =~ s/;+$// ; - $i{analytics_saved_values} .= qq~|~ ; + # $i{analytics_saved_values} =~ s/;+$// ; + # $i{analytics_saved_values} .= qq~|~ ; - } + # } - $i{analytics_saved_values} =~ s/\|+$// ; + # $i{analytics_saved_values} =~ s/\|+$// ; - $ignore{analytics_saved_values} = (($id && $i{analytics_saved_values} eq $db{$table}{$id}{analytics_saved_values}) || (!$i{analytics_saved_values} && !$db{$table}{$id}{analytics_saved_values})) ? 1 : 0 ; + # $ignore{analytics_saved_values} = (($id && $i{analytics_saved_values} eq $db{$table}{$id}{analytics_saved_values}) || (!$i{analytics_saved_values} && !$db{$table}{$id}{analytics_saved_values})) ? 1 : 0 ; } #------------------------------------------------------------------------------------------ @@ -374,104 +374,112 @@ sub set_default_i_vals { sub list_screen { - $trigger_jquery_raw .= qq~ - function deleteMinItem_custom (name,id) { - BootstrapDialog.confirm({ - title: 'Confirm Delete', - message: 'Are you sure you want to delete '+name+'?', - type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING - callback: function(result) { - if (result) { - let delete_url = "$useropts{scripts}/get/get_delete_event_quote.pl?"+id+"&$table" ; - \$.get(delete_url) ; - \$("#analytics_event_row_"+id).html("") ; - } - } - }) ; - } - ~ ; + # $trigger_jquery_raw .= qq~ + # function deleteMinItem_custom (name,id) { + # BootstrapDialog.confirm({ + # title: 'Confirm Delete', + # message: 'Are you sure you want to delete '+name+'?', + # type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY <-- Default value is BootstrapDialog.TYPE_WARNING + # callback: function(result) { + # if (result) { + # let delete_url = "$useropts{scripts}/get/get_delete_event_quote.pl?"+id+"&$table" ; + # \$.get(delete_url) ; + # \$("#analytics_event_row_"+id).html("") ; + # } + # } + # }) ; + # } + # ~ ; - &db_min_ro('users','id,username,name,email','','','') ; - foreach my $_id (keys %{$db{users}}) { - $username{$_id} = $db{users}{$_id}{username} ; - $name{$_id} = $db{users}{$_id}{name} ; - $email{$_id} = $db{users}{$_id}{email} ; - } + # &db_min_ro('users','id,username,name,email','','','') ; + # foreach my $_id (keys %{$db{users}}) { + # $username{$_id} = $db{users}{$_id}{username} ; + # $name{$_id} = $db{users}{$_id}{name} ; + # $email{$_id} = $db{users}{$_id}{email} ; + # } - &db_min_ro('sport_types','*','','','') ; - foreach my $_id (keys %{$db{sport_types}}) { $sport_type{$_id} = $db{sport_types}{$_id}{name} ; } + # &db_min_ro('sport_types','*','','','') ; + # foreach my $_id (keys %{$db{sport_types}}) { $sport_type{$_id} = $db{sport_types}{$_id}{name} ; } - if ($iaction eq 'completed' or $i{options} eq 'completed') { push @report_sql, "q.event_completed='1'" ; } - if ($iaction eq 'accepted' or $i{options} eq 'accepted') { push @report_sql, "q.event_accepted='1'" ; } - if ($iaction eq 'rejected' or $i{options} eq 'rejected') { push @report_sql, "q.event_rejected='1'" ; } - if ($iaction eq 'closed' or $i{options} eq 'closed') { push @report_sql, "(q.event_cancelled='1' OR (q.event_expiry<'$now_year-$now_mm-$now_dd' AND q.event_accepted<>'1'))" ; } - if ($iaction eq 'pending' or $i{options} eq 'pending') { push @report_sql, "q.event_pending='1'" ; } - if ($iaction eq 'list' or $i{options} eq 'list') { push @report_sql, "q.event_cancelled<>'1'" ; } + # if ($iaction eq 'completed' or $i{options} eq 'completed') { push @report_sql, "q.event_completed='1'" ; } + # if ($iaction eq 'accepted' or $i{options} eq 'accepted') { push @report_sql, "q.event_accepted='1'" ; } + # if ($iaction eq 'rejected' or $i{options} eq 'rejected') { push @report_sql, "q.event_rejected='1'" ; } + # if ($iaction eq 'closed' or $i{options} eq 'closed') { push @report_sql, "(q.event_cancelled='1' OR (q.event_expiry<'$now_year-$now_mm-$now_dd' AND q.event_accepted<>'1'))" ; } + # if ($iaction eq 'pending' or $i{options} eq 'pending') { push @report_sql, "q.event_pending='1'" ; } + # if ($iaction eq 'list' or $i{options} eq 'list') { push @report_sql, "q.event_cancelled<>'1'" ; } - my $t1 = $table ; - my $t2 = 'countries' ; - my $t3 = 'customers' ; - my $t4 = 'event_quotes' ; - our $tables = "$t1,$t2,$t3,$t4" ; + # my $t1 = $table ; + # my $t2 = 'countries' ; + # my $t3 = 'customers' ; + # my $t4 = 'event_quotes' ; + # our $tables = "$t1,$t2,$t3,$t4" ; - if ($is_schools_manager || $is_operator) { - @report_sql_or = () ; - foreach $_reg_id (keys %{$glob_regids{$userid}}) { - push @report_sql_or, "q.region_id = '$_reg_id'" - } - my $sql_or = join(' OR ',@report_sql_or) ; - push @report_sql, "($sql_or)" if $sql_or ; - push @report_sql, "(q.event_created='1')" if $is_schools_manager ; - # push @report_sql, "(q.user_id='$userid')" if $is_schools_manager ; - push @report_sql, "(q.event_accepted='1')" if $is_operator && !$i{options} ; - } + # if ($is_schools_manager || $is_operator) { + # @report_sql_or = () ; + # foreach $_reg_id (keys %{$glob_regids{$userid}}) { + # push @report_sql_or, "q.region_id = '$_reg_id'" + # } + # my $sql_or = join(' OR ',@report_sql_or) ; + # push @report_sql, "($sql_or)" if $sql_or ; + # push @report_sql, "(q.event_created='1')" if $is_schools_manager ; + # # push @report_sql, "(q.user_id='$userid')" if $is_schools_manager ; + # push @report_sql, "(q.event_accepted='1')" if $is_operator && !$i{options} ; + # } - push @report_sql, "(q.event_completed <> '1')" if $iaction eq 'list' ; + # push @report_sql, "(q.event_completed <> '1')" if $iaction eq 'list' ; - my $srch_where_sql = join(' AND ', @report_sql) ; my $sql_where = ($srch_where_sql) ? "WHERE $srch_where_sql" : '' ; + # my $srch_where_sql = join(' AND ', @report_sql) ; my $sql_where = ($srch_where_sql) ? "WHERE $srch_where_sql" : '' ; - &db_min_raw("SELECT q.id AS 'quote_id', - q.sport_type_ids, - q.start_date_time, - q.event_name, - q.event_expiry, - q.client_id, - q.event_date, - q.date_created, - q.country_id, - q.event_cancelled, - q.event_accepted, - q.event_completed, - q.event_pending, - q.event_created, - q.event_rejected, - q.created_by, - q.additional_notes, - q.total_fixtures, - q.service_type_id, - q.event_quote_id, - q.fixtures_saved_values, - q.analytics_saved_values, - c.name AS 'country', - t.name AS 'customer', - eq.event_system_id_multiple - FROM $t1 q LEFT JOIN $t2 c ON q.country_id = c.id - LEFT JOIN $t3 t ON q.client_id = t.id - LEFT JOIN $t4 eq ON q.event_quote_id = eq.id - $sql_where;"); + # &db_min_raw("SELECT q.id AS 'quote_id', + # q.sport_type_ids, + # q.start_date_time, + # q.event_name, + # q.event_expiry, + # q.client_id, + # q.event_date, + # q.date_created, + # q.country_id, + # q.event_cancelled, + # q.event_accepted, + # q.event_completed, + # q.event_pending, + # q.event_created, + # q.event_rejected, + # q.created_by, + # q.additional_notes, + # q.total_fixtures, + # q.service_type_id, + # q.event_quote_id, + # q.fixtures_saved_values, + # q.analytics_saved_values, + # c.name AS 'country', + # t.name AS 'customer', + # eq.event_system_id_multiple + # FROM $t1 q LEFT JOIN $t2 c ON q.country_id = c.id + # LEFT JOIN $t3 t ON q.client_id = t.id + # LEFT JOIN $t4 eq ON q.event_quote_id = eq.id + # $sql_where;"); - foreach $row (@$rows_array_ref) { - for (0 .. $col_cnt){ - # &common_debug("[$_] $col_name{$_} -> @$row[$_]") ; - $db{$tables}{@$row[0]}{$col_name{$_}} = @$row[$_] ; - } - } + # foreach $row (@$rows_array_ref) { + # for (0 .. $col_cnt){ + # # &common_debug("[$_] $col_name{$_} -> @$row[$_]") ; + # $db{$tables}{@$row[0]}{$col_name{$_}} = @$row[$_] ; + # } + # } - &db_min_ro('event_systems','id,name,description','','','') ; + # &db_min_ro('event_systems','id,name,description','','','') ; &db_min_ro('customers','id,name','','','') ; &db_min_ro('sport_types','id,name','','','') ; + + my $srch_where_sql = join(' AND ', @report_sql) ; + + &db_min_ro('credits_allocated','*',$srch_where_sql,'','') ; + + &db_min_ro('credits_bought','*',$srch_where_sql,'','') ; + + &db_min_ro('credits_used','*',$srch_where_sql,'','') ; &analytics_event_bookings_tabs_hash ; # load for PDF links "e_list ; # load for PDF links @@ -487,378 +495,119 @@ sub quote_list { # our @sql_col_display = ("nr","date","customer","user","event","venue","location","sports_type","date_from","date_to","days","type") ; # our @sql_col_display = ("nr","event_start","event_end","date_added","customer","user","event","venue","location","sports_type","days","type") ; - our @sql_col_display = ("nr","event_start","event_end","date_added","customer","event","sport","total_fixtures","service_type") ; + our @sql_col_display = ("client_name","sport","standard","premium","individual") ; - our @col_display_excel = @sql_col_display ; - - push @sql_col_display, "" ; + my %credits_remaining = () ; my %total_credits_remaining = () ; - &report_xlsx_export_header("Analytics-Events",'analytics_events') ; - - our $ws2 = 'Individual Games' ; - - &xlsxcreator_add_worksheet($ws2) ; - - my %individual_games = () ; - - our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; + my %credit_types = (1 => "Standard", 2 => "Premium", 3 => "Individual") ; - foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) { - - next unless $id ; - - my $quote_expiry = $db{$tables}{$id}{event_expiry} ; $quote_expiry =~ s/\-//iog ; - our $quote_accepted = $db{$tables}{$id}{event_accepted} ; - our $quote_pending = $db{$tables}{$id}{event_pending} ; - our $quote_cancelled = $db{$tables}{$id}{event_cancelled} ; - our $quote_completed = $db{$tables}{$id}{event_completed} ; - our $quote_created = $db{$tables}{$id}{event_created} ; - our $quote_rejected = $db{$tables}{$id}{event_rejected} ; - - if ($quote_completed) { - $sortprefix = 'd' ; - } elsif ($quote_accepted) { - $sortprefix = 'c' ; - } elsif ($quote_rejected) { - $sortprefix = 'x' ; - } elsif ($quote_cancelled) { - $sortprefix = 'z' ; - } elsif ($quote_created) { # create by schools_manager - $sortprefix = 'a' ; - } elsif ($quote_pending) { - $sortprefix = 'b' ; - } - - if ($usertype eq 'support') { - next unless $quote_accepted && !$quote_completed ; - } - - # if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all') { next ; } - - my $quote_date = $db{$tables}{$id}{event_date} ; $quote_date =~ s/\-//iog ; - - $yr = substr($quote_date,0,4) ; - $mm = substr($quote_date,4,2) ; - $dd = substr($quote_date,6,2) ; - - my ($yr2,$mm2,$dd2) = Add_Delta_Days($yr,$mm,$dd,60); # - - $mm2 = sprintf("%02s",$mm2) ; - $dd2 = sprintf("%02s",$dd2) ; - - $quote_date = "$yr2$mm2$dd2" ; - - if ($quote_date && $quote_date < "$now_year$now_mm$now_dd" && $quote_accepted!=1 && - $iaction ne 'report' && $iaction ne 'accepted' && $iaction ne 'closed' && $iaction ne 'all' && - $i{options} ne 'accepted' && $i{options} ne 'closed' && $i{options} ne 'all') { next ; } - - $print_tbody .= qq~~ ; - - $xlsxcol = 0 ; - - my $quote_nr = $db{$tables}{$id}{quote_nr} ; - - my @fixtures_saved_values = split(/\|/,$db{$tables}{$id}{fixtures_saved_values}) ; - my @analytics_saved_values = split(/\|/,$db{$tables}{$id}{analytics_saved_values}) ; - - my $row_cnt = 0 ; - foreach (@fixtures_saved_values) { - my $date = (substr($_,0,1) eq ';') ? substr($db{$tables}{$id}{start_date_time},0,10) : substr($_,0,10) ; - my $time = (substr($_,0,1) eq ';') ? substr($db{$tables}{$id}{start_date_time},11,5) : substr($_,11,5) ; - $individual_games{$date}{$time}{$id}{fixtures} .= qq~$_\|~ ; - $individual_games{$date}{$time}{$id}{analytics} .= qq~$analytics_saved_values[$row_cnt]\|~ ; - $row_cnt++ ; - } - - foreach (@sql_col_display) { - - unless ($_) { next ; } # blank for the buttons column - my $val = $db{$tables}{$id}{$_} ; - my $align = qq~ class="dt-center"~ ; - my $nowrap = '' ; - my $val_xlsx = '' ; - - if ($_ eq 'nr') { - - $nowrap = 'nowrap' ; - $sort_val = sprintf("%06d",$id) ; - $sort_val = ($quote_accepted) ? qq~5~ . $sort_val : ($quote_completed) ? qq~4~ . $sort_val : ($quote_pending) ? qq~3~ . $sort_val : ($quote_rejected) ? qq~2~ . $sort_val : ($quote_cancelled) ? qq~1~ . $sort_val : qq~0~ . $sort_val ; - $val = qq~$sort_val~ . &common_min_get_event_quote_button($id,$tables,"analytics-event-bookings") ; - $val .= qq~~ if $db{$tables}{$id}{event_quote_id} ; - $val_xlsx = $id ; - # javascript:editMinItem('10922','event-quotes'); - if ($quote_completed) { - &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format80) ; - } elsif ($quote_accepted) { - &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format77) ; - } elsif ($quote_created) { - &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format78) ; # yellow - } elsif ($quote_pending) { - &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format79) ; # orange - } elsif ($quote_cancelled) { - &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format81) ; # red - } - - } elsif ($_ eq 'event_start') { - my $sort_val = $db{$tables}{$id}{start_date_time} =~ s/[\-:\s]//gr; - $val_xlsx = &common_min_date_as_string(substr($db{$tables}{$id}{start_date_time},0,16)) ; - $val = qq~$sort_val~ . $val_xlsx ; - $nowrap = 'nowrap' ; - } elsif ($_ eq 'event_end') { - - if ($db{$tables}{$id}{end_date_time}) { - my $sort_val = $db{$tables}{$id}{end_date_time} =~ s/[- :]//g ; - $val_xlsx = &common_min_date_as_string(substr($db{$tables}{$id}{end_date_time},0,16)) ; - $val = qq~$sort_val~ . $val_xlsx ; - } elsif ($db{$tables}{$id}{fixtures_saved_values}) { - my $latest_date = "" ; my $latest_date_val = "" ; - foreach (split(/\|/,$db{$tables}{$id}{fixtures_saved_values})) { - next unless $_ ; - my @saved_vals = split(/\;/,$_) ; - next unless $saved_vals[0] ; - my $date_val = $saved_vals[0] ; - $date_val =~ s/[- :]//g ; - $latest_date = $saved_vals[0] if !$latest_date_val || ($latest_date_val && $latest_date_val < $date_val) ; - $latest_date_val = $latest_date ; - $latest_date_val =~ s/[- :]//g ; - } - $val = substr($latest_date,0,10) ; - if ($val) { - my $sort_val = $val ; - $sort_val =~ s/[- :]//g ; - $val_xlsx = &common_min_date_as_string($val) ; - $val = qq~$sort_val~ . &common_min_date_as_string($val) ; - } - } - - $nowrap = 'nowrap' ; - } elsif ($_ eq 'date_added') { - my $sort_val = $db{$tables}{$id}{date_created} =~ s/[\-:\s]//gr; - $val_xlsx = &common_min_date_as_string($db{$tables}{$id}{date_created}) ; - $val = qq~$sort_val~ . $val_xlsx ; - $val_xlsx .= qq~ [Added By: $username{$db{$tables}{$id}{created_by}}]~ ; - $val = qq~$val~ ; - $nowrap = 'nowrap' ; - } elsif ($_ eq 'event') { - $val = $db{$tables}{$id}{event_name} ; - $nowrap = '' ; - } elsif ($_ eq 'customer') { - $nowrap = 'nowrap' ; - } elsif ($_ eq 'country_id') { - $val = $db{$tables}{$id}{country} ; - } elsif ($_ eq 'sport') { - $val = join("
    ", map { $sport_type{$_} } split(/\;/,$db{$tables}{$id}{sport_type_ids})) ; - $val_xlsx = $val ; - $val_xlsx =~ s/\
    /\;/g ; - } elsif ($_ eq 'total_fixtures') { - $val = ($db{$tables}{$id}{total_fixtures}) ? $db{$tables}{$id}{total_fixtures} : 1 ; - } elsif ($_ eq 'service_type') { - $db{$tables}{$id}{service_type_id} = ($db{$tables}{$id}{service_type_id}) ? $db{$tables}{$id}{service_type_id} : 2 ; - $val = $service_types{$db{$tables}{$id}{service_type_id}} ; - } - $print_tbody .= qq~$val~ ; - - if ($_ ne 'nr') { - $val_xlsx = $val unless $val_xlsx ; - &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val_xlsx,$format82) ; - } - $xlsxcol++ ; - - } - - $xlsxrow++ ; - - my $quote_nr = $quote_nr ; $quote_nr =~ s/'//iog; unless ($quote_nr) { $quote_nr = $id ; } - - my $edit_butt = qq~~ ; - my $delete_butt = qq~~ ; - # ($glod_user_level < 3 || $quote_accepted || $quote_completed || $quote_rejected || $quote_pending) ? '' : - my $copy_butt = qq~~ ; - - $edit_butt = qq~$edit_butt ~ if $edit_butt ; - $copy_butt = qq~$copy_butt ~ if $copy_butt ; - $delete_butt = qq~$delete_butt ~ if $delete_butt ; - - $print_tbody .= qq~ $edit_butt$copy_butt$delete_butt~ ; + foreach (keys %{$db{credits_allocated}}) { + my $credit_type = $db{credits_allocated}{$_}{credit_type} ; + next unless $credit_type ; + $credit_type = lc $credit_types{$credit_type} ; + $credits_remaining{$db{credits_allocated}{$_}{client_id}}{$db{credits_allocated}{$_}{sport_type_id}}{$credit_type} += $db{credits_allocated}{$_}{credits} ; + $total_credits_remaining{$db{credits_allocated}{$_}{client_id}}{$credit_type} += $db{credits_allocated}{$_}{credits} ; } - - my @day_name = ("","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday") ; - my @month_name = ("","January","February","March","April","May","June","July","August","September","October","November","December") ; - my $xlsxrow2 = 0 ; my $xlsxcol2 = 0 ; + foreach (keys %{$db{credits_bought}}) { + my $credit_type = $db{credits_bought}{$_}{credit_type} ; + next unless $credit_type ; + $credit_type = lc $credit_types{$credit_type} ; + $credits_remaining{$db{credits_bought}{$_}{client_id}}{$db{credits_bought}{$_}{sport_type_id}}{$credit_type} += $db{credits_bought}{$_}{credits} ; + $total_credits_remaining{$db{credits_bought}{$_}{client_id}}{$credit_type} += $db{credits_bought}{$_}{credits} ; + } - my %team_ids = () ; + foreach (keys %{$db{credits_used}}) { + $credits_remaining{$db{credits_used}{$_}{client_id}}{$db{credits_used}{$_}{sport_type_id}}{standard} -= $db{credits_used}{$_}{standard_credits_used} ; + $credits_remaining{$db{credits_used}{$_}{client_id}}{$db{credits_used}{$_}{sport_type_id}}{premium} -= $db{credits_used}{$_}{premium_credits_used} ; + $credits_remaining{$db{credits_used}{$_}{client_id}}{$db{credits_used}{$_}{sport_type_id}}{individual} -= $db{credits_used}{$_}{individual_credits_used} ; + $total_credits_remaining{$db{credits_used}{$_}{client_id}}{standard} -= $db{credits_used}{$_}{standard_credits_used} ; + $total_credits_remaining{$db{credits_used}{$_}{client_id}}{premium} -= $db{credits_used}{$_}{premium_credits_used} ; + $total_credits_remaining{$db{credits_used}{$_}{client_id}}{individual} -= $db{credits_used}{$_}{individual_credits_used} ; + } - foreach my $a (keys %individual_games) { - foreach my $b (keys %{$individual_games{$a}}) { - foreach my $c (keys %{$individual_games{$a}{$b}}) { - my @abc = split(/\|/,$individual_games{$a}{$b}{$c}{fixtures}) ; - foreach (@abc) { - my @abcd = split(/\;/,$_) ; - $team_ids{$abcd[4]} = 1 ; - $team_ids{$abcd[6]} = 1 ; + my $row_cnt = 0 ; + + foreach my $client_id (sort { $db{customers}{$a}{name} cmp $db{customers}{$b}{name} } keys %credits_remaining) { + + my $all_sports = 0 ; + + foreach my $sport_type_id (sort { $db{sport_types}{$a}{name} cmp $db{sport_types}{$b}{name} } keys %{$credits_remaining{$client_id}}) { + + if ($sport_type_id eq 'all') { + # $all_sports = 1 ; + } + } + + $print_tbody .= qq~~ ; + $row_cnt++ ; + + foreach my $col (@sql_col_display) { + + my $nowrap = "" ; + my $align = qq~ class="dt-center"~ ; + + my $val = '' ; + + if ($col eq 'client_name') { + my $row_val = sprintf("%09d",$row_cnt) ; + $val = qq~$row_val~ . $db{customers}{$client_id}{name} ; + } elsif ($col eq 'sport') { + $align = qq~ class="dt-right"~ ; + $val = ($all_sports) ? "Total (All Sports)" : "Total" ; + } elsif ($col eq 'standard' || $col eq 'premium' || $col eq 'individual') { + $val = $total_credits_remaining{$client_id}{$col} ; + $val = &common_commify($val) ; + } + + $print_tbody .= qq~$val~ ; + } + + $print_tbody .= qq~~ ; + + unless ($all_sports) { + + foreach my $sport_type_id (sort { $db{sport_types}{$a}{name} cmp $db{sport_types}{$b}{name} } keys %{$credits_remaining{$client_id}}) { + + $print_tbody .= qq~~ ; + $row_cnt++ ; + + foreach my $col (@sql_col_display) { + + my $nowrap = "" ; + my $align = qq~ class="dt-center"~ ; + + my $val = '' ; + + if ($col eq 'client_name') { + my $row_val = sprintf("%09d",$row_cnt) ; + $val = qq~$row_val~ ; + } elsif ($col eq 'sport') { + $val = ($sport_type_id ne 'all') ? $db{sport_types}{$sport_type_id}{name} : "All Sports" ; + } elsif ($col eq 'standard' || $col eq 'premium' || $col eq 'individual') { + $val = $credits_remaining{$client_id}{$sport_type_id}{$col} ; + $val = 0 unless $val ; + $val = &common_commify($val) ; + } + + $print_tbody .= qq~$val~ ; + } + + $print_tbody .= qq~~ ; + } } } - my $team_sql = join(" OR ", map{ "id='$_'" } keys %team_ids) ; - - &db_switch_conn('sss') ; - - &db_min_ro('teams','id,name',$team_sql,'','') ; - - &db_switch_conn('aisa') ; - - my $heading_count = 0 ; my %seen_event_sport = () ; - - foreach my $date (sort {$a cmp $b} keys %individual_games) { - - my ($year,$month,$day) = split(/\-/,$date) ; - my $day_of_week = Day_of_Week($year,$month,$day) ; - my $day_add = ($day eq '1') ? "st" : ($day eq '2') ? "nd" : ($day eq '3') ? "rd" : "th" ; - my $date_name = "$day_name[$day_of_week] $day$day_add $month_name[$month]" ; - - &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"$date_name",$format109) ; - - my $first_game = 1 ; - - my $contain_tbc_events = 0 ; - my $contain_confired_events = 0 ; - - foreach my $time (sort {$a cmp $b} keys %{$individual_games{$date}}) { - - foreach my $a_id (sort { $a <=> $b } keys %{$individual_games{$date}{$time}}) { - - $individual_games{$date}{$time}{$a_id}{fixtures} =~ s/\|+$// ; - $individual_games{$date}{$time}{$a_id}{analytics} =~ s/\|+$// ; - my @individual_games_fixtures = split(/\|/,$individual_games{$date}{$time}{$a_id}{fixtures}) ; - my @individual_games_analytics= split(/\|/,$individual_games{$date}{$time}{$a_id}{analytics}) ; - - my $row_cnt = scalar @individual_games_fixtures ; - $row_cnt = scalar @individual_games_analytics if scalar @individual_games_analytics > scalar @individual_games_fixtures ; - $row_cnt = 0 unless $row_cnt ; - - next unless $row_cnt ; - - my $tbc_game = 1 ; - - foreach my $row_nr (0 .. $row_cnt - 1) { - - my @data_split = split(/\;/,$individual_games_fixtures[$row_nr]) ; - - my $customer_name = uc $db{customers}{$db{$tables}{$a_id}{client_id}}{name} ; - my $sport_name = ($db{$tables}{$a_id}{sport_type_ids} && $db{$tables}{$a_id}{sport_type_ids} !~ /;/) ? $db{sport_types}{$db{$tables}{$a_id}{sport_type_ids}}{name} : $db{sport_types}{$data_split[1]}{name} ; - $sport_name = uc $sport_name ; - - $heading_count++ unless $seen_cleint_sport{$db{$tables}{$a_id}{client_id}}{$sport_name} ; - $heading_count = $heading_count%3 ; - $seen_cleint_sport{$db{$tables}{$a_id}{client_id}}{$sport_name} = 1 ; - - my $heading_format = ($heading_count == 1) ? $format110 : ($heading_count == 2) ? $format111 : ($heading_count == 0) ? $format112 : $format112 ; - - if (!$data_split[6]) { - $tbc_games{$date}{$db{$tables}{$a_id}{client_id}}{$sport_name}++ ; - $contain_tbc_events = 1 ; - next ; - } else { - $contain_confired_events = 1 ; - $tbc_game = 0 ; - } - - $xlsxrow2++ if $first_game ; - $first_game = 0 ; - $xlsxrow2++ ; - - &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," $customer_name $sport_name ANALYTICS",$heading_format) ; - $xlsxrow2++ ; - - &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," $db{teams}{$data_split[4]}{name} vs $db{teams}{$data_split[6]}{name}",$format1) ; - $xlsxrow2++ ; - - if ($data_split[0]) { - &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," " . substr($data_split[0],11,5),$format1) ; - } else { - &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," " . substr($db{$tables}{$a_id}{start_date_time},11,5),$format1) ; - } - - if ($db{$tables}{$a_id}{event_system_id_multiple}) { - $db{$tables}{$a_id}{event_system_id_multiple} =~ s/f-//g ; - my $systems = join(";", map { "$db{event_systems}{$_}{name} ($db{event_systems}{$_}{description})" } split(/\;/,$db{$tables}{$a_id}{event_system_id_multiple})) ; - $systems =~ s/ ()//g ; - - foreach (split(/\;/,$systems)) { - next unless $_ ; - $xlsxrow2++ ; - &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," $_",$format115) ; - } - } - - if ($individual_games_analytics[$row_nr]) { - - my @data_split_2 = split(/\;/,$individual_games_analytics[$row_nr]) ; - - if ($data_split_2[0] eq '1' && $data_split_2[1]) { - $xlsxrow2++ ; - &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2," " . $data_split_2[1],$format1) ; - } - if ($data_split_2[0] eq '1' && $data_split_2[2]) { - $xlsxrow2++ ; - &xlsxcreator_write_url($ws2,$xlsxrow2,$xlsxcol2,$data_split_2[2],"$data_split_2[2]") ; - } - - } - - } - $xlsxrow2++ unless $tbc_game ; - } - } - - my $abcbc = 0 ; - - $xlsxrow2++ if $contain_tbc_events && !$contain_confired_events ; - - foreach my $client_id (sort { $a <=> $b } keys %{$tbc_games{$date}}) { - foreach my $sport_name (sort { $a <=> $b } keys %{$tbc_games{$date}{$client_id}}) { - $xlsxrow2++ ; - &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"$db{customers}{$client_id}{name} $sport_name ANALYTICS",$format116) ; - $xlsxrow2++ ; - &xlsxcreator_write_xlsx($ws2,$xlsxrow2,$xlsxcol2,"Other $tbc_games{$date}{$client_id}{$sport_name} games still to be confirmed",$format113) ; - $abcbc = 1 ; - } - } - - $xlsxrow2++ if $abcbc ; - $xlsxrow2++ ; - } - - $worksheet{$ws2}->set_column(0,0,75) ; - $worksheet{$ws}->set_column(0,0,10) ; - $worksheet{$ws}->set_column(1,5,30) ; - $worksheet{$ws}->set_column(6,8,20) ; - - &report_xlsx_export_footer('L',15,'analytics_events') ; - - if ($usertype eq 'support') { - $fnsortcol = 1 ; # start date + # if ($usertype eq 'support') { + $fnsortcol = 0 ; # start date $fnsortorder = 'asc' ; - } + # } # &common_min_extra_crumb("search-$lcpage\s","Search Screen") if $glod_user_level > 3 ; &common_min_extra_crumb("filter-$lcpage\s","Search Screen") if $glod_user_level > 3 ; - # 12~yBf-w0xwLJcY7rY49dFy6Fw0tohiEHDUOw.png:Screenshot_2025-10-24_082334.png:Screenshot_2025-10-24_082804.png:32482_F.jpg|134~File_-_2025-10-08T074305.322.jpg:File_-_2025-10-09T080750.400.jpg:File_-_2025-10-10T091621.052.jpg:30729_F.jpg|309~Screenshot_2025-10-24_083010.png::Screenshot_2025-10-24_083250.png:31023vF.jpg - # 11685 - # |309~;;;08:02:50 - - - - - # 12~2025-10-08 07:59:14;2025-10-09 08:22:14;2025-10-10 09:35:18;2025-10-11 08:49:36|309~2025-10-08 08:15:26;;2025-10-10 08:56:42;2025-10-11 08:41:10|134~2025-10-08 07:43:03;2025-10-09 08:07:59;2025-10-10 09:14:17;2025-10-11 08:33:47 - # 161 - # 2025-10-24 09:29:09 - - } #------------------------------------------------------------------------------- sub thead { @@ -1671,69 +1420,81 @@ sub page_opts { our $savjqy = 1 ; our $max_cams = 10 ; - &common_min_add_box_icon ; + # &common_min_add_box_icon ; our %casuals = (); } #------------------------------------------------------------------------------- sub report_ifields { - + + if ($i{customer_name} && $i{customer_name} ne 'all') { + push @report_sql, "(client_id='$i{customer_name}')" ; + &db_min_ro('customers','id,name',"`id`='$i{customer_name}'",'','') ; + push @report_results, "customer = `$db{customers}{$i{customer_name}}{name}`" ; + } + + if ($i{sport_type_ids} && $i{sport_type_ids} ne 'all') { + &db_min_ro('sport_types',"id,name","id='$i{sport_type_ids}'",'','') ; + push @report_sql, "(sport_type_id='$i{sport_type_ids}')" ; + push @report_results, "sport_type = `$db{sport_types}{$i{sport_type_ids}}{name}`" ; + } + if ($i{start_date_from} && $i{start_date_to}) { - push @report_sql, " (('$i{start_date_from}' <= start_date_time AND start_date_time <= '$i{start_date_to}') OR ('$i{start_date_from}' <= end_date_time AND end_date_time <= '$i{start_date_to}' AND end_date_time IS NOT NULL)) " ; + # push @report_sql, " (('$i{start_date_from}' <= start_date_time AND start_date_time <= '$i{start_date_to}') OR ('$i{start_date_from}' <= end_date_time AND end_date_time <= '$i{start_date_to}' AND end_date_time IS NOT NULL)) " ; our @months = ("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") ; my $start_date_from = &common_min_date_as_string($i{start_date_from}) ; my $start_date_to = &common_min_date_as_string($i{start_date_to}) ; push @report_results, " (START DATE BETWEEN '$start_date_from' AND '$start_date_to') OR (END DATE BETWEEN '$start_date_from' AND '$start_date_to')" ; } - if ($i{country}) { - push @report_sql, "(q.country_id = '$i{country}')" ; - push @report_results, "country_id = `$i{country}`" ; - } + # if ($i{country}) { + # push @report_sql, "(q.country_id = '$i{country}')" ; + # push @report_results, "country_id = `$i{country}`" ; + # } - if ($i{customer_name} && $i{customer_name} ne 'all') { - push @report_sql, "(q.client_id = '$i{customer_name}')" ; - &db_min_ro('customers','id,name',"`id`='$i{customer_name}'",'','') ; - push @report_results, "customer = `$db{customers}{$i{customer_name}}{name}`" ; - } + # if ($i{customer_name} && $i{customer_name} ne 'all') { + # push @report_sql, "(q.client_id = '$i{customer_name}')" ; + # &db_min_ro('customers','id,name',"`id`='$i{customer_name}'",'','') ; + # push @report_results, "customer = `$db{customers}{$i{customer_name}}{name}`" ; + # } - if ($i{accepted} || $i{options} eq 'accepted') { - push @report_sql, "(q.event_accepted='1' AND q.event_completed<>'1')" ; - push @report_results, "event_accepted = `Yes`" ; - } + # if ($i{accepted} || $i{options} eq 'accepted') { + # push @report_sql, "(q.event_accepted='1' AND q.event_completed<>'1')" ; + # push @report_results, "event_accepted = `Yes`" ; + # } - if ($i{options} eq 'accepted') { - push @report_sql, "(q.event_accepted='1')" ; - push @report_results, "Event is Accepted" ; - } elsif ($i{options} eq 'completed') { - push @report_sql, "(q.event_completed='1')" ; - push @report_results, "Event is Completing" ; - } elsif ($i{options} eq 'pending') { - push @report_sql, "(q.event_pending='1')" ; - push @report_results, "Event is Pending" ; - } elsif ($i{options} eq 'cancelled') { - push @report_sql, "(q.event_cancelled='1' OR (q.event_expiry IS NOT NULL AND q.event_expiry<'$now_year-$now_mm-$now_dd' AND q.event_accepted<>'1'))" ; - push @report_results, "Event is Cancelled" ; - } elsif ($i{options} eq 'rejected') { - push @report_sql, "(q.event_rejected='1')" ; - push @report_results, "Event is Rejecting" ; - } + # if ($i{options} eq 'accepted') { + # push @report_sql, "(q.event_accepted='1')" ; + # push @report_results, "Event is Accepted" ; + # } elsif ($i{options} eq 'completed') { + # push @report_sql, "(q.event_completed='1')" ; + # push @report_results, "Event is Completing" ; + # } elsif ($i{options} eq 'pending') { + # push @report_sql, "(q.event_pending='1')" ; + # push @report_results, "Event is Pending" ; + # } elsif ($i{options} eq 'cancelled') { + # push @report_sql, "(q.event_cancelled='1' OR (q.event_expiry IS NOT NULL AND q.event_expiry<'$now_year-$now_mm-$now_dd' AND q.event_accepted<>'1'))" ; + # push @report_results, "Event is Cancelled" ; + # } elsif ($i{options} eq 'rejected') { + # push @report_sql, "(q.event_rejected='1')" ; + # push @report_results, "Event is Rejecting" ; + # } - $preferred_title{region_id} = "Region" ; - $preferred_title{city_id} = "City" ; - $preferred_title{organisation_ids} = "Venue" ; - $preferred_title{sport_type_ids} = "Sport Type" ; + # $preferred_title{region_id} = "Region" ; + # $preferred_title{city_id} = "City" ; + # $preferred_title{organisation_ids} = "Venue" ; + # $preferred_title{sport_type_ids} = "Sport Type" ; - if ($i{sport_type_ids} && $i{sport_type_ids} ne 'all') { - &db_min_ro('sport_types',"id,name","id='$i{sport_type_ids}'",'','') ; - push @report_sql, "FIND_IN_SET($i{sport_type_ids},REPLACE(q.sport_type_ids,';',','))" ; - push @report_results, "sport_types INCLUDE `$db{sport_types}{$i{sport_type_ids}}{name}`" ; - } + # if ($i{sport_type_ids} && $i{sport_type_ids} ne 'all') { + # &db_min_ro('sport_types',"id,name","id='$i{sport_type_ids}'",'','') ; + # push @report_sql, "FIND_IN_SET($i{sport_type_ids},REPLACE(q.sport_type_ids,';',','))" ; + # push @report_results, "sport_types INCLUDE `$db{sport_types}{$i{sport_type_ids}}{name}`" ; + # } - if ($usertype eq 'analytics_client') { - push @report_sql, "(q.client_id='$userid')" ; - } + # if ($usertype eq 'analytics_client') { + # push @report_sql, "(q.client_id='$userid')" ; + # } $report_results_msg = uc join(', ', @report_results) ; diff --git a/scripts/audit_trail.pl b/scripts/audit_trail.pl new file mode 100644 index 0000000..e489a85 --- /dev/null +++ b/scripts/audit_trail.pl @@ -0,0 +1,618 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; +# unless ($username eq 'handre') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use CGI::Carp qw(fatalsToBrowser); +use CGI; +use Crypt::PasswdMD5; +use Date::Calc qw(:all); +use Excel::Writer::XLSX ; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $debug = 1 ; + +our $event_id = 0 ; +our $changed_by = 0 ; +our $open_new_tab = qq~target="_blank"~ ; + +if ($action eq 'view') { + + $event_id = $ARGV[1] ; + $changed_by = $ARGV[2] ; + +} + +#-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- + +&page_opts ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +print "Content-type: text/html\n\n"; + +if ($iaction eq 'view') { + &list_screen; + &screen2 ; +} elsif ($iaction eq 'report') { + &common_min_load_params ; + &report_ifields; + &list_screen; + &screen3 ; +} + +&common_min_action; + +exit; + +#------------------------------------------------------------------------------------------ + +sub validate { + + # &users_validate; + +} #------------------------------------------------------------------------------------------ + +sub insert { + + # &users_insert ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + # &users_update ; + +} #------------------------------------------------------------------------------------------ + +sub process_multi_select { + + # &users_process_multi_select ; + +} #------------------------------------------------------------------------------------------ + +sub report_screen { + + # &filter_screen if $ENV{QUERY_STRING} eq 'filter' ; + + our $lcol = 2 ; + our $fcol = 5 ; + + # my ($set_year,$set_month,$set_day) = Add_Delta_Days($now_year,$now_mm,$now_dd,-42) ; # 6 weeks back + + # $set_month = sprintf("%02s", $set_month) ; + # $set_day = sprintf("%02s", $set_day) ; + + # my $set_ccyy_dd_mm = $set_year . '-' . $set_month . '-' . $set_day ; + + + $print_box_content_rows .= &common_min_forms_start('report') ; + + $allow_deselect{event} = 1 ; + $allow_deselect{changed_by} = 1 ; + + $preferred_title{event_from} = 'Event Date From' ; + $print_box_content_rows .= &common_min_form_datetimepicker('event_from',"$now_year-$now_mm-$now_dd 00:00:00",720) ; + $preferred_title{event_to} = 'Event Date To' ; + $print_box_content_rows .= &common_min_form_datetimepicker('event_to',"$now_year-$now_mm-$now_dd 23:59:59",0) ; + + &common_min_select_opts('changed_by','users','name','','','',"`user_type` <> 'casual_a' AND `user_type` <> 'casual_calibrator' AND `user_type` <> 'installation_partner' AND `username` NOT LIKE 'handre%' AND `username` NOT LIKE 'rory%'",'','','','name') ; + + &common_min_select_opts('event','event_quotes','ref','','','id',"",'','','','ref') ; + + # $preferred_title{region_id} = "Region" ; + + # $print_box_content_rows .= &common_min_form_select('system_id','') ; + $print_box_content_rows .= &common_min_form_select('event','') ; + $print_box_content_rows .= &common_min_form_select('changed_by','') ; + + $print_box_content_rows .= &common_min_forms_end('','','report') ; + + local $all_select_ids_string = join(",",@all_select_ids) ; + $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true });~ ; + + &common_min_search_screen ; + +} #------------------------------------------------------------------------------- + +sub report_ifields { + +} #------------------------------------------------------------------------------- + +sub list_screen { + + # my $file_path = "$cgipath/data/logs/events/changes.dat" ; + + # open(my $fh, '<', $file_path) or die "Could not open file '$file_path' $!"; + + my $prev_line = qq~~ ; my $line_cnt = 0 ; my %audit_data = () ; my %leng = () ; + + my $event_from_val = $i{event_from} ; + my $event_to_val = $i{event_to} ; + + $event_from_val =~ s/[:\- ]//g; + $event_to_val =~ s/[:\- ]//g; + + &db_min_ro('event_quotes_changes','id,changes','','','') ; + + foreach my $id (sort {$b <=> $a} keys %{$db{event_quotes_changes}}) { + + my $line = $db{event_quotes_changes}{$id}{changes} ; + + # while (my $line = <$fh>) { + + $event_quotes_categories = 1 if $line =~ /category_id_1=/ || $line =~ /category_id_2=/ ; + $countries = 1 if $line =~ /country_id=/ ; + $users = 1 if $line =~ /operator_ids=/ ; + $sport_types = 1 if $line =~ /sport_type_ids=/ ; + $customers = 1 if $line =~ /quote_to=/ ; + $organisations = 1 if $line =~ /organisation_ids=/ ; + $cities = 1 if $line =~ /city_id=/ ; + $event_types = 1 if $line =~ /type=/ ; + $event_type_details = 1 if $line =~ /type_details_id=/ ; + $event_cost_items = 1 if $line =~ /description_workings_event=/ || $line =~ /description_costing_event=/ || $line =~ /item_costing_event=/ ; + $clubs = 1 if $line =~ /club_ids=/ ; + $event_systems = 1 if $line =~ /event_system_id_multiple=/ ; + $poc_exists = 1 if $line =~ /poc_id=/ && $line !~ /poc_id='0'/ && $line !~ /poc_id=''/ ; + $recipient_exists = 1 if $line =~ /recipient_id=/ && $line !~ /recipient_id='0'/ && $line !~ /recipient_id=''/ ; + $region_id_exists = 1 if $line =~ /region_id=/ && $line !~ /region_id='0'/ && $line !~ /region_id=''/ ; + + my @line_split = split(/\|/,$line) ; + $line_split[0] = substr($line_split[0],4) ; + + # print "\n $line_split[3]" ; + + next if $i{event_from} && $event_from_val > $line_split[0] ; + next if $i{event_to} && $event_to_val < $line_split[0] ; + + next if $line_split[2] =~ /camera_system_id/ ; + + my @user_s = split(/\=/,$line_split[3]) ; + + my @event_id_s = split(/\=/,$line_split[2]) ; + + my $user_changed = $user_s[1] ; + $user_changed =~ s/\'//g ; + my $event_id = $event_id_s[1] ; + $event_id =~ s/\'//g ; + + next if $i{event} && $i{event} ne $event_id ; + next if $i{changed_by} && $i{changed_by} ne $user_changed ; + + my $nr_of_splits = scalar @line_split ; + + my $line_of_changes = qq~~ ; + + if ($nr_of_splits == 6) { + $line_of_changes = $line_split[-1] ; + } elsif ($line_split[4] =~/changed_from/ || $line_split[4] =~ /action='Edit'/ || $line_split[4] =~ /action='Add'/) { + for (5 .. $nr_of_splits-1) { + $line_of_changes .= qq~$line_split[$_]|~ ; + } + chop $line_of_changes if $line_of_changes ; + } else { + for (4 .. $nr_of_splits-1) { + $line_of_changes .= qq~$line_split[$_]|~ ; + } + chop $line_of_changes if $line_of_changes ; + } + + $audit_data{data}{$event_id}{$line_split[1]} = $line_of_changes ; + $audit_data{user}{$event_id}{$line_split[1]} = $user_changed; + + if ($line_split[4] eq 'changed_from') { + $audit_data{changed_from}{$event_id}{$line_split[1]} = 1 ; + } + } + + &db_open_ro; + $db_ignore_open_close=1; + &load_vars ; + $db_ignore_open_close=0 ; + &db_close_conn ; + + close($fh) ; + + foreach my $event_id (sort {$b <=> $a} keys %{$audit_data{data}}) { + # next if $db{event_quotes}{$event_id}{id} ; + foreach my $date_updated (sort {$b cmp $a} keys %{$audit_data{data}{$event_id}}) { + + foreach my $changed_field (split(/,/,$audit_data{data}{$event_id}{$date_updated})) { + + chomp $changed_field ; + + my @field_split = split(/\=/,$changed_field) ; + + # next if ((!$prev_field_val{$field_split[0]} || $prev_field_val{$field_split[0]} eq "''" || $prev_field_val{$field_split[0]} eq "'0'") && ($field_split[1] eq "''" || $field_split[1] eq "'0'")) || $field_split[0] eq 'last_update' || $field_split[0] eq 'id' || $field_split[0] eq 'quote_nr' ; + next if $field_split[1] eq "''" || ($field_split[1] eq "'0'" && $field_split[0] ne 'custom_set') || $field_split[0] eq 'last_update' || $field_split[0] eq 'id' || $field_split[0] eq 'quote_nr' ; # $field_split[0] eq 'sub_total' || $field_split[0] eq 'grand_total' || $field_split[0] eq 'vat_total' || $field_split[0] eq 'total_amount_workings_event' || $field_split[0] eq 'total_grand_amount_workings_event' || $field_split[0] eq 'total_vat_amount_workings_event' || $field_split[0] eq 'total_grand_amount_workings_event' ; + + if ($changed_field =~ /=/ && ($seen_data_field{$event_id}{$field_split[0]} || $audit_data{changed_from}{$event_id}{$date_updated})) { + + $field_split[1] =~ s/\'//g ; + + # print "\n 1 field_split : $field_split[0] = $field_split[1]" if $field_split[0] eq 'ref' ; + + if ($field_split[0] eq 'custom_set') { + $field_split[1] = ($field_split[1] eq "1") ? "Yes" : "No" ; + } elsif ($field_split[0] eq 'club_ids') { + $field_split[1] = join ";", map { "$db{clubs}{$_}{name}" } split ";" , $field_split[1] ; + } elsif ($field_split[0] eq 'event_system_id_multiple') { + $field_split[1] = join ";", map { "$db{event_systems}{$_}{name} [$db{event_systems}{$_}{description}]" } split ";" , $field_split[1] ; + $field_split[0] = 'event_systems' + } elsif ($field_split[0] eq 'operator_ids') { + while ($field_split[1] =~ /(\d+)/g) { + my $op_id = $1; + $field_split[1] =~ s/\d+/$db{users}{$op_id}{name}/g ; + last ; + } + } elsif ($field_split[0] eq 'sport_type_ids') { + while ($field_split[1] =~ /(\d+)/g) { + my $op_id = $1; + $field_split[1] =~ s/\d+/$db{sport_types}{$op_id}{name}/g ; + last ; + } + } elsif ($field_split[0] eq 'city_id') { + while ($field_split[1] =~ /(\d+)/g) { + my $op_id = $1; + $field_split[1] =~ s/\d+/$db{cities}{$op_id}{city}/g ; + last ; + } + } elsif ($field_split[0] eq 'organisation_ids') { + while ($field_split[1] =~ /(\d+)/g) { + my $op_id = $1; + $field_split[1] =~ s/\d+/$db{organisations}{$op_id}{name}/g ; + last ; + } + } elsif ($field_split[0] eq 'type_details_id') { + while ($field_split[1] =~ /(\d+)/g) { + my $op_id = $1; + $field_split[1] =~ s/\d+/$db{event_type_details}{$op_id}{name}/g ; + last ; + } + } elsif ($field_split[0] eq 'description_workings_event' || $field_split[0] eq 'description_costing_event') { + $field_split[1] = join ";", map { "$db{event_cost_items}{$_}{name}" } split ";" , $field_split[1] ; + } elsif ($field_split[0] eq 'daily_operator_ids') { + my $new_string = qq~~ ; my $system_cnt = 0 ; + foreach my $system_ops (split("|",$field_split[1])) { + $system_cnt++ ; + next if $system_ops !~ /(\d+)/g ; + my $sys_string = qq~~ ; my $day_cnt = 0 ; + $new_string .= qq~System $system_cnt : [~ ; + foreach my $system_op_id (split(";",$system_ops)) { + $day_cnt++ ; + $sys_string .= qq~Day $day_cnt : $db{users}{$system_op_id}{name};~ if $system_op_id ; ; + } + chop $sys_string if $sys_string; + $sys_string .= qq~];~ ; + } + chop $sys_string if $sys_string ; + $field_split[1] = qq~$sys_string~ ; + } elsif ($field_split[0] eq 'qty') { + $field_split[0] = "Actual Days" ; + } elsif ($field_split[0] eq 'type') { + $field_split[1] = $db{event_types}{$field_split[1]}{name} ; + } elsif ($field_split[0] eq 'operator_workings_event') { + $field_split[1] = join ";", map { "$db{users}{$_}{name}" } split ";" , $field_split[1] ; + } elsif ($field_split[0] eq 'days_active') { + my $days_active_str = qq~~ ; my $day_cnt = 0 ; + foreach my $days_active (split(";",$field_split[1])) { + $day_cnt++ ; + $days_active_str .= qq~Day $day_cnt;~ if $days_active ; + } + chop $days_active_str if $days_active_str ; + $field_split[1] = $days_active_str ; + } elsif ($field_split[0] eq 'event_length') { + $full_half_day{1} = "Full Day" ; + $full_half_day{2} = "Half Day" ; + my $day_cnt = 1 ; + $field_split[1] = join ";", map { "$full_half_day{$_}" } split ";" , $field_split[1] ; + } elsif ($field_split[0] eq 'quote_to') { + $field_split[1] = $db{customers}{$field_split[1]}{name} ; + } elsif ($field_split[0] eq 'country_id') { + $field_split[1] = $db{countries}{$field_split[1]}{name} ; + } elsif ($field_split[0] eq 'quote_completed' || $field_split[0] eq 'quote_accepted' || $field_split[0] eq 'quote_pending' || $field_split[0] eq 'quote_cancelled' || $field_split[0] eq 'quote_rejected') { + $field_split[1] =~ s/1/Yes/g ; + } elsif ($field_split[0] eq 'vat_workings_event' || $field_split[0] eq 'excl_workings_event' || $field_split[0] eq 'vat_costing_event' || $field_split[0] eq 'excl_costing_event') { + $field_split[1] =~ s/1/Yes/g ; + $field_split[1] =~ s/0/No/g ; + } elsif ($field_split[0] eq 'category_id_1' || $field_split[0] eq 'category_id_2') { + $field_split[1] = $db{event_quotes_categories}{$field_split[1]}{category} ; + } elsif ($field_split[0] eq 'ref') { + $field_split[0] = "Event Name" ; + } elsif ($field_split[0] eq 'poc_id') { + $field_split[1] = "$db{event_quotes_poc}{$field_split[1]}{name} [$db{event_quotes_poc}{$field_split[1]}{contact_nr}]" ; + } elsif ($field_split[0] eq 'recipient_id') { + $field_split[1] = "$db{event_quotes_recipient}{$field_split[1]}{name} [$db{event_quotes_recipient}{$field_split[1]}{contact_nr}]"; + } elsif ($field_split[0] eq 'region_id') { + $field_split[1] = $db{regions}{$field_split[1]}{name}; + } elsif ($field_split[0] eq 'item_costing_event') { + $field_split[1] = join ";", map { "$db{event_cost_items}{$_}{name}" } split ";" , $field_split[1] ; + } else { + next if $field_split[1] !~ /\b\d+\b/ ; + } + + # '502;713;620;621;614;612 + $field_split[0] =~ s/amount_usd_workings_event/Amount Expenses Tab/g ; + $field_split[0] =~ s/amount_workings_event/Tot Amount Expenses Tab/g ; + # $field_split[0] =~ s/_costing_event/Costings Tab/g ; + $field_split[0] =~ s/_workings_event/_expenses_tab/g ; + $field_split[0] =~ s/_id//g ; + $field_split[0] = join ' ', map { ucfirst $_ } split /_/ , $field_split[0] ; + + $audit_data{refined_data}{$event_id}{$date_updated} .= qq~'
    $field_split[0]='$field_split[1]~ ; + + } elsif ((!$field_split[1] && $changed_field !~ /=/) && $seen_data_field{$event_id}{$prev_field}) { + $field_split[0] =~ s/\'//g ; + if ($prev_field eq 'Operators') { + $audit_data{refined_data}{$event_id}{$date_updated} .= qq~;$db{users}{$field_split[0]}{name}~ ; + } elsif ($prev_field eq 'Sport Types') { + $audit_data{refined_data}{$event_id}{$date_updated} .= qq~;$db{sport_types}{$field_split[0]}{name}~ ; + } elsif ($prev_field eq 'City') { + $audit_data{refined_data}{$event_id}{$date_updated} .= qq~;$db{cities}{$field_split[0]}{city}~ ; + } elsif ($prev_field eq 'Organisations') { + $audit_data{refined_data}{$event_id}{$date_updated} .= qq~;$db{organisations}{$field_split[0]}{name}~ ; + } elsif ($prev_field eq 'Type Details') { + $audit_data{refined_data}{$event_id}{$date_updated} .= qq~;$db{event_type_details}{$field_split[0]}{name}~ ; + } else { + $audit_data{refined_data}{$event_id}{$date_updated} .= qq~,$field_split[0]~ ; + } + } + $seen_data_field{$event_id}{$field_split[0]} = 1 if $changed_field =~ /=/ ; + $prev_field = $field_split[0] if $changed_field =~ /=/ ; + $prev_field_val{$field_split[0]} = $field_split[1] if $changed_field =~ /=/ ; + } + } + } + + our $xlsx_title_heading = "Audit Trail Report" ; + our $xlsxdir = "audit_trail" ; + our $xlsxreportname = "Audit_Trail_Report" ; + + our @sql_col_display = ("nr","event","date_changed","changed_by","changed_from") ; + + &report_xlsx_export_header("$xlsxreportname",$xlsxdir,'',$xlsx_title_heading) ; + $xlsxrow-- ; + + my $formatting = $format84 ; + + foreach my $event_id (sort {$b <=> $a} keys %{$audit_data{refined_data}}) { + + + my $button = &common_min_get_event_quote_button($event_id) ; + + foreach my $date_updated (sort {$b cmp $a} keys %{$audit_data{refined_data}{$event_id}}) { + + # chop $audit_data{refined_data}{$event_id}{$date_updated} if $audit_data{refined_data}{$event_id}{$date_updated} ; + $audit_data{refined_data}{$event_id}{$date_updated} = substr($audit_data{refined_data}{$event_id}{$date_updated},5) . "'" ; + + next unless $audit_data{refined_data}{$event_id}{$date_updated} ; + + my $blanks_excluded = qq~~ ; + + foreach (split("
    ",$audit_data{refined_data}{$event_id}{$date_updated})) { + my @split = split("=",$_) ; + $blanks_excluded .= qq~$_
    ~ if $split[1] =~ /\b\d+\b/ || $split[1] =~ /[a-zA-Z]/ ; + } + $blanks_excluded = substr($blanks_excluded,0,-4) ; + + next unless $blanks_excluded ; + + $print_tbody .= qq~ + + $button + $db{event_quotes}{$event_id}{ref} + $date_updated + $db{users}{$audit_data{user}{$event_id}{$date_updated}}{name} + $blanks_excluded + + ~ ; + + &xlsxcreator_write_xlsx($ws,$xlsxrow,0,$event_id,$formatting) ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,1,$db{event_quotes}{$event_id}{ref},$formatting) ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,2,$date_updated,$formatting) ; + &xlsxcreator_write_xlsx($ws,$xlsxrow,3,$db{users}{$audit_data{user}{$event_id}{$date_updated}}{name},$formatting) ; + + foreach (split("
    ",$blanks_excluded)) { + &xlsxcreator_write_xlsx($ws,$xlsxrow,4,$_,$formatting) ; + $xlsxrow++ ; + } + # $xlsxrow++ ; + } + # + } + + &report_xlsx_export_footer('E',15,$xlsxdir) ; + +} #------------------------------------------------------------------------------------------ + +sub load_vars { + + &db_min_ro('event_quotes_categories','*','','','') if $event_quotes_categories ; + &db_min_ro('countries','id,name','','','') if $countries ; + &db_min_ro('users','id,name','','','') if $users ; + &db_min_ro('sport_types','id,name','','','') if $sport_types ; + &db_min_ro('customers','id,name','','','') if $customers ; + &db_min_ro('organisations','id,name','','','') if $organisations ; + &db_min_ro('cities','id,city','','','') if $cities ; + &db_min_ro('event_types','id,name','','','') if $event_types ; + &db_min_ro('event_type_details','id,name','','','') if $event_type_details ; + &db_min_ro('event_cost_items','id,name','','','') if $event_cost_items ; + &db_min_ro('clubs','id,name','','','') if $clubs ; + &db_min_ro('event_systems','id,name,description','','','') if $event_systems ; + &db_min_ro('event_quotes_poc','*','','','') if $poc_exists ; + &db_min_ro('event_quotes_recipient','*','','','') if $recipient_exists ; + &db_min_ro('regions','id,name','','','') if $region_id_exists ; + &db_min_ro('event_quotes','id,ref,quote_completed,quote_accepted,quote_rejected,quote_cancelled,quote_created,quote_pending,event_system_id_multiple,fixed_system_overall_status',"",'','') ; + # &db_min_ro('event_quotes','id',"ref LIKE '% test %' OR ref LIKE 'test %' OR ref LIKE '% test' OR ref LIKE '%testing%'",'','') ; + +} #------------------------------------------------------------------------------------------ + +sub sort_fields { + + &users_sort_fields ; + +} #------------------------------------------------------------------------------- + +sub add_db_fields { + + # &users_add_db_fields ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + # &users_edit_db_fields ; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + + # called from common_add_screen + # &users_add_screen ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + # &users_edit_screen ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + $print_thead = qq~NrEventDate ChangedChanged ByChanged From~; + +} #------------------------------------------------------------------------------- + +sub page_opts { + +our $glyphicon = 'list' ; +our $lcpage = 'audit-trail' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; +# our $table = 'users' ; +# our $user_type = 'casual' ; + +$page_title = "Audit Trail" ; + +# &common_min_add_extras ; + +} #------------------------------------------------------------------------------- + +sub screen2 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +my $page = "event-quotes" ; if ($s{no}) { $page = $lcpage ; } + +&common_min_table('id',$page,'list','',1) ; + +# &common_min_alert_type ; + +# &common_min_footer('id','') ; + +&common_min_dialog ; + +print < + + + $print_top + +
    +
    + $events_content +
    + +
    + +
    +
    +
    +
    +

    $boxtitle Changes

    +
    +
    + $print_box_content_rows +
    +
    +
    +
    +
    + +
    + +
    + + + + + +$dialog{'common'}{'js'} + + + + + + +$print_footer_jscript +$print_footer_forms + + +ENDOFTEXT +# + +exit ; + +} #------------------------------------------------------------------------------------------ + +sub screen3 { + +&thead; + +if ($isaved) { $alert = &common_min_alert('success',"$ucpage $isaved!",'ok') ; } else { &common_min_alert_type ; } + +my $page = "event-quotes" ; if ($s{no}) { $page = $lcpage ; } + +&common_min_table('id',$page,'list') ; + +# &common_min_extra_crumb("manage-$lcpage\s","Manage $ucfirstpage\s") ; + +require _blank ; + +exit ; + +} #------------------------------------------------------------------------------------------ + +use common ; +use today ; +use report ; +use xlsxcreator ; +# use users ; + +1; \ No newline at end of file diff --git a/scripts/calendar_test.pl b/scripts/calendar_test.pl index d93bc3f..1417c3a 100644 --- a/scripts/calendar_test.pl +++ b/scripts/calendar_test.pl @@ -32,7 +32,7 @@ $fullcalendar_events = qq(\$(document).ready(function() { editable: false, eventLimit: true, // allow "more" link when too many events events: { - url: '$useropts{'scripts'}/get/get_db_cal_events_test2.pl', + url: '$useropts{'scripts'}/get/get_db_cal_events_test.pl', error: function() { \$('#script-warning').show(); } diff --git a/scripts/cameras.pl b/scripts/cameras.pl index 520460b..e77f4b4 100644 --- a/scripts/cameras.pl +++ b/scripts/cameras.pl @@ -672,7 +672,7 @@ $opts{linked_vpu_id} = qq~~ ; $sel = '' ; if ($db{$table}{$id}{camera_system_id} == 1 or $db{$table}{$id}{camera_system_id} == 2 or $db{$table}{$id}{camera_system_id} == 14) { - my $dbtable = "itv_admin_db.$table" ; + my $dbtable = "aisa_admin_db.$table" ; &db_min_ro($dbtable,'id,camera_nr,serial_nr,linked_vpu_id,quote_linked_vpu,camera_system_id',"(camera_nr LIKE 'vpu%' OR camera_nr LIKE 'S1%' OR camera_nr LIKE 'S2%') AND (quote_linked_vpu IS NULL OR quote_linked_vpu = '' OR quote_linked_vpu = '$db{cameras}{$id}{serial_nr}') AND (event_linked_vpu IS NULL OR event_linked_vpu = '')",'','') ; local %is_linked = () ; @@ -948,12 +948,12 @@ sub build_boxes_left { %done_col_val = () ; - &common_min_select_opts('event_linked_vpu','itv_admin_db.cameras','camera_nr',$db{$table}{$id}{event_linked_vpu},'','',"camera_nr LIKE 'VPU%' AND (quote_linked_vpu = '' OR quote_linked_vpu IS NULL)",'serial_nr') unless $cam_nr_prefix eq 'VP' ; + &common_min_select_opts('event_linked_vpu','aisa_admin_db.cameras','camera_nr',$db{$table}{$id}{event_linked_vpu},'','',"camera_nr LIKE 'VPU%' AND (quote_linked_vpu = '' OR quote_linked_vpu IS NULL)",'serial_nr') unless $cam_nr_prefix eq 'VP' ; $print_box_content_rows .= &common_min_box_top('star','Events',$box_right_bg); $preferred_title{event_linked_vpu} = 'Event System' ; $print_box_content_rows .= qq~
    ~ ; $print_box_content_rows .= &common_min_form_select('event_linked_vpu',$db{$table}{$id}{event_linked_vpu},1) ; $fcol=5 ; - &common_min_select_opts('event_system_id','itv_admin_db.event_systems','description',$db{$table}{$id}{event_system_id},'') ; + &common_min_select_opts('event_system_id','aisa_admin_db.event_systems','description',$db{$table}{$id}{event_system_id},'') ; $allow_deselect{event_system_id} = 1 ; $print_box_content_rows .= &common_min_form_select_col('event_system_id',$db{$table}{$id}{event_system_id}) ; $print_box_content_rows .= qq~
    ~ ; diff --git a/scripts/credits_bought.pl b/scripts/credits_bought.pl index 42ac275..db0f8d6 100644 --- a/scripts/credits_bought.pl +++ b/scripts/credits_bought.pl @@ -3,7 +3,7 @@ BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } require cfg ; - +# unless ($username eq 'handre') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } #--------------------------------------------------------------------------------------------------------------------------------------------------------------------- use CGI::Carp qw(fatalsToBrowser); @@ -19,360 +19,366 @@ $action = $ARGV[0] ; our ($q) = CGI -> new() ; our $iaction = $q -> param('iaction') || $action ; our $isaved = $q -> param('isaved') || '' ; - -our $debug = 1 ; +# our $debug = 1 ; # our $testing = 1 ; +our $double_box_layout = 1 ; + +# our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + #-------- page opts -------------------------------------------------------------------------------------------------------------------------------------------------- -&page_opts ; +&page_opts ; #--------------------------------------------------------------------------------------------------------------------------------------------------------------------- -print "Content-type: text/html\n\n"; - -our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab - -if ($username ne 'handre') { +# unless ($useropts{it}{$username}) { +unless ($glod_user_level >= 5) { print "Development in Progress!!!" ; exit ; } - -&db_open_ro ; - $db_ignore_open_close = 1 ; - &common_min_action; - $db_ignore_open_close = 0 ; -&db_close_conn ; +print "Content-type: text/html\n\n"; -exit; +if ($iaction eq 'update') { + &common_min_load_params ; + &validate ; + &update ; + &common_min_screen2 ; + exit ; +} + +&common_min_action ; + +exit ; #------------------------------------------------------------------------------------------ sub validate { - my $exists = '' ; + my $exists = '' ; + &db_min_ro($table,'*','','','') ; - $i{name} = &common_fix_str($i{name}) ; + foreach my $id (keys %{$db{$table}}) { + next if $i{id} && $i{id} eq $id ; + if ($db{$table}{$id}{credit_type} eq $i{credit_type} && $db{$table}{$id}{client_id} eq $i{client_id} && ($db{$table}{$id}{sport_type_id} eq 'all' || $db{$table}{$id}{sport_type_id} eq $i{sport_type_id} || $i{sport_type_id} eq 'all')) { + $exists = 1 ; + } + } - ## REMOVE LATER --------------------------------- + my $credits_out_of_range = (length $i{credits} > 10) ? 1 : 0 ; - $i{city} = $i{name} ; - - ## REMOVE LATER --------------------------------- - - &db_min_ro($table,'*',"name='$i{name}'",'name','') ; - - foreach my $id (keys %{$db{$table}}) { if ($db{$table}{$id}{name} eq $i{name}) { $exists = 1 ; } } - - if ($exists) { - $alert = &common_min_alert('warning',"CITY NAME ALREADY EXISTS!",'ok') ; + if ($credits_out_of_range) { + $i{id} = $i{orig_id} if $i{orig_id} ; + $alert = &common_min_alert('warning',"THE CREDITS NUMBER CONTAIN TOO MANY CHARACTERS!",'ok') ; %col_name = (); - &common_min_add_screen; + &common_min_error_screen; &common_min_screen1; - } - + exit ; + } + + if ($exists) { + $i{id} = $i{orig_id} if $i{orig_id} ; + $alert = &common_min_alert('warning',"CREDITS ALREADY EXIST FOR THIS CLIENT, SPORT AND CREDIT TYPE!",'ok') ; + %col_name = (); + &common_min_error_screen; + # $i{id} = $i{orig_id} if $i{orig_id} ; + &common_min_screen1; + exit ; + } + } #------------------------------------------------------------------------------------------ sub insert { &add_db_fields ; - - &set_default_vals ; - - $i{id} = &db_min_get_max($table,'id') ; - - $ignore{country_id} = 1 ; + + $i{id} = &db_min_get_max($table,'id') ; &db_min_insert($table) ; + + # exit ; } #------------------------------------------------------------------------------------------ sub update { - unless ($i{id}) { $error = qq(NO ID) ; return ; } + unless ($i{id}) { + $error = qq(NO ID) ; + return ; + } &edit_db_fields ; - &set_default_vals ; - - $ignore{country_id} = 1 ; + $ignore{id} = 1 ; &db_min_upd($table,"id='$i{id}'") ; } #------------------------------------------------------------------------------------------ -sub set_default_vals { +sub build_rates_fields { - &db_min_ro('regions','id,name',"id = $i{region_id}",'','') ; - $i{province} = $db{regions}{$i{region_id}}{name}; + my ($field_name,$row_cnt) = @_ ; + + # $ii{$field_name} = qq~$db{$table}{1}{$field_name}~ ; + $ii{$field_name} .= ';' if $ii{$field_name} ; + $ii{$field_name} .= qq~$i{"$field_name\_$row_cnt"}~ ; + $i{$field_name} = $ii{$field_name} ; } #------------------------------------------------------------------------------------------ sub list_screen { - &db_min_ro('regions','id,name,country_id',"",'','') ; + &db_min_ro('sport_types','*','','','') ; - &db_min_ro('countries','id,name',"",'','') ; + &db_min_ro('customers','id,name','','','') ; - &db_min_ro('event_quotes','id,city_id',"city_id <> 0",'','') ; - - foreach my $_id (keys %{$db{event_quotes}}) { - $type_id_used{$_} = 1 ; - my @city_ids = split(/\,/,$db{event_quotes}{$_id}{city_id}); - foreach my $_cid (@city_ids) { - $type_id_used{$_cid} = 1 ; - } - } - - &db_min_ro($table,'*','','','') ; - - foreach my $id (keys %{$db{$table}}) { + &db_min_ro($table,'*','','id','') ; + + my $excl = "" ; + + our @sql_col_display = ("id","client","sport","credit_type","credits","") ; + + my %credit_types = (1 => "Standard", 2 => "Premium", 3 => "Individual") ; + + my $row_cnt = 0 ; + + foreach my $id (sort { $db{customers}{$db{$table}{$a}{client_id}}{name} cmp $db{customers}{$db{$table}{$b}{client_id}}{name} || $db{sport_types}{$db{$table}{$a}{sport_type_id}}{name} cmp $db{sport_types}{$db{$table}{$b}{sport_type_id}}{name} || $db{$table}{$a}{credit_type} <=> $db{$table}{$b}{credit_type} } keys %{$db{$table}}) { - my $edit_butt = qq~ ~ ; - my $del_butt = qq~ ~ ; + $print_tbody .= qq~~ ; - if ($glod_user_level >= 3) { - $edit_butt = qq~ ~ ; - } + $row_cnt++ ; - if ($glod_user_level >= 3) { - $del_butt = qq~ ~ ; - } + foreach my $col (@sql_col_display) { - if ($type_id_used{$id}) { - $edit_butt = qq~ ~ ; - $del_butt = qq~ ~ ; + $val = $db{$table}{$id}{$col} ; + my $nowrap = "" ; + my $align = qq~ class="dt-center"~ ; + + if ($col eq "id") { + + my $row_val = sprintf("%09d",$row_cnt) ; + $val = qq~$row_val$id~ ; + $align = qq~ class="dt-left"~ ; + } elsif ($col eq "client") { + $val = $db{customers}{$db{$table}{$id}{client_id}}{name} ; + } elsif ($col eq "sport") { + $val = $db{sport_types}{$db{$table}{$id}{sport_type_id}}{name} ; + $val = "All" if $db{$table}{$id}{sport_type_id} eq 'all' ; + } elsif ($col eq "credit_type") { + $val = $credit_types{$db{$table}{$id}{credit_type}} ; + } elsif ($col eq "credits") { + $val = &common_commify($val); + } elsif ($col eq '') { + $align = qq~ class="dt-left"~ ; + my $edit_butt = '' ; + my $del_butt = '' ; + # if ($useropts{super}{$username}) { + # $edit_butt = qq~ ~ ; + # } + # if ($useropts{boss}{$username} or $useropts{super}{$username}) { + # $del_butt = qq~ ~ if not $seen_event_item_costing{$id}; + # $del_butt = qq~ ~ if $seen_event_item_costing{$id}; + # } + $edit_butt = qq~ ~ ; + $del_butt = qq~ ~ ; + + $val = qq~$edit_butt$del_butt~ ; + } + $print_tbody .= qq~$val~ ; } - - $print_tbody .= qq~ - $id - $db{$table}{$id}{name} - $db{$table}{$id}{city_short} - $db{$table}{$id}{lat} - $db{$table}{$id}{lng} - $db{regions}{$db{$table}{$id}{region_id}}{name} - $db{countries}{$db{regions}{$db{$table}{$id}{region_id}}{country_id}}{name} - - $edit_butt - $del_butt - - ~ ; + $print_tbody .= qq~~ ; } } #------------------------------------------------------------------------------------------ sub add_db_fields { - - &sort_fields; + # &sort_fields; &hidden_db_fields; - # $ignore{id} = 1 ; } #------------------------------------------------------------------------------------------ sub edit_db_fields { - - &sort_fields; + # &sort_fields; &hidden_db_fields; - $hidden{id} = 1 ; # 1 = bypass for db update } #------------------------------------------------------------------------------------------ sub hidden_db_fields { - $ignore{iaction} = 1 ; - $required{name} = 1 ; - # $required{province} = 1 ; - $required{region_id} = 1 ; - - # $ignore{country_id} = 1 ; + $ignore{selected_add_credit_types} = 1 ; + $ignore{iaction} = 1 ; + $ignore{orig_id} = 1 ; + &sort_fields ; + } #------------------------------------------------------------------------------------------ sub sort_fields { - %sort_field = () ; - - # $ignore{country_id} = '' ; - - - $sort_field{3} = 'name' ; $preferred_title{city_short} = "City Name" ; - $sort_field{4} = 'city_short' ; $preferred_title{city_short} = "City Acronym" ; - # $sort_field{3} = 'province' ; $preferred_title{province} = 'Region' ; - $sort_field{5} = 'lat' ; $preferred_title{lat} = 'Latitude' ; - $sort_field{6} = 'lng' ; $preferred_title{lng} = 'Longitude' ; - $sort_field{7} = 'region_id' ; - $sort_field{8} = 'country_id' ; - } #------------------------------------------------------------------------------- sub add_screen { - # called from common_add_screen + &sort_fields ; &select_opts ; - + + &build_boxes ; + } #------------------------------------------------------------------------------------------ sub edit_screen { - + &select_opts ; + &build_boxes ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes { + + our ($lcol,$fcol) = &common_min_columns() ; + + $add_form_fields = '' ; + + $print_box_content_rows .= &common_min_forms_start($table,$skip) ; + + $print_box_content_rows .= qq~~ if $i{id} ; + + $add_form_fields .= qq~ +
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + ~ ; + # align='center' + $add_form_fields .= qq~
    ~ ; + $fcol = 2 ; + $add_form_fields .= &common_min_form_select_col("client_id") ; + + $fcol = 1 ; + $add_form_fields .= &common_min_form_select_col("sport_type_id") ; + $fcol = 1 ; + $lcol = 3 ; + + # $i{credit_type} = $db{$table}{$i{id}}{credit_type} if $db{$table}{$i{id}}{credit_type} ; + + $add_form_fields .= &common_min_form_select_col("credit_type") ; + $fcol = 1 ; + # $add_form_fields .= qq~
    ~ ; + + # $i{credits} = $db{$table}{$i{id}}{credits} if $db{$table}{$i{id}}{credits} ; + + $required{credits} = 'data-validation="length number" data-validation-length="0-10"' ; + + $add_form_fields .= &common_min_form_input_col("credits",$i{credits}) ; + $add_form_fields .= qq~
    ~ ; + + my $save_action = ($i{id}) ? 'update' : 'save' ; + + my $custom_class = ($invoice_exists && !$useropts{super}{$username} && !$useropts{it}{$username}) ? "custom" : "primary" ; + our $custom_back_button = ($save_action eq 'update') ? qq~  ~ : qq~~ ; + our $addbkb = ($save_action eq 'update') ? 1 : 0 ; + $add_form_fields .= &common_min_forms_end($iid,$table,$save_action,$skip) ; + + my $add_edit = ucfirst $iaction ; + + my $orig_id = $i{id} ; + + $orig_id = "New" unless $orig_id; + + if ($save_action eq 'update') { + $add_form_fields .= qq~~ ; + $i{id} = &db_min_get_max($table,'id') ; + } + + $print_box_content_rows .= &common_min_box_top(''," $add_edit : $orig_id",$box_right_bg) ; + $print_box_content_rows .= $add_form_fields ; + $print_box_content_rows .= &common_min_box_foot ; + + $trigger_jquery_raw .= qq~ + \$("#credits_bought-form [id^='savebutt']").on("click", function (e) { + if (this.id.includes("_new")) { + \$("input[name='iaction']").val("save") ; + \$("input[name='id']").val("$i{id}") ; + } + if (!\$("#selectClient_id").val() || !\$("#selectSport_type_id").val() || !\$("#selectCredit_type").val() || !\$("input[name='credits']").val()) { + noty({text:'Please select all of the input!',layout:"center",type:"error",timeout:10000}) ; + return ; + } + \$("#credits_bought-form").submit() ; + }) ; + ~ ; + + $i{id} = $orig_id if $orig_id ne 'new' ; + } #------------------------------------------------------------------------------------------ sub select_opts { - - # $required{based_in} = 1 ; - # $select{based_in} = 1 ; - # $opts{based_in} = qq~~ ; - # my $sql_or = '' ; + &common_min_select_opts('sport_type_id','sport_types','name','',0,'','') ; - # if ($is_schools_manager || $is_operator) { - # @report_sql_or = () ; - # foreach $_reg_id (keys %{$glob_regids{$userid}}) { - # push @report_sql_or, "id = '$_reg_id'" - # } - # $sql_or = join(' OR ',@report_sql_or) ; - # } + $i{client_id} = ($i{client_id}) ? $i{client_id} : $db{$table}{$i{id}}{client_id} ; + $i{sport_type_id} = ($i{sport_type_id}) ? $i{sport_type_id} : $db{$table}{$i{id}}{sport_type_id} ; + $i{credit_type} = ($i{credit_type}) ? $i{credit_type} : $db{$table}{$i{id}}{credit_type} ; + $i{credits} = ($i{credits}) ? $i{credits} : $db{$table}{$i{id}}{credits} ; - my $sql_or = ($is_schools_manager || $is_operator) ? join(' OR ', map { "id = '$_'" } keys %{$glob_regids{$userid}}) : '' ; + # $i{sport_type_id} = $db{$table}{$i{id}}{sport_type_id} if $db{$table}{$i{id}}{sport_type_id} ; - $allow_deselect{country_id} = 1 ; + $opts{sport_type_id} .= qq~~ ; + + $opts{sport_type_id} =~ s/value="\Q$i{sport_type_id}\E"/value="$i{sport_type_id}" SELECTED/g if $i{sport_type_id} ; - # &common_min_select_opts('province','regions','name',$db{$table}{$i{id}}{province},'','',$sql_or,'name'); + &common_min_select_opts('client_id','customers','name','',0,'',"analytics='1'") ; + + # $i{client_id} = ($i{client_id}) ? $i{client_id} : $db{$table}{$i{id}}{client_id} ; + + $opts{client_id} =~ s/value="\Q$i{client_id}\E"/value="$i{client_id}" SELECTED/g if $i{client_id} ; + + my %radio_opts_hash = (1 => "standard",2 => "premium",3 => "individuals") ; + + $opts{credit_type} = "`) ; - }); - - updateChosen(\$field) ; - return json_list.length ; - }; - - const getInputValue = name => \$(`input[name='\${name}']`).val(); - - const clearSelect = (\$el) => { - \$el.empty(); - \$el.append(``).trigger("chosen:updated"); - }; - - // _______________________________________________ - - \$countrySelect.change( async function() { - \$("input[name='custom_selected_country']").val("1") ; - await update_region_drop_down_from_country(\$countrySelect.val()) ; - }) ; - - async function update_region_drop_down_from_country (countryId) { - - clearSelect(\$regionSelect) ; - - const regionUrl = `$useropts{scripts}/get/get_regions_from_country.pl?country_id=\${countryId}` ; - const regions = await fetchJSON(regionUrl); - - for (const data of regions) { - map_region_to_country[data.id] = countryId ; - } - - const regionCount = populateSelect(\$regionSelect, regions, r => r.code ? `\${r.name} [\${r.code}]` : r.name , "") ; - - if (regionCount === 0 && \$countrySelect.val()) { - \$regionSelect.append(``).trigger("chosen:updated") ; - } - - } - - // _______________________________________________ - - \$regionSelect.change( async function() { - \$("input[name='custom_selected_region']").val("1") ; - \$("input[name='custom_selected_country']").val("1") ; - const regionId = \$regionSelect.val() ; - await update_country_from_region(regionId,1) ; - }); - - async function update_country_from_region (regionId,update_country=0) { - if (map_region_to_country[regionId] || regionId == '13') { - \$countrySelect.val(map_region_to_country[regionId]).trigger("chosen:updated") ; - } else if (!\$("input[name='custom_selected_country']").val() || update_country) { - const lookupUrl = `$useropts{scripts}/get/get_country_from_region.pl?country_id=®ion_id=\${regionId}`; - const regionMeta = await fetchJSON(lookupUrl); - const { country_id } = regionMeta[0] ?? {} ; - if (country_id) { - map_region_to_country[regionId] = country_id; - \$countrySelect.val(country_id).trigger("chosen:updated"); - } - } - } - - // _______________________________________________ - - ~ ; - } #------------------------------------------------------------------------------------------ sub thead { - - $print_thead = qq~IDCITY NAMECITY ACRONYMLATLNGREGIONCOUNTRY ~ ; - + + &common_min_thead ; + # $print_thead = qq(IDNAMEEXCLUDED FROM EXPENSES ) ; + } #------------------------------------------------------------------------------- sub page_opts { - our $glyphicon = 'map-marker' ; - our $lcpage = 'cities' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; - our $table = 'cities' ; + our $glyphicon = 'facetime-video' ; + our $lcpage = 'credits-bought' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ; + our $table = 'credits_bought' ; + + $s{no} = 1 ; - $s{no} = 1 ; - &common_min_add_extras ; + our $savjqy = 1 ; + } #------------------------------------------------------------------------------- use common ; diff --git a/scripts/cron/auto_get_next_day_events.pl b/scripts/cron/auto_get_next_day_events.pl index 6004c7d..05f9731 100644 --- a/scripts/cron/auto_get_next_day_events.pl +++ b/scripts/cron/auto_get_next_day_events.pl @@ -1,7 +1,7 @@ #!/usr/bin/perl BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } - + use CGI::Carp qw(fatalsToBrowser); use Mail::POP3Client; use MIME::Parser; @@ -20,11 +20,11 @@ require cfg_paths ; &config_set_vars ; &config_set_paths ; -# perl /usr/lib/cgi-bin/scripts/cron/auto_get_next_day_events.pl 1 +# perl /usr/lib/cgi-bin/aisa/scripts/cron/auto_get_next_day_events.pl 1 #--------------------------------------------------------------------------------------------------------------------------------------------------------------------- -our $debug = $ARGV[0] ; our $username = 'rory' if $debug == 1 ; print "Content-type: text/html\n\n" if $debug == 1 ; +our $debug = $ARGV[0] ; our $username = 'rory' if $debug == 1 ; # print "Content-type: text/html\n\n" if $debug == 1 ; #--------------------------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/scripts/cron/email_sql_backup.pl b/scripts/cron/email_sql_backup.pl index a87e322..89bdd87 100644 --- a/scripts/cron/email_sql_backup.pl +++ b/scripts/cron/email_sql_backup.pl @@ -11,7 +11,7 @@ use Date::Calc qw(:all); our $debug = $ARGV[0] ; our $username = $ARGV[1] ; -# perl /usr/lib/cgi-bin/scripts/cron/email_sql_backup.pl 1 rory +# perl /usr/lib/cgi-bin/aisa/scripts/cron/email_sql_backup.pl 1 rory #------------------------------------------------------------------------------------------ diff --git a/scripts/cron/get_exchange_rates.pl b/scripts/cron/get_exchange_rates.pl index 3764d91..a12457a 100644 --- a/scripts/cron/get_exchange_rates.pl +++ b/scripts/cron/get_exchange_rates.pl @@ -1,6 +1,12 @@ #!/usr/bin/perl -BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } +# BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +# our $cgipath = "/home/aisa/libs" ; + +use lib '/home/aisa/libs/modules' ; + +# our $htmlpath = "/var/www/aisadmin.co.za/public_html" ; use Fcntl qw(:flock); use CGI::Carp qw(fatalsToBrowser); @@ -9,12 +15,14 @@ use LWP::Simple qw($ua get); #------------------------------------------------------------------------------- -my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +# my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); our $debug = $ARGV[0] ; # https://itvadmin.co.za/cgi-bin/scripts/cron/get_exchange_rates.pl?1 -if ($debug) { our $username = 'rory' ; print "Content-type: text/html\n\n"; } +if ($debug) { our $username = 'rory' ; } # print "Content-type: text/html\n\n"; + +# &config_set_vars ; exit; @@ -40,92 +48,93 @@ sub fetch_exchange_rates { sub fetch_exchange_rates_using_json_send_post_api_1 { -my ($from_curr,$to_curr) = @_ ; + my ($from_curr,$to_curr) = @_ ; -my $url = "http://currency-api.appspot.com/api/$from_curr/$to_curr.json" ; + my $url = "http://currency-api.appspot.com/api/$from_curr/$to_curr.json" ; -my $json = get $url ; -print "Couldn't get $url ! $!" unless defined $json ; + my $json = get $url ; + print "Couldn't get $url ! $!" unless defined $json ; -&common_debug($json); -# exit; + &common_debug($json); + # exit; -my $perl_scalar = decode_json $json ; + my $perl_scalar = decode_json $json ; -# my $rate = $perl_scalar->{'rate'} ; -my $rate = $perl_scalar->{'amount'} ; # rounded to 2 decimal places + # my $rate = $perl_scalar->{'rate'} ; + my $rate = $perl_scalar->{'amount'} ; # rounded to 2 decimal places -$exchng_rate{$from_curr}{$to_curr} = $rate ; + $exchng_rate{$from_curr}{$to_curr} = $rate ; } #------------------------------------------------------------------------------- sub fetch_exchange_rates_using_json_send_post_api_2 { -my ($from_curr,$to_curr) = @_ ; + my ($from_curr,$to_curr) = @_ ; -my $cft = $from_curr . '_' . $to_curr ; + my $cft = $from_curr . '_' . $to_curr ; -my $url = "http://free.currencyconverterapi.com/api/v5/convert?q=$cft&compact=y&apiKey=1ada7dd66cf88a0211cd" ; # rory@kre8it.co.za API key -# my $url = "http://free.currencyconverterapi.com/api/v5/convert?q=$cft&compact=y&apiKey=1a0ae2c44dc4a60c7539" ; # vivian@filmfreight.co.za API key + my $url = "http://free.currencyconverterapi.com/api/v5/convert?q=$cft&compact=y&apiKey=1ada7dd66cf88a0211cd" ; # rory@kre8it.co.za API key + # my $url = "http://free.currencyconverterapi.com/api/v5/convert?q=$cft&compact=y&apiKey=1a0ae2c44dc4a60c7539" ; # vivian@filmfreight.co.za API key -my $json = get $url ; -die "Couldn't get $url ! $!" unless defined $json ; + my $json = get $url ; + die "Couldn't get $url ! $!" unless defined $json ; -my $decoded_json = decode_json $json ; + my $decoded_json = decode_json $json ; -if ($debug) { print "json=$json \n" ; } + if ($debug) { print "json=$json \n" ; } -my $ccapirate = $decoded_json->{$cft}->{'val'} ; # rounded to 2 decimal places + my $ccapirate = $decoded_json->{$cft}->{'val'} ; # rounded to 2 decimal places -$exchng_rate_ccapi{$from_curr}{$to_curr} = $ccapirate ; + $exchng_rate_ccapi{$from_curr}{$to_curr} = $ccapirate ; } #------------------------------------------------------------------------------- sub save_info { -unless (%exchng_rate) { return ; } + unless (%exchng_rate) { return ; } -$exchgfile = "/usr/lib/cgi-bin/scripts/cron/feed.dat"; + # $exchgfile = "/usr/lib/cgi-bin/scripts/cron/feed.dat"; + $exchgfile = "/usr/lib/cgi-bin/aisa/scripts/cron/feed.dat"; -open (IFILE, "+>>$exchgfile") or die "can't open $exchgfile : $!" ; -flock (IFILE, LOCK_EX) or die "can't lock $exchgfile : $!" ; -seek (IFILE, 0, 0) or die "can't rewind $exchgfile : $!" ; -@exchng = ; -seek (IFILE, 0, 0) or die "can't rewind $exchgfile : $!" ; -truncate (IFILE, 0) or die "can't truncate $exchgfile : $!" ; - -foreach $line (@exchng) { - chomp $line; - @linex = split(/\|/,$line); - - my $from = $linex[0] ; - my $to = $linex[1] ; - my $rate = $linex[2] ; - my $prate = $linex[3] ; - my $ccapirate = $linex[4] ; - - if ($exchng_rate{$from}{$to}) { - $prate = $rate ; - $rate = $exchng_rate{$from}{$to} ; - } - - if ($exchng_rate_ccapi{$from}{$to}) { - $ccapirate = $exchng_rate_ccapi{$from}{$to} ; - } - - $done{$from}{$to} = 1 ; - - print IFILE "$from|$to|$rate|$prate|$ccapirate|\n"; - } - -foreach my $from (keys %exchng_rate) { - foreach my $to (keys %{$exchng_rate{$from}}) { - if ($done{$from}{$to}) { next ; } - print IFILE "$from|$to|$exchng_rate{$from}{$to}||$exchng_rate_ccapi{$from}{$to}|\n"; - } - } + open (IFILE, "+>>$exchgfile") or die "can't open $exchgfile : $!" ; + flock (IFILE, LOCK_EX) or die "can't lock $exchgfile : $!" ; + seek (IFILE, 0, 0) or die "can't rewind $exchgfile : $!" ; + @exchng = ; + seek (IFILE, 0, 0) or die "can't rewind $exchgfile : $!" ; + truncate (IFILE, 0) or die "can't truncate $exchgfile : $!" ; + + foreach $line (@exchng) { + chomp $line; + @linex = split(/\|/,$line); + + my $from = $linex[0] ; + my $to = $linex[1] ; + my $rate = $linex[2] ; + my $prate = $linex[3] ; + my $ccapirate = $linex[4] ; + + if ($exchng_rate{$from}{$to}) { + $prate = $rate ; + $rate = $exchng_rate{$from}{$to} ; + } + + if ($exchng_rate_ccapi{$from}{$to}) { + $ccapirate = $exchng_rate_ccapi{$from}{$to} ; + } + + $done{$from}{$to} = 1 ; + + print IFILE "$from|$to|$rate|$prate|$ccapirate|\n"; + } + + foreach my $from (keys %exchng_rate) { + foreach my $to (keys %{$exchng_rate{$from}}) { + if ($done{$from}{$to}) { next ; } + print IFILE "$from|$to|$exchng_rate{$from}{$to}||$exchng_rate_ccapi{$from}{$to}|\n"; + } + } -close (IFILE) ; + close (IFILE) ; } #---------------------------------------------------------------------------------------- diff --git a/scripts/cron/mysql_backup.pl b/scripts/cron/mysql_backup.pl index 1a845f6..1a0ba45 100644 --- a/scripts/cron/mysql_backup.pl +++ b/scripts/cron/mysql_backup.pl @@ -10,10 +10,10 @@ use Date::Manip; #------------------------------------------------------------------------------- -my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); +# my @ARGV = split(/\&/, $ENV{'QUERY_STRING'}); my $debug = $ARGV[0] ; -# test link : https://www.itvadmin.co.za/cgi-bin/scripts/cron/mysql_backup.pl?1 +# perl /usr/lib/cgi-bin/aisa/scripts/cron/mysql_backup.pl 1 #------------------------------------------------------------------------------- @@ -48,43 +48,71 @@ my $bkday = substr($date2,6,2); #------------------------------------------------------------------------------- -my $db = "itv_admin_db"; -my $dbhost = "localhost"; -my $dbuser = "itv_admin_user"; -my $dbpass = "!Ja16Q7P0X3SVTWr"; -my $date = "`date +%Y-%m-%d`"; my $path = "/home/mysqlbak"; my $ext = "bz2"; -if ($debug) { print "Content-type: text/html\n\n"; } +# if ($debug) { print "Content-type: text/html\n\n"; } -flush_old($path,$ext); -my($dbh,$sth,$query); +&flush_old($path,$ext); +&backup_db('ais') ; # || $debug == 1 ; +# &restore_db('d_ais',"$path/$bak_name") if $now_hour == 0 ; # || $debug == 1 ; +&backup_db('sss') ; +# &restore_db('d_sss',"$path/$bak_name") if $now_hour == 0 || $debug == 1 ; -my $dsn = "DBI:mysql:$db;host=$dbhost"; -$dbh = DBI->connect($dsn,$dbuser,$dbpass,{PrintError => 0, RaiseError => 1}) or die "Unable to connect, $DBI::errstr"; -$query = qq^SHOW DATABASES^; -$sth = $dbh->prepare($query); -$sth->execute(); - -while(my $ref = $sth->fetchrow_array()) { - unless ($ref eq 'itv_admin_db') { next ; } - if ($debug) { print "ref=$ref \n"; } - my @bp = `mysqldump --user=$dbuser --password=$dbpass --add-drop-table $ref | bzip2 -1 > $path/$ref.$date.$now_hour$now_min.$ext`; -} - -$sth->finish(); -$dbh->disconnect(); - -my $dow = Day_of_Week($now_year,$now_mm,$now_dd); -our $ftp_file_name = "itv_admin_db.$dow.bz2" ; -&uploader_filmfreight("$path/itv_admin_db.$now_year-$now_mm-$now_dd.$now_hour$now_min.$ext","/mysqlbak",$ftp_file_name,'n') ; +# &backup_db('sfm') if $now_hour == 0 || $debug == 1 ; +# &backup_db('sfg') if $now_hour == 0 || $debug == 1 ; +# &backup_db('rim') if $now_hour == 0 || $debug == 1 ; # - - - - - - - - - - - - - - - - - if ($debug) { print "Done."; } # - - - - - - - - - - - - - - - - - +sub backup_db { + + # my ($db,$dbhost,$dbuser,$dbpass) = @_ ; + my ($dbsrv) = @_ ; + + my ($db,$dbhost,$dbuser,$dbpass) = &ops_db_credentials($dbsrv); + + my ($dbh,$sth,$query); + + my $dsn = "DBI:mysql:$db;host=$dbhost"; + $dbh = DBI->connect($dsn,$dbuser,$dbpass,{PrintError => 0, RaiseError => 1}); + $query = qq^SHOW DATABASES^; + $sth = $dbh->prepare($query); + $sth->execute(); + + while(my $ref = $sth->fetchrow_array()) { + + print "\n $ref -> $dsn\n" if $debug ; + + unless ($ref eq $db) { next ; } + # my $bak_name = "$ref.$date.$now_hour$now_min.$ext" ; + our $bak_name = "$ref.$now_year-$now_mm-$now_dd.$now_hour$now_min.$ext" ; + my @bp = `mysqldump --host=$dbhost --user=$dbuser --password=$dbpass --add-drop-table $ref | bzip2 -1 > $path/$bak_name`; + # my @bp = `mysqldump -h "$dbhost" -u "$dbuser" -p "$dbpass" --add-drop-table $ref | bzip2 -1 > $path/$bak_name`; + # &common_send_smtp_mail('','k@re8it.com','','',"K8 MySQL Backup : $bak_name"," $path/$bak_name ",'html','',$path,$bak_name,'zip') if $now_hour == 2 ; + } + + $sth->finish(); + $dbh->disconnect(); + +} # - - - - - - - - - - - - - - - - - + +# sub restore_db { + + # my ($dbsrv,$mysqlbakfile) = @_ ; + + # my ($db,$dbhost,$dbuser,$dbpass) = &ops_db_credentials($dbsrv); + + # system `bunzip2 -c $mysqlbakfile | mysql -f -u$dbuser -p'$dbpass' -h$dbhost $db`; + + # # system `mysql -f -u$dbuser -p'$dbpass' -h$dbhost $db < $mysqlbakfile` ; + +# } # - - - - - - - - - - - - - - - - - + sub flush_old { + my ($path,$ext) = @_; opendir BP_DIR,"$path" or die "Cannot open $path: $!\n"; my @old_backups = grep { /\.$ext$/ } readdir BP_DIR; @@ -100,11 +128,81 @@ sub flush_old { my @args = ("rm","-f","$path/$_"); system(@args); } -} - -# - - - - - - - - - - - - - - - - - + +} # - - - - - - - - - - - - - - - - - use common ; -use uploader ; +use today ; +use db ; + +# # my $db = "itv_admin_db"; +# # my $dbhost = "localhost"; +# # my $dbuser = "itv_admin_user"; +# # my $dbpass = "!Ja16Q7P0X3SVTWr"; +# # my $date = "`date +%Y-%m-%d`"; +# # my $path = "/home/mysqlbak"; +# # my $ext = "bz2"; + +# my $db = "aisa_admin_db"; +# my $dbhost = "localhost"; +# my $dbuser = "aisa_admin_user"; +# my $dbpass = "s5pCDPUZo18oip29!"; +# my $date = "`date +%Y-%m-%d`"; +# my $path = "/home/mysqlbak"; +# my $ext = "bz2"; + +# if ($debug) { print "Content-type: text/html\n\n"; } + +# flush_old($path,$ext); +# my($dbh,$sth,$query); + +# my $dsn = "DBI:mysql:$db;host=$dbhost"; +# $dbh = DBI->connect($dsn,$dbuser,$dbpass,{PrintError => 0, RaiseError => 1}) or die "Unable to connect, $DBI::errstr"; +# $query = qq^SHOW DATABASES^; +# $sth = $dbh->prepare($query); +# $sth->execute(); + +# while(my $ref = $sth->fetchrow_array()) { + # # unless ($ref eq 'itv_admin_db') { next ; } + # unless ($ref eq 'aisa_admin_db') { next ; } + # if ($debug) { print "ref=$ref \n"; } + # my @bp = `mysqldump --user=$dbuser --password=$dbpass --add-drop-table $ref | bzip2 -1 > $path/$ref.$date.$now_hour$now_min.$ext`; +# } + +# $sth->finish(); +# $dbh->disconnect(); + +# my $dow = Day_of_Week($now_year,$now_mm,$now_dd); +# # our $ftp_file_name = "itv_admin_db.$dow.bz2" ; +# # &uploader_filmfreight("$path/itv_admin_db.$now_year-$now_mm-$now_dd.$now_hour$now_min.$ext","/mysqlbak",$ftp_file_name,'n') ; +# our $ftp_file_name = "aisa_admin_db.$dow.bz2" ; +# &uploader_filmfreight("$path/aisa_admin_db.$now_year-$now_mm-$now_dd.$now_hour$now_min.$ext","/mysqlbak",$ftp_file_name,'n') ; + +# # - - - - - - - - - - - - - - - - - +# if ($debug) { print "Done."; } +# # - - - - - - - - - - - - - - - - - + +# sub flush_old { + # my ($path,$ext) = @_; + # opendir BP_DIR,"$path" or die "Cannot open $path: $!\n"; + # my @old_backups = grep { /\.$ext$/ } readdir BP_DIR; + # closedir BP_DIR; + + # for (@old_backups) { + # my ($db_bk_name,$db_bk_date,$db_bk_time,$db_bk_ext) = split(/\./); + # $db_bk_date =~ s/\-//g; + # my $bk_7_days_back_date = "$bkyear$bkmonth$bkday"; + # # print "
    1. $_ -> $db_bk_date = $bkyear$bkmonth$bkday" ; + # if ($db_bk_date > $bk_7_days_back_date) { next; } + # # print "
    2. $_ -> $db_bk_date = $bkyear$bkmonth$bkday" ; + # my @args = ("rm","-f","$path/$_"); + # system(@args); + # } +# } + +# # - - - - - - - - - - - - - - - - - + +# use common ; +# use uploader ; 1; \ No newline at end of file diff --git a/scripts/cron/remove_expired_sessions_mysql.pl b/scripts/cron/remove_expired_sessions_mysql.pl index 5748810..0fb1905 100644 --- a/scripts/cron/remove_expired_sessions_mysql.pl +++ b/scripts/cron/remove_expired_sessions_mysql.pl @@ -6,7 +6,7 @@ use CGI::Carp qw(fatalsToBrowser); use Date::Calc qw(:all); use DBI; - # /usr/lib/cgi-bin/scripts/cron/remove_expired_sessions_mysql.pl 1 + # /usr/lib/cgi-bin/aisa/scripts/cron/remove_expired_sessions_mysql.pl 1 #------------------------------------------------------------------------------- diff --git a/scripts/cron/sss_aisa_upload_check.pl b/scripts/cron/sss_aisa_upload_check.pl index d9b0ea8..86e3fc4 100644 --- a/scripts/cron/sss_aisa_upload_check.pl +++ b/scripts/cron/sss_aisa_upload_check.pl @@ -1,13 +1,21 @@ #!/usr/bin/perl -BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } +# our $cron_loc = 'aisa' ; + +# BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +our $cgipath = "/home/aisa/libs" ; + +use lib '/home/aisa/libs/modules' ; + +our $htmlpath = "/var/www/aisadmin.co.za/public_html" ; use CGI::Carp qw(fatalsToBrowser); use Date::Calc qw(:all); use DBI; use File::Copy; -# perl /usr/lib/cgi-bin/scripts/cron/sss_aisa_upload_check.pl 1 +# perl /usr/lib/cgi-bin/aisa/scripts/cron/sss_aisa_upload_check.pl 1 #------------------------------------------------------------------------------- diff --git a/scripts/demos.pl b/scripts/demos.pl index bd66ed9..cdf69a4 100644 --- a/scripts/demos.pl +++ b/scripts/demos.pl @@ -4057,10 +4057,15 @@ sub select_opts { my $selcntry = ($db{$table}{$id}{country_id}) ? $db{$table}{$id}{country_id} : 242 ; &common_min_select_opts('country_id','countries','name',$selcntry,1,'country','','id'); - $db{event_quotes}{''}{quote_to} = 5 if $iaction eq 'add' ; # SuperSport Schools (Pty) Ltd + # $db{event_quotes}{''}{quote_to} = 5 if $iaction eq 'add' ; # SuperSport Schools (Pty) Ltd + $db{event_quotes}{''}{quote_to} = 139 if $iaction eq 'add' ; # SuperSport Schools (Pty) Ltd $onload = qq~onload=dispCustomer();~ if $iaction eq 'add' ; # SuperSport Schools (Pty) Ltd + + my $saved_demo_id = $db{event_quotes}{$id}{quote_to} ; + $db{event_quotes}{$id}{quote_to} = 139 ; + # &event_tabs_customer_select_opts('customers','name','','quote_to'); + &event_tabs_customer_select_opts('customers','name',"name='Demo' OR id = '$saved_demo_id'",'quote_to'); - &event_tabs_customer_select_opts('customers','name','','quote_to'); $trigger_jquery_raw .= qq~ \$("#selectQuote_to").change(function() { @@ -4210,8 +4215,8 @@ sub report_ifields { } - if ($i{customer_name}) { - push @report_sql, "(q.quote_to = '$i{customer_name}' OR q.quote_to = '0')" ; + if ($i{customer_name}) { + push @report_sql, "(q.quote_to = '$i{customer_name}' OR q.quote_to = '0' OR q.quote_to = '1' OR q.quote_to = '5' OR q.quote_to = '96')" ; &db_min_ro('customers','id,name',"`id`='$i{customer_name}'",'','') ; push @report_results, "customer = `$db{customers}{$i{customer_name}}{name}`" ; } @@ -4304,8 +4309,11 @@ sub filter_screen { $print_box_content_rows .= &common_min_forms_start('report') ; my $defualt_customer = 0 ; $defualt_customer = 139 if $usertype ne 'school_manager' ; - &common_min_select_opts('customer_name','customers','name',$defualt_customer,'','',"events='1'") ; - + + # &common_min_select_opts('customer_name','customers','name',$defualt_customer,'','',"events='1'") ; # AND name = 'Demo' + &common_min_select_opts('customer_name','customers','name',$defualt_customer,'','',"events='1' AND name = 'Demo'") ; # AND name = 'Demo' + + # $allow_deselect{customer_name} = '' ; $print_box_content_rows .= &common_min_form_select('customer_name','') ; $preferred_title{event_from} = 'Event Date From' ; @@ -4384,7 +4392,9 @@ sub filter_screen { # local $all_select_ids_string = join(",",@all_select_ids) ; # $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true });~ ; - $trigger_jquery_raw .= qq~\$("#report-form [id^='select']").chosen({ allow_single_deselect:true });~ ; + + $trigger_jquery_raw .= qq~\$("#report-form [id^='select']:not([id^='selectCustomer_name']").chosen({ allow_single_deselect:true });~ ; + # $trigger_jquery_raw .= qq~\$("#report-form [id^='select']").chosen({ allow_single_deselect:true });~ ; &common_min_search_screen ; diff --git a/scripts/dialog/add_fixtures_analyst.pl b/scripts/dialog/add_fixtures_analyst.pl new file mode 100644 index 0000000..cafe864 --- /dev/null +++ b/scripts/dialog/add_fixtures_analyst.pl @@ -0,0 +1,227 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +&today ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use DBI; +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; +$selectfield = $ARGV[1] ; + +# our $debug = 1 ; +our $table = 'all_fixtures_analysts' ; +our $dialog = 1 ; + +our ($q) = CGI -> new() ; +$iaction = $q -> param('iaction') || $action ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + if ($iaction eq 'add'){ + &common_min_add_screen ; + &screen1 ; + } + + if ($iaction eq 'save'){ + &common_min_load_params ; + &validate ; + &insert ; + &screen2 ; + } + + &common_min_action; + + $db_ignore_open_close = 0 ; +&db_close_conn ; + + +exit ; + +#------------------------------------------------------------------------------------------ + +sub insert { + + &add_db_fields ; # $i{last_edited_by} = $userid ; $i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + + &validate ; + + $ignore{sel_field} = 1 ; + + $i{id} = &db_min_get_max($table,'id') ; + + &db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub validate { + + # called from common_min_action + + my $exists = '' ; + + # $i{name} = &common_fix_str($i{name}) ; + + &db_min_ro($table,'id,name',"coding_provider_id='$i{coding_provider_id}'",'','') ; + + foreach my $id (keys %{$db{$table}}) { + if (lc $db{$table}{$id}{name} eq lc $i{name}) { + $exists = 1 ; + } + } + + if ($exists) { + $alert = &common_min_alert('warning',"'$i{name}' AS A FIXTURES ANALYST NAME FOR THIS CODING PROVIDER ALREADY EXISTS!",'warning-sign') ; + %col_name = () ; + &common_min_add_screen; + &screen1; + } + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + + $box_header_title = "Add Fixtures Analyst" ; + $hidden_action = 'save' ; + $head_col_width = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + $ignore{iaction} = 1 ; + $hidden{id} = 2 ; + $hidden{sel_field} = 2 ; + $required{name} = 1 ; + $required{coding_provider_id} = 1 ; + $sort_field{1} = "name" ; + $sort_field{2} = "coding_provider_id" ; + $select{coding_provider_id} = 1 ; + + if ($i{name}) { + $trigger_jquery_raw .= qq~ + \$("input[name='name']").val("$i{name}") ; + ~ ; + } + + if ($i{coding_provider_id}) { + $trigger_jquery_raw .= qq~ + \$("#selectCoding_provider_id").val("$i{coding_provider_id}").trigger("chosen:updated") ; + ~ ; + } + + $trigger_jquery_raw .= qq~\$("#selectCoding_provider_id").chosen({ allow_single_deselect:false,search_contains:true });~ ; + + if ($usertype eq 'coding_provider') { + &db_min_ro('users','id,name,username',"id='$userid'",'','') ; + } else { + &db_min_ro('users','id,name,username',"user_type='coding_provider'",'','') ; + } + + foreach (keys %{$db{users}}) { + my $selected = ($_ eq $userid) ? "SELECTED" : "" ; + $opts{coding_provider_id} .= qq~~ ; + } + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub screen1 { + + $trigger_jquery_raw .= qq~ + \$('#btn-close-customer').click( function (e) { + parent.BootstrapDialog.closeAll() ; + }); + ~ ; + + &common_min_dialog_load_screen ; + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + + $i{name} =~ s/\'/\\'/g ; + $i{name} =~ s/\"/\\"/g ; + + $trigger_jquery_raw = qq~ + + function get_row_nr (id,nr_of_characters_in_id_to_determine_row) { + + let lastIndex = id.lastIndexOf('_'); + lastIndex = parseInt(lastIndex) ; + let row_nr_1 = id.substring(1+lastIndex); + + if (!nr_of_characters_in_id_to_determine_row || nr_of_characters_in_id_to_determine_row == 1) { + return row_nr_1 ; + } + + let id_2 = id.substring(0,lastIndex); + lastIndex = id_2.lastIndexOf('_'); + lastIndex = parseInt(lastIndex) ; + let row_nr_2 = id_2.substring(1+lastIndex); + + if (nr_of_characters_in_id_to_determine_row == 2) { + return row_nr_2+"_"+row_nr_1 ; + } + + } + + let input_coding_provider = "$i{coding_provider_id}" ; + + const table_ = parent.\$('#$useropts{table_id}').DataTable()._('tr') ; + + console.log("table_.length : "+table_.length) ; + + for (let i = 1 ; i <= table_.length ; i++) { + + let \$td = parent.\$("#$useropts{table_id} tr:eq("+i+") td:nth-last-child(3)") ; + let \$selects = \$td.find("select") ; + + console.log("i : "+i) ; + console.log("1 selects.length : "+\$selects.length) ; + + if (!\$selects.length) { + continue ; + } + + console.log("1 selects.length : "+\$selects.length) ; + + \$selects.each(function () { + let row_nr = get_row_nr (this.id,2) ; + + if (input_coding_provider == parent.\$("#selectCoding_provider_"+row_nr).val()) { + parent.\$("#"+this.id).append("").trigger("chosen:updated") ; + } + }); + } + + parent.BootstrapDialog.closeAll() ; + + ~ ; + + &common_min_dialog_save_screen ; + +} #------------------------------------------------------------------------------------------ + +use today ; +use dialog ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/dialog/add_fixtures_charge_free_reason.pl b/scripts/dialog/add_fixtures_charge_free_reason.pl new file mode 100644 index 0000000..f056356 --- /dev/null +++ b/scripts/dialog/add_fixtures_charge_free_reason.pl @@ -0,0 +1,207 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +&today ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use DBI; +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +our $action = $ARGV[0] ; +our $selectfield = $ARGV[1] ; +our $analytics_id = $ARGV[2] ; +our $row_cnt = $ARGV[3] ; +our $default_reason = $ARGV[4] ; + +$is_from_analytics_event = "" unless $is_from_analytics_event ; + +# our $debug = 1 ; +our $table = 'analytics_event_bookings' ; + +our ($q) = CGI -> new() ; +$iaction = $q -> param('iaction') || $action ; + +our $dialog = 1 ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +if ($iaction eq 'add'){ + &common_min_add_screen ; + &screen1 ; +} + +if ($iaction eq 'save'){ + &common_min_load_params ; + &update ; + &screen2 ; +} + +&common_min_action; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub update { + + &add_db_fields ; # $i{last_edited_by} = $userid ; $i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + + $ignore{sel_field} = 1 ; + + my %ii = %i ; + + %i = () ; + + # &db_min_ro($table,'1,cant_charge_client_reasons',"id='$analytics_id'",'','') if $analytics_id ; + + # my @reasons = ($db{$table}{1}{cant_charge_client_reasons}) ? split(/\:|;/,$db{$table}{1}{cant_charge_client_reasons}) : (undef) ; + + $i{reason} = $ii{reason} ; + + $i{reason} =~ s/\:\|;//g ; + + $i{reason} =~ s/ +$//g ; + + $i{reason} =~ s/^ //g ; + + # $#reasons = $row_cnt-1 if $#reasons < $row_cnt-1 ; # Pads with undef automatically + + # @reasons = map { defined($_) ? $_ : "" } @reasons ; + + # $reasons[$row_cnt-1] = $i{reason} ; + + # $i{cant_charge_client_reasons} = join(":|;",@reasons) ; + + # $i{cant_charge_client_reasons} =~ s/\:\|;+$//g ; + + # &db_min_upd($table,"id='$analytics_id'") if $analytics_id ; + +} #------------------------------------------------------------------------------------------ + + +sub add_screen { + + $box_header_title = 'Add Reason' ; + $hidden_action = 'save' ; + $head_col_width = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + $ignore{iaction} = 1 ; + $hidden{id} = 2 ; + $hidden{sel_field} = 2 ; + $required{reason} = 1 ; + $textarea{reason} = 1 ; + + $db{$table}{''}{sel_field} = $selectfield if $selectfield ; + $default_reason =~ s/\_new_line_character_/\n/g ; + $default_reason =~ s/\\ / /g ; + $default_reason =~ s/\%A0/ /g ; + $db{$table}{''}{reason} = "$default_reason" ; + + $sort_field{1} = "reason" ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub screen1 { + + $trigger_jquery_raw .= qq~ + \$('#btn-close-customer').click(function (e) { + parent.BootstrapDialog.closeAll() ; + }); + ~ ; + + &common_min_dialog_load_screen ; + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + + my $reason_tooltip = "$i{reason}" ; + + $reason_tooltip =~ s/\R/
    /g; + $reason_tooltip =~ s/ /\ /g; + + my $reason_default = "$i{reason}" ; + + $reason_default =~ s/\R/_new_line_character_/g; + $reason_default =~ s/ /\ /g ; + + # my $data_base_value = "$i{cant_charge_client_reasons}" ; + + # $data_base_value =~ s/\R/
    /g; + + $trigger_jquery_raw .= qq~ + + let reasons = parent.\$("input[name='cant_charge_client_reasons']").val() ; + + let reasons_arr = reasons ? reasons.split(":|;") : [undefined] ; + + let row_cnt = $row_cnt ; + + if (reasons_arr.length < row_cnt) { + reasons_arr.length = row_cnt; + reasons_arr = reasons_arr.map(v => v !== undefined ? v : ""); + } + + reasons_arr[row_cnt - 1] = "$reason_default" ; + let joined_reasons = reasons_arr.join(":|;"); + + ~ ; + + $trigger_jquery_raw .= qq~ + + let analytics_id = $analytics_id ; + + let update_url = "$useropts{scripts}/get/get_analytics_charge_client.pl?analytics_id="+analytics_id+"&row_cnt="+row_cnt+"&reason=$reason_default" ; + + \$.get(update_url) ; + + ~ if $analytics_id ; + + $trigger_jquery_raw .= qq~ + + parent.\$("input[name='cant_charge_client_reasons']").val(joined_reasons) ; + + if (parent.\$("#reason_icon_$row_cnt").html()) { + parent.\$("#reason_icon_$row_cnt").remove() + } + + let html_cant_charge = "  " ; + + console.log('$useropts{scripts}/get/update_analytics_cant_charge_client_fixtures.pl?analytics_id=1011&row_cnt=$row_cnt&reason=$reason_default') ; + + let checkbox_html = "" ; + + parent.\$("#c_cant_charge_client_fixtures_$row_cnt").html(checkbox_html+""+html_cant_charge).trigger("chosen:updated") ; + + parent.\$("#checkboxCant_charge_client_fixtures_$row_cnt").prop("checked",true) ; + parent.\$('[data-toggle="tooltip"]').tooltip({html:true}); + parent.BootstrapDialog.closeAll() ; + ~; + + &common_min_dialog_save_screen ; + +} #------------------------------------------------------------------------------------------ + +use today ; +use dialog ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/dialog/add_fixtures_charge_free_table_reason.pl b/scripts/dialog/add_fixtures_charge_free_table_reason.pl new file mode 100644 index 0000000..e295f04 --- /dev/null +++ b/scripts/dialog/add_fixtures_charge_free_table_reason.pl @@ -0,0 +1,224 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +&today ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use DBI; +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +our $action = $ARGV[0] ; +our $selectfield = $ARGV[1] ; +our $analytics_id = $ARGV[2] ; +our $row_cnt = $ARGV[3] ; +our $default_reason = $ARGV[4] ; +our $parent_all_fixtures = $ARGV[5] ; + +exit if $parent_all_fixtures && !$analytics_id ; + +$is_from_analytics_event = "" unless $is_from_analytics_event ; + +# our $debug = 1 ; +our $table = 'analytics_event_bookings' ; + +our ($q) = CGI -> new() ; +$iaction = $q -> param('iaction') || $action ; + +our $dialog = 1 ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +if ($iaction eq 'add'){ + &common_min_add_screen ; + &screen1 ; +} + +if ($iaction eq 'save'){ + &common_min_load_params ; + &update ; + &screen2 ; +} + +&common_min_action; + +exit ; + +#------------------------------------------------------------------------------------------ + +sub update { + + &add_db_fields ; # $i{last_edited_by} = $userid ; $i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + + $ignore{sel_field} = 1 ; + + my %ii = %i ; + + %i = () ; + + # &db_min_ro($table,'1,cant_charge_client_reasons',"id='$analytics_id'",'','') if $analytics_id ; + + # my @reasons = ($db{$table}{1}{cant_charge_client_reasons}) ? split(/\:|;/,$db{$table}{1}{cant_charge_client_reasons}) : (undef) ; + + $i{reason} = $ii{reason} ; + + $i{reason} =~ s/\:\|;//g ; + + $i{reason} =~ s/ +$//g ; + + $i{reason} =~ s/^ //g ; + + # $#reasons = $row_cnt-1 if $#reasons < $row_cnt-1 ; # Pads with undef automatically + + # @reasons = map { defined($_) ? $_ : "" } @reasons ; + + # $reasons[$row_cnt-1] = $i{reason} ; + + # $i{cant_charge_client_reasons} = join(":|;",@reasons) ; + + # $i{cant_charge_client_reasons} =~ s/\:\|;+$//g ; + + # &db_min_upd($table,"id='$analytics_id'") if $analytics_id ; + +} #------------------------------------------------------------------------------------------ + + +sub add_screen { + + $box_header_title = 'Add Reason' ; + $hidden_action = 'save' ; + $head_col_width = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + $ignore{iaction} = 1 ; + $hidden{id} = 2 ; + $hidden{sel_field} = 2 ; + $required{reason} = 1 ; + $textarea{reason} = 1 ; + + $db{$table}{''}{sel_field} = $selectfield if $selectfield ; + $default_reason =~ s/\_new_line_character_/\n/g ; + $default_reason =~ s/\\ / /g ; + $default_reason =~ s/\%A0/ /g ; + $default_reason =~ s/\%C2/ /g ; + $default_reason =~ s/_blank_space_/ /g ; + $db{$table}{''}{reason} = "$default_reason" ; + + $sort_field{1} = "reason" ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub screen1 { + + $trigger_jquery_raw .= qq~ + \$('#btn-close-customer').click(function (e) { + parent.BootstrapDialog.closeAll() ; + }); + ~ ; + + &common_min_dialog_load_screen ; + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + + my $reason_tooltip = "$i{reason}" ; + + $reason_tooltip =~ s/\R/
    /g; + $reason_tooltip =~ s/ /\ /g; + + my $reason_default = "$i{reason}" ; + + $reason_default =~ s/\R/_new_line_character_/g; + $reason_default =~ s/ /_blank_space_/g ; + + # my $data_base_value = "$i{cant_charge_client_reasons}" ; + + # $data_base_value =~ s/\R/
    /g; + + my $cant_charge_client_id = ($parent_all_fixtures) ? qq~cant_charge_client_$row_cnt\_$analytics_id~ : qq~cant_charge_client_fixtures_$row_cnt~ ; + + my $ucfirst_cant_charge_client_id = ucfirst $cant_charge_client_id ; + + my $reasons_field_name = ($parent_all_fixtures) ? "cant_charge_client_reasons_$analytics_id" : "cant_charge_client_reasons" ; + + $trigger_jquery_raw .= qq~ + + let reasons = parent.\$("input[name='$reasons_field_name']").val() ; + + let reasons_arr = reasons ? reasons.split(":|;") : [undefined] ; + + let row_cnt = $row_cnt ; + + if (reasons_arr.length < row_cnt) { + reasons_arr.length = row_cnt ; + reasons_arr = reasons_arr.map(v => v !== undefined ? v : "") ; + } + + reasons_arr[row_cnt - 1] = "$reason_default" ; + let joined_reasons = reasons_arr.join(":|;") ; + + ~ ; + + $trigger_jquery_raw .= qq~ + + let analytics_id = "$analytics_id" ; + + let update_url = "$useropts{scripts}/get/get_analytics_charge_client.pl?analytics_id="+analytics_id+"&row_cnt="+row_cnt+"&reason=$reason_default" ; + + // console.log("update_url : "+update_url) ; + + \$.get(update_url) ; + + ~ if $analytics_id ; + + $trigger_jquery_raw .= qq~ + + parent.\$("input[name='$reasons_field_name']").val(joined_reasons) ; + + // if (parent.\$("#reason_icon_$row_cnt").html()) { + // parent.\$("#reason_icon_$row_cnt").remove() ; + // } + + if (parent.\$("#reason_icon_$row_cnt\_$analytics_id").html()) { + parent.\$("#reason_icon_$row_cnt\_$analytics_id").remove() ; + } + + let html_cant_charge = "  " ; + + let checkbox_html = "" ; + + parent.\$("#c_$cant_charge_client_id").html(checkbox_html+""+html_cant_charge).trigger("chosen:updated") ; + // parent.\$("#checkbox$ucfirst_cant_charge_client_id").after(html_cant_charge).trigger("chosen:updated") ; + + parent.\$("#checkbox$ucfirst_cant_charge_client_id").prop("checked",true) ; + + parent.\$('[data-toggle="tooltip"]').tooltip({html:true}) ; + parent.BootstrapDialog.closeAll() ; + ~; + + &common_min_dialog_save_screen ; + +} #------------------------------------------------------------------------------------------ + +use today ; +use dialog ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/dialog/add_team_test.pl b/scripts/dialog/add_team_test.pl new file mode 100644 index 0000000..e0f6624 --- /dev/null +++ b/scripts/dialog/add_team_test.pl @@ -0,0 +1,266 @@ +#!/usr/bin/perl + +BEGIN { use lib '/usr/home/cfg' ; require push_inc ; } + +require cfg ; + +print "Content-type: text/html\n\n"; + +&today ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use DBI; +use CGI::Carp qw(fatalsToBrowser); +use CGI; + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +our $action = $ARGV[0] ; +our $selectfield = $ARGV[1] ; +our $home_or_away_team = $ARGV[2] ; + +# our $debug = 1 ; +our $table = 'teams' ; +our $dialog = 1 ; + +our ($q) = CGI -> new() ; +$iaction = $q -> param('iaction') || $action ; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +&db_open_ro ; + our $db_ignore_open_close = 1 ; # do one open and one close instead of repeating it + + &db_switch_conn('sss') ; + + if ($iaction eq 'add'){ + &common_min_add_screen; + &screen1; + } + + if ($iaction eq 'save'){ + &common_min_load_params ; + &validate ; + &insert ; + &screen2 ; + } + + &common_min_action; + + $db_ignore_open_close = 0 ; +&db_close_conn ; + + +exit ; + +#------------------------------------------------------------------------------------------ + +sub insert { + + &add_db_fields ; # $i{last_edited_by} = $userid ; $i{last_updated} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + + our $exists = '' ; + + &validate ; + + return if $exists ; + + $ignore{sel_field} = 1 ; + + $i{id} = &db_min_get_max($table,'id') ; + + &db_min_insert($table) ; + +} #------------------------------------------------------------------------------------------ + +sub validate { + + # called from common_min_action + + $i{name} = &common_fix_str($i{name}) ; + + &db_min_ro($table,'id,name,region_id,matched_region_id,aisa_client_id','','','') ; + + foreach my $id (keys %{$db{$table}}) { + if (lc $db{$table}{$id}{name} eq lc $i{name}) { + $exists = 1 ; + if (!$db{$table}{$id}{region_id} && !$db{$table}{$id}{aisa_client_id}) { + %ii = %i ; + %i = () ; + my %ignore_old = %ignore ; + $ignore{name} = 1 ; + $ignore{matched_region_id} = 1 ; + $i{region_id} = $ii{region_id} ; + $i{aisa_client_id} = $ii{aisa_client_id} ; + &db_min_upd($table,"id='$id'") ; + %i = %ii ; + %ignore = %ignore_old ; + # $alert = &common_min_alert('warning',"'$i{name}' AS A TEAM NAME ALREADY EXISTS!",'warning-sign') ; + # %col_name = () ; + # &common_min_add_screen; + # &screen1; + # exit ; + } + $i{id} = $id ; + $i{name} = $db{$table}{$id}{name} ; + } + } + + # if ($exists) { + # $alert = &common_min_alert('warning',"'$i{name}' AS A TEAM NAME ALREADY EXISTS!",'warning-sign') ; + # %col_name = () ; + # &common_min_add_screen; + # &screen1; + # } + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + + $box_header_title = "Add $home_or_away_team Team" ; + $hidden_action = 'save' ; + $head_col_width = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub add_db_fields { + + $ignore{iaction} = 1 ; + $hidden{id} = 2 ; + $hidden{sel_field} = 2 ; + $required{name} = 1 ; + $required{region_id} = 1 ; + $required{aisa_client_id} = 1 if $home_or_away_team eq 'Home' ; + $select{region_id} = 1 ; + $sort_field{1} = "name" ; + $sort_field{2} = "region_id" ; + $sort_field{3} = "aisa_client_id" ; + $preferred_title{region_id} = "Region" ; + $preferred_title{aisa_client_id} = "Client" ; + + if ($i{name}) { + $trigger_jquery_raw .= qq~ + \$("input[name='name']").val("$i{name}") ; + ~ ; + } + + if ($i{region_id}) { + $trigger_jquery_raw .= qq~ + \$("#selectRegion_id").val("$i{region_id}").trigger("chosen:updated") ; + ~ ; + } else { + $trigger_jquery_raw .= qq~ + \$("#selectRegion_id").val(parent.\$("#selectRegion_id").val()).trigger("chosen:updated") ; + ~ ; + } + if ($i{aisa_client_id}) { + $trigger_jquery_raw .= qq~ + \$("#selectAisa_client_id").val("$i{aisa_client_id}").trigger("chosen:updated") ; + ~ ; + } else { + $trigger_jquery_raw .= qq~ + if (parent.\$("#selectClient_id").val()) { + let parent_client = parent.\$("#selectClient_id").val() ; + if (parent_client == null) { parent_client = "" ; } + parent_client = parent_client.toString() ; + parent_client = parent_client.split(":") ; + \$("#selectAisa_client_id").append("").trigger("chosen:updated") ; + \$("#selectAisa_client_id").val(parent_client[0]).trigger("chosen:updated") ; + } + ~ ; + } + + $trigger_jquery_raw .= qq~\$("#selectRegion_id").chosen({ allow_single_deselect:false });~ ; + + if ($home_or_away_team eq 'Home') { + $trigger_jquery_raw .= qq~ + \$("#selectAisa_client_id").chosen({ allow_single_deselect:false }); + ~ ; + } elsif ($home_or_away_team eq 'Away') { + $trigger_jquery_raw .= qq~ + \$("#selectAisa_client_id").chosen({ allow_single_deselect:true }); + ~ ; + } + + # &db_min_ro('teams',"DISTINCT aisa_client_id","aisa_client_id <> '0'",'','') ; + + # my $exclude_client_sql = join(" AND ", map{ "id != '$_'" } keys %{$db{teams}}) ; + &common_min_select_opts('region_id','regions','name') ; + &db_switch_conn('aisa') ; + # $opts{aisa_client_id} = qq~~ ; + &common_min_select_opts('aisa_client_id','customers','name','','','',"") ; + &db_switch_conn('sss') ; + $db{$table}{''}{sel_field} = $selectfield if $selectfield ; + +} #------------------------------------------------------------------------------------------ + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub screen1 { + + $trigger_jquery_raw .= qq~ + \$('#btn-close-customer').click( function (e) { + parent.BootstrapDialog.closeAll() ; + }); + ~ ; + + &common_min_dialog_load_screen ; + +} #------------------------------------------------------------------------------------------ + +sub screen2 { + + $trigger_jquery_raw = qq~ + + let parent_client = parent.\$("#selectClient_id").val() ; + if (parent_client == null) { parent_client = "" ; } + parent_client = parent_client.toString() ; + parent_client = parent_client.split(":") ; + + let home_or_away_team = "$home_or_away_team" ; + + for (let i = 1; i <= 100; i++) { + + if (!parent.\$("#fixtures_"+i).html()) { + break ; + } + + if ((!parent_client[0] && parent.\$("#selectRegion_id").val() == "$i{region_id}") || (parent_client[0] && parent_client[0] == "$i{aisa_client_id}") || (!parent_client[0] && !parent.\$("#selectRegion_id").val())) { + // parent.\$("#selectHome_team_fixtures_"+i).append("").trigger("chosen:updated") ; + // parent.\$("input[name='home_team_fixtures_"+i+"']").val("$i{id}") ; + // parent.\$("input[name='typeahead_home_team_fixtures_"+i+"']").val("$i{name}") ; + if (!parent.\$("input[name='changed_home_team_"+i+"']").val() && home_or_away_team == "Home") { + // parent.\$("#selectHome_team_fixtures_"+i).val("$i{id}").trigger("chosen:updated") ; + parent.\$("input[name='home_team_fixtures_"+i+"']").val("$i{id}") ; + parent.\$("input[name='typeahead_home_team_fixtures_"+i+"']").val("$i{name}") ; + } + } + + // if (parent.\$("#selectRegion_id").val() == "$i{region_id}") { + // parent.\$("#selectAway_team_fixtures_"+i).append("").trigger("chosen:updated") ; + + if (home_or_away_team == "Away") { + parent.\$("input[name='away_team_fixtures_"+i+"']").val("$i{id}") ; + parent.\$("input[name='typeahead_away_team_fixtures_"+i+"']").val("$i{name}") ; + } + // } + + } + + parent.BootstrapDialog.closeAll() ; + + ~ ; + + &common_min_dialog_save_screen ; + +} #------------------------------------------------------------------------------------------ + +use today ; +use dialog ; +use common ; + +1; \ No newline at end of file diff --git a/scripts/dialog/events.pl b/scripts/dialog/events.pl index 4fa59be..d873762 100644 --- a/scripts/dialog/events.pl +++ b/scripts/dialog/events.pl @@ -20,7 +20,9 @@ use POSIX; our $qid = $ARGV[0] ; our $qaction = $ARGV[1] ; -if ($qid eq 'event') { +our $event_or_analytics = ($qid eq 'event') ? "event" : ($qid eq 'analytics') ? "analytics" : "" ; + +if ($qid eq 'event' || $qid eq 'analytics') { $qid = $qaction ; $qaction = 'view' ; } @@ -518,84 +520,90 @@ sub view_form { $table = 'event_quotes' ; - # &db_min_ro($table,'quote_nr,nr,quote_date,customer,country_id,ref,date_from,date_to,qty,currency,grand_total,invoice_nr',"quote_nr='$id'",'','') ; - # &db_min_ro($table,'quote_nr,quote_date,country_id,ref,date_from,date_to,qty,currency,grand_total,invoice_nr',"quote_nr='$id'",'','') ; + if ($event_or_analytics eq 'event') { + + # &db_min_ro($table,'quote_nr,nr,quote_date,customer,country_id,ref,date_from,date_to,qty,currency,grand_total,invoice_nr',"quote_nr='$id'",'','') ; + # &db_min_ro($table,'quote_nr,quote_date,country_id,ref,date_from,date_to,qty,currency,grand_total,invoice_nr',"quote_nr='$id'",'','') ; - $sort_field{1} = 'quote_nr' ; - $sort_field{2} = 'ref' ; - $sort_field{3} = 'date_from' ; - $sort_field{4} = 'date_to' ; - $sort_field{5} = 'type_of_system' ; - $sort_field{6} = 'type_details' if $usertype ne 'schools_manager' ; - # $sort_field{7} = 'system_name' if $usertype ne 'schools_manager' ; - $sort_field{7} = 'system_details' if $usertype ne 'schools_manager' ; - # $sort_field{8} = 'club_name' ; - $sort_field{9} = 'days' ; - $sort_field{10} = 'operators' ; - $sort_field{11} = 'sport_type_ids' ; - $sort_field{12} = 'city' ; - $sort_field{13} = 'region' ; - $sort_field{14} = 'venue' ; + $sort_field{1} = 'quote_nr' ; + $sort_field{2} = 'ref' ; + $sort_field{3} = 'date_from' ; + $sort_field{4} = 'date_to' ; + $sort_field{5} = 'type_of_system' ; + $sort_field{6} = 'type_details' if $usertype ne 'schools_manager' ; + # $sort_field{7} = 'system_name' if $usertype ne 'schools_manager' ; + $sort_field{7} = 'system_details' if $usertype ne 'schools_manager' ; + # $sort_field{8} = 'club_name' ; + $sort_field{9} = 'days' ; + $sort_field{10} = 'operators' ; + $sort_field{11} = 'sport_type_ids' ; + $sort_field{12} = 'city' ; + $sort_field{13} = 'region' ; + $sort_field{14} = 'venue' ; + + # $sort_field{1} = 'quote_nr' ; + # $sort_field{2} = 'ref' ; + # $sort_field{3} = 'date_from' ; + # $sort_field{4} = 'date_to' ; + # $sort_field{5} = 'type' ; + # $sort_field{6} = 'sport_type_ids' ; + # # $sort_field{7} = 'ligr' ; + # $sort_field{8} = 'location' ; + # $sort_field{9} = 'city_id' ; + # $sort_field{10} = 'organisation_ids' ; + # # $sort_field{5} = 'country_id' ; + # $sort_field{11} = 'quote_to' ; + # $sort_field{12} = 'notes' ; + # $sort_field{13} = 'nr_of_casuals' ; + # $sort_field{14} = 'operator_names_type_a' ; + # $sort_field{15} = 'nr_of_casuals_2' ; + # $sort_field{16} = 'operator_names_type_b' ; - # $sort_field{1} = 'quote_nr' ; - # $sort_field{2} = 'ref' ; - # $sort_field{3} = 'date_from' ; - # $sort_field{4} = 'date_to' ; - # $sort_field{5} = 'type' ; - # $sort_field{6} = 'sport_type_ids' ; - # # $sort_field{7} = 'ligr' ; - # $sort_field{8} = 'location' ; - # $sort_field{9} = 'city_id' ; - # $sort_field{10} = 'organisation_ids' ; - # # $sort_field{5} = 'country_id' ; - # $sort_field{11} = 'quote_to' ; - # $sort_field{12} = 'notes' ; - # $sort_field{13} = 'nr_of_casuals' ; - # $sort_field{14} = 'operator_names_type_a' ; - # $sort_field{15} = 'nr_of_casuals_2' ; - # $sort_field{16} = 'operator_names_type_b' ; + $sort_field{17} = 'poc_name' ; + $sort_field{18} = 'poc_contact_nr' ; + $sort_field{19} = 'category_1' ; + $sort_field{20} = 'category_1_sub_categories' ; + $sort_field{21} = 'category_2' ; + $sort_field{22} = 'category_2_sub_categories' ; + $sort_field{23} = 'recipient_name' ; + $sort_field{24} = 'recipient_nr' ; + $sort_field{25} = 'additional_notes' ; + $sort_field{26} = 'format_of_title' ; + + $preferred_title{organisation_ids} = "Venue(s)" ; + $preferred_title{sport_type_ids} = "Sport Types(s)" ; + + foreach (sort {$a <=> $b} keys %sort_field) { push @sql_fields, $sort_field{$_} ; } + + for (1 .. $max_operators) { + push @sql_fields, "operator_$_\_workings_event" ; + } + + my $select = join(",", @sql_fields) ; + + &db_min_ro('event_quotes_poc','id,name,contact_nr','','','') ; + + &db_min_ro('event_quotes_categories','id,category','','','') ; + + &db_min_ro('event_systems','id,name,description','','','') ; + + &db_min_ro('sport_types','id,name','','','') ; + + &db_min_ro('regions','id,name','','','') ; + + &db_min_ro('cities','id,name','','','') ; + + &db_min_ro('organisations','id,name','','','') ; + + &db_min_ro('event_type_details','id,name','','','') ; - $sort_field{17} = 'poc_name' ; - $sort_field{18} = 'poc_contact_nr' ; - $sort_field{19} = 'category_1' ; - $sort_field{20} = 'category_1_sub_categories' ; - $sort_field{21} = 'category_2' ; - $sort_field{22} = 'category_2_sub_categories' ; - $sort_field{23} = 'recipient_name' ; - $sort_field{24} = 'recipient_nr' ; - $sort_field{25} = 'additional_notes' ; - $sort_field{26} = 'format_of_title' ; + # &db_min_ro($table,"$select,casual_worker,casual_worker_2,user_id","quote_nr='$id'",'','') ; - $preferred_title{organisation_ids} = "Venue(s)" ; - $preferred_title{sport_type_ids} = "Sport Types(s)" ; - - foreach (sort {$a <=> $b} keys %sort_field) { push @sql_fields, $sort_field{$_} ; } - - for (1 .. $max_operators) { - push @sql_fields, "operator_$_\_workings_event" ; } - my $select = join(",", @sql_fields) ; - - &db_min_ro('event_quotes_poc','id,name,contact_nr','','','') ; + my $analytics_sql_where = ($event_or_analytics eq 'event') ? "event_quote_id <> '0' AND event_quote_id = '$id'" : ($event_or_analytics eq 'analytics') ? "id= '$id'" : "" ; - &db_min_ro('event_quotes_categories','id,category','','','') ; - - &db_min_ro('event_systems','id,name,description','','','') ; - - &db_min_ro('sport_types','id,name','','','') ; - - &db_min_ro('regions','id,name','','','') ; - - &db_min_ro('cities','id,name','','','') ; - - &db_min_ro('organisations','id,name','','','') ; - - &db_min_ro('event_type_details','id,name','','','') ; - - # &db_min_ro($table,"$select,casual_worker,casual_worker_2,user_id","quote_nr='$id'",'','') ; - - &db_min_ro('analytics_event_bookings','id,event_quote_id,fixtures_saved_values,analytics_saved_values,start_date_time,sport_type_ids,event_name',"event_quote_id <> '0' AND event_quote_id = '$id'",'','') ; + &db_min_ro('analytics_event_bookings','id,event_quote_id,fixtures_saved_values,analytics_saved_values,start_date_time,end_date_time,sport_type_ids,event_name',"$analytics_sql_where",'','') ; &db_switch_conn('sss') ; @@ -614,14 +622,19 @@ sub view_form { my $analytics_required = 0 ; - foreach my $id (sort { $b <=> $a } keys %{$db{analytics_event_bookings}}) { + foreach my $aid (sort { $b <=> $a } keys %{$db{analytics_event_bookings}}) { + + if ($event_or_analytics eq 'analytics') { + $db{$table}{$id}{date_from} = $db{analytics_event_bookings}{$aid}{start_date_time} ; + $db{$table}{$id}{date_to} = $db{analytics_event_bookings}{$aid}{end_date_time} ; + } $analytics_event_exists = 1 ; # $analytics_event_exists = 0 ; # $db{analytics_event_bookings}{$id}{analytics_saved_values} = "" ; # $db{analytics_event_bookings}{$id}{fixtures_saved_values} = "" ; - $analytics_required = 1 if !$db{analytics_event_bookings}{$id}{analytics_saved_values} && !$db{analytics_event_bookings}{$id}{fixtures_saved_values} ; + $analytics_required = 1 if !$db{analytics_event_bookings}{$aid}{analytics_saved_values} && !$db{analytics_event_bookings}{$aid}{fixtures_saved_values} ; $sort_field{27} = 'fixture_date/Time_from' ; $sort_field{28} = 'sport' ; @@ -631,11 +644,11 @@ sub view_form { $sort_field{32} = 'stream_key' ; $sort_field{33} = 'stream_URL' ; - $db{analytics_event_bookings}{$id}{fixtures_saved_values} =~ s/\|+$// ; + $db{analytics_event_bookings}{$aid}{fixtures_saved_values} =~ s/\|+$// ; - $db{analytics_event_bookings}{$id}{fixtures_saved_values} = ";;;" unless $db{analytics_event_bookings}{$id}{fixtures_saved_values} ; + $db{analytics_event_bookings}{$aid}{fixtures_saved_values} = ";;;" unless $db{analytics_event_bookings}{$aid}{fixtures_saved_values} ; - @fixtures_saved_values = split(/\|/,$db{analytics_event_bookings}{$id}{fixtures_saved_values}) ; + @fixtures_saved_values = split(/\|/,$db{analytics_event_bookings}{$aid}{fixtures_saved_values}) ; my $fixtures_row_cnt = 0 ; @@ -643,29 +656,36 @@ sub view_form { my @abc = split(/\;/,$_) ; $fixtures_row_cnt++ ; - $analytics_saved_values{$id}{$fixtures_row_cnt}{$sort_field{27}} = ($abc[0]) ? &common_min_date_as_string($abc[0]) : ($db{analytics_event_bookings}{$id}{start_date_time}) ? &common_min_date_as_string($db{analytics_event_bookings}{$id}{start_date_time}) : &common_min_date_as_string("$now_year-$now_mm-$now_dd 08:00:00") ; - $analytics_saved_values{$id}{$fixtures_row_cnt}{$sort_field{28}} = ($abc[1]) ? $db{sport_types}{$abc[1]}{name} : ($db{analytics_event_bookings}{$id}{sport_type_ids} && $db{analytics_event_bookings}{$id}{sport_type_ids} !~ /;/) ? $db{sport_types}{$db{analytics_event_bookings}{$id}{sport_type_ids}}{name} : "N/A" ; - $analytics_saved_values{$id}{$fixtures_row_cnt}{$sort_field{29}} = ucfirst $abc[2] . ' ' . uc $abc[3] ; - $analytics_saved_values{$id}{$fixtures_row_cnt}{$sort_field{30}} = ($abc[4] && $abc[6]) ? $db{teams}{$abc[4]}{name} . ' vs ' . $db{teams}{$abc[6]}{name} : ($abc[4]) ? $db{teams}{$abc[4]}{name} . ' vs N/A' : ($abc[6]) ? 'N/A vs ' . $db{teams}{$abc[6]}{name} : "" ; + $analytics_saved_values{$aid}{$fixtures_row_cnt}{$sort_field{27}} = ($abc[0]) ? &common_min_date_as_string($abc[0]) : ($db{analytics_event_bookings}{$aid}{start_date_time}) ? &common_min_date_as_string($db{analytics_event_bookings}{$aid}{start_date_time}) : &common_min_date_as_string("$now_year-$now_mm-$now_dd 08:00:00") ; + $analytics_saved_values{$aid}{$fixtures_row_cnt}{$sort_field{28}} = ($abc[1]) ? $db{sport_types}{$abc[1]}{name} : ($db{analytics_event_bookings}{$aid}{sport_type_ids} && $db{analytics_event_bookings}{$aid}{sport_type_ids} !~ /;/) ? $db{sport_types}{$db{analytics_event_bookings}{$aid}{sport_type_ids}}{name} : "N/A" ; + $analytics_saved_values{$aid}{$fixtures_row_cnt}{$sort_field{29}} = ucfirst $abc[2] . ' ' . uc $abc[3] ; + $analytics_saved_values{$aid}{$fixtures_row_cnt}{$sort_field{30}} = ($abc[4] && $abc[6]) ? $db{teams}{$abc[4]}{name} . ' vs ' . $db{teams}{$abc[6]}{name} : ($abc[4]) ? $db{teams}{$abc[4]}{name} . ' vs N/A' : ($abc[6]) ? 'N/A vs ' . $db{teams}{$abc[6]}{name} : "" ; } - @analytics_saved_values_arr = split(/\|/,$db{analytics_event_bookings}{$id}{analytics_saved_values}) ; + @analytics_saved_values_arr = split(/\|/,$db{analytics_event_bookings}{$aid}{analytics_saved_values}) ; my $analytics_row_cnt = 0 ; foreach (@analytics_saved_values_arr) { my @abc = split(/\;/,$_) ; + + $abc[1] =~ s/\_semi_colon_character_/\;/g ; + $abc[1] =~ s/\_pipe_character_/\|/g ; + + $abc[2] =~ s/\_semi_colon_character_/\;/g ; + $abc[2] =~ s/\_pipe_character_/\|/g ; + $analytics_row_cnt++ ; - $analytics_saved_values{$id}{$analytics_row_cnt}{$sort_field{31}} = ($abc[0] eq '1') ? "Yes" : ($abc[0] eq "2") ? "No" : "" ; - $analytics_saved_values{$id}{$analytics_row_cnt}{$sort_field{32}} = $abc[1] ; - $analytics_saved_values{$id}{$analytics_row_cnt}{$sort_field{33}} = ($abc[2]) ? qq~Click Here~ : qq~~ ; + $analytics_saved_values{$aid}{$analytics_row_cnt}{$sort_field{31}} = ($abc[0] eq '1') ? "Yes" : ($abc[0] eq "2") ? "No" : "" ; + $analytics_saved_values{$aid}{$analytics_row_cnt}{$sort_field{32}} = $abc[1] ; + $analytics_saved_values{$aid}{$analytics_row_cnt}{$sort_field{33}} = ($abc[2]) ? qq~Click Here~ : qq~~ ; } if ($analytics_row_cnt > $fixtures_row_cnt) { for ($fixtures_row_cnt + 1 .. $analytics_row_cnt) { - $analytics_saved_values{$id}{$_}{$sort_field{27}} = ($db{analytics_event_bookings}{$id}{start_date_time}) ? &common_min_date_as_string($db{analytics_event_bookings}{$id}{start_date_time}) : &common_min_date_as_string("$now_year-$now_mm-$now_dd 08:00:00") ; - $analytics_saved_values{$id}{$_}{$sort_field{28}} = ($db{analytics_event_bookings}{$id}{sport_type_ids} && $db{analytics_event_bookings}{$id}{sport_type_ids} !~ /;/) ? $db{sport_types}{$db{analytics_event_bookings}{$id}{sport_type_ids}}{name} : "N/A" ; + $analytics_saved_values{$aid}{$_}{$sort_field{27}} = ($db{analytics_event_bookings}{$aid}{start_date_time}) ? &common_min_date_as_string($db{analytics_event_bookings}{$aid}{start_date_time}) : &common_min_date_as_string("$now_year-$now_mm-$now_dd 08:00:00") ; + $analytics_saved_values{$aid}{$_}{$sort_field{28}} = ($db{analytics_event_bookings}{$aid}{sport_type_ids} && $db{analytics_event_bookings}{$aid}{sport_type_ids} !~ /;/) ? $db{sport_types}{$db{analytics_event_bookings}{$aid}{sport_type_ids}}{name} : "N/A" ; } } @@ -756,192 +776,195 @@ sub view_form { } } } - - &db_min_ro($table,"*","quote_nr='$id'",'','') ; - if ($db{$table}{$id}{city_id} =~ /,/) { - $sort_field{12} = 'cities' ; - } else { - $sort_field{13} = '' ; - } - - &db_min_ro('event_quotes_min',"*","id='$id'",'','') ; + if ($event_or_analytics eq 'event') { - &db_min_ro('users','id,name,user_type,phone',"user_type LIKE 'casual%'",'','') ; - foreach (keys %{$db{users}}) { - $casual_name{$_} = $db{users}{$_}{name} ; - # my $casual_type = $db{users}{$_}{user_type} ; $casual_type =~ s/_casual//g ; - $casual_type{$_} = uc substr($db{users}{$_}{user_type},-1,1) ; - } - # %col_name = () ; - # &db_min_ro('countries','id,name',"id=$db{$table}{$id}{country_id}",'','') if $db{$table}{$id}{country_id} ; - # foreach (keys %{$db{countries}}) { $country{$_} = $db{countries}{$_}{name} ; } - %col_name = () ; - &db_min_ro('event_types','id,name',"id=$db{$table}{$id}{type}",'','') if $db{$table}{$id}{type} ; - foreach (keys %{$db{event_types}}) { $event_type{$_} = $db{event_types}{$_}{name} ; } - %col_name = () ; - &db_min_ro('customers','id,name',"id=$db{$table}{$id}{quote_to}",'','') if $db{$table}{$id}{quote_to} ; - foreach (keys %{$db{customers}}) { $customers{$_} = $db{customers}{$_}{name} ; } - %col_name = () ; - # &db_min_ro('events','id,event_quote_nr,category,user_id',"event_quote_nr='$id'",'','') ; - - # my $user_id = $db{$table}{$id}{user_id} ; - my $quote_nr = $db{$table}{$id}{quote_nr} ; - my $start = $db{$table}{$id}{date_from} ; - my $end = $db{$table}{$id}{date_to} ; - my $date_start = substr($start,0,10); - my $date_end = substr($end,0,10); - - # for (1 .. $max_operators) { - # local $field = "operator_$_\_workings_event" ; - # $op_id = $db{$table}{$id}{$field} ; - - my %selected_names = () ; - - # &common_debug("operator_workings_event : $db{event_quotes_min}{$id}{operator_workings_event} , id : $id") ; - - foreach my $op_id (split(";",$db{event_quotes_min}{$id}{operator_workings_event})) { - next unless $op_id ; - next if $done_op{$op_id}{$quote_nr} ; - $this_user_subscribed{$op_id} = 1 ; - $cat{$date_start}{$date_end}{$quote_nr}{$op_id} = 'assigned' ; - $ccnt{$date_start}{$date_end}{$casual_type{$op_id}}{$quote_nr}++ ; - $subscribed_names{$date_start}{$date_end}{$casual_type{$op_id}}{$quote_nr} .= "$casual_name{$op_id}, " ; - $done_op{$op_id}{$quote_nr} = 1 ; - # $selected_names{operator_names_type_a}{$op_id}{$id} = 'SELECTED' if $casual_type{$op_id} eq 'A' ; - # $selected_names{operator_names_type_b}{$op_id}{$id} = 'SELECTED' if $casual_type{$op_id} eq 'B' ; + &db_min_ro($table,"*","quote_nr='$id'",'','') ; - # &common_debug("op_id : $op_id , casual_type : $casual_type{$op_id} , id : $id") ; - - } - - &db_min_ro('events','id,event_quote_nr,category,user_id,startdate,enddate',"user_id='$userid' OR event_quote_nr='$id'",'','') ; - - # &db_min_ro('events','id,event_quote_nr,category,user_id,startdate,enddate',"(user_id='$userid' OR event_quote_nr='$id') AND startdate LIKE '$date_start%' AND enddate LIKE '$date_end%'",'','') ; - foreach (keys %{$db{events}}) { - my $start = $db{events}{$_}{startdate} ; my $edate_start = substr($start,0,10); - my $end = $db{events}{$_}{enddate} ; my $edate_end = substr($end,0,10); - $qnr = $db{events}{$_}{event_quote_nr} ; - $uid = $db{events}{$_}{user_id} ; - - if ($date_start ne $edate_start) { next ; } - if ($date_end ne $edate_end) { next ; } - - # $booked_this_one{$uid}{$qnr}{$db{events}{$_}{category}} = 1 ; - - $cat{$edate_start}{$edate_end}{$qnr}{$uid} = $db{events}{$_}{category} ; - # $ccnt{$edate_start}{$edate_end}{$casual_type{$uid}}{$qnr}++ if $cat{$edate_start}{$edate_end}{$qnr}{$uid} eq 'available' ; - # $subscribed_names{$edate_start}{$edate_end}{$casual_type{$uid}}{$qnr} .= "$casual_name{$uid}, " if $cat{$edate_start}{$edate_end}{$qnr}{$uid} eq 'available' ; - &check_dates_booked($qnr,$uid,$db{events}{$_}{startdate},$db{events}{$_}{enddate}) if $cat{$edate_start}{$edate_end}{$qnr}{$uid} eq 'available' ; - } - - my $casual_1_type = $db{$table}{$id}{casual_worker} ; - my $casual_2_type = $db{$table}{$id}{casual_worker_2} ; - - $preferred_title{date_from} = 'Date From' ; - $preferred_title{date_to} = 'Date To' ; - $preferred_title{quote_to} = 'Client' ; - $preferred_title{nr_of_casuals} = 'Nr of Operators' ; # . $casual_1_type ; - $preferred_title{nr_of_casuals_2} = 'Nr of Operators' ; # . $casual_2_type ; - $preferred_title{ref} = 'Event Name' ; - - $lcol = 2 ; $fcol = 8 ; - - # foreach (sort { $col_name{$a} cmp $col_name{$b} } keys %col_name) { - # $col = $col_name{$_} ; - - my $casuals_1_subscribed = sprintf("%0.0f",$ccnt{$date_start}{$date_end}{$casual_1_type}{$id}) ; - my $casuals_2_subscribed = sprintf("%0.0f",$ccnt{$date_start}{$date_end}{$casual_2_type}{$id}) ; - chop $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} ; chop $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} ; - chop $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} ; chop $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} ; - my $casual_1_names_subscribed = '[' . $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} . ']' if $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} ; - my $casual_2_names_subscribed = '[' . $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} . ']' if $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} ; - - # my $operator_id = 0 ; - # my %selected_names = () ; - # for (1 .. $max_operators) { - # $operator_id = $db{$table}{$id}{"operator_$_\_workings_event"} ; - # $selected_names{operator_names_type_a}{$operator_id}{$id} = 'SELECTED' if $operator_id and $casual_type{$operator_id} eq 'A' ; - # $selected_names{operator_names_type_b}{$operator_id}{$id} = 'SELECTED' if $operator_id and $casual_type{$operator_id} eq 'B' ; - # } - # $selected_names{operator_names_type_a}{48}{$id} = 'SELECTED' ; - - foreach my $casual_id (keys %casual_name){ - $opts{operator_names_type_a} .= qq() if $casual_type{$casual_id} eq 'A' ; - $opts{operator_names_type_b} .= qq() if $casual_type{$casual_id} eq 'B' ; - } - - my @club_ids_arr = () ; - foreach (split(";",$db{$table}{$id}{club_ids})) { - push @club_ids_arr , "`id` = '$_'" if $_ ; - } - my $club_ids_sql = join(" OR ",@club_ids_arr) ; - $club_ids_sql = "($club_ids_sql)" if $club_ids_sql ; - - &db_min_ro('clubs','id,name',"$club_ids_sql",'',''); - - if ($date_start eq $date_end) { - $sort_field{3} = 'date' ; - $sort_field{4} = '' ; - $preferred_title{date_from} = 'Date' ; - } - - my @times_from = split(/\;/,$db{$table}{$id}{times_from}) ; - my @times_to = split(/\;/,$db{$table}{$id}{times_to}) ; - my @times_from_com = () ; my @times_to_com = () ; - push @times_from_com,substr($db{$table}{$id}{date_from},11) ; - - my @days_active = split(/\;/,$db{$table}{$id}{days_active}) ; - - my %dates_hash = () ; - - for (1 .. 10) { - my ($year,$month,$day) = split(/\-/,substr($db{$table}{$id}{date_from},0,10)) ; - my ($new_year,$new_month,$new_day) = Add_Delta_Days($year,$month,$day,$_-1) ; - $new_day = sprintf("%02s",$new_day) ; $new_month = sprintf("%02s",$new_month) ; - $dates_hash{$_} = "$new_year-$new_month-$new_day" ; - push @times_from_com,$times_from[$_-2] if $times_from[$_-2] && $_ > 1 ; - push @times_from_com,substr($db{$table}{$id}{date_from},11) if !$times_from[$_-2] && $_ > 1 ; - last if substr($db{$table}{$id}{date_to},0,10) eq "$new_year-$new_month-$new_day" ; - push @times_to_com,$times_to[$_-1] if $times_to[$_-1] ; - push @times_to_com,substr($db{$table}{$id}{date_to},11) if !$times_to[$_-1] ; - } - - my $system_count = 0 ; my $system_day_cnt = 0 ; my %system_has_daily_op = () ; - - foreach my $system_row (split(/\|/,$db{$table}{$id}{daily_operator_ids})) { - $system_count++ ; - next unless $system_row ; - $system_day_cnt = 0 ; - foreach my $col (split(/\;/,$system_row)) { - $system_day_cnt++ ; - next unless $col ; - $default_op_ids{$system_count}{$system_day_cnt} = $col if $col ; - $system_daily_ops{$system_count} .= qq~Day $system_day_cnt : $db{users}{$col}{name}, ~ if $col ; + if ($db{$table}{$id}{city_id} =~ /,/) { + $sort_field{12} = 'cities' ; + } else { + $sort_field{13} = '' ; } - chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ; - chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ; - } - $system_count = 0 ; + + &db_min_ro('event_quotes_min',"*","id='$id'",'','') ; + + &db_min_ro('users','id,name,user_type,phone',"user_type LIKE 'casual%'",'','') ; + foreach (keys %{$db{users}}) { + $casual_name{$_} = $db{users}{$_}{name} ; + # my $casual_type = $db{users}{$_}{user_type} ; $casual_type =~ s/_casual//g ; + $casual_type{$_} = uc substr($db{users}{$_}{user_type},-1,1) ; + } + # %col_name = () ; + # &db_min_ro('countries','id,name',"id=$db{$table}{$id}{country_id}",'','') if $db{$table}{$id}{country_id} ; + # foreach (keys %{$db{countries}}) { $country{$_} = $db{countries}{$_}{name} ; } + %col_name = () ; + &db_min_ro('event_types','id,name',"id=$db{$table}{$id}{type}",'','') if $db{$table}{$id}{type} ; + foreach (keys %{$db{event_types}}) { $event_type{$_} = $db{event_types}{$_}{name} ; } + %col_name = () ; + &db_min_ro('customers','id,name',"id=$db{$table}{$id}{quote_to}",'','') if $db{$table}{$id}{quote_to} ; + foreach (keys %{$db{customers}}) { $customers{$_} = $db{customers}{$_}{name} ; } + %col_name = () ; + # &db_min_ro('events','id,event_quote_nr,category,user_id',"event_quote_nr='$id'",'','') ; + + # my $user_id = $db{$table}{$id}{user_id} ; + my $quote_nr = $db{$table}{$id}{quote_nr} ; + my $start = $db{$table}{$id}{date_from} ; + my $end = $db{$table}{$id}{date_to} ; + my $date_start = substr($start,0,10); + my $date_end = substr($end,0,10); - # push @times_to_com, substr($db{$table}{$id}{date_to},11) ; - - # my $system_count = 0 ; my $system_day_cnt = 0 ; my %system_has_daily_op = () ; + # for (1 .. $max_operators) { + # local $field = "operator_$_\_workings_event" ; + # $op_id = $db{$table}{$id}{$field} ; - # foreach my $system_row (split(/\|/,$db{$table}{$id}{daily_operator_ids})) { - # $system_count++ ; - # next unless $system_row ; - # $system_day_cnt = 0 ; - # foreach my $col (split(/\;/,$system_row)) { - # $system_day_cnt++ ; - # next unless $col ; - # $default_op_ids{$system_count}{$system_day_cnt} = $col if $col ; - # $system_daily_ops{$system_count} .= qq~Day $system_day_cnt : $db{users}{$col}{name}, ~ if $col ; + my %selected_names = () ; + + # &common_debug("operator_workings_event : $db{event_quotes_min}{$id}{operator_workings_event} , id : $id") ; + + foreach my $op_id (split(";",$db{event_quotes_min}{$id}{operator_workings_event})) { + next unless $op_id ; + next if $done_op{$op_id}{$quote_nr} ; + $this_user_subscribed{$op_id} = 1 ; + $cat{$date_start}{$date_end}{$quote_nr}{$op_id} = 'assigned' ; + $ccnt{$date_start}{$date_end}{$casual_type{$op_id}}{$quote_nr}++ ; + $subscribed_names{$date_start}{$date_end}{$casual_type{$op_id}}{$quote_nr} .= "$casual_name{$op_id}, " ; + $done_op{$op_id}{$quote_nr} = 1 ; + # $selected_names{operator_names_type_a}{$op_id}{$id} = 'SELECTED' if $casual_type{$op_id} eq 'A' ; + # $selected_names{operator_names_type_b}{$op_id}{$id} = 'SELECTED' if $casual_type{$op_id} eq 'B' ; + + # &common_debug("op_id : $op_id , casual_type : $casual_type{$op_id} , id : $id") ; + + } + + &db_min_ro('events','id,event_quote_nr,category,user_id,startdate,enddate',"user_id='$userid' OR event_quote_nr='$id'",'','') ; + + # &db_min_ro('events','id,event_quote_nr,category,user_id,startdate,enddate',"(user_id='$userid' OR event_quote_nr='$id') AND startdate LIKE '$date_start%' AND enddate LIKE '$date_end%'",'','') ; + foreach (keys %{$db{events}}) { + my $start = $db{events}{$_}{startdate} ; my $edate_start = substr($start,0,10); + my $end = $db{events}{$_}{enddate} ; my $edate_end = substr($end,0,10); + $qnr = $db{events}{$_}{event_quote_nr} ; + $uid = $db{events}{$_}{user_id} ; + + if ($date_start ne $edate_start) { next ; } + if ($date_end ne $edate_end) { next ; } + + # $booked_this_one{$uid}{$qnr}{$db{events}{$_}{category}} = 1 ; + + $cat{$edate_start}{$edate_end}{$qnr}{$uid} = $db{events}{$_}{category} ; + # $ccnt{$edate_start}{$edate_end}{$casual_type{$uid}}{$qnr}++ if $cat{$edate_start}{$edate_end}{$qnr}{$uid} eq 'available' ; + # $subscribed_names{$edate_start}{$edate_end}{$casual_type{$uid}}{$qnr} .= "$casual_name{$uid}, " if $cat{$edate_start}{$edate_end}{$qnr}{$uid} eq 'available' ; + &check_dates_booked($qnr,$uid,$db{events}{$_}{startdate},$db{events}{$_}{enddate}) if $cat{$edate_start}{$edate_end}{$qnr}{$uid} eq 'available' ; + } + + my $casual_1_type = $db{$table}{$id}{casual_worker} ; + my $casual_2_type = $db{$table}{$id}{casual_worker_2} ; + + $preferred_title{date_from} = 'Date From' ; + $preferred_title{date_to} = 'Date To' ; + $preferred_title{quote_to} = 'Client' ; + $preferred_title{nr_of_casuals} = 'Nr of Operators' ; # . $casual_1_type ; + $preferred_title{nr_of_casuals_2} = 'Nr of Operators' ; # . $casual_2_type ; + $preferred_title{ref} = 'Event Name' ; + + $lcol = 2 ; $fcol = 8 ; + + # foreach (sort { $col_name{$a} cmp $col_name{$b} } keys %col_name) { + # $col = $col_name{$_} ; + + my $casuals_1_subscribed = sprintf("%0.0f",$ccnt{$date_start}{$date_end}{$casual_1_type}{$id}) ; + my $casuals_2_subscribed = sprintf("%0.0f",$ccnt{$date_start}{$date_end}{$casual_2_type}{$id}) ; + chop $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} ; chop $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} ; + chop $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} ; chop $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} ; + my $casual_1_names_subscribed = '[' . $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} . ']' if $subscribed_names{$date_start}{$date_end}{$casual_1_type}{$id} ; + my $casual_2_names_subscribed = '[' . $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} . ']' if $subscribed_names{$date_start}{$date_end}{$casual_2_type}{$id} ; + + # my $operator_id = 0 ; + # my %selected_names = () ; + # for (1 .. $max_operators) { + # $operator_id = $db{$table}{$id}{"operator_$_\_workings_event"} ; + # $selected_names{operator_names_type_a}{$operator_id}{$id} = 'SELECTED' if $operator_id and $casual_type{$operator_id} eq 'A' ; + # $selected_names{operator_names_type_b}{$operator_id}{$id} = 'SELECTED' if $operator_id and $casual_type{$operator_id} eq 'B' ; # } - # chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ; - # chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ; - # } - # $system_count = 0 ; + # $selected_names{operator_names_type_a}{48}{$id} = 'SELECTED' ; + + foreach my $casual_id (keys %casual_name){ + $opts{operator_names_type_a} .= qq() if $casual_type{$casual_id} eq 'A' ; + $opts{operator_names_type_b} .= qq() if $casual_type{$casual_id} eq 'B' ; + } + + my @club_ids_arr = () ; + foreach (split(";",$db{$table}{$id}{club_ids})) { + push @club_ids_arr , "`id` = '$_'" if $_ ; + } + my $club_ids_sql = join(" OR ",@club_ids_arr) ; + $club_ids_sql = "($club_ids_sql)" if $club_ids_sql ; + + &db_min_ro('clubs','id,name',"$club_ids_sql",'',''); + + if ($date_start eq $date_end) { + $sort_field{3} = 'date' ; + $sort_field{4} = '' ; + $preferred_title{date_from} = 'Date' ; + } + + my @times_from = split(/\;/,$db{$table}{$id}{times_from}) ; + my @times_to = split(/\;/,$db{$table}{$id}{times_to}) ; + my @times_from_com = () ; my @times_to_com = () ; + push @times_from_com,substr($db{$table}{$id}{date_from},11) ; + + my @days_active = split(/\;/,$db{$table}{$id}{days_active}) ; + + my %dates_hash = () ; + + for (1 .. 10) { + my ($year,$month,$day) = split(/\-/,substr($db{$table}{$id}{date_from},0,10)) ; + my ($new_year,$new_month,$new_day) = Add_Delta_Days($year,$month,$day,$_-1) ; + $new_day = sprintf("%02s",$new_day) ; $new_month = sprintf("%02s",$new_month) ; + $dates_hash{$_} = "$new_year-$new_month-$new_day" ; + push @times_from_com,$times_from[$_-2] if $times_from[$_-2] && $_ > 1 ; + push @times_from_com,substr($db{$table}{$id}{date_from},11) if !$times_from[$_-2] && $_ > 1 ; + last if substr($db{$table}{$id}{date_to},0,10) eq "$new_year-$new_month-$new_day" ; + push @times_to_com,$times_to[$_-1] if $times_to[$_-1] ; + push @times_to_com,substr($db{$table}{$id}{date_to},11) if !$times_to[$_-1] ; + } + + my $system_count = 0 ; my $system_day_cnt = 0 ; my %system_has_daily_op = () ; + + foreach my $system_row (split(/\|/,$db{$table}{$id}{daily_operator_ids})) { + $system_count++ ; + next unless $system_row ; + $system_day_cnt = 0 ; + foreach my $col (split(/\;/,$system_row)) { + $system_day_cnt++ ; + next unless $col ; + $default_op_ids{$system_count}{$system_day_cnt} = $col if $col ; + $system_daily_ops{$system_count} .= qq~Day $system_day_cnt : $db{users}{$col}{name}, ~ if $col ; + } + chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ; + chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ; + } + $system_count = 0 ; + + # push @times_to_com, substr($db{$table}{$id}{date_to},11) ; + + # my $system_count = 0 ; my $system_day_cnt = 0 ; my %system_has_daily_op = () ; + + # foreach my $system_row (split(/\|/,$db{$table}{$id}{daily_operator_ids})) { + # $system_count++ ; + # next unless $system_row ; + # $system_day_cnt = 0 ; + # foreach my $col (split(/\;/,$system_row)) { + # $system_day_cnt++ ; + # next unless $col ; + # $default_op_ids{$system_count}{$system_day_cnt} = $col if $col ; + # $system_daily_ops{$system_count} .= qq~Day $system_day_cnt : $db{users}{$col}{name}, ~ if $col ; + # } + # chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ; + # chop $system_daily_ops{$system_count} if $system_daily_ops{$system_count} ; + # } + # $system_count = 0 ; + } foreach my $cnt (sort {$a <=> $b} keys %sort_field) { @@ -1309,17 +1332,19 @@ sub view_form { our $files_attach = qq~~ ; + my $pdf_tooltip_extra = ($event_or_analytics eq 'analytics') ? "ANALYTICS EVENT" : "EVENT" ; + my $pdf_tooltip_extra2 = ($event_or_analytics eq 'analytics') ? "Analytics Event" : "Event" ; $files_attach .= qq~ ~ if $glod_user_level > 1 ; - + for (1 .. 3) { $working_uploads = &get_event_uploads($qid,"upload_$_",'id') ; @@ -1768,7 +1793,22 @@ $trigger_jquery_raw .= qq(\$("#savebutt").click(function() { &common_min_footer('id','') ; &common_min_dialog ; - + +my $events_table_body = ($event_or_analytics eq 'event') ? qq~ +
    +
    +
    +
    +

    $boxtitle Event

    +
    +
    + $print_box_content_rows +
    +
    +
    +
    +~ : qq~~ ; + print <
    -
    -
    -
    -
    -

    $boxtitle Event

    -
    -
    - $print_box_content_rows -
    -
    -
    -
    + $events_table_body $analytics_table_body
    diff --git a/scripts/dialog/import_analytics_fixtures.pl b/scripts/dialog/import_analytics_fixtures.pl index bbc460e..0e53e94 100644 --- a/scripts/dialog/import_analytics_fixtures.pl +++ b/scripts/dialog/import_analytics_fixtures.pl @@ -78,12 +78,14 @@ sub read_import { my $file_total_amnt = 0 ; my $file_nr_of_rows = 0 ; our %coding_type = ("s" => "Standard","p" => "Premium") ; - our %footage_type = ("s" => "SSS","r" => "Raw") ; + # our %footage_type = ("s" => "SSS","r" => "Raw") ; + our %footage_type = ("s" => "Pixellot","r" => "YouTube") ; our %coding_type2 = ("standard" => "s","premium" => "p") ; - our %footage_type2 = ("sss" => "s","raw" => "r") ; + our %footage_type2 = ("sss" => "s","raw" => "r","pixellot" => "s","youtube" => "r") ; + our %service_type2 = ("live coding" => 1,"individual 48 hrs" => 2,"post coding 24 hrs" => 3) ; - our %fixtures_input_vals = () ; + our %fixtures_input_vals = () ; our %fixtures_input_vals_2 = () ; our $suffix = "fixtures" ; @@ -179,13 +181,15 @@ sub read_import { my %seen_row = () ; - for my $col_cnt (1 .. 12) { + for my $col_cnt (1 .. 13) { my $val = $def_split[$col_cnt - 1] ; next if !$val || $val =~ /Analytics-Fixtures/ + || $val =~ /Analytics Fixtures/ || $val =~ /Fixture Date/ + || $val =~ /Fixtures Date/ || $val =~ /Time From/ || $val =~ /Sport/ || $val =~ /Team/ @@ -193,10 +197,14 @@ sub read_import { || $val =~ /Away Team/ || $val =~ /Coding Type/ || $val =~ /Footage Type/ + || $val =~ /Service Type/ || $val =~ /Age Group/ || $val =~ /Stream Forwarding/ || $val =~ /Stream Key/ || $val =~ /Stream URL/ + || $val =~ /Stream url/ + || $val =~ /Stream Url/ + || $val =~ /Cant Charge Client/ ; $table_row_cnt++ unless $seen_row{$row_cnt} ; @@ -209,6 +217,7 @@ sub read_import { } elsif ($col_cnt == 3 || $col_cnt == 4) { $val = lc $val ; } elsif ($col_cnt == 5 || $col_cnt == 7) { + $fixtures_input_vals_2{$table_row_cnt}{$col_cnt} = $val if $val; $val = $team_name_to_id{lc $val} ; } elsif ($col_cnt == 6) { $val = $analytics_ht_colors_name_to_id{lc $val} ; @@ -216,10 +225,15 @@ sub read_import { $val = $coding_type2{lc $val} ; } elsif ($col_cnt == 9) { $val = $footage_type2{lc $val} ; - } elsif ($col_cnt == 10) { + } elsif ($col_cnt == 10) { + $val = $service_type2{lc $val} ; + } elsif ($col_cnt == 11) { $val = (lc $val eq 'yes') ? 1 : (lc $val eq 'no') ? 2 : 0 ; - } - + } elsif ($col_cnt == 12 || $col_cnt == 13) { + $val =~ s/_x000D_//g ; + $val = join("_new_line_character_", map {"$_"} split("\n",$val)) ; + } + $fixtures_input_vals{$table_row_cnt}{$col_cnt} = $val if $val; } @@ -228,36 +242,55 @@ sub read_import { } - our %col_cnt_field_id = () ; + our %col_cnt_field_id = () ; our %col_cnt_field_id_2 = () ; - $col_cnt_field_id{1} = "datetimepickerStart_date_time_fixtures_" ; - $col_cnt_field_id{2} = "selectReadonly_sport_fixtures_" ; - $col_cnt_field_id{3} = "selectAge_group_fixtures_" ; - $col_cnt_field_id{4} = "selectTeam_fixtures_" ; - $col_cnt_field_id{5} = "selectHome_team_fixtures_" ; - $col_cnt_field_id{6} = "selectHt_colour_fixtures_" ; - $col_cnt_field_id{7} = "selectAway_team_fixtures_" ; - $col_cnt_field_id{8} = "selectCoding_type_fixtures_" ; - $col_cnt_field_id{9} = "selectFootage_type_fixtures_" ; - $col_cnt_field_id{10} = "selectStream_forwarding_fixtures_" ; - $col_cnt_field_id{11} = "textareaStream_key_fixtures_" ; - $col_cnt_field_id{12} = "textareaStream_URL_fixtures_" ; + $col_cnt_field_id{1} = "datetimepickerStart_date_time_fixtures_" ; + $col_cnt_field_id{2} = "selectReadonly_sport_fixtures_" ; + $col_cnt_field_id{3} = "selectAge_group_fixtures_" ; + $col_cnt_field_id{4} = "selectTeam_fixtures_" ; + $col_cnt_field_id{5} = "input[name='home_team_fixtures_" ; + $col_cnt_field_id_2{5} = "input[name='typeahead_home_team_fixtures_" ; + $col_cnt_field_id{6} = "selectHt_colour_fixtures_" ; + $col_cnt_field_id{7} = "input[name='away_team_fixtures_" ; + $col_cnt_field_id_2{7} = "input[name='typeahead_away_team_fixtures_" ; + $col_cnt_field_id{8} = "selectCoding_type_fixtures_" ; + $col_cnt_field_id{9} = "selectFootage_type_fixtures_" ; + $col_cnt_field_id{10} = "selectService_type_fixtures_" ; + $col_cnt_field_id{11} = "selectStream_forwarding_fixtures_" ; + $col_cnt_field_id{12} = "textareaStream_key_fixtures_" ; + $col_cnt_field_id{13} = "textareaStream_URL_fixtures_" ; - our $col_cnt_field_id_str = qq~~ ; + our $col_cnt_field_id_str = qq~~ ; our $col_cnt_field_id_str_2 = qq~~ ; - our $col_cnt_field_id_str2 = qq~"10":"selectStream_forwarding_analytics_","11":"textareaStream_key_analytics_","12":"textareaStream_URL_analytics_"~ ; + our $col_cnt_field_id_str2 = qq~"11":"selectStream_forwarding_analytics_","12":"textareaStream_key_analytics_","13":"textareaStream_URL_analytics_"~ ; foreach (keys %col_cnt_field_id) { $col_cnt_field_id_str .= qq~"$_":"$col_cnt_field_id{$_}",~ ; } - chop $col_cnt_field_id_str ; + $col_cnt_field_id_str =~ s/\,+$//g ; + + foreach (keys %col_cnt_field_id_2) { + $col_cnt_field_id_str_2 .= qq~"$_":"$col_cnt_field_id_2{$_}",~ ; + } + $col_cnt_field_id_str_2 =~ s/\,+$//g ; our $max_row_cnt = 0 ; - our $fixtures_input_vals_str = qq~~ ; + our $fixtures_input_vals_str = qq~~ ; + our $fixtures_input_vals_str_2 = qq~~ ; our %add_select_options = () ; + foreach my $row_cnt (sort {$a <=> $b} keys %fixtures_input_vals_2) { + $fixtures_input_vals_str_2 .= qq~"$row_cnt":{~ ; + foreach my $col_cnt (sort {$a <=> $b} keys %{$fixtures_input_vals_2{$row_cnt}}) { + $fixtures_input_vals_str_2 .= qq~"$col_cnt":"$fixtures_input_vals_2{$row_cnt}{$col_cnt}",~ ; + } + $fixtures_input_vals_str_2 =~ s/\,+$//g ; + $fixtures_input_vals_str_2 .= qq~},~ ; + } + $fixtures_input_vals_str_2 =~ s/\,+$//g ; + foreach my $row_cnt (sort {$a <=> $b} keys %fixtures_input_vals) { $max_row_cnt = $row_cnt if !$max_row_cnt || $row_cnt > $max_row_cnt ; @@ -267,19 +300,23 @@ sub read_import { if ($col_cnt == 2) { $add_select_options{selectReadonly_sport_fixtures}{$fixtures_input_vals{$row_cnt}{$col_cnt}} = $db{sport_types}{$fixtures_input_vals{$row_cnt}{$col_cnt}}{name} ; } elsif ($col_cnt == 5) { - $add_select_options{selectHome_team_fixtures}{$fixtures_input_vals{$row_cnt}{$col_cnt}} = $db{teams}{$fixtures_input_vals{$row_cnt}{$col_cnt}}{name} ; + # $add_select_options{selectHome_team_fixtures}{$fixtures_input_vals{$row_cnt}{$col_cnt}} = $db{teams}{$fixtures_input_vals{$row_cnt}{$col_cnt}}{name} ; } elsif ($col_cnt == 7) { - $add_select_options{selectAway_team_fixtures}{$fixtures_input_vals{$row_cnt}{$col_cnt}} = $db{teams}{$fixtures_input_vals{$row_cnt}{$col_cnt}}{name} ; - } elsif ($col_cnt == 10) { + # $add_select_options{selectAway_team_fixtures}{$fixtures_input_vals{$row_cnt}{$col_cnt}} = $db{teams}{$fixtures_input_vals{$row_cnt}{$col_cnt}}{name} ; + } elsif ($col_cnt == 11) { } } - chop $fixtures_input_vals_str ; + $fixtures_input_vals_str =~ s/\,+$//g ; $fixtures_input_vals_str .= qq~},~ ; } - - chop $fixtures_input_vals_str ; + $fixtures_input_vals_str =~ s/\,+$//g ; + + $fixtures_input_vals_str =~ s/\R\z// ; # Removes any line-ending character (\n, \r\n, or \r) + + # print "\n fixtures_input_vals_str : $fixtures_input_vals_str" ; + return unless $max_row_cnt ; } #------------------------------------------------------------------------------------------ @@ -357,8 +394,8 @@ exit ; } #------------------------------------------------------------------------------------------ sub screen2 { - - $trigger_jquery_raw .= qq~let value_exists ;~ ; + + $trigger_jquery_raw .= qq~let value_exists ; ~ ; my $sport_options = qq~~ ; foreach (keys %{$add_select_options{selectReadonly_sport_fixtures}}) { @@ -369,12 +406,14 @@ sub screen2 { foreach my $field (keys %add_select_options) { my %seen_value = () ; - $trigger_jquery_raw .= qq~parent.\$("#selectSport_type_ids").val([$sport_options]).trigger("chosen:updated") ;~ if $field eq "selectReadonly_sport_fixtures" && $sport_options ; + $trigger_jquery_raw .= qq~ + parent.\$("#selectSport_type_ids").val([$sport_options]).trigger("chosen:updated") ; + ~ if $field eq "selectReadonly_sport_fixtures" && $sport_options ; foreach my $value (keys %{$add_select_options{$field}}) { $trigger_jquery_raw .= qq~ - value_exists = \$("#$field"+"_1 option[value='$value']").length > 0 ; + value_exists = parent.\$("#$field"+"_1 option[value='$value']").length > 0 ; if (!value_exists) { parent.\$("#$field"+"_1").append("").trigger("chosen:updated") ; for (let k = 2; k <= 100; k++) { @@ -388,12 +427,16 @@ sub screen2 { } } - + # let fixtures_input_vals = {$fixtures_input_vals_str} ; $trigger_jquery_raw .= qq~ let col_cnt_field_id = {$col_cnt_field_id_str} ; + let col_cnt_field_id_2 = {$col_cnt_field_id_str_2} ; let col_cnt_field_id2 = {$col_cnt_field_id_str2} ; + let fixtures_input_vals = {$fixtures_input_vals_str} ; + let fixtures_input_vals_2 = {$fixtures_input_vals_str_2} ; + let max_row_cnt = parseInt("$max_row_cnt") ; let default_val ; let earliest_date ; let latest_date ; @@ -403,7 +446,7 @@ sub screen2 { } for (let j = 1; j <= max_row_cnt; j++) { - + if (!parent.\$("#fixtures_"+j).html()) { add_row(j) ; } else if (parent.\$("#fixtures_"+j).css("display") === "none" && parent.\$("#fixtures_"+j).html()) { @@ -436,16 +479,45 @@ sub screen2 { parent.\$("input[name='changed_home_team_"+j+"']").val("") ; } - for (let col_cnt = 2; col_cnt <= 9; col_cnt++) { - if (fixtures_input_vals[j][col_cnt]) { - parent.\$("#"+col_cnt_field_id[col_cnt]+""+j).val(fixtures_input_vals[j][col_cnt]).trigger("chosen:updated"); + for (let col_cnt = 2; col_cnt <= 10; col_cnt++) { + + if (col_cnt == 5 || col_cnt == 7) { + continue ; } - } - for (let col_cnt = 10; col_cnt <= 12; col_cnt++) { + if (fixtures_input_vals[j][col_cnt]) { - parent.\$("#"+col_cnt_field_id[col_cnt]+""+j).val(fixtures_input_vals[j][col_cnt]).trigger("chosen:updated"); + parent.\$("#"+col_cnt_field_id[col_cnt]+""+j).val(fixtures_input_vals[j][col_cnt]).trigger("chosen:updated") ; + } + + } + + for (let col_cnt = 2; col_cnt <= 10; col_cnt++) { + + if (col_cnt != 5 && col_cnt != 7) { + continue ; + } + + let input_name = col_cnt_field_id[col_cnt] ; + + if (fixtures_input_vals[j][col_cnt]) { + parent.\$(input_name+""+j+"']").val(fixtures_input_vals[j][col_cnt]) ; + } + + input_name = col_cnt_field_id_2[col_cnt] ; + + if (fixtures_input_vals_2[j][col_cnt]) { + parent.\$(input_name+""+j+"']").val(fixtures_input_vals_2[j][col_cnt]) ; + } + + } + + for (let col_cnt = 11; col_cnt <= 13; col_cnt++) { + if (fixtures_input_vals[j][col_cnt]) { + let input_val = fixtures_input_vals[j][col_cnt] ; + input_val = input_val.replaceAll("_new_line_character_","\\n") ; + parent.\$("#"+col_cnt_field_id[col_cnt]+""+j).val(input_val).trigger("chosen:updated") ; if (parent.\$("#analytics_"+j).html()) { - parent.\$("#"+col_cnt_field_id2[col_cnt]+""+j).val(fixtures_input_vals[j][col_cnt]).trigger("chosen:updated"); + parent.\$("#"+col_cnt_field_id2[col_cnt]+""+j).val(input_val).trigger("chosen:updated") ; } } } @@ -505,40 +577,52 @@ sub screen2 { $trigger_jquery_raw .= qq~ function add_row (i) { - + + parent.\$("input[name='home_team_fixtures_1']").after("") ; + parent.\$("input[name='away_team_fixtures_1']").after("") ; + let html = "
    " ; - html += "" ; - html += "" ; - - html += "
    " ; - - html += add_datetimepicker(i,"start_date_time_$suffix",1,6,\$("input[name='start_date_time']").val()) ; - html += add_select(i,"readonly_sport_$suffix\_" + i, "selectReadonly_sport_$suffix\_" + i, "Select Sport "+i, "", 2, 4, 100, "", "") ; - html += "" ; - html += add_select(i,"age_group_$suffix\_" + i,"selectAge_group_$suffix\_" + i,"Select Age Group "+i,"",3,2,100,"","") ; - - html += "
    " ; - - html += "
    " ; - - html += add_select(i,"team_$suffix\_" + i, "selectTeam_$suffix\_" + i, "Select Team "+i, "", 4, 1, 100, "", "") ; - html += add_select(i,"home_team_$suffix\_" + i, "selectHome_team_$suffix\_" + i, "Select Home Team "+i, "", 5, 3, 100, "", "") ; - html += add_select(i,"ht_colour_$suffix\_" + i, "selectHt_colour_$suffix\_" + i, "Select Ht Colour "+i, "", 6, 2, 100, "", "") ; - html += add_select(i,"away_team_$suffix\_" + i, "selectAway_team_$suffix\_" + i, "Select Away Team "+i, "", 7, 3, 100, "", "") ; - html += add_select(i,"coding_type_$suffix\_" + i, "selectCoding_type_$suffix\_" + i, "Select Coding Type "+i,"", 8, 2, 100, "", "") ; - html += add_select(i,"footage_type_$suffix\_" + i, "selectFootage_type_$suffix\_" + i, "Select Footage Type "+i, "", 9, 1, 100, "", "") ; + html += "" ; + html += "" ; - html += "
    " ; - - html += add_select(i,"stream_forwarding_$suffix\_" + i, "selectStream_forwarding_$suffix\_" + i, "Select Stream Forwarding "+i,"", 10, 1, 100, "", "") ; - html += add_textarea (i,"stream_key_$suffix\_"+i,"textareaStream_key_$suffix\_"+i,"Stream Key "+i,11,"",1) ; - html += add_textarea (i,"stream_URL_$suffix\_"+i,"textareaStream_URL_$suffix\_"+i,"Stream URL "+i,12,"",1) ; + html += "
    " ; + + html += add_datetimepicker(i,"start_date_time_$suffix",1,6,\$("input[name='start_date_time']").val()) ; + html += add_select(i,"readonly_sport_$suffix\_"+i,"selectReadonly_sport_$suffix\_"+i,"Select Sport "+i,"",2,4,100,"","") ; + html += "" ; + html += add_select(i,"age_group_$suffix\_" + i,"selectAge_group_$suffix\_" + i,"Select Age Group "+i,"",3,2,100,"","") ; + + html += "
    " ; + + html += "
    " ; + + html += add_select(i,"team_$suffix\_"+i,"selectTeam_$suffix\_"+i, "Select Team "+i,"",4,1,100,"","") ; + // html += add_select(i,"home_team_$suffix\_"+i,"selectHome_team_$suffix\_"+i, "Select Home Team "+i,"",5,2,100,"","") ; + html += add_input(i,"typeahead_home_team_$suffix\_" + i, "inputTypeahead_home_team_$suffix\_" + i, "Select Home Team "+i, 5, "", 2,'') ; + html += add_select(i,"ht_colour_$suffix\_" + i, "selectHt_colour_$suffix\_" + i, "Select Ht Colour "+i, "", 6, 2, 100, "", "") ; + // html += add_select(i,"away_team_$suffix\_" + i, "selectAway_team_$suffix\_" + i, "Select Away Team "+i, "", 7, 2, 100, "", "") ; + html += add_input(i,"typeahead_away_team_$suffix\_" + i, "inputTypeahead_away_team_$suffix\_" + i, "Select Away Team "+i, 5, "", 2,'') ; + html += add_select(i,"coding_type_$suffix\_" + i, "selectCoding_type_$suffix\_" + i, "Select Coding Type "+i,"", 8, 2, 100, "", "") ; + html += add_select(i,"footage_type_$suffix\_" + i, "selectFootage_type_$suffix\_" + i, "Select Footage Type "+i, "", 9, 1, 100, "", "") ; + html += add_select(i,"service_type_$suffix\_" + i, "selectService_type_$suffix\_" + i, "Select Service Type "+i, "", 10, 2, 100, "", "") ; + + html += "
    " ; + html += "
    " ; + + html += add_select(i,"stream_forwarding_$suffix\_" + i, "selectStream_forwarding_$suffix\_" + i, "Select Stream Forwarding "+i,"", 11, 2, 100, "", "") ; + html += add_textarea (i,"stream_key_$suffix\_"+i,"textareaStream_key_$suffix\_"+i,"Stream Key "+i,12,"",4) ; + html += add_textarea (i,"stream_URL_$suffix\_"+i,"textareaStream_URL_$suffix\_"+i,"Stream URL "+i,13,"",4) ; + html += add_checkbox (i,"cant_charge_client_$suffix\_"+i,"textareaCant_charge_client_$suffix\_"+i,14,2) ; + + html += "
    " ; html += "
    " ; parent.\$("#fixtures_table").append(html).trigger("chosen:updated") ; - + + parent.create_typeahead('fixtures_table',"[name^='typeahead_away_team_$suffix\_"+i+"'],[name^='typeahead_home_team_$suffix\_"+i+"']") ; + parent.\$('#datetimepickerStart_date_time_$suffix\_'+i).datetimepicker({language: 'pt-BR'}) ; let options ; @@ -560,12 +644,11 @@ sub screen2 { $trigger_jquery_raw .= qq~ - parent.\$("#selectAge_group_$suffix\_"+i+",#selectTeam_$suffix\_"+i+",#selectStream_forwarding_$suffix\_"+i).chosen({ allow_single_deselect:false }) ; - parent.\$("#selectReadonly_sport_$suffix\_"+i+",#selectHome_team_$suffix\_"+i+",#selectHt_colour_$suffix\_"+i+",#selectAway_team_$suffix\_"+i+",#selectCoding_type_$suffix\_"+i+",#selectFootage_type_$suffix\_"+i).chosen({ allow_single_deselect:false }) ; - parent.\$("#selectReadonly_sport_$suffix\_"+i+"_chosen,#selectAge_group_$suffix\_"+i+"_chosen,#selectTeam_$suffix\_"+i+"_chosen,#selectHome_team_$suffix\_"+i+"_chosen,#selectHt_colour_$suffix\_"+i+"_chosen,#selectAway_team_$suffix\_"+i+"_chosen,#selectCoding_type_$suffix\_"+i+"_chosen,#selectFootage_type_$suffix\_"+i+"_chosen").css("width","100%") ; - + parent.\$("#selectService_type_$suffix\_"+i+",#selectAge_group_$suffix\_"+i+",#selectTeam_$suffix\_"+i+",#selectStream_forwarding_$suffix\_"+i).chosen({ allow_single_deselect:false }) ; + parent.\$("#selectReadonly_sport_$suffix\_"+i+",#selectHt_colour_$suffix\_"+i+",#selectCoding_type_$suffix\_"+i+",#selectFootage_type_$suffix\_"+i).chosen({ allow_single_deselect:false }) ; + parent.\$("#selectService_type_$suffix\_"+i+"_chosen,#selectReadonly_sport_$suffix\_"+i+"_chosen,#selectAge_group_$suffix\_"+i+"_chosen,#selectTeam_$suffix\_"+i+"_chosen,#selectHt_colour_$suffix\_"+i+"_chosen,#selectCoding_type_$suffix\_"+i+"_chosen,#selectFootage_type_$suffix\_"+i+"_chosen").css("width","100%") ; } - + function get_row_nr (id) { let lastIndex = id.lastIndexOf('_') ; lastIndex = parseInt(lastIndex) ; @@ -574,6 +657,11 @@ sub screen2 { return row_nr ; } + function add_checkbox (row_nr,field_name,field_id,tindex,fcol,checked) { + let checkbox = "
    " ; + return checkbox ; + } + function add_textarea (row_nr,field_name,field_id,placeholder,tindex,readonly,fcol,default_val="",width="100",height="22.5",hide="") { let textarea = "
    " ; return textarea ; @@ -606,21 +694,39 @@ sub screen2 { if (!str) return str; // Handle empty string return str.charAt(0).toUpperCase() + str.slice(1) ; } - + parent.BootstrapDialog.closeAll() ; ~ ; - - # - - # $trigger_jquery_raw .= qq~ - # parent.\$("#alertbar").html(""); - # parent.location.reload(); - # parent.BootstrapDialog.closeAll() ; - # ~ unless $debug ; - - &common_min_dialog_save_screen ; + &common_min_dialog_save_screen_test_2 ; + +} #------------------------------------------------------------------------------------------ + +sub common_min_dialog_save_screen_test_2 { + +print < + + + + ITV Admin + + + +$extra_js + + + +ENDOFTEXT +# + +exit ; } #------------------------------------------------------------------------------------------ @@ -673,4 +779,5 @@ exit ; use today ; use common ; -use common_min ; \ No newline at end of file +use common_min ; +use common_shared ; \ No newline at end of file diff --git a/scripts/event_quotes_test.pl b/scripts/event_quotes_test.pl new file mode 100644 index 0000000..9ae9b86 --- /dev/null +++ b/scripts/event_quotes_test.pl @@ -0,0 +1,4975 @@ +#!/usr/bin/perl + +use lib "/home/libs/modules" ; +use lib "/home/libs/html" ; + +use CGI qw( :standard ); +use CGI::Carp qw(fatalsToBrowser); + +require cfg ; + +print header; # CGI.pm method + +# unless ($username eq 'handre'or $username eq 'rory') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +use Fcntl qw(:flock); +use File::Copy; +use File::Basename; +use Date::Calc qw(:all); +use Excel::Writer::XLSX; +use LWP::Simple qw($ua get); +use JSON ; + +&today; + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +@ARGV = split(/\\*\&/, $ENV{'QUERY_STRING'}); +$action = $ARGV[0] ; + +our ($q) = CGI -> new() ; +our $iaction = $q -> param('iaction') || $action ; +our $isaved = $q -> param('isaved') || '' ; + +# our $redirtype = 'search' ; + +# our $testing = 1 ; +# our $debug = 1 ; +# &common_debug("glod_user_level = $glod_user_level [$usertype]") ; + +# unless ($username eq 'rory') { print ">>>> DEVELOPMENT IN PROGRESS <<<<" ; exit ; } + +#--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +if ($is_operator && $glod_user_level == 2) { $glod_user_level = 3 ; } # upgrade operators level 2&3 to 3&4 + +our $nr_of_system_names_and_clubs = 15 ; our @all_select_ids = () ; our $minify_jquery = 1 ; + +&db_open_ro; + $db_ignore_open_close=1; + + &page_opts ; + + if ($iaction eq 'filter' || $iaction eq 'search' || $iaction eq 'report'){ + our $srchscr = 1 ; + our $savjqy = 0 ; + } + + #------------------------------------------------------------------------------------------------------------------------------------------------------------------ + + our $table = 'event_quotes'; + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # use File::Copy; + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # use File::Path 'make_path'; + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my $src_dir = "$htmlpath/uploads/uploads/7408"; + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my $dst_dir = "$htmlpath/uploads/uploads/test_copy"; + + + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # return unless -d $src_dir ; + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # mkdir $dst_dir unless -d $dst_dir ; + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # opendir(my $dh, $src_dir) or die "Can't open $src_dir: $!"; + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my $file_counter = 0 ; + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my @files = readdir($dh); + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # foreach my $file (@files) { + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # next if $file =~ /^\.\.?$/ ; + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my $src_file = "$src_dir/$file"; + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # my $dst_file = "$dst_dir/$file"; + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # if(-f $src_file) { + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # copy("$src_file", " $dst_file") or die "File cannot be copied." ; + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # } + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # } + + # while (my $file = readdir($dh)) { + # next if $file =~ /^\.\.?$/; # Skip '.' and '..' + # last if !$file || $file_counter >= 3 ; + # my $src_file = "$src_dir/$file"; + # my $dst_file = "$dst_dir/$file"; + # # print "\n 21 copy : $src_file, $dst_file" ; + # # system("cp", $src_file, $dst_file) == 0 or die "Failed to copy $src_file to $dst_file: $!"; + # # print "Successfully copied $src_file to $dst_file\n"; + # # if (copy($src_file, $dst_file)) { + # # print "Successfully copied $src_file to $dst_file\n"; + # # } else { + # # print "\nFailed to copy $src_file to $dst_file: $!"; + # # } + # $file_counter++ ; + # } + + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # closedir($dh); + + # while (1) { + # print "\n Hello World" ; + # last ; + # } + + # use File::Copy; + # use File::Path 'make_path'; + + # my $src_dir = "$htmlpath/uploads/uploads/7408"; + # my $dst_dir = "$htmlpath/uploads/uploads/test_copy"; + + # mkdir $dst_dir unless -d $dst_dir ; + + # opendir(my $dh, $src_dir) or die "Can't open $src_dir: $!"; + + # my $file_count = 0 ; + + # while (my $file = readdir($dh)) { + # next if $file =~ /^\.\.?$/; # Skip '.' and '..' + # $file_count++; + # last if $file_count == 3 ; + # } + + + + # print "\nfile $file_count" ; + # while (my $file = readdir($dh)) { + # my $src_file = "$src_dir/$file"; + # my $dst_file = "$dst_dir/$file"; + # # copy($src_dir, $dst_dir) or warn "Failed to copy $src_file to $dst_file: $!"; + # last ; + # } + + # closedir($dh); + + # for (7645 .. 20000) { + # my $src_dir = "$htmlpath/uploads/uploads/$_"; + # if (-d $src_dir) { + # rmdir $src_dir ; + # } + # } + + if ($iaction eq 'add') { + &add_screen; + &common_min_screen1; + } elsif ($iaction eq 'edit') { + &common_min_load_params ; + &edit_screen ; + &common_min_screen1 ; + } elsif ($iaction eq 'save') { + &common_min_load_params ; + &insert ; + # &log_changes ; + &edit_or_list ; + } elsif ($iaction eq 'update') { + &common_min_load_params ; + &update ; + &log_changes ; + &edit_or_list ; + } elsif ($iaction eq 'copy') { + &common_min_load_params ; + © ; + &edit_screen ; + &common_min_screen1; + } elsif ($iaction eq 'delete') { + &common_min_load_params ; + &delete ; + &common_min_screen2; + } + + &common_min_action; + $db_ignore_open_close=0 ; +&db_close_conn ; +exit; + +#------------------------------------------------------------------------------------------ + +sub edit_or_list { + +exit if $testing && substr($username,0,4) eq 'rory' ; + +# if ($i{saveandexit} eq 'yes') { + # &list_screen ; + # &common_min_screen3; + # } +# else + # { + &edit_screen ; + &common_min_screen1; + # } + +} #------------------------------------------------------------------------------------------ + +sub insert { + + # &db_min_ro('users',"id,1 AS 'schools_manager'","`user_type`='schools_manager' AND `id`='$userid'",'','') ; + + # $i{quote_created} = 1 if $is_schools_manager ; + # $i{quote_created} = 1 if $glod_user_level < 4 ; + $i{quote_created} = 1 if $glod_user_level < 3 ; + $i{quote_pending} = 1 unless $i{quote_accepted} || $i{quote_cancelled} || $i{quote_completed} || $i{quote_rejected} ; + + &set_default_i_vals; + + my $quote_cancelled = $i{quote_cancelled} ; my $quote_accepted = $i{quote_accepted} ; my $quote_rejected = $i{quote_rejected} ; + + # $i{operator_ids} = '' ; + &build_event_details_fields($quote_accepted,$quote_rejected,$quote_cancelled) ; + &process_multi_select($quote_accepted,$quote_rejected,$quote_cancelled) ; + # &process_times_from ; + &add_db_fields ; + + $i{last_update} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{datetime} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + $i{user_id} = $userid ; + + # &creat_db_cols; + + $i{id} = &db_min_get_max($table,'id') ; + + my $attachmentdir = $htmlpath . "/uploads/uploads/$i{id}" ; + mkdir $attachmentdir if not -d $attachmentdir and ($i{iattachupload_1} or $i{iattachupload_2} or $i{iattachupload_3}) ; + &common_upload_files("uploads/$i{id}") ; + &process_upload_ifields; + + &build_working_fields($i{id},$quote_accepted,$quote_rejected,$quote_cancelled) ; + + $i{quote_nr} = $i{id} ; + my $quote_nr = $i{quote_nr} ; + + $ignore{selected_event_length} = 1 ; + # $i{event_length} = $i{selected_event_length} ; + + $i{custom_set} = 0 unless $i{custom_set} ; + + foreach (keys %i) { + next if $ignore{$_} ; + &common_debug(" $_ : $i{$_}") ; + } + + &db_min_insert($table) ; + + &build_event_quotes_min_fields($quote_accepted,$quote_rejected,$quote_cancelled) ; + $i{quote_nr} = $quote_nr ; + + # our $line = qq~$now_year$now_year$now_mm$now_dd$now_hour$now_min$now_sec|$now_year-$now_mm-$now_dd $now_hour:$now_min:$now_sec|event_quote_id='$i{id}'|user_id=$userid|action='Add'|~ ; + # foreach (keys %i) { + # next if $hidden{$_} == 1 || $ignore{$_} ; + + # $line .= qq~$_='$i{$_}',~ ; + # } + + &db_min_insert('event_quotes_min') ; + +} #------------------------------------------------------------------------------------------ + +sub update { + + unless ($i{id}) { + $error = qq(NO ID) ; + return ; + } + + our $quote_accepted = $i{quote_accepted} ; + our $status = &common_status_txt($i{quote_completed},$i{quote_accepted},$i{quote_pending},$i{quote_cancelled},$i{quote_rejected}) ; + + &set_default_i_vals ; + + &db_min_ro($table,"id,quote_accepted,grand_total,operator_ids,quote_cancelled,quote_rejected","`id`='$i{id}'",'','') ; + + my $quote_cancelled = $db{$table}{$i{id}}{quote_cancelled} ; + my $quote_accepted = $db{$table}{$i{id}}{quote_accepted} ; + my $quote_rejected = $db{$table}{$i{id}}{quote_rejected} ; + + &build_event_details_fields($quote_accepted,$quote_rejected,$quote_cancelled) ; + &process_multi_select($quote_accepted,$quote_rejected,$quote_cancelled) ; + &edit_db_fields ; + + # &creat_db_cols ; + + $i{last_update} = "$now_ccyy_mm_dd $now_hour:$now_min:$now_sec" ; + + my $attachmentdir = $htmlpath . "/uploads/uploads/$i{id}" ; + mkdir $attachmentdir if not -d $attachmentdir and ($i{iattachupload_1} or $i{iattachupload_2} or $i{iattachupload_3}) ; + + &common_upload_files("uploads/$i{id}") ; + &process_upload_ifields ; + # &process_times_from ; + + our $hidden_expenses_amounts_exist = 0 ; + + &build_working_fields($i{id},$quote_accepted,$quote_rejected,$quote_cancelled) ; + + $i{quote_nr} = $i{id} ; + my $quote_nr = $i{quote_nr} ; + + &db_min_ro($table,"*","`id`='$i{id}'",'','') ; + + our $line = qq~$now_year$now_year$now_mm$now_dd$now_hour$now_min$now_sec|$now_year-$now_mm-$now_dd $now_hour:$now_min:$now_sec|event_quote_id='$i{id}'|user_id=$userid|changed_from|~ ; + + my %col_to_be_updated = () ; my %ignore_for_now = () ; + + foreach (keys %i) { + $col_to_be_updated{$_} = 1 ; + } + + foreach my $col (keys %{$db{$table}{$i{id}}}) { + next if $ignore{$col} or $hidden{$col} == 1 or substr($col,0,3) eq 'new' or not $col_to_be_updated{$col} ; + if (($i{$col} or $db{$table}{$i{id}}{$col}) and $db{$table}{$i{id}}{$col} ne $i{$col}) { + # $line .= qq~$col='$i{$col}',~ ; + $line .= qq~$col='$db{$table}{$i{id}}{$col}',~ ; + } elsif ((not $i{$col} and not $db{$table}{$i{id}}{$col}) or (($i{$col} or $db{$table}{$i{id}}{$col}) and $db{$table}{$i{id}}{$col} eq $i{$col})) { + $ignore{$col} = 1 ; $ignore_for_now{$col} = 1 ; + } + } + + $ignore{selected_event_length} = 1 ; + # $i{event_length} = $i{selected_event_length} ; + + $i{custom_set} = 0 unless $i{custom_set} ; + + &db_min_upd($table,"id='$i{id}'") ; + + &build_event_quotes_min_fields($quote_accepted,$quote_rejected,$quote_cancelled) ; + $i{quote_nr} = $quote_nr ; + + &db_min_ro('event_quotes_min','*',"id='$i{id}'",'','') ; + + foreach (keys %i) { + $col_to_be_updated{$_} = 1 ; + } + + foreach my $col (keys %{$db{event_quotes_min}{$i{id}}}) { + next if $ignore{$col} or $hidden{$col} == 1 or substr($col,0,3) eq 'new' or not $col_to_be_updated{$col} ; + if (($i{$col} or $db{event_quotes_min}{$i{id}}{$col}) and $db{event_quotes_min}{$i{id}}{$col} ne $i{$col}) { + # $line .= qq~$col='$i{$col}',~ ; + $line .= qq~$col='$db{event_quotes_min}{$i{id}}{$col}',~ ; + } elsif ((not $i{$col} and not $db{event_quotes_min}{$i{id}}{$col}) or (($i{$col} or $db{event_quotes_min}{$i{id}}{$col}) and $db{event_quotes_min}{$i{id}}{$col} eq $i{$col})) { + $ignore{$col} = 1 ; $ignore_for_now{$col} = 1 ; + } + } + + &db_min_upd('event_quotes_min',"id='$i{id}'") ; + + foreach (keys %ignore_for_now) { + $ignore{$_} = '' ; + } + +} #------------------------------------------------------------------------------------------ + +sub log_changes { + + chop $line if $line ; + + &common_log_changes("events/changes.dat",$line) if $line ; + + if ($db{$table}{$i{id}}{quote_accepted} && $line) { # Can you change it that she only gets emails where an Accepted Event been edited by school manager and when they upload docs afterwards, She just need notification if there been changes to event she or anyone else already accepted it + # if (!$quote_accepted || $is_schools_manager || $glod_user_level < 4) { + if (!$quote_accepted || $is_schools_manager || $glod_user_level < 3) { + &send_email_to_manager($i{id},$status,$line) ; + } + } + +} #------------------------------------------------------------------------------------------ + +sub process_times_from { + + # for (1 .. 6) { + # $ignore{"time_from_$_"} = 1 ; + # $ignore{"time_to_$_"} = 1 ; + # $i{times_from} .= qq~$i{"time_from_$_"};~ if $_ > 1 ; + # $i{times_to} .= qq~$i{"time_to_$_"};~ if $_ < 6 ; + # } + # chop $i{times_from} if $i{times_from} ; + # chop $i{times_to} if $i{times_to} ; + +} #------------------------------------------------------------------------------------------ + +sub send_email_to_manager { + + my ($event_id,$status,$msg) = @_ ; + + return if $username eq 'marizen' ; # don't send to marizen if she did the change. + + my $usernametemp = (substr($username,0,4) eq 'rory') ? 'rory' : $username ; + + my $attachpath = "$pdfpath/event_details" ; $attachfile = "Event_Details-$event_id.pdf" ; + + my $subj = 'Event [' . $event_id . ']' ; + $subj .= " $status" if $status ; + $subj .= " by $username" if $username ; + $subj .= " : $i{ref}" if $i{ref} ; + + my $event_details_pdf = get("$useropts{domain}$useropts{'scripts'}/pdf/event_details_pdf.pl?$event_id&&") ; + my $to = ($useropts{it}{$usernametemp}) ? "$usernametemp\@kre8it.co.za" : $email_events{1} ; + $got_mail_add{$to} = 1 ; + my $cc = ($is_schools_manager) ? "$useremail" : (!$got_mail_add{$useremail}) ? "$useremail" : '' ; + # my $bcc = ($useropts{it}{$usernametemp}) ? '' : 'rory@kre8it.co.za' ; + my $bcc = '' ; + &common_send_smtp_mail('',$to,$cc,$bcc,"$subj","Click here to view event details

    $msg",'','html','',$attachpath,$attachfile,'',0,0) ; + +} #------------------------------------------------------------------------------------------ + +sub build_event_details_fields { + + my ($quote_accepted,$quote_rejected,$quote_cancelled) = @_ ; + + # $i{operator_ids} .= qq~;\~;~ ; + my $cnt_last_row = 0 ; + for (1 .. $nr_of_system_names_and_clubs) { + $cnt_last_row = $_ if $i{"system_name_$_"} or $i{"club_name_$_"} ; + + my $system_name = "system_name_$_" ; + my $club_name = "club_name_$_" ; + my $op_name = "operator_id_calibration_$_" ; + $ignore{$system_name} = 1 ; + $ignore{$club_name} = 1 ; + $ignore{$op_name} = 1 ; + } + + return if ($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3 ; + + unless ($cnt_last_row) { + $i{club_ids} = qq~~ ; + $i{event_system_id_multiple} = qq~~ ; + return ; + } + # return if $is_schools_manager ; + # return if $glod_user_level < 4 ; + # return if $glod_user_level < 3 ; + + $i{operator_ids} = '' ; + + for (1 .. $nr_of_system_names_and_clubs) { + + my $system_name = "system_name_$_" ; + my $club_name = "club_name_$_" ; + my $op_name = "operator_id_calibration_$_" ; + + $i{club_ids} .= qq~$i{$club_name};~ ; + $i{event_system_id_multiple} .= qq~$i{$system_name};~ ; + $i{operator_ids} .= qq~$i{$op_name},~ if $_ <= $cnt_last_row ; + } + + $ignore{club_name} = 1 ; + chop $i{club_ids} if $i{club_ids} ; chop $i{event_system_id_multiple} if $i{event_system_id_multiple} ; + # chop $i{operator_ids} if $i{operator_ids} ; + +} #------------------------------------------------------------------------------------------ + +sub process_daily_details_from_the_events_datails_tab { + + my ($id) = @_ ; + + my $final_day = 0 ; + for (1 .. 20) { + $final_day = $_ if $i{"day_$_"} ; + } + + for my $event_row (1 .. 15) { + $ignore{"clicked_button_$event_row"} = 1 ; + for my $event_day (1 .. 20) { + $ignore{"custom_operator_$event_row\_$event_day"} = 1 ; + if ($i{"clicked_button_$event_row"}) { + $i{"custom_operator_$event_row\_$event_day"} = "" unless $i{"day_$event_day"} ; + $i{daily_operator_ids} .= qq~$i{"custom_operator_$event_row\_$event_day"};~ ; + } + if ($event_row == 1) { + $ignore{"time_from_$event_day"} = 1 ; + $ignore{"time_to_$event_day"} = 1 ; + $ignore{"day_$event_day"} = 1 ; + $ignore{"event_length_$event_day"} = 1 ; + $ignore{"selected_$event_day\_event_length"} = 1; + + $i{times_from} .= qq~$i{"time_from_$event_day"};~ if $event_day > 1 && $i{"day_$event_day"} ; + $i{times_from} .= qq~;~ if $event_day > 1 && !$i{"day_$event_day"} ; + $i{times_to} .= qq~$i{"time_to_$event_day"};~ if $event_day < $final_day && $i{"day_$event_day"}; + $i{times_to} .= qq~;~ if $event_day < $final_day && !$i{"day_$event_day"}; + $i{days_active} .= qq~$i{"day_$event_day"};~ ; + $i{event_length} .= ($i{"day_$event_day"}) ? qq~$i{"event_length_$event_day"};~ : qq~;~ ; + } + } + chop $i{daily_operator_ids} if $i{daily_operator_ids} && $i{"clicked_button_$event_row"} ; + $i{daily_operator_ids} .= qq~|~ ; + } + chop $i{daily_operator_ids} if $i{daily_operator_ids} ; + chop $i{times_from} if $i{times_from} ; + chop $i{times_to} if $i{times_to} ; + chop $i{days_active} if $i{days_active} ; + chop $i{event_length} if $i{event_length} ; + + # $ignore{daily_operator_ids} = 1 if $i{daily_operator_ids} eq $db{$table}{$id}{daily_operator_ids} ; + # $ignore{times_from} = 1 if $i{times_from} eq $db{$table}{$id}{times_from} ; + # $ignore{times_to} = 1 if $i{times_to} eq $db{$table}{$id}{times_to} ; + # $ignore{days_active} = 1 if $i{days_active} eq $db{$table}{$id}{days_active} ; + # $ignore{event_length} = 1 if $i{event_length} eq $db{$table}{$id}{event_length} ; + +} #------------------------------------------------------------------------------------------ + +sub build_working_fields { + + my ($id,$quote_accepted,$quote_rejected,$quote_cancelled) = @_ ; + + if (($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) { + + ### ADD IGNORE WITH EVENT SYSTEM NAME TABLE + for my $col (1 .. 20) { + $ignore{"time_from_$col"} = 1 ; + $ignore{"time_to_$col"} = 1 ; + $ignore{"day_$col"} = 1 ; + for (1 .. 15) { + $ignore{"custom_operator_$_\_$col"} = 1 ; + } + } + $ignore{total_amount_workings_event} = 1 ; + $ignore{total_vat_amount_workings_event} = 1 ; + $ignore{total_grand_amount_workings_event} = 1 ; + + return ; + } + + # if ($glod_user_level < 3) { + # $ignore{daily_operator_ids} = 1 ; + # $ignore{event_length} = 1 ; + # $ignore{times_from} = 1 ; + # $ignore{times_to} = 1 ; + # $ignore{event_length} = 1 ; + # } + + &process_daily_details_from_the_events_datails_tab($id) ; + + my $diplayed_exp_tab = 0 ; my $hidden_exp_tab = 0 ; + if ($glod_user_level > 3) { + # if ($glod_user_level > 2) { + $diplayed_exp_tab = 1 ; + } elsif ($glod_user_level < 4) { + # } elsif ($glod_user_level < 3) { + $hidden_exp_tab = 1 ; + # $ignore{sub_total} = 1 ; + # $ignore{vat_total} = 1 ; + # $ignore{grand_total} = 1 ; + } + + # return if !$diplayed_exp_tab && !$hidden_exp_tab ; + + $i{sub_total} = $i{sub_total_costing_event} ; + $i{vat_total} = $i{vat_total_costing_event} ; + $i{grand_total} = $i{grand_total_costing_event} ; + # $i{profit_loss} =~ s/\,//g ; + # $i{sub_total} =~ s/\,//g ; + # $i{vat_total} =~ s/\,//g ; + # $i{grand_total} =~ s/\,//g ; + + $ignore{sub_total_workings_event} = 1 ; + $ignore{vat_total_workings_event} = 1 ; + $ignore{grand_total_workings_event} = 1 ; + $ignore{sub_total_costing_event} = 1 ; + $ignore{vat_total_costing_event} = 1 ; + $ignore{grand_total_costing_event} = 1 ; + $ignore{sub_total} = 1 if $i{sub_total} eq $db{$table}{$id}{sub_total} ; + $ignore{vat_total} = 1 if $i{vat_total} eq $db{$table}{$id}{vat_total} ; + $ignore{grand_total} = 1 if $i{grand_total} eq $db{$table}{$id}{grand_total} ; + + for (1 .. 50) { + + $y{1}{$_} = "excl_costing_event_$_" ; + $y{2}{$_} = "description_costing_event_$_" ; + $y{3}{$_} = "qty_full_day_costing_event_$_" ; + $y{4}{$_} = "amount_usd_costing_event_$_" ; + $y{5}{$_} = "amount_ttl_costing_event_$_" ; + $y{6}{$_} = "vat_costing_event_$_" ; + $y{7}{$_} = "excl_workings_event_$_" ; + $y{8}{$_} = "description_workings_event_$_" ; + $y{9}{$_} = "operator_workings_event_$_" ; + $y{10}{$_} = "remarks_workings_event_$_" ; + $y{11}{$_} = "supplier_workings_event_$_" ; + $y{12}{$_} = "ref_nr_workings_event_$_" ; + $y{13}{$_} = "qty_workings_event_$_" ; + $y{14}{$_} = "amount_usd_workings_event_$_" ; + $y{15}{$_} = "amount_ttl_workings_event_$_" ; + $y{16}{$_} = "vat_workings_event_$_" ; + $y{17}{$_} = "qty_half_day_costing_event_$_" ; + # $y{18}{$_} = "qty_full_day_costing_event_$_" ; + # $y{17}{$_} = "curr_amnt_costing_event_$_" ; + + $hidden_expenses_amounts_exist = ($hidden_expenses_amounts_exist || ($glod_user_level < 4 && ($y{8}{$_} || $y{9}{$_} || $y{13}{$_} || $i{$y{14}{$_}} || $i{$y{15}{$_}}))) ? 1 : 0 ; + + foreach my $a (keys %y) { + foreach my $b (keys %{$y{$a}}) { + $ignore{$y{$a}{$b}} = 1 ; + $x{$a}{$b} = $i{$y{$a}{$b}} ; + } + } + } + + # return if $i{custom_set} ; + + if ($i{custom_set}) { + $i{total_amount_workings_event} = $i{sub_total_workings_event} ; + $i{total_vat_amount_workings_event} = $i{vat_total_workings_event} ; + $i{total_grand_amount_workings_event} = $i{grand_total_workings_event} ; + return ; + } + + $i{total_amount_workings_event} = 0 ; + $i{total_vat_amount_workings_event} = 0 ; + $i{total_grand_amount_workings_event} = 0 ; + + my %operator_day_count = () ; my %operator_row = () ; + my $operator_count = 0 ; + my %ii = () ; + + # $i{operator_ids} = $db{$table}{$id}{operator_ids} if $glod_user_level < 3 ; + + my @operator_ids = split(/\,/,$i{operator_ids}) ; + + &db_min_ro('event_systems','id,system_type','','','') ; + + for my $system_name_row_nr (1 .. $nr_of_system_names_and_clubs) { + + my $field4 = "system_name_$system_name_row_nr" ; + + # next if !$i{$field4} || $i{$field4} < 0 ; + + $i{$field4} = -1 if !$i{$field4} && $i{"clicked_button_$system_name_row_nr"} ; + + next unless $i{$field4} ; + + for my $days (1 .. 20) { + + my $day_field = "day_$days" ; + next unless $i{$day_field} ; + + my $field1 = "custom_operator_$system_name_row_nr\_$days" ; + my $field2 = "operator_id_calibration_$system_name_row_nr" ; + my $field3 = "event_length_$days" ; + + if ($i{$field1}) { + if ($i{$field4} eq '-1') { + $operator_day_count{blank_system}{$i{$field1}}++ ; + } elsif ($i{$field3} eq '1' && $db{event_systems}{$i{$field4}}{system_type} ne 'fixed') { #full day + $operator_day_count{afull_day_mobile}{$i{$field1}}++ ; + } elsif (($i{$field3} eq '1' && $db{event_systems}{$i{$field4}}{system_type} eq 'fixed') or ($i{$field3} eq '2' && $db{event_systems}{$i{$field4}}{system_type} ne 'fixed')) { #full day + $operator_day_count{bfull_day_fixed_half_day_mobile}{$i{$field1}}++ ; + } elsif ($i{$field3} eq '2' && $db{event_systems}{$i{$field4}}{system_type} eq 'fixed') { + $operator_day_count{chalf_day_fixed}{$i{$field1}}++ ; + } + } + } + } + + + if ($i{operator_ids}) { + my $cnt = 0 ; + foreach my $op_id (@operator_ids) { + $cnt++ ; + next unless $op_id ; + my $field5 = "system_name_$cnt" ; + + $i{$field5} = -1 if !$i{$field5} && $i{"operator_id_calibration_$cnt"} ; + + # if ($i{$field5} && $i{$field5} > 0) { + + for my $days (1 .. 20) { + my $day_field = "day_$days" ; + next unless $i{$day_field} ; + my $field6 = "event_length_$days" ; + if ($i{$field5} eq '-1') { + $operator_day_count{blank_system}{$op_id}++ ; + } elsif ($i{$field6} eq '1' && $db{event_systems}{$i{$field5}}{system_type} && $db{event_systems}{$i{$field5}}{system_type} ne 'fixed') { #full day + $operator_day_count{afull_day_mobile}{$op_id}++ ; + } elsif (($i{$field6} eq '1' && $db{event_systems}{$i{$field5}}{system_type} eq 'fixed') or ($i{$field6} eq '2' && $db{event_systems}{$i{$field5}}{system_type} && $db{event_systems}{$i{$field5}}{system_type} ne 'fixed')) { #full day + $operator_day_count{bfull_day_fixed_half_day_mobile}{$op_id}++ ; + } elsif ($i{$field6} eq '2' && $db{event_systems}{$i{$field5}}{system_type} eq 'fixed') { + $operator_day_count{chalf_day_fixed}{$op_id}++ ; + } + } + + next if $i{$field5} eq '-1' || $db{event_systems}{$i{$field5}}{system_type} ; + + # } else { + for my $days (1 .. 20) { + my $day_field = "day_$days" ; + next unless $i{$day_field} ; + my $field6 = "event_length_$days" ; + if ($i{$field6} eq '1' && $i{type} ne '3') { #full day + $operator_day_count{afull_day_mobile}{$op_id}++ ; + } elsif (($i{$field6} eq '1' && $i{type} eq '3') or ($i{$field6} eq '2' && $i{type} ne '3')) { #full day + $operator_day_count{bfull_day_fixed_half_day_mobile}{$op_id}++ ; + } elsif ($i{$field6} eq '2' && $i{type} eq '3') { + $operator_day_count{chalf_day_fixed}{$op_id}++ ; + } + } + # } + } + } + + my %iii = %i ; + our %i2 = () ; + + for (1 .. 50) { + if ($i{"description_workings_event_$_"} eq '14' && $i{"operator_workings_event_$_"}) { + my $op = $i{"operator_workings_event_$_"} ; + my $day_len = ($i{"amount_usd_workings_event_$_"} eq '1000.00') ? "afull_day_mobile" : ($i{"amount_usd_workings_event_$_"} eq '750.00') ? "bfull_day_fixed_half_day_mobile" : ($i{"amount_usd_workings_event_$_"} eq '500.00') ? "chalf_day_fixed" : "" ; + if ($day_len) { + $saved_values{$day_len}{$op}{saved_values} = 1 ; + $saved_values{$day_len}{$op}{supplier_workings_event} = $i{"supplier_workings_event_$_"} ; + $saved_values{$day_len}{$op}{ref_nr_workings_event} = $i{"ref_nr_workings_event_$_"} ; + $saved_values{$day_len}{$op}{remarks_workings_event} = $i{"remarks_workings_event_$_"} ; + $saved_values{$day_len}{$op}{vat_workings_event} = $i{"vat_workings_event_$_"} ; + $saved_values{$day_len}{$op}{excl_workings_event} = $i{"excl_workings_event_$_"} ; + # $saved_values{$day_len}{$op}{amount_usd_workings_event} = $i{"amount_usd_workings_event_$_"} if $day_len eq "other" ; + } + } + $i{"description_workings_event_$_"} = "" ; + $i{"operator_workings_event_$_"} = "" ; + $i{"qty_workings_event_$_"} = "" ; + $i{"amount_usd_workings_event_$_"} = "" ; + $i{"amount_ttl_workings_event_$_"} = "" ; + $i{"excl_workings_event_$_"} = "1"; + $i{"vat_workings_event_$_"} = "" ; + $i{"supplier_workings_event_$_"} = "" ; + $i{"ref_nr_workings_event_$_"} = "" ; + $i{"remarks_workings_event_$_"} = "" ; + + } + + my $row_cnt = 0 ; + + foreach my $len (sort keys %operator_day_count) { + + foreach $op_id (sort keys %{$operator_day_count{$len}}) { + + $row_cnt++ ; + $i2{description_workings_event} .= '14;' ; + $i2{operator_workings_event} .= "$op_id;" ; + $i2{qty_workings_event} .= "$operator_day_count{$len}{$op_id};" ; + + # my $custom_saved_amnt = $saved_values{"other"}{$op_id}{amount_usd_workings_event} ; + + $i2{amount_usd_workings_event} .= ($len eq 'blank_system') ? '0.00' : ($len eq "afull_day_mobile") ? '1000.00' : ($len eq "bfull_day_fixed_half_day_mobile") ? '750.00' : '500.00' ; + $i2{amount_usd_workings_event} .= qq~;~ ; + my $amnt = ($len eq 'blank_system') ? 0 : ($len eq "afull_day_mobile") ? 1000 * $operator_day_count{$len}{$op_id} : ($len eq "bfull_day_fixed_half_day_mobile") ? 750 * $operator_day_count{$len}{$op_id} : 500 * $operator_day_count{$len}{$op_id} ; + $amnt = sprintf ("%0.2f",$amnt) ; + + $i2{amount_workings_event} .= "$amnt;" ; + $i{total_amount_workings_event} += $amnt if !$saved_values{$len}{$op_id}{excl_workings_event} ; + if ($saved_values{$len}{$op_id}{saved_values}) { + foreach (keys %{$saved_values{$len}{$op_id}}) { + $i2{$_} .= qq~$saved_values{$len}{$op_id}{$_};~ if $_ ne "saved_values" ; + $i{total_vat_amount_workings_event} += $amnt*0.15 if !$saved_values{$len}{$op_id}{excl_workings_event} && $saved_values{$len}{$op_id}{vat_workings_event} && $_ eq "vat_workings_event" ; + } + } else { + $i2{supplier_workings_event} .= ";" ; + $i2{ref_nr_workings_event} .= ";" ; + $i2{remarks_workings_event} .= ";" ; + $i2{vat_workings_event} .= "1;" ; + $i2{excl_workings_event} .= "0;" ; + $i{total_vat_amount_workings_event} += $amnt*0.15 ; + } + } + } + + for (1 .. 50) { + if ($iii{"description_workings_event_$_"} && $iii{"description_workings_event_$_"} ne '14') { + $row_cnt++ ; + $i2{"excl_workings_event"} .= qq~$iii{"excl_workings_event_$_"};~ ; + $i2{"description_workings_event"} .= qq~$iii{"description_workings_event_$_"};~ ; + $i2{"operator_workings_event"} .= qq~$iii{"operator_workings_event_$_"};~ ; + $i2{"remarks_workings_event"} .= qq~$iii{"remarks_workings_event_$_"};~ ; + $i2{"supplier_workings_event"} .= qq~$iii{"supplier_workings_event_$_"};~ ; + $i2{"ref_nr_workings_event"} .= qq~$iii{"ref_nr_workings_event_$_"};~ ; + $i2{"qty_workings_event"} .= qq~$iii{"qty_workings_event_$_"};~ ; + $i2{"amount_usd_workings_event"} .= qq~$iii{"amount_usd_workings_event_$_"};~ ; + $i2{"amount_workings_event"} .= qq~$iii{"amount_ttl_workings_event_$_"};~ ; + $i2{"vat_workings_event"} .= qq~$iii{"vat_workings_event_$_"};~ ; + $iii{"amount_ttl_workings_event_$_"} =~ s/\,//g ; + $i{total_amount_workings_event} += $iii{"amount_ttl_workings_event_$_"} if !$iii{"excl_workings_event_$_"} ; + $i{total_vat_amount_workings_event} += $iii{"amount_ttl_workings_event_$_"} * 0.15 if !$iii{"excl_workings_event_$_"} && $iii{"vat_workings_event_$_"} ; + + } + } + + unless ($row_cnt) { + $i2{excl_workings_event} = qq~~ ; + $i2{description_workings_event} = qq~~ ; + $i2{operator_workings_event} = qq~~ ; + $i2{remarks_workings_event} = qq~~ ; + $i2{supplier_workings_event} = qq~~ ; + $i2{ref_nr_workings_event} = qq~~ ; + $i2{qty_workings_event} = qq~~ ; + $i2{amount_usd_workings_event} = qq~~ ; + $i2{amount_workings_event} = qq~~ ; + $i2{vat_workings_event} = qq~~ ; + } + + $i{total_grand_amount_workings_event} = $i{total_vat_amount_workings_event} + $i{total_amount_workings_event} ; + + $i{profit_loss} = $db{$table}{$id}{grand_total} - $i{total_grand_amount_workings_event} ; + + $i{total_amount_workings_event} = sprintf("%0.2f",$i{total_amount_workings_event}) ; + $i{total_vat_amount_workings_event} = sprintf("%0.2f",$i{total_vat_amount_workings_event}) ; + $i{total_grand_amount_workings_event} = sprintf("%0.2f",$i{total_grand_amount_workings_event}) ; + $i{profit_loss} = sprintf("%0.2f",$i{profit_loss}) ; + + foreach (keys %i2) { + # chop $i2{$_} if $i2{$_} ; + # $i{$_} = $i2{$_} ; + } + +} #------------------------------------------------------------------------------------------ + +sub build_event_quotes_min_fields { + + my ($quote_accepted,$quote_rejected,$quote_cancelled) = @_ ; + + my $category_details = qq~$i{category_1_details}|;|$i{category_2_details}~ if $i{category_1_details} || $i{category_2_details} ; + $i{category_details} = $category_details ; + + $ignore{last_update} = 1 ; + $ignore{poc_contact_nr} = 1 ; + $ignore{format_of_title} = 1 ; + $ignore{additional_notes} = 1 ; + $ignore{poc_name} = 1 ; + $ignore{upload_1} = 1 ; + $ignore{upload_2} = 1 ; + $ignore{upload_3} = 1 ; + $ignore{email} = 1 ; + $ignore{address} = 1 ; + $ignore{country_id} = 1 ; + $ignore{quote_date} = 1 ; + $ignore{contact_name} = 1 ; + $ignore{notes} = 1 ; + $ignore{tel} = 1 ; + $ignore{category_id_1} = 1 ; + $ignore{category_id_2} = 1 ; + $ignore{custom_set} = 1 ; + $ignore{quote_accepted} = 1 ; + $ignore{quote_cancelled} = 1 ; + $ignore{quote_rejected} = 1 ; + $ignore{quote_completed} = 1 ; + + return if ($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3 ; + + $iid = $i{id} ; + my $custom_set = $i{custom_set} ; + %i = %i2 ; + $i{custom_set} = $custom_set ; + if ($glod_user_level > 3) { + + for (1 .. 50) { + next unless $x{2}{$_} ; + $i{excl_costing_event} .= "$x{1}{$_};" ; + $i{item_costing_event} .= "$x{2}{$_};"; + $i{qty_costing_event} .= "$x{3}{$_};"; + $i{usd_amnt_costing_event} .= "$x{4}{$_};"; + $i{item_ttl_costing_event} .= "$x{5}{$_};"; + $i{vat_costing_event} .= "$x{6}{$_};"; + $i{qty_half_day_costing_event} .= "$x{17}{$_};"; + + # $i{curr_amnt_costing_event} .= "$x{17}{$_};"; + } + if ($i{custom_set}) { + for (1 .. 50) { + next unless $x{8}{$_} ; + $i{excl_workings_event} .= "$x{7}{$_};"; + $i{description_workings_event} .= "$x{8}{$_};"; + $i{operator_workings_event} .= "$x{9}{$_};"; + $i{remarks_workings_event} .= "$x{10}{$_};"; + $i{supplier_workings_event} .= "$x{11}{$_};"; + $i{ref_nr_workings_event} .= "$x{12}{$_};"; + $i{qty_workings_event} .= "$x{13}{$_};"; + $i{amount_usd_workings_event} .= "$x{14}{$_};"; + $i{amount_workings_event} .= "$x{15}{$_};"; + $i{vat_workings_event} .= "$x{16}{$_};"; + } + } + } elsif ($glod_user_level < 4 && $hidden_expenses_amounts_exist) { + + for (1 .. 50) { + # $i{description_workings_event} .= "$x{8}{$_};"; + # $i{operator_workings_event} .= "$x{9}{$_};"; + # $i{qty_workings_event} .= "$x{13}{$_};"; + # $i{amount_usd_workings_event} .= "$x{14}{$_};"; + # $i{amount_workings_event} .= "$x{15}{$_};"; + # $i{vat_workings_event} .= "$x{16}{$_};"; + } + } + + foreach (keys %i) { chop $i{$_} ; } + + $i{category_details} = $category_details ; + $i{id} = $iid ; + +} #------------------------------------------------------------------------------------------ + +sub process_multi_select { + + my ($quote_accepted,$quote_rejected,$quote_cancelled) = @_ ; + + # $ignore{event_system_id} = 1 ; + + # if ($usertype ne 'schools_manager') { + # if ($glod_user_level > 3) { + + # return if ($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3 ; + + if (($quote_accepted || $quote_rejected || $quote_cancelled) && $glod_user_level < 3) { + $ignore{operatorids} = 1 ; + $ignore{typedetailsid} = 1 ; + $ignore{organisationids} = 1 ; + $ignore{sporttypeids} = 1 ; + $ignore{operator_ids} = 1 ; + } + + local @operatorids = split(/\,/,$i{operatorids}) ; + $i{nr_of_casuals} = scalar @operatorids || '0' ; $i{nr_of_casuals_2} = '0' ; + my $operatorids = join(",",@operatorids) ; + $operatorids =~ s/\s//g; # remove white space + $ignore{operatorids} = 1 ; + + $i{operator_ids} .= $operatorids ; + $i{operator_ids} = 0 unless $i{operator_ids} ; + chop $i{operator_ids} if substr($i{operator_ids},-1,1) eq ',' ; + + if ($glod_user_level > 2) { + + local @typedetailsid = split(/\,/,$i{typedetailsid}) ; + my $typedetailsid = join(",",@typedetailsid) ; + $typedetailsid =~ s/\s//g; # remove white space + $ignore{typedetailsid} = 1 ; + $i{type_details_id} = $typedetailsid ; + $i{type_details_id} = 0 unless $i{type_details_id} ; + + # @event_system_ids = split(/\,/,$i{event_system_ids}) ; + # my @db_event_system_ids = () ; foreach (@event_system_ids) { push @db_event_system_ids, $_ ; } + # my $db_event_system_ids = join(';',@db_event_system_ids) ; + # $ignore{event_system_ids} = 1 ; + # $i{event_system_id_multiple} = $db_event_system_ids ; + } + + $ignore{city_ids} = 1 ; + $i{city_id} = $i{city_ids} ; + + local @organisationids = split(/\,/,$i{organisationids}) ; + my $organisationids = join(",",@organisationids) ; + $organisationids =~ s/\s//g; # remove white space + $ignore{organisationids} = 1 ; + $i{organisation_ids} = $organisationids ; + $i{organisation_ids} = 0 unless $i{organisation_ids} ; + + local @sporttypeids = split(/\,/,$i{sporttypeids}) ; + my $sporttypeids = join(",",@sporttypeids) ; + $sporttypeids =~ s/\s//g; # remove white space + $ignore{sporttypeids} = 1 ; + $i{sport_type_ids} = $sporttypeids ; + $i{sport_type_ids} = 0 unless $i{sport_type_ids} ; + +} #------------------------------------------------------------------------------------------ + +sub copy { + + unless ($i{id}) { + $error = qq~NO ID~ ; + return ; + } + + my $id = $i{id} ; + + &db_min_copy($table,$i{id}) ; + + &db_min_copy('event_quotes_min',$id) ; + +} #------------------------------------------------------------------------------------------ + +# sub copy { + + # unless ($i{id}) { + # $error = qq~NO ID~ ; + # return ; + # } + + # my $id = $i{id} ; + + # &db_min_copy($table,$i{id}) ; + + # my $id2 = $i{id} ; + + # $i{id} = $id ; + + # &db_min_copy('event_quotes_min',$i{id}) ; + + # $i{id} = $id ; + + # # use File::Copy; + # # # use File::Path 'make_path'; + + + + # # my $src_dir = "$htmlpath/uploads/uploads/$id"; + # # my $dst_dir = "$htmlpath/uploads/uploads/$id2"; + + # # return unless -d $src_dir ; + + # # mkdir $dst_dir unless -d $dst_dir ; + + # # opendir(my $dh, $src_dir) or die "Can't open $src_dir: $!"; + # # my $file_counter = 0 ; + # # while (my $file = readdir($dh)) { + # # next if $file =~ /^\.\.?$/; # Skip '.' and '..' + # # last if !$file || $file_counter >= 3 ; + # # my $src_file = "$src_dir/$file"; + # # my $dst_file = "$dst_dir/$file"; + # # copy($src_dir, $dst_dir) or warn "Failed to copy $src_file to $dst_file: $!"; + # # $file_counter++ ; + # # } + + # # closedir($dh); + +# } #------------------------------------------------------------------------------------------ + + +sub delete { + + unless ($i{id}) { $error = uc "NO ID" ; return ; } + + &db_min_delete('event_quotes',"`id`='$i{id}'") ; + &db_min_delete('event_quotes_min',"`id`='$i{id}'") ; + +} #------------------------------------------------------------------------------------------ + +sub process_upload_ifields { + + foreach (keys %uploads_file) { $i{$_} = $uploads_file{$_} ; $ignore{$_} = '' ; } + +} #------------------------------------------------------------------------------------------ + +sub set_default_i_vals { + + my $srch_where_sql = "`id`='$i{id}'" ; + + $iaction eq 'save' ? &db_min_ro($table,'*','','id DESC',1) : &db_min_ro($table,'*',$srch_where_sql,'','') ; + + foreach (sort { $col_name{$a} cmp $col_name{$b} } keys %col_name) { + $col = $col_name{$_} ; + + # &common_min_debug("1. [$col] [$i{$col}]"); + + if (substr($col,0,4) eq 'vat_' or substr($col,0,5) eq 'excl_' or substr($col,0,4) eq 'qty_') { + $i{$col} = 0 unless $i{$col} ; + } # only create the column if it doesn't exist + + if (substr($col,0,5) eq 'date_') { + $i{$col} = 'NULL' unless $i{$col} ; + } # only create the column if it doesn't exist + + if (substr($col,0,11) eq 'amount_ttl_' or substr($col,0,9) eq 'usd_amnt_' or substr($col,0,10) eq 'curr_amnt_' or substr($col,0,9) eq 'item_ttl_' or substr($col,-6,6) eq '_total') { + $i{$col} = '0.00' unless $i{$col} ; + } + + if ((substr($col,6,9) eq '_costing_' and substr($col,0,5) eq 'item_' and $i{$col}) or ($col eq 'quote_to' and $i{$col})) { + my @valarr = split(/\:/,$i{$col}) ; + $i{$col} = $valarr[0] ; # set the value to only be the id + } + } + + $i{quote_completed} = 0 unless $i{quote_completed} ; + $i{quote_accepted} = 0 unless $i{quote_accepted} ; + $i{quote_pending} = 0 unless $i{quote_pending} ; + $i{quote_cancelled} = 0 unless $i{quote_cancelled} ; + $i{quote_rejected} = 0 unless $i{quote_rejected} ; + $i{annual_invoice} = 0 unless $i{annual_invoice} ; + $i{nr_of_casuals_2} = 0 unless $i{nr_of_casuals_2} ; + $ignore{invoice_date} = 1 unless length($i{invoice_date}) == 10 ; + + if ($i{quote_completed}) { + $i{quote_accepted} = 1 ; + $i{quote_cancelled} = 0 ; + $i{quote_pending} = 0 ; + $i{quote_rejected} = 0 ; + } elsif ($i{quote_accepted}) { + $i{quote_cancelled} = 0 ; + $i{quote_completed} = 0 ; + $i{quote_pending} = 0 ; + $i{quote_rejected} = 0 ; + } elsif ($i{quote_rejected}) { + $i{quote_cancelled} = 0 ; + $i{quote_completed} = 0 ; + $i{quote_pending} = 0 ; + $i{quote_accepted} = 0 ; + } elsif ($i{quote_pending}) { + $i{quote_cancelled} = 0 ; + $i{quote_rejected} = 0 ; + } + + $i{ligr} = ($i{ligr}) ? 'Yes' : 'No' ; + + $i{city_id} = 0 unless $i{city_id} ; + $i{region_id} = 0 unless $i{region_id} ; + $i{category_id_1} = 0 unless $i{category_id_1} ; + $i{category_id_2} = 0 unless $i{category_id_2} ; + $i{po_nr} = 0 unless $i{po_nr} ; + + # $i{grand_total} = '0.00' unless $i{grand_total} ; + $i{format_of_title} = uc $i{format_of_title} ; + $i{ref} = uc $i{ref} ; + $i{category_1_details} = uc $i{category_1_details} ; + $i{category_2_details} = uc $i{category_2_details} ; + +} #---------------------------------------------------------------------------------------- + +sub list_screen { + + &db_min_ro('event_type_details','id,name','','','') ; + &db_min_ro('event_quotes_categories','id,category','','','') ; + &db_min_ro('event_systems','id,name,description,system_type','','','') ; + &db_min_ro('clubs','id,name','','','') ; + &db_min_ro('cities','id,city,province','','','') ; + + &db_min_ro('users','id,username,name,email','','','') ; + foreach my $_id (keys %{$db{users}}) { + $username{$_id} = $db{users}{$_id}{username} ; + $name{$_id} = $db{users}{$_id}{name} ; + $email{$_id} = $db{users}{$_id}{email} ; + } + + &db_min_ro('sport_types','*','','','') ; + foreach my $_id (keys %{$db{sport_types}}) { $sort_type{$_id} = $db{sport_types}{$_id}{name} ; } + + &db_min_ro('organisations','id,name','','','') ; + foreach my $_id (keys %{$db{organisations}}) { $organisation{$_id} = $db{organisations}{$_id}{name} ; } + + if ($iaction eq 'completed' or $i{options} eq 'completed') { push @report_sql, "q.quote_completed='1'" ; } + if ($iaction eq 'accepted' or $i{options} eq 'accepted') { push @report_sql, "q.quote_accepted='1'" ; } + if ($iaction eq 'rejected' or $i{options} eq 'rejected') { push @report_sql, "q.quote_rejected='1'" ; } + if ($iaction eq 'closed' or $i{options} eq 'closed') { push @report_sql, "(q.quote_cancelled='1' OR (q.quote_expiry<'$now_year-$now_mm-$now_dd' AND q.quote_accepted<>'1'))" ; } + if ($iaction eq 'pending' or $i{options} eq 'pending') { push @report_sql, "q.quote_pending='1'" ; } + if ($iaction eq 'list' or $i{options} eq 'list') { push @report_sql, "q.quote_cancelled<>'1'" ; } + + my $t1 = 'event_quotes'; + my $t2 = 'countries' ; + my $t3 = 'cities' ; + my $t4 = 'customers' ; + my $t5 = 'event_types' ; + my $t6 = 'regions' ; + my $t7 = 'event_quotes_min' ; + our $tables = "$t1,$t2,$t3,$t4,$t5,$t6,$t7" ; + + if ($is_schools_manager || $is_operator) { + @report_sql_or = () ; + foreach $_reg_id (keys %{$glob_regids{$userid}}) { + push @report_sql_or, "q.region_id = '$_reg_id'" + } + my $sql_or = join(' OR ',@report_sql_or) ; + push @report_sql, "($sql_or)" if $sql_or ; + push @report_sql, "(q.quote_created='1')" if $is_schools_manager ; + # push @report_sql, "(q.user_id='$userid')" if $is_schools_manager ; + push @report_sql, "(q.quote_accepted='1')" if $is_operator && !$i{options} ; + } + + push @report_sql, "(q.quote_completed <> '1')" if $iaction eq 'list' ; + + my $srch_where_sql = join(' AND ', @report_sql) ; my $sql_where = ($srch_where_sql) ? "WHERE $srch_where_sql" : '' ; + + &db_min_raw("SELECT q.id AS 'quote_id', + q.quote_nr, + q.sport_type_ids, + q.city_id, + q.region_id, + q.organisation_ids, + q.date_from, + q.date_to, + q.grand_total, + q.ref, + q.qty, + q.quote_expiry, + q.quote_to, + q.invoice_nr, + q.quote_date, + q.type, + q.currency, + q.country_id, + q.quote_cancelled, + q.quote_accepted, + q.quote_completed, + q.quote_pending, + q.quote_created, + q.quote_rejected, + q.activetab, + q.user_id, + q.category_1, + q.category_id_1, + q.category_2, + q.category_id_2, + q.additional_notes, + q.poc_name, + q.poc_contact_nr, + q.type_details_id, + q.club_ids, + q.event_system_id_multiple, + q.operator_ids, + q.format_of_title, + q.emailed_op_ids, + q.fixed_system_overall_status, + q.daily_operator_ids, + c.name AS 'country', + t.name AS 'customer', + y.city, + y.province, + r.code AS 'reg_code', + r.name AS 'region', + e.name AS 'event_type', + emin.category_details + FROM $t1 q LEFT JOIN $t2 c ON q.country_id = c.id + LEFT JOIN $t3 y ON q.city_id = y.id + LEFT JOIN $t4 t ON q.quote_to = t.id + LEFT JOIN $t5 e ON q.type = e.id + LEFT JOIN $t6 r ON q.region_id = r.id + LEFT JOIN $t7 emin ON q.id = emin.quote_nr + $sql_where;"); + + foreach $row (@$rows_array_ref) { + for (0 .. $col_cnt){ + # &common_debug("[$_] $col_name{$_} -> @$row[$_]") ; + $db{$tables}{@$row[0]}{$col_name{$_}} = @$row[$_] ; + } + } + + + &tab_hash ; # load for PDF links + "e_list ; # load for PDF links + + if ($iaction eq 'update' or $iaction eq 'save'){ + &common_min_extra_crumb("list-$lcpage\s","List $ucfirstpage\s") ; + } + + our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + +} #------------------------------------------------------------------------------------------ + +sub quote_list { + + # our @sql_col_display = ("nr","date","customer","user","event","venue","location","sports_type","date_from","date_to","days","type") ; + # our @sql_col_display = ("nr","event_start","event_end","date_added","customer","user","event","venue","location","sports_type","days","type") ; + + if ($usertype eq 'support') { + our @sql_col_display = ("nr","event_start","days","event","location","sport","system_name","club_names","operators") ; + our @col_display_excel = @sql_col_display ; + } else { + our @sql_col_display = ("nr","event_start","event_end","days","date_added","customer","user","event","venue","location","sport","type","operators") ; + if ($userid eq '24') { + # if ($glod_user_level > 3) { + push @sql_col_display, "amount" ; + push @sql_col_display, "invoice_nr" ; + } + + our @col_display_excel = ("nr","event","event_start","event_end","days","type_of_system","system_details","system_name","sport_type","cities","region","venue","club_names","operators","client","poc_name","poc_contact_nr","category_1","category_1_details","category_2","category_2_details","format_of_title") ; + } + + push @sql_col_display, "" ; + + &report_xlsx_export_header_events("Events",'events') ; + + my @month_fullname = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") ; # if ($i{export_to_excel}) { &report_xls_export_header("Event Quotes",'event_quotes') ; } + my @day_of_week_text = ("", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") ; + + foreach my $id (sort {$b <=> $a} keys %{$db{$tables}}) { + + next unless $id ; + + my $quote_expiry = $db{$tables}{$id}{quote_expiry} ; $quote_expiry =~ s/\-//iog ; + my $invoice_nr = $db{$tables}{$id}{invoice_nr} ; + my $quote_accepted = $db{$tables}{$id}{quote_accepted} ; + my $quote_pending = $db{$tables}{$id}{quote_pending} ; + my $quote_cancelled = $db{$tables}{$id}{quote_cancelled} ; + my $quote_completed = $db{$tables}{$id}{quote_completed} ; + my $quote_created = $db{$tables}{$id}{quote_created} ; + my $quote_rejected = $db{$tables}{$id}{quote_rejected} ; + my @cat_details = split('\|;\|',$db{$tables}{$id}{category_details}) ; + + if ($quote_completed) { + $sortprefix = 'd' ; + } elsif ($quote_accepted) { + $sortprefix = 'c' ; + } elsif ($quote_rejected) { + $sortprefix = 'x' ; + } elsif ($quote_cancelled) { + $sortprefix = 'z' ; + } elsif ($quote_created) { # create by schools_manager + $sortprefix = 'a' ; + } elsif ($quote_pending) { + $sortprefix = 'b' ; + } + + if ($usertype eq 'support') { + next unless $quote_accepted && !$quote_completed ; + } + + # if ($quote_expiry and $quote_expiry<"$now_year$now_mm$now_dd" and $iaction ne 'report' and $iaction ne 'accepted' and $iaction ne 'closed' and $iaction ne 'all') { next ; } + + my $quote_date = $db{$tables}{$id}{quote_date} ; $quote_date =~ s/\-//iog ; + + $yr = substr($quote_date, 0, 4) ; + $mm = substr($quote_date, 4, 2) ; + $dd = substr($quote_date, 6, 2) ; + + my ($yr2,$mm2,$dd2) = Add_Delta_Days($yr,$mm,$dd,60); # + + $mm2 = sprintf("%02s", $mm2) ; + $dd2 = sprintf("%02s", $dd2) ; + + $quote_date = "$yr2$mm2$dd2" ; + + if ($quote_date && $quote_date < "$now_year$now_mm$now_dd" && $quote_accepted!=1 && + $iaction ne 'report' && $iaction ne 'accepted' && $iaction ne 'closed' && $iaction ne 'all' && + $i{options} ne 'accepted' && $i{options} ne 'closed' && $i{options} ne 'all') + { next ; } + + $print_tbody .= qq~~ ; + + $xlsxcol=0; + + my $quote_nr = $db{$tables}{$id}{quote_nr} ; + + foreach (@sql_col_display) { + unless ($_) { next ; } # blank for the buttons column + my $val = $db{$tables}{$id}{$_} ; + my $align = qq~ class="dt-center"~ ; + my $nowrap = '' ; + + # if ($_ eq 'event_end') { $val = substr($db{$tables}{$id}{date_to},0,10) ; $align = qq~ class="dt-center" style="width:6.9%"~ ; } + # elsif ($_ eq 'event_start') { $val = substr($db{$tables}{$id}{date_from},0,10) ; $nowrap = 'nowrap' ; } + if ($_ eq 'event_end') { $val = substr($db{$tables}{$id}{date_to},0,16) ; $align = qq~ class="dt-center"~ ; $nowrap = 'nowrap' ; } + elsif ($_ eq 'event_start') { my ($dy,$dm,$dd,$th,$tm,$ts) = &common_min_split_sql_date_time($db{$tables}{$id}{date_from}) ; my $sccyymmddhrmnsc = $dy . $dm . $dd . $th . $tm . $ts ; $val = "$sortprefix$sccyymmddhrmnsc" . substr($db{$tables}{$id}{date_from},0,16) ; $nowrap = 'nowrap' ; } + elsif ($_ eq 'event') { $val = $db{$tables}{$id}{ref} ; $nowrap = 'nowrap' ; } + elsif ($_ eq 'customer') { $nowrap = 'nowrap' ; } + elsif ($_ eq 'date_added') { $val = $db{$tables}{$id}{quote_date} ; $nowrap = 'nowrap' ; } + elsif ($_ eq 'curr') { $val = $db{$tables}{$id}{currency} ; } + elsif ($_ eq 'location') { $val = ($db{$tables}{$id}{city} & $db{$tables}{$id}{reg_code}) ? "$db{$tables}{$id}{city}, $db{$tables}{$id}{reg_code}" : ($db{$tables}{$id}{city}) ? $db{$tables}{$id}{city} : $db{$tables}{$id}{reg_code} ; $nowrap = 'nowrap' ; } + elsif ($_ eq 'country_id') { $val = $db{$tables}{$id}{country} ; } + elsif ($_ eq 'days') { $val = $db{$tables}{$id}{qty} ; } + elsif ($_ eq 'type') { my $txt = uc substr($db{$tables}{$id}{event_type},0,1); $val = qq~$txt~; $nowrap = 'nowrap' ; } + elsif ($_ eq 'amount') { my $ttl = sprintf("%0.2f",($db{$tables}{$id}{grand_total})) ; $val = &common_commify($ttl) ; } + elsif ($_ eq 'system_name') { + $val = '' ; + foreach my $event_id (split(";",$db{$tables}{$id}{event_system_id_multiple})) { + $val .= qq~$db{event_systems}{$event_id}{name} [$db{event_systems}{$event_id}{description}], ~ ; + } + chop $val if $val ; chop $val if $val ; + } elsif ($_ eq 'club_names') { + $val = '' ; + foreach my $club_id (split(";",$db{$tables}{$id}{club_ids})) { + $val .= qq~$db{clubs}{$club_id}{name}, ~ ; + } + chop $val if $val ; chop $val if $val ; + } elsif ($_ eq 'operators') { + $val = '' ; $op_cnt = 0 ; + my %seen_op_id = () ; + my @op_ids = split(/,/,$db{$tables}{$id}{operator_ids}) ; + for my $op_id (@op_ids) { + next if $seen_op_id{$op_id} || !$op_id ; + $seen_op_id{$op_id} = 1 ; $op_cnt++; + $val .= qq~$name{$op_id}
    ~ ; + } + foreach my $op_ids (split(/\|/,$db{$tables}{$id}{daily_operator_ids})) { + foreach my $opid (split(/\;/,$op_ids)) { + next if $seen_op_id{$opid} || !$opid ; + $seen_op_id{$opid} = 1 ; $op_cnt++; + $val .= qq~$name{$opid}
    ~ ; + } + } + $val = substr($val,0,-4) if $val ; + # $val = qq~~ if $val ; + $glyph_icon = ($op_cnt > 1) ? qq~~ : qq~~ ; + $val = qq~$glyph_icon~ if $val ; + + } elsif ($_ eq 'venue') { + my @oids = split(/\,/,$db{$tables}{$id}{organisation_ids}) ; + my @venues = map { $organisation{$_} } @oids; + $val = join(", ",@venues) ; + # foreach $_oid (@oids) { + # $val .= $organisation{$_oid} . ',' ; + # } + # chop $val ; + } elsif ($_ eq 'sport') { + my @sptyps = split(/\,/,$db{$tables}{$id}{sport_type_ids}) ; + my @sports = map { $sort_type{$_} } @sptyps; + $val = join(", ",@sports) ; # foreach $_sp (@sptyps) { $val .= $sort_type{$_sp} . ', ' ; } + # chop $val if $val ; + } elsif ($_ eq 'nr') { + + $val = &common_min_get_event_quote_button($id,$tables) ; + + + # my $class = 'info' ; my $style = '' ; + # if ($quote_completed) { + # $class = 'success' ; # green + # $tt_txt = 'Completed' ; + # } elsif ($quote_accepted) { + # $class = 'info' ; # blue + # $tt_txt = 'Accepted' ; + # my @fixed_system_overall_statuses = split(/\;/,$db{$tables}{$id}{fixed_system_overall_status}) ; + # my @event_system_ids = split(/\;/,$db{$tables}{$id}{event_system_id_multiple}) ; + # my $event_sys_cnt = 0 ; my $event_sys_test_status = 0 ; my $got_some_fixed = 0 ; my $fixed_status_color = '164473' ; # Dark Blue + # foreach my $event_id (@event_system_ids) { + # if ($db{event_systems}{$event_id}{system_type} eq 'fixed') { + # $tt_txt = 'Accepted and tests show All Clear for the Fixed Systems' if $tt_txt eq 'Accepted' ; + # $got_some_fixed = 1 ; + # if ($fixed_system_overall_statuses[$event_sys_cnt] == 3) { # Not Clear + # $fixed_status_color = '5d09d3' ; # Dark Purple + # $tt_txt = 'Accepted but Not Clear on some Fixed Systems' ; + # } elsif ($fixed_system_overall_statuses[$event_sys_cnt] == 2) { # Sound Issue + # $fixed_status_color = '5d092c' ; + # $tt_txt = 'Accepted but Sound Issue found on some Fixed Systems' ; + # } + # } + # $event_sys_cnt++; + # } + # if ($got_some_fixed) { $style = "style='background-color:#$fixed_status_color;border-color:#$fixed_status_color'"; } + # } elsif ($quote_rejected) { + # $style = 'style="background-color:#ca0ad3;border-color:#ca0ad3"'; # purple + # $tt_txt = 'Rejected' ; + # } elsif ($quote_cancelled) { + # $class = 'danger' ; # red + # $tt_txt = 'Cancelled' ; + # } elsif ($quote_created) { # create by schools_manager + # $style = 'style="background-color:#f6e305;border-color:#f6e305"'; # yellow + # $tt_txt = 'Pending, created by School Manager' ; + # } elsif ($quote_pending) { + # $class = 'warning' ; # orange + # $tt_txt = 'Pending' ; + # } + + # my $tt = qq~data-toggle="tooltip" data-placement="right" data-title="$tt_txt"~; + + # # &common_debug("$quote_nr quote_created [$quote_created] $style") if $quote_created ; + + # # $val = ($is_schools_manager) ? qq~$quote_nr~ : qq~$quote_nr~ ; + # # $val = ($glod_user_level < 4 || $quote_cancelled) ? qq~$quote_nr~ : qq~$quote_nr~ ; + # $val = ($glod_user_level < 3 || $quote_cancelled) ? qq~$quote_nr~ : qq~$quote_nr~ ; + } + elsif ($_ eq 'user') { + $val = '' ; + # $val = $db{users}{$db{$tables}{$id}{user_id}}{username} if $db{$tables}{$id}{user_id} ; + $val = $username{$db{$tables}{$id}{user_id}} ; + } + + $print_tbody .= qq~$val~ ; + } + + my $start_date = substr($db{$tables}{$id}{date_from},0,10); + my $end_date = substr($db{$tables}{$id}{date_to},0,10); + # my @event_dates = () ; + + my $year = substr($db{$tables}{$id}{date_from}, 0, 4) ; + my $month = substr($db{$tables}{$id}{date_from}, 5, 2) ; + my $day = substr($db{$tables}{$id}{date_from}, 8, 2) ; + + my $year_end = substr($db{$tables}{$id}{date_to}, 0, 4 ) ; + my $month_end = substr($db{$tables}{$id}{date_to}, 5, 2 ) ; + my $day_end = substr($db{$tables}{$id}{date_to}, 8, 2 ) ; + + # push @event_dates, $year . '-' . $month . '-' . $day ; + + # my $Dd = Delta_Days($year,$month,$day, $year_end,$month_end,$day_end); + + my $row_count = 0; + # for my $event_date (sort @event_dates) { + $xlsxcol = 0 ; + $row_count++ ; + + if (($quote_created and not $quote_accepted and not $quote_completed) or ($quote_completed and not $quote_created and not $quote_accepted and not $quote_completed)) { + $xlsxrow-- ; + } + + my @event_sys = split(/;/,$db{$tables}{$id}{event_system_id_multiple}) ; + my $cnt_event_sys = 0 ; + foreach (split(/;/,$db{$tables}{$id}{event_system_id_multiple})) { + $cnt_event_sys++ ; + } + $cnt_event_sys = 1 unless $cnt_event_sys ; + + foreach my $col_name (@col_display_excel) { + + next if ($quote_created and not $quote_accepted and not $quote_completed) or ($quote_completed and not $quote_created and not $quote_accepted and not $quote_completed) ; + + $val = $db{$tables}{$id}{$col_name} ; + + # $xlsxrow-- if $col_name ne 'event_start' ; + + if ($col_name eq 'event_end') { $val = substr($db{$tables}{$id}{date_to},0,16) ; } + elsif ($col_name eq 'event_start') { $val = substr($db{$tables}{$id}{date_from},0,16) ; } + elsif ($col_name eq 'nr') { + $val = $id ; + if ($quote_completed) { + for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format80) ; $xlsxrow++; } # green + $xlsxrow = $xlsxrow - $cnt_event_sys ; + } elsif ($quote_accepted) { + for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format77) ; $xlsxrow++; } # blue + $xlsxrow = $xlsxrow - $cnt_event_sys ; + } elsif ($quote_created) { # create by schools_manager + # next ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format78) ; # yellow + } elsif ($quote_pending) { + # next ; + # &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format79) ; # orange + } elsif ($quote_cancelled) { + for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format81) ; $xlsxrow++; } # red + $xlsxrow = $xlsxrow - $cnt_event_sys ; + } + $xlsxcol++ ; + next ; + } elsif ($col_name eq 'event') { + $val = $db{$tables}{$id}{ref} ; + for (1 .. $cnt_event_sys) { &xlsxcreator_write_xlsx($ws,$xlsxrow,$xlsxcol,$val,$format82) ; $xlsxrow++; } + $xlsxrow = $xlsxrow - $cnt_event_sys ; + $xlsxcol++; + next ; + } elsif ($col_name eq 'date') { + $val = substr($event_date, 5, 2 ) ; + $val = substr($event_date, 8, 2 ) . ' ' . $month_fullname[$val - 1] . ' ' . substr($event_date, 0, 4 ) ; + } elsif ($col_name eq 'days') { + $val = $db{$tables}{$id}{qty} ; + } elsif ($col_name eq 'type_of_system') { + $val = $db{$tables}{$id}{event_type} ; + } elsif ($col_name eq 'system_details') { + $val = '' ; + foreach my $type_id (split(",",$db{$tables}{$id}{type_details_id})) { + $val .= qq~$db{event_type_details}{$type_id}{name}, ~; + } + chop $val if $val ; chop $val if $val ; + } elsif ($col_name eq 'system_name') { + + for (0 .. $cnt_event_sys-1) { + $val = qq~$db{event_systems}{$event_sys[$_]}{name}~ unless $db{event_systems}{$event_sys[$_]}{description} ; + $val = qq~$db{event_systems}{$event_sys[$_]}{name} [$db{event_systems}{$event_sys[$_]}{description}]~ if $db{event_systems}{$event_sys[$_]}{description} ; + if ($event_date ne $end_date){ + &report_write_events($val, 0) ; + } else { + &report_write_events($val, 1) ; + } + $xlsxrow++; + } + $xlsxrow = $xlsxrow - $cnt_event_sys ; + + } elsif ($col_name eq 'sport_type') { + my @sptyps2 = split(/\,/,$db{$tables}{$id}{sport_type_ids}) ; + $val = '' ; + foreach $_sp (@sptyps2) { + $val .= qq~$sort_type{$_sp} & ~ ; + } + chop $val if $val ; chop $val if $val ; + # } elsif ($_ eq 'cities' && $row_count == 1) { + } elsif ($col_name eq 'cities') { + $val = qq~$db{$tables}{$id}{city}~ ; + if ($db{$tables}{$id}{city_id} =~ /,/) { + $val = '' ; + foreach my $c_id (split(",",$db{$tables}{$id}{city_id})) { + $val .= qq~$db{cities}{$c_id}{city}, ~ ; + } + chop $val if $val ; chop $val if $val ; + } + } elsif ($col_name eq 'region') { + $val = qq~$db{$tables}{$id}{region}~ ; + } elsif ($col_name eq 'venue') { + $val = '' ; + foreach my $venue_id (split(",",$db{$tables}{$id}{organisation_ids})) { + $val .= qq~$organisation{$venue_id} & ~ ; + } + chop $val if $val ; chop $val if $val ; chop $val if $val ; + } elsif ($col_name eq 'club_names') { + $val = '' ; + foreach my $club_id (split(";",$db{$tables}{$id}{club_ids})) { + $val .= qq~$db{clubs}{$club_id}{name}, ~ ; + } + chop $val if $val ; chop $val if $val ; + } + + elsif ($col_name eq 'operators') { + $val = '' ; + # my @op_split3 = split(/;~;/,$db{$table}{$id}{operator_ids}) ; + # foreach my $op_id (split(/\,/,$op_split3[0])) { + foreach my $op_id (split(/\,/,$db{$tables}{$id}{operator_ids})) { + $val .= qq~$name{$op_id} [$email{$op_id}], ~ ; + } + chop $val if $val ; chop $val if $val ; + } + elsif ($col_name eq 'client') { + $val = $db{$tables}{$id}{customer} ; + } elsif ($col_name eq 'category_1') { + $val = $db{event_quotes_categories}{$db{$tables}{$id}{category_id_1}}{category} ; + } elsif ($col_name eq 'category_1_details') { + $val = $cat_details[0] ; + } elsif ($col_name eq 'category_2') { + $val = $db{event_quotes_categories}{$db{$tables}{$id}{category_id_2}}{category} ; + } elsif ($col_name eq 'category_2_details') { + $val = $cat_details[1] ; + } elsif ($row_count != 1) { + # $val = '' ; + } + + if ($col_name ne 'system_name') { + + for (1 .. $cnt_event_sys) { + if ($event_date ne $end_date){ + &report_write_events($val, 0) ; + } else { + &report_write_events($val, 1) ; + } + $xlsxrow++; + } + $xlsxrow = $xlsxrow - $cnt_event_sys ; + } + + # } + # ------------------------------------------------------------------------- HTML AFTER + $xlsxcol++; + } + + $xlsxrow = $cnt_event_sys + $xlsxrow ; + + my $quote_nr = $quote_nr ; $quote_nr =~ s/'//iog; unless ($quote_nr) { $quote_nr = $id ; } + + # if ($useropts{boss}{$username} or $useropts{super}{$username}) { } + + # my $view_butt = qq~~ ; + my $edit_butt = qq~~ ; + # my $delete_butt = ($glod_user_level < 4 || $quote_accepted || $quote_completed || $quote_rejected || $quote_pending) ? '' : qq~~ ; + my $delete_butt = ($glod_user_level < 3 || $quote_accepted || $quote_completed || $quote_rejected || $quote_pending) ? '' : qq~~ ; + + my $copy_butt = qq~~ ; + + # my $copy_butt = qq~~; + # my $pdf_butt = qq~~; + my $pdf_butt .= qq~~; + + $email_butt = qq~~; + + my %emailed_op_ids = () ; my $all_op_ids = 1 ; my $cnt_op_ids = 0 ; + foreach my $op_id (split(/\;/,$db{$tables}{$id}{emailed_op_ids})) { + $emailed_op_ids{$op_id} = 1 ; + } + + foreach my $op_id2 (split(/\,/,$db{$tables}{$id}{operator_ids})) { + $all_op_ids = 0 if $op_id2 and not $emailed_op_ids{$op_id2} ; + $cnt_op_ids++ if $op_id2 ; + } + + if ($all_op_ids and $cnt_op_ids) { + $trigger_jquery_raw .= qq~ + \$("#email_$id").css({ + "background-color": "lightgrey", + "border-color": "lightgrey" + }); + ~ ; + } + + if ($glod_user_level < 3) { + $delete_butt = '' ; + if ($quote_completed || $quote_cancelled || $quote_rejected) { + $edit_butt = '' ; + } + } + + # $edit_butt = '' if $usertype eq 'support' ; + # $edit_butt = '' if $quote_cancelled && !$useropts{it}{$username}; + + $edit_butt = qq~$edit_butt ~ if $edit_butt ; + $copy_butt = qq~$copy_butt ~ if $copy_butt ; + $delete_butt = qq~$delete_butt ~ if $delete_butt ; + $pdf_butt = qq~$pdf_butt ~ if $pdf_butt ; + $email_butt = qq~$email_butt ~ if $email_butt ; + + if ($quote_created and not $quote_completed and not $quote_accepted) { + $pdf_butt = qq~~ ; $email_butt = qq~~ ; + } + + # $email_butt = qq~ ~ unless $email_butt ; + # $pdf_butt = qq~ ~ unless $pdf_butt ; + + $print_tbody .= qq~ $edit_butt$copy_butt$delete_butt$pdf_butt$email_butt~ ; + } + + $worksheet{$ws}->set_column(0,0,10) ; + $worksheet{$ws}->set_column(1,1,50) ; + $worksheet{$ws}->set_column(2,3,20) ; + $worksheet{$ws}->set_column(4,4,10) ; + $worksheet{$ws}->set_column(5,10,30) ; + $worksheet{$ws}->set_column(11,11,75) ; + $worksheet{$ws}->set_column(12,21,30) ; + + &report_xlsx_export_footer('L',15,'events') ; + + if ($usertype eq 'support') { + $fnsortcol = 1 ; # start date + $fnsortorder = 'asc' ; + } + + # &common_min_extra_crumb("search-$lcpage\s","Search Screen") if $glod_user_level > 3 ; + &common_min_extra_crumb("filter-$lcpage\s","Search Screen") if $glod_user_level > 3 ; + +} #------------------------------------------------------------------------------- + +sub thead { + + &common_min_thead ; + +} #------------------------------------------------------------------------------- + +sub add_db_fields { + + &hidden_fields ; + $hidden{id} = 2 ; + +} #------------------------------------------------------------------------------------------ + +sub edit_db_fields { + + &hidden_fields ; + $hidden{id} = 1 ; + # $readonly{ref} = 'READONLY' ; + +} #------------------------------------------------------------------------------------------ + +sub view_db_fields { + + &hidden_fields ; + $hidden{id} = 1 ; + $label{ref} = 1 ; + $label{qty} = 1 ; + $label{date_from} = 1 ; + $label{date_to} = 1 ; + $label{sport_type_ids} = 1 ; + $label{region_id} = 1 ; + $label{city_id} = 1 ; + $label{organisation_ids} = 1 ; + +} #------------------------------------------------------------------------------------------ + +sub hidden_fields { + + # if ($glod_user_level < 4) { + if ($glod_user_level < 3) { + + $ignore{type_of_system} = 1 ; + $ignore{system_details} = 1 ; + $ignore{system_name} = 1 ; + $ignore{operators} = 1 ; + # $ignore{operator_ids} = 1 ; + } + + if ($glod_user_level < 4) { + # if ($glod_user_level < 3) { + $ignore{po_nr} = 1 ; + $ignore{income} = 1 ; + $ignore{sub_total} = 1 ; + $ignore{vat_total} = 1 ; + $ignore{grand_total} = 1 ; + $ignore{custom_set} = 1 ; + + } + + # $ignore{custom_set} = 1 ; + + $ignore{event_system_calibration_ids} = 1 ; + $ignore{event_system_calibration_status} = 1 ; + + $ignore{category_1_details} = 1 ; + $ignore{category_2_details} = 1 ; + + $ignore{iattachslip} = 1 ; + $ignore{iattachupload_1} = 1 ; + $ignore{iattachupload_2} = 1 ; + $ignore{iattachupload_3} = 1 ; + + $ignore{iattachupload_1} = 1 ; + $ignore{iattachupload_2} = 1 ; + $ignore{iattachupload_3} = 1 ; + + $ignore{sport_type_ids_readonly} = 1 ; + $ignore{region_id_readonly} = 1 ; + $ignore{city_id_readonly} = 1 ; + $ignore{organisation_ids_readonly} = 1 ; + + # $ignore{date_to} = 1 ; + # $ignore{date_from} = 1 ; + $ignore{iaction} = 1 ; + $required{qty} = 4 ; # number + $required{quote_nr} = 1 ; + $readonly{quote_nr} = 'READONLY' ; + $required{quote_to} = 1 ; + $required{currency} = 1 ; + $required{roe} = 1 ; + $required{ref} = 1 ; + $required{region_id} = 1 ; + $required{city_id} = 1 ; + + $required{poc_name} = 1 ; + $required{poc_contact_nr} = 1 ; + $required{category_id_1} = 1 ; + $required{category_1_details} = 1 ; + $required{category_id_2} = 1 ; + $required{category_2_details} = 1 ; + + $hidden{quote_date} = 2 ; + $hidden{last_update} = 2 ; + $hidden{user_id} = 2 ; + $hidden{datetime} = 2 ; + $ignore{saveandexit} = 1 ; + $ignore{income} = 1 ; + $ignore{expenses} = 1 ; + $trigger_jquery_raw .= qq~var curr_changed=0;~; + $trigger_jquery_raw .= qq~var curr_changedW=0;~; + $trigger_jquery_raw .= qq~\$.validate();~; + $extra_js .= qq~~; + +} #------------------------------------------------------------------------------------------ + +sub add_screen { + + # &db_open_ro; + # $db_ignore_open_close=1; + + $selected{max_cams}{10} = 'SELECTED'; + &select_opts('') ; + %col_name = () ; + &db_min_ro($table,'*',"id > 1 AND id < 10",'','') ; + + $page_title = substr($page_title,0,-1) ; + $db{$table}{''}{quote_nr} = &db_min_get_max($table,'quote_nr') ; + $db{$table}{''}{qty} = 1 ; + + # if ($username eq 'rory') { $db{$table}{''}{quote_nr} = 1000 ; } + + &add_db_fields ; + + &build_boxes('','save') ; + + local $all_select_ids_string = join(",",@all_select_ids) ; + $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true });~ ; + + # $db_ignore_open_close=0; + # &db_close_conn; + +} #------------------------------------------------------------------------------------------ + +sub view_screen { + + &edit_screen ; + +} #------------------------------------------------------------------------------------------ + +sub edit_screen { + + unless ($i{id}) { $warning = qq(NO ID) ; return ; } + + # my $users_cols = "id,name,user_type" ; $users_cols = "id,name,user_type,region_ids" if $glod_user_level < 4 ; + my $users_cols = "id,name,user_type" ; $users_cols = "id,name,user_type,region_ids" if $glod_user_level < 3 ; + + &db_min_ro('users',$users_cols,"`user_type` LIKE 'casual%' OR `user_type` = 'schools_manager'",'','') ; + foreach (keys %{$db{users}}) { + next if $db{users}{$_}{user_type} eq 'schools_manager' ; + $casual_name{$_} = $db{users}{$_}{name} ; + $casual_type{$_} = uc substr($db{users}{$_}{user_type},-1,1) ; + $casuals{$_} = 1 if substr($db{users}{$_}{user_type},0,6) eq 'casual' ; + } + + # unless ($iaction eq 'save' or $iaction eq 'update') { + &db_min_ro($table,'*',"id='$i{id}'",'','') ; + # } + + # if ($glod_user_level < 4) { + + # my @abcdef = split(/ /,$db{$table}{$i{id}}{date_from}) ; + + # my ($year1,$month1,$day1) = split(/-/,$abcdef[0]) ; + + # my ($hour1,$min1,$sec1) = split(/:/,$abcdef[1]) ; + + # $trigger_jquery .= qq~ + + # const date1 = new Date("$year1-$month1-$day1T$hour1:$min1:$sec1"); + # const date2 = new Date("$now_year-$now_mm-$now_ddT$now_hour:$now_min:$now_sec"); + + # let timeDiffMillis = Math.abs(date1 - date2); + # let timeDiffHours = timeDiffMillis / (1000 * 60 * 60); + + # if (date1 >= date2 && timeDiffHours <= 18) { + # \$("#cancelbutt").removeClass('btn btn-danger').addClass('btn btn-void'); + # } + + # ~ ; + # } + + my @system_name_ids = split(";",$db{$table}{$i{id}}{event_system_id_multiple}) ; + my @club_ids = split(";",$db{$table}{$i{id}}{club_ids}) ; + my @op_ids = split(",",$db{$table}{$i{id}}{operator_ids}) ; + + my $cnt_rows = 0 ; + for (1 .. $nr_of_system_names_and_clubs) { + $cnt_rows = $_ if $system_name_ids[$_ - 1] or $club_ids[$_ - 1] ; + } + + our @table_op_ids = () ; + our @multi_select_op_ids = () ; + + for (1 .. $cnt_rows) { + push @table_op_ids,$op_ids[$_ - 1] if $op_ids[$_ - 1] ; + push @table_op_ids,0 unless $op_ids[$_ - 1] ; + } + for ($cnt_rows+1 .. $nr_of_system_names_and_clubs) { + push @multi_select_op_ids,$op_ids[$_ - 1] if $op_ids[$_ - 1] ; + } + + our $quote_completed = $db{$table}{$i{id}}{quote_completed} ; + our $quote_accepted = $db{$table}{$i{id}}{quote_accepted} ; + our $quote_pending = $db{$table}{$i{id}}{quote_pending} ; + our $quote_cancelled = $db{$table}{$i{id}}{quote_cancelled} ; + our $quote_rejected = $db{$table}{$i{id}}{quote_rejected} ; + + # our $cancel_butt = ($d_check[2] > $now_ccyymmddhrmnsc && $iaction eq 'edit' && ($quote_completed || $quote_accepted || $quote_pending) && ($glod_user_level > 2 || $is_schools_manager)) ? 1 : 0 ; + our $cancel_butt = ($iaction eq 'edit' && ($quote_completed || $quote_accepted || $quote_pending) && ($glod_user_level > 2 || $is_schools_manager)) ? 1 : 0 ; + our $invoice_exists = 1 if $db{$table}{$i{id}}{invoice_nr} ; + + # if ($is_schools_manager) { + if ($is_schools_manager || $glod_user_level < 4) { + my @ed_from = &common_split_sql_time($db{$table}{$i{id}}{date_from}) ; + my @d_check = &common_add_delta_dhms($ed_from[0],$ed_from[1],$ed_from[2],$ed_from[3],$ed_from[4],$ed_from[5],0,-18,0,0) ; # go 18 hours back from event start + + if ($d_check[2] < $now_ccyymmddhrmnsc) { + $cancel_butt = 0 ; + } + } + + # &common_debug("cancel_butt=$cancel_butt [$i{id}] [$db{$table}{$i{id}}{date_from}] [($d_check[2] > $now_ccyymmddhrmnsc && iaction=$iaction eq 'edit' && (quote_completed=$quote_completed || quote_accepted=$quote_accepted || quote_pending=$quote_pending) && (glod_user_level=$glod_user_level > 2 || is_schools_manager=$is_schools_manager))]"); + + &db_min_ro('events','id,event_quote_nr,category,user_id,startdate,enddate',"event_quote_nr='$db{$table}{$i{id}}{quote_nr}'",'','') ; + + $max_cams = $db{$table}{$i{id}}{max_cams} if $db{$table}{$i{id}}{max_cams} ; + + $page_title = substr($page_title,0,-1) ; + $page_title .= " : $i{id}" ; + + $custom_back_button = qq~ ~ ; + # $custom_back_button = qq~$val~ ; + + # our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab + &common_min_footer('id',"$lcpage\s"); + + &edit_db_fields ; + + $selected{max_cams}{$db{$table}{$i{id}}{max_cams}} = 'SELECTED'; + $selected{casual_worker}{$db{$table}{$i{id}}{casual_worker}} = 'SELECTED'; + $selected{casual_worker_2}{$db{$table}{$i{id}}{casual_worker_2}} = 'SELECTED'; + + # my @assigned_users_a = split(/\:/,$db{$table}{$i{id}}{operator_names_type_a}) ; + # my @assigned_users_b = split(/\:/,$db{$table}{$i{id}}{operator_names_type_b}) ; + + # for (@assigned_users_a){ $selected{operator_names_type_a}{$_} = 'SELECTED'; } + # for (@assigned_users_b){ $selected{operator_names_type_b}{$_} = 'SELECTED'; } + + # $selected{operator_names_type_b}{$db{$table}{$i{id}}{operator_names_type_b}} = 'SELECTED'; + + &select_opts($i{id}) ; + + our $saveandexit = 1 ; + + &build_boxes($i{id},'update') ; + + &common_min_extra_crumb("filter-$lcpage\s","Search $ucfirstpage\s") if $glod_user_level > 3 ; + + local $all_select_ids_string = join(",",@all_select_ids) ; + $trigger_jquery_raw .= qq~\$("$all_select_ids_string").chosen({ allow_single_deselect:true });~ ; + +} #------------------------------------------------------------------------------------------ + +sub build_boxes { + + my ($id,$action) = @_ ; + + our @jquery_trigger_fields = () ; + our @jquery_custom_vat_ids = () ; + our @jquery_duty_ids = () ; + our @jquery_workings_trigger_fields = () ; + + push @jquery_trigger_fields, 'inputRoe' ; + push @jquery_workings_trigger_fields, 'inputRoe' ; + + for (1 .. 15) { + push @jquery_workings_trigger_fields, "checkboxVat_workings_event_$_" ; + push @jquery_workings_trigger_fields, "checkboxExcl_workings_event_$_" ; + # push @jquery_workings_trigger_fields, "checkboxVat_$_\_workings_casual_users" ; + # push @jquery_workings_trigger_fields, "checkboxExcl_$_\_workings_casual_users" ; + } + &tab_curr_symbols; + + foreach $col(keys %required) { + &common_min_forms_required ; + } + + our $tab_cnt = 0 ; + + &tab_load_vars; + + $print_box_content_rows .= &common_min_forms_start($table) ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq~ +
    +
    ~ ; + &build_boxes_top($id); + $print_box_content_rows .= qq~ +
    +
    + ~ ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq~
    ~ ; + + &tab_cnt; + + $print_box_content_rows .= qq(
    + +
    ); + + our %tab_sections = () ; + + foreach (keys %cntxt) { + + my $tab_name = &tab_names($_) ; my $active = '' ; + + # # if ($is_schools_manager) { + # if ($glod_user_level < 4) { + # $active = ($_==2) ? 'active' : '' ; + # } else { + # $active = (($_==1 && $db{$table}{$id}{activetab} eq '') || ($db{$table}{$id}{activetab} eq $tab_name)) ? 'active' : '' ; + # } + + $active = ($_==2) ? 'active' : '' ; + + # if (($_==1) and ($db{$table}{$id}{activetab} eq '')) { + # $active = 'active' ; + # } + # elsif ($db{$table}{$id}{activetab} eq $tab_name) { + # $active = 'active' ; + # } + + my $colsleft = 12 ; my $showright = '' ; + + if ($cntxt{$_} eq 'one' or $cntxt{$_} eq 'seven') { + $colsleft = 6 ; + $showright = 1 ; + } + + $print_box_content_rows .= qq~
    ~; + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_left($id,$_); + $print_box_content_rows .= qq~
    ~ ; + + if ($showright) { + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_right($id,$_); + $print_box_content_rows .= qq~
    ~ ; + } + + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~
    ~ ; + + if ($id) { + $print_box_content_rows .= qq~ +
    +
    ~ ; + $print_box_content_rows .= ($tab_name eq 'Quote') ? qq~~ : qq~~ ; + $print_box_content_rows .= &common_min_box_foot; + } + + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~
    ~ ; + $print_box_content_rows .= qq~
    ~ ; + } + + $print_box_content_rows .= qq~ +
    +
    + ~ ; + + $print_box_content_rows .= qq~
    ~ ; + + #-------------------------------------------------------------------------- + + $print_box_content_rows .= qq~
    ~ ; + &build_boxes_bottom($id); + $print_box_content_rows .= qq~
    ~ ; + + #-------------------------------------------------------------------------- + + + $print_box_content_rows .= &common_min_forms_end($id,$table,$action,$skip) ; + + my $jquery_trigger_ids = '#' . join(",#",@jquery_trigger_fields) ; + my $jquery_workings_trigger_ids = '#' . join(",#",@jquery_workings_trigger_fields) ; + + my $jq_tab_var = '' ; + my $jq_tab = '' ; + my $inp_tab_val = '' ; + foreach (keys %cntxt) { + $jq_tab_var .= qq(var totalTab_$_=0 ; ) ; + $jq_tab .= qq(totalTab_$_=0 ; ) ; + } # $inp_tab_val .= qq(\$("#inputTotal_tab_$_").val(totalTab_$_.toFixed(2)) ;) ; + + # $trigger_jquery_raw .= qq~ + # \$("#selectCurrency").change(function() { + # curr_changed=1; + # curr_changedW=1; + # console.log("1. curr_changed: "+curr_changed) ; + # calcCurr(); + # }); + + # \$('#event_quotes-form:checkbox').change(function() { + # calcAll(); + # }); + + # function calcCosting(excl,item,qty,usd,conv,vat,ttl) + # { + # var itval = item.val(); + # var uval = usd.val(); + # var cval = conv.val(); // currency amount + # var qval = qty.val(); + # var vval = vat.val(); + # // var tval = ttl.val(); + + # if (excl.val() != 0){ + + # var xval = 1; + + # } + + # else if (excl.val() == 0){ + + # var xval = 0; + + # } + # //var xval = excl.val(); + # var dis = \$("#selectDiscount").val(); + # var roe = \$("#inputRoe").val(); // getNum() + + # if (!itval) { + # calcAll(); + # return ; + # } + + # var arrP = itval.split(":"); // 3:0.00:100.00:200.00:223.00:223.00:250.00:250.00:200.00 // id:freight:nett:main_price:gross_10_1_50:gross_10_51_plus:gross_20_1_50:gross_20_51_plus:gross_50 // + # var list = { freight:arrP[1], nett:arrP[2], main_price:arrP[3], source_admin:arrP[4], perc3:arrP[5], perc5:arrP[6], perc6:arrP[6], perc8:arrP[7], perc10:arrP[8], perc15:arrP[9], perc20:arrP[10] }; + + # if (!qval) { + # qval=1; + # qty.val(qval); + # } // set quantity if blank + + # if (!uval) // set USD amount if no amount + # { + # var uval = list.main_price; + # if (dis==3 && qval>0) + # { + # uval=list.perc3; + # } + # else if (dis==5 && qval>0) + # { + # uval=list.perc5; + # } + # else if (dis==6 && qval>0) + # { + # uval=list.perc6; + # } + # else if (dis==8 && qval>0) + # { + # uval=list.perc8; + # } + # else if (dis==10 && qval>0) + # { + # uval=list.perc10; + # } + # else if (dis==15 && qval>0) + # { + # uval=list.perc15; + # } + # else if (dis==20 && qval>0) + # { + # uval=list.perc20; + # } + # } + + # var usdAmnt = uval * 1 ; + # // var currAmnt = usdAmnt / roe ; + # var currAmnt = usdAmnt * roe ; + # var ttlAmnt = currAmnt * qval ; + + # usd.val(usdAmnt.toFixed(2)) ; // set USD currency amount + # conv.val(currAmnt.toFixed(2)) ; // set foreign currency amount + # ttl.val(ttlAmnt.toFixed(2)) ; // set total amount + + # calcAll(); // recalculate the entire sheet + + # console.log("COSTINGS CALCCOSTINGS build boxes : USD AMOUNT="+usdAmnt + "CURR AMOUNT="+currAmnt + "TOTAL AMOUNT="+ttlAmnt) ; + + # // alert(usdAmnt+'(inputAmount_usd_$field):'+usd+':'+qty+'(inputQty_$field)') ; // 0.00:100.00:200.00:223.00:223.00:250.00:250.00:200.00 // + # } + + # function calcCostingWorkings(excl,item,qty,usd,conv,vat) + # { + # var itvalW = item.val(); + # var uvalW = usd.val(); + # var cvalW = conv.val(); // currency amount + # var qvalW = qty.val(); + # var vvalW = vat.val(); + # var xvalW = excl.val(); + + # if (excl.val() != 0){ + # var xvalW = 1 ; + # } + # else if (excl.val() == 0){ + # var xvalW = 0 ; + # } + + # // var disW = \$("#selectDiscount").val(); + # var roeW = \$("#inputRoe").val(); // getNum() + + # if (!itvalW) { + # calcAllWorkings(); + # return ; + # } + + # if (!qvalW) { + # qvalW = 1 ; + # qtyW.val(qvalW) ; + # } // set quantity if blank + + # var usdAmntW = uvalW * 1 ; + # var currAmntW = usdAmntW * roeW ; + # var ttlAmntW = currAmntW * qvalW ; + + # usd.val(usdAmntW.toFixed(2)) ; // set USD currency amount + # // conv.val(currAmntW.toFixed(2)) ; // set foreign currency amount + # conv.val(ttlAmntW.toFixed(2)) ; // set foreign currency amount + # // ttl.val(ttlAmntW.toFixed(2)) ; // set total amount + + # calcAllWorkings(); // recalculate the entire sheet + + # // console.log("WORKINGS CALCCOSTINGSWORKINGS build boxes : USD AMOUNT="+usdAmntW + "CURR AMOUNT="+currAmntW + "TOTAL AMOUNT="+ttlAmntW) ; + + # console.log("calcCostingWorkings tabs: EXCL="+xvalW+", DESCRIPTION="+item+", AMOUNT USD="+uvalW+", QTY="+qvalW+", AMOUNT="+ttlAmntW+", VAT="+vvalW) ; + + # } + + # function calcCurr() + # { + # var roe = \$("#inputRoe") ; + # // roe.val(1); // default currency to 1 + # // var curr = \$("#selectCurrency").val() ; + # // var url = "$useropts{scripts}/get/get_roe.pl?" + curr ; + # // \$.get(url, function(json) { + # // \$.each(json, function(key, data) { + # // roe.val(data.sell_rate); + # // }); + # // calcAll(); + # // }, + # // 'json'); + # } + # ~; + + # $trigger_jquery_raw .= qq~ + # var currArr = {}; // var vat_total = {} ; var total_total = {} ; var subtotal = {} ; var fs_total = {} ; + # var currArrW = {}; + + # $js_curr_arr + + # var currVal = \$("#selectCurrency").val() ; + # var prevRoe = '' ; + # var curRoe = '' ; + + # var currValW = \$("#selectCurrency").val() ; + # var prevRoeW = '' ; + # var curRoeW = '' ; + + # var grandTtl = 0 ; + # var grandSub = 0 ; + # var grandVat = 0 ; + + # var grandTtlW = 0 ; + # var grandSubW = 0 ; + # var grandVatW = 0 ; + + # $jq_tab_var + # \$("$jquery_trigger_ids").change(function() { + # // calcAll(); + # }); + + # function calcAll() + # { + # if (!\$("#selectCurrency\_chosen").val()) { + # \$("#selectCurrency\_chosen").val('ZAR'); + # \$("#selectCurrency\_chosen").trigger("chosen:updated"); + # } + + # if (!\$("#inputRoe").val() || \$("#inputRoe").val() <= 0) { \$("#inputRoe").val(1) ; } + + # grandTtl= 0 ; + # grandSub = 0 ; + # grandVat = 0 ; + + # $jq_tab + # $re_calc_jquery + + # \$("#inputSub_total").val(grandSub.toFixed(2)) ; + # \$("#inputVat_total").val(grandVat.toFixed(2)) ; + # \$("#inputGrand_total").val(grandTtl.toFixed(2)) ; + # \$("#inputIncome").val(grandTtl.toFixed(2)) ; + + # calcProfitLoss() ; + + # console.log("COSTINGS CALC_ALL: SUB TOTAL="+grandSub + "VAT TOTAL="+grandVat + "GRAND TOTAL="+grandTtl ) ; + + # curr_changed=0; + # // console.log("2. curr_changed: "+curr_changed) ; + # } + + # // \$("$jquery_workings_trigger_ids").change(function() { + # ///calcAllWorkings(); + # // }); + + # function calcAllWorkings() + # { + # if (!\$("#selectCurrency\_chosen").val()) { + # \$("#selectCurrency\_chosen").val('ZAR'); + # \$("#selectCurrency\_chosen").trigger("chosen:updated"); + # } + + # if (!\$("#inputRoe").val()) { \$("#inputRoe").val(1) ; } + + # grandTtlW = 0 ; + # grandSubW = 0 ; + # grandVatW = 0 ; + + # $re_calc_jqueryW + + # \$("#inputTotal_amount_workings_event").val(grandSubW.toFixed(2)) ; + # \$("#inputTotal_vat_amount_workings_event").val(grandVatW.toFixed(2)) ; + # \$("#inputTotal_grand_amount_workings_event").val(grandTtlW.toFixed(2)) ; + # \$("#inputExpenses").val(grandTtlW.toFixed(2)) ; // Profit loss calculation + + # calcProfitLoss() ; + + # console.log("WORKINGS CALC_ALLWORKINGS: SUB TOTAL="+grandSubW + "VAT TOTAL="+grandVatW + "GRAND TOTAL="+grandTtlW ) ; + + # curr_changedW=0; + + # } + + # function calcProfitLoss() + # { + + # let inc = \$("#inputIncome").val() ; + # let exp = \$("#inputExpenses").val() ; + + # let pl = inc - exp ; + + # \$("#inputProfit_loss").val(pl.toFixed(2)) ; + # } + # ~ ; + + # $onload .= qq(onload="calcAll();"); + if ($iaction eq 'add'){ $onload .= qq~onload="calcCurr();"~ ; } + # $onload .= qq~onload="calcCurr();"~ ; + + &build_workings_costings_forms_jquery if $glod_user_level > 4 ; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_top { + + my ($id) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(3,6) ; + + $add_form_fields = '' ; + + $fcol=8 ; + + $add_form_fields .= qq~
    ~ ; + $preferred_title{quote_nr} = "Nr" ; + $add_form_fields .= &common_min_form_input('quote_nr',$db{$table}{$id}{quote_nr},'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + if (($db{$table}{$id}{quote_date} eq '') or ($db{$table}{$id}{quote_date} eq '0000-00-00')) { + $db{$table}{$id}{quote_date} = $now_ccyy_mm_dd ; + } + $preferred_title{quote_date} = "Date" ; + $add_form_fields .= &common_min_form_datepicker('quote_date',$db{$table}{$id}{quote_date}) ; + my $plus_n_days_ccyy_mm_dd = &common_add_delta_days(14) ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $preferred_title{quote_to} = "Client" ; + $add_form_fields .= &common_min_form_select('quote_to',$db{$table}{$id}{quote_to},'') ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $dlg{quote_to} = qq~ + ~ ; + $fcol = 7; + $add_form_fields .= &common_min_form_select('country_id',$db{$table}{$id}{country_id},'') ; + $add_form_fields .= qq~
    ~ ; + $fcol = 8; + $print_box_content_rows .= &common_min_box_top('qrcode',"Quote",'BABEC2'); + $print_box_content_rows .= qq~ +
    +
    + $add_form_fields +
    +
    ~; + $print_box_content_rows .= qq~ +
    +
    +   +
    +
    ~ ; + $print_box_content_rows .= &common_min_box_foot; + + $trigger_jquery .= qq~ + + let qu_to = \$("select[name='quote_to']").val() ; + var colonIndex = qu_to.indexOf(":") ; var extractedNumber ; + if (colonIndex !== -1) { + extractedNumber = qu_to.substring(0, colonIndex); + } else { + extractedNumber = qu_to ; + } + if (extractedNumber != 5) { + \$("#inputPoc_name").removeAttr("data-validation") ; + \$("#inputPoc_contact_nr").removeAttr("data-validation") ; + \$("#selectCategory_id_1").removeAttr("data-validation") ; + \$("#textareaCategory_1_details").removeAttr("data-validation") ; + \$("#selectCategory_id_2").removeAttr("data-validation") ; + \$("#textareaCategory_2_details").removeAttr("data-validation") ; + + \$("label[for='inputPoc_name'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='inputPoc_contact_nr'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='selectCategory_id_1'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='textareaCategory_1_details'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='selectCategory_id_2'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='textareaCategory_2_details'] i.glyphicon-asterisk.yellow").remove(); + } + ~ ; + + $trigger_jquery_raw .= qq~ + + \$("select[name='quote_to']").change(function() { + + let qu_to = \$("select[name='quote_to']").val() ; + var colonIndex = qu_to.indexOf(":") ; var extractedNumber ; + if (colonIndex !== -1) { + extractedNumber = qu_to.substring(0, colonIndex); + } else { + extractedNumber = qu_to ; + } + + if (extractedNumber != 5) { + \$("#inputPoc_name").removeAttr("data-validation") ; + \$("#inputPoc_contact_nr").removeAttr("data-validation") ; + \$("#selectCategory_id_1").removeAttr("data-validation") ; + \$("#textareaCategory_1_details").removeAttr("data-validation") ; + \$("#selectCategory_id_2").removeAttr("data-validation") ; + \$("#textareaCategory_2_details").removeAttr("data-validation") ; + + \$("label[for='inputPoc_name'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='inputPoc_contact_nr'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='selectCategory_id_1'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='textareaCategory_1_details'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='selectCategory_id_2'] i.glyphicon-asterisk.yellow").remove(); + \$("label[for='textareaCategory_2_details'] i.glyphicon-asterisk.yellow").remove(); + } else if (extractedNumber == 5 && \$("label[for='inputPoc_name']").find("i.glyphicon.glyphicon-asterisk.yellow").length === 0) { + + \$("label[for='inputPoc_name']").append('') ; + \$("label[for='inputPoc_contact_nr']").append('') ; + \$("label[for='selectCategory_id_1']").append('') ; + \$("label[for='textareaCategory_1_details']").append('') ; + \$("label[for='selectCategory_id_2']").append('') ; + \$("label[for='textareaCategory_2_details']").append('') ; + + \$("#inputPoc_name").attr("data-validation", "required"); + \$("#inputPoc_contact_nr").attr("data-validation", "required"); + \$("#selectCategory_id_1").attr("data-validation", "required"); + \$("#textareaCategory_1_details").attr("data-validation", "required"); + \$("#selectCategory_id_2").attr("data-validation", "required"); + \$("#textareaCategory_2_details").attr("data-validation", "required"); + + } + }); + ~ ; + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_left { + + my ($id,$tab) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(3,6) ; + + &tab_build_qt_left($id,$tab); + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_right { + + my ($id,$tab) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(3,6) ; + + &tab_build_qt_right($id,$tab); + +} #---------------------------------------------------------------------------------------- + +sub build_boxes_bottom { + + my ($id) = @_ ; + + our ($lcol,$fcol) = &common_min_columns(2,2) ; + + $add_form_fields = '' ; + + # --------------- START GRAND TOTAL ---------------------------------------------------------------------------------------------------------------------- + + $print_box_content_rows .= &common_min_form_input('activetab',$db{$table}{$id}{activetab},'hidden') ; + + # --------------- END RAND TOTAL ------------------------------------------------------------------------------------------------------------------------ + +} #---------------------------------------------------------------------------------------- + +sub build_extra_name_row_1 { + + my ($row_cnt,$display) = @_ ; + my $count_dates_in_first_extra_row = 0 ; + $display = ($display) ? "style='display:none;'" : "" ; + my $extra_row_hearders_1 = qq~
    ~ ; + for (1 .. 20) { + $count_dates_in_first_extra_row++ if $days_active_arr[$_ - 1] ; + $date_is_displayed_in_first_extra_row{$_} = 1 if $days_active_arr[$_ - 1] && $count_dates_in_first_extra_row <= 10 ; + $extra_row_hearders_1 .= ($days_active_arr[$_ - 1] && $count_dates_in_first_extra_row <= 10 && $some_row_has_daily_op_1) ? qq~
    ~ : qq~~ ; + } + $extra_row_hearders_1 .= qq~
    ~ ; + return $extra_row_hearders_1 ; + +} #---------------------------------------------------------------------------------------- + +sub build_extra_name_row_2 { + + my ($row_cnt,$display) = @_ ; + $display = ($display) ? "style='display:none;'" : "" ; + my $extra_row_hearders_2 = qq~
    ~ ; + for (11 .. 20) { + $extra_row_hearders_2 .= ($some_row_has_daily_op_2 && $days_active_arr[$_ - 1] && !$date_is_displayed_in_first_extra_row{$_}) ? qq~
    ~ : qq~~ ; + } + $extra_row_hearders_2 .= qq~
    ~ ; + return $extra_row_hearders_2; + +} #---------------------------------------------------------------------------------------- + +sub build_system_name_form { + + my ($system_ids,$club_ids,$quote_accepted,$quote_rejected,$quote_cancelled,$daily_operator_ids,$days_active) = @_ ; + + my @system_name_ids = split(";",$system_ids) ; + my @club_ids = split(";",$club_ids) ; + our @days_active_arr = split(/\;/,$days_active) ; + my @daily_op_ids = () ; + + local $system_count = 0 ; local $system_day_cnt = 0 ; my %row_has_daily_op = () ; my $some_row_has_daily_op = 0 ; our $some_row_has_daily_op_1 = 0 ; our $some_row_has_daily_op_2 = 0 ; my $active_days_count = 0 ; + + foreach my $row (split(/\|/,$daily_operator_ids)) { + $system_count++ ; + next unless $row ; + $system_day_cnt = 0 ; + foreach my $default_op (split(/\;/,$row)) { + $system_day_cnt++ ; + next if !$days_active_arr[$system_day_cnt-1] ; + $active_days_count++ ; + $default_op_ids{$system_count}{$system_day_cnt} = $default_op if $default_op ; + $row_has_daily_op{$system_count} = 1 if $default_op ; + $row_has_daily_op_1{$system_count} = 1 if $default_op && $active_days_count <= 10 ; + $row_has_daily_op_2{$system_count} = 1 if $default_op && $active_days_count > 10 ; + $some_row_has_daily_op = 1 if $default_op ; + $some_row_has_daily_op_1 = 1 if $default_op && $active_days_count <= 10 ; + $some_row_has_daily_op_2 = 1 if $default_op && $active_days_count > 10 ; + + } + } + + $active_days_count = 0 ; my $total_days = 0 ; + + foreach (@days_active_arr) { + $active_days_count++ if $_ ; + $total_days++ ; + } + + $some_row_has_daily_op = 0 if $active_days_count > 6 ; + + $fcol = 2 ; $lcol = 2 ; + + $dlg_add_club = ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) ? '
    ' : qq~
    ~ ; + + my $dlg_operator_ids = '' ; + + # if ($glod_user_level > 2 || ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled))) { + $add_form_fields .= qq~ +
    +
    + +
    +
    +
    +
    + +
    +
    + +
    + $dlg_add_club +
    + +
    + $dlg_operator_ids +
    +
    + ~ ; + + our %date_is_displayed_in_first_extra_row = () ; + + if ($active_days_count <= 6) { + + for (1 .. 20) { + $add_form_fields .= ($some_row_has_daily_op && $days_active_arr[$_ - 1]) ? qq~
    ~ : ($some_row_has_daily_op && !$days_active_arr[$_ - 1] && $final_day >= $_) ? qq~~ : + qq~~ ; + } + $add_form_fields .= qq~
    ~ ; + + } else { + + for (1 .. 20) { + $add_form_fields .= qq~~ ; + } + $add_form_fields .= qq~
    ~ ; + + } + + my $note_display_butt = qq~~ ; + + my $system_name_id = "" ; my $club_name_id = "" ; + + my @plus_button_ids = () ; my @event_system_ids = () ; my @event_club_ids = () ; my @event_operator_ids = () ; my @overall_op_ids = () ; + + my @table_system_name_ids = () ; my @table_club_name_ids = () ; my @table_operator_calibration_ids = () ; + + my $old_op_opts = $opts{operator_ids} ; + $opts{operator_ids} =~ s/\SELECTED//g ; + + for my $row_cnt (1 .. $nr_of_system_names_and_clubs) { + + my $select_sys_name = 0 ; my $select_club_name = 0 ; + + $add_form_fields .= ($active_days_count > 6 && $some_row_has_daily_op_1 && $row_cnt > 1 && ($row_has_daily_op{$row_cnt} || $system_name_ids[$row_cnt - 1] || $club_ids[$row_cnt - 1] || $table_op_ids[$row_cnt - 1])) ? qq~
    ~ : qq~~ ; + + $add_form_fields .= qq~~ if $row_cnt > 1 and not $system_name_ids[$row_cnt - 1] and not $club_ids[$row_cnt - 1] ; + $add_form_fields .= qq~
    ~ if $row_cnt == 1 or $system_name_ids[$row_cnt - 1] or $club_ids[$row_cnt - 1] ; + + push @plus_button_ids,"#btn_system_name_$row_cnt" ; + + my $input_fields_dates_1 = qq~~ ; + my $input_fields_1 = qq~~ ; + my $input_fields_dates_2 = qq~~ ; + my $input_fields_2 = qq~~ ; + + # if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + # $add_form_fields .= qq~
    ~ if $row_cnt > 1 and not $system_name_ids[$row_cnt - 1] and not $club_ids[$row_cnt - 1] ; + # } + + if ($row_cnt == 1 || $row_has_daily_op{$row_cnt} || $system_name_ids[$row_cnt - 1] || $club_ids[$row_cnt - 1] || $table_op_ids[$row_cnt - 1]) { + + if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + + $system_name_id = "inputSystem_name_" ; $club_name_id = "inputClub_name_" ; + $readonly{"system_name_$row_cnt"} = "READONLY" ; $readonly{"club_name_$row_cnt"} = "READONLY" ; $readonly{"operator_id_calibration_$row_cnt"} = "READONLY" ; + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + $fcol = 4 ; + $add_form_fields .= &common_min_form_input_col("system_name_$row_cnt",$db{event_systems}{$system_name_ids[$row_cnt - 1]}{name}) ; + $add_form_fields .= &common_min_form_input_col("club_name_$row_cnt",$db{clubs}{$club_ids[$row_cnt - 1]}{name}) ; + $add_form_fields .= &common_min_form_input_col("operator_id_calibration_$row_cnt",$db{users}{$table_op_ids[$row_cnt - 1]}{name}) ; + $add_form_fields .= qq~
    ~ ; + $fcol = 1 ; + if ($row_has_daily_op{$row_cnt} && $some_row_has_daily_op) { + for (1 .. 20) { + $readonly{"custom_operator_$row_cnt\_$_"} = "READONLY" ; + $add_form_fields .= ($days_active_arr[$_ - 1]) ? &common_min_form_input_col("custom_operator_$row_cnt\_$_",$db{users}{$default_op_ids{$row_cnt}{$_}}{name}) : "" ; + } + + } elsif ($row_has_daily_op{$row_cnt} && $some_row_has_daily_op_1) { + + my $displayed_dates = 0 ; + # $add_form_fields .= qq~
    ~ ; + + $input_fields_dates_1 = qq~
    ~ ; + $input_fields_1 = qq~
    ~ ; + $input_fields_dates_2 = qq~~ ; + $input_fields_2 = qq~~ ; + + my %date_used = () ; + + for (1 .. 20) { + if ($days_active_arr[$_ - 1] && $displayed_dates < 10) { + $input_fields_dates_1 .= qq~
    ~ ; + $readonly{"custom_operator_$row_cnt\_$_"} = "READONLY" ; + $input_fields_1 .= &common_min_form_input_col("custom_operator_$row_cnt\_$_",$db{users}{$default_op_ids{$row_cnt}{$_}}{name}) ; + $displayed_dates++ ; + $date_used{$_} = 1 ; + } + } + + for (11 .. 20) { + + if ($days_active_arr[$_ - 1] && !$date_used{$_}) { + $input_fields_2 = qq~
    ~ unless $input_fields_2 ; + $input_fields_dates_2 = qq~
    ~ unless $input_fields_dates_2 ; + $input_fields_dates_2 .= qq~
    ~ ; + $readonly{"custom_operator_$row_cnt\_$_"} = "READONLY" ; + $input_fields_2 .= &common_min_form_input_col("custom_operator_$row_cnt\_$_",$db{users}{$default_op_ids{$row_cnt}{$_}}{name}) ; + } + } + + $input_fields_1 .= qq~
    ~ ; + $input_fields_dates_1 .= qq~
    ~ ; + $input_fields_2 .= qq~
    ~ if $input_fields_2 ; + $input_fields_dates_2 .= qq~
    ~ if $input_fields_dates_2 ; + + } + + + $fcol = 4 ; + + } else { + + $system_name_id = "selectSystem_name_" ; $club_name_id = "selectClub_name_" ; $op_name_id = "selectOperator_id_calibration_" ; + + push @event_system_ids,"#$system_name_id$row_cnt\_chosen" ; + push @event_club_ids,"#$club_name_id$row_cnt\_chosen" ; + push @event_operator_ids,"#$op_name_id$row_cnt\_chosen" ; + push @overall_op_ids,"#selectOperator_id_calibration_$row_cnt" ; + + $opts{"system_name_$row_cnt"} = $opts{event_system_id} ; $opts{"club_name_$row_cnt"} = $opts{club_ids} ; $opts{"operator_id_calibration_$row_cnt"} = $opts{operator_ids} ; + $allow_deselect{"system_name_$row_cnt"} = 1 ; $allow_deselect{"club_name_$row_cnt"} = 1 ; $allow_deselect{"operator_id_calibration_$row_cnt"} = 1 ; + + my $sys_name_id = $system_name_ids[$row_cnt - 1] ; + if ($sys_name_id) { + $trigger_jquery_raw .= qq~\$("#selectSystem_name_$row_cnt").val('$sys_name_id') ; \$("#selectSystem_name_$row_cnt").trigger("chosen:updated") ; ~ ; + } else { + push @table_system_name_ids,"#selectSystem_name_$row_cnt" ; + } + + my $club_id = $club_ids[$row_cnt - 1] ; + if ($club_id) { + $trigger_jquery_raw .= qq~\$("#selectClub_name_$row_cnt").val('$club_id') ; \$("#selectClub_name_$row_cnt").trigger("chosen:updated") ; ~ ; + } else { + push @table_club_name_ids,"#selectClub_name_$row_cnt" ; + } + + my $op_id = $table_op_ids[$row_cnt - 1] ; + + $preferred_title{"operator_id_calibration_$row_cnt"} = "Operator $row_cnt" ; + + $fcol = 4 ; + + $add_form_fields .= qq~
    ~ ; + $add_form_fields .= qq~
    ~ ; + + $add_form_fields .= &common_min_form_select_col("system_name_$row_cnt",$system_name_ids[$row_cnt - 1]) if $row_cnt == 1 ; + $add_form_fields .= &common_min_form_select_col("system_name_$row_cnt",'') if $row_cnt > 1 ; + $add_form_fields .= &common_min_form_select_col("club_name_$row_cnt",$club_ids[$row_cnt - 1]) if $row_cnt == 1 ; + $add_form_fields .= &common_min_form_select_col("club_name_$row_cnt",'') if $row_cnt > 1 ; + $add_form_fields .= &common_min_form_select_col("operator_id_calibration_$row_cnt",'') ; + + $add_form_fields .= qq~
    ~ ; + + $fcol = 2 ; + + my $clicked_op_butt = ($row_has_daily_op{$row_cnt}) ? qq~value="1"~ : qq~~ ; + + # if ($glod_user_level > 2) { + my $clicked_any_button = ($row_cnt == 1) ? "" : "" ; + $add_form_fields .= qq~~ ; + push @table_plus_button_ids,"#add_daily_operators_$row_cnt" ; # my $daily_op_exists = 0 ; + # } + + if (!$row_has_daily_op{$row_cnt} && $op_id) { + $trigger_jquery_raw .= qq~\$("#selectOperator_id_calibration_$row_cnt").val('$op_id') ; \$("#selectOperator_id_calibration_$row_cnt").trigger("chosen:updated") ; ~ ; + } + else { + push @table_operator_calibration_ids,"#selectOperator_id_calibration_$row_cnt" ; + } + + for (1 .. 20) { + push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ; + } + + if ($active_days_count <= 6) { + + for (1 .. 20) { + + # push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ; + + my $style_disp = ($row_has_daily_op{$row_cnt} && $days_active_arr[$_ - 1]) ? "" : "style='display:none;'" ; + + if (!$row_has_daily_op{$row_cnt} || ($style_disp && $row_has_daily_op{$row_cnt} && $final_day < $_)) { + $add_form_fields .= qq~
    ~ ; + } else { + # $style_disp = ($row_has_daily_op{$row_cnt} && $days_active_arr[$_ - 1]) ? "" : "style='display:none;'" ; + $style_disp = (!$days_active_arr[$_ - 1]) ? "style='display:none;'" : "" ; + my $class = ($style_disp) ? 0 : 1 ; + push @all_select_ids,"#selectCustom_operator_$row_cnt\_$_" ; #####CHECK!!!!!!!!!!!!!!!!!!!!!!!!!! + # push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ; + $add_form_fields .= qq~
    ~ ; + + $trigger_jquery_raw .= qq~ + \$("#selectCustom_operator_$row_cnt\_$_").val("$default_op_ids{$row_cnt}{$_}") ; \$("#selectCustom_operator_$row_cnt\_$_").trigger("chosen:updated") ; + + if (!\$("#clicked_any_button").text()) { + \$("#clicked_any_button").text("1") ; + } + if (!\$("input[name='clicked_button_$row_cnt']").val()){ + \$("input[name='clicked_button_$row_cnt']").val("1") ; + } + ~ if $default_op_ids{$row_cnt}{$_} ; + } + } + + my $extra_row_hearders_1 = &build_extra_name_row_1($row_cnt,1) ; + + $add_form_fields .= qq~
    $extra_row_hearders_1$extra_row_hearders_2$extra_row_hearders_1
    ~ ; + + my $final_day_in_extra_row_1 = 0 ; + foreach (sort {$a <=> $b} keys %date_is_displayed_in_first_extra_row) { + $final_day_in_extra_row_1 = $_ ; + } + + for (1 .. 20) { + + # push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ; + + if ($_ <= $final_day_in_extra_row_1) { + + my $style_disp = ($days_active_arr[$_ - 1]) ? "" : "style='display:none;'" ; + my $class = ($style_disp) ? 0 : 1 ; + + push @all_select_ids,"#selectCustom_operator_$row_cnt\_$_" ; #####CHECK!!!!!!!!!!!!!!!!!!!!!!!!!! + # push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ; + $add_form_fields .= qq~
    ~ ; + + $trigger_jquery_raw .= qq~ + \$("#selectCustom_operator_$row_cnt\_$_").val("$default_op_ids{$row_cnt}{$_}") ; \$("#selectCustom_operator_$row_cnt\_$_").trigger("chosen:updated") ; + + if (!\$("#clicked_any_button").text()) { + \$("#clicked_any_button").text("1") ; + } + if (!\$("input[name='clicked_button_$row_cnt']").val()){ + \$("input[name='clicked_button_$row_cnt']").val("1") ; + } + ~ if $default_op_ids{$row_cnt}{$_} ; + + } else { + $add_form_fields .= qq~~ ; + } + } + $style_disp = ($active_days_count >= 10) ? "" : "style='display:none;'" ; + + my $extra_row_hearders_2 = ($active_days_count >= 10) ? &build_extra_name_row_2($row_cnt,0) : &build_extra_name_row_2($row_cnt,1) ; + $add_form_fields .= qq~
    $extra_row_hearders_2
    ~ ; + for (11 .. 20) { + + if (!$date_is_displayed_in_first_extra_row{$_} && $days_active_arr[$_ - 1] && $_ <= $final_day) { + + push @all_select_ids,"#selectCustom_operator_$row_cnt\_$_" ; #####CHECK!!!!!!!!!!!!!!!!!!!!!!!!!! + # push @daily_op_ids,"#selectCustom_operator_$row_cnt\_$_" ; + $add_form_fields .= qq~
    ~ ; + $trigger_jquery_raw .= qq~ + \$("#selectCustom_operator_$row_cnt\_$_").val("$default_op_ids{$row_cnt}{$_}") ; \$("#selectCustom_operator_$row_cnt\_$_").trigger("chosen:updated") ; + + if (!\$("#clicked_any_button").text()) { + \$("#clicked_any_button").text("1") ; + } + if (!\$("input[name='clicked_button_$row_cnt']").val()){ + \$("input[name='clicked_button_$row_cnt']").val("1") ; + } + ~ if $default_op_ids{$row_cnt}{$_} ; + } else { + $add_form_fields .= qq~~ ; + } + } + } + $select_sys_name = $system_name_ids[$row_cnt] ; + $select_sys_name = '' unless $select_sys_name ; + } + + $add_form_fields .= qq~
    $input_fields_dates_1$input_fields_1$input_fields_dates_2$input_fields_2~ ; + + } + + # $add_form_fields .= ($active_days_count > 6 && $some_row_has_daily_op_1 && ($row_cnt == 1 || $row_has_daily_op{$row_cnt} || $system_name_ids[$row_cnt - 1] || $club_ids[$row_cnt - 1] || $table_op_ids[$row_cnt - 1])) ? qq~
     
    ~ : qq~~ ; + + $note_display_butt = '' ; + + if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + $note_display_butt = qq~display:none;~ ; + } else { + if ($row_cnt > 1 and not $system_name_ids[$row_cnt-1] and not $club_ids[$row_cnt-1]) { + $note_display_butt = qq~display:none;~ ; + } + if ($system_name_ids[$row_cnt] or $club_ids[$row_cnt]) { + $note_display_butt = qq~display:none;~ ; + } + $add_form_fields .= qq~ +
    +
    +
    + + + +
    +
    + ~ ; + } + + # $trigger_jquery_raw .= qq~ + # \$("#btn_system_name_$row_cnt").click(function () { + # var v = $row_cnt + 1 ; var v2 = $row_cnt + 2 ; + # \$("#btn_row_$row_cnt").hide(); + # if (v < 15 && \$('#system_name_row_'+v2).is(':hidden')) { + # \$("#btn_row_"+v).show(); + # } + # \$("#system_name_row_"+v).show(); + # }); + # ~ ; + + # $trigger_jquery .= qq~\$("#$system_name_id$row_cnt\_chosen").css("width","100%");~ ; + # $trigger_jquery .= qq~\$("#$club_name_id$row_cnt\_chosen").css("width","100%");~ ; + # $trigger_jquery .= qq~\$("#$op_name_id$row_cnt\_chosen").css("width","90%");~ ; + + } + + $opts{operator_ids} = $old_op_opts ; + + my $table_system_name_ids_string = join(",",@table_system_name_ids) ; + my $table_club_name_ids_string = join(",",@table_club_name_ids) ; + my $table_operator_calibration_ids_string = join(",",@table_operator_calibration_ids) ; + + my @all_table_ids = () ; + push @all_table_ids,$table_system_name_ids_string if $table_system_name_ids_string ; + push @all_table_ids,$table_club_name_ids_string if $table_club_name_ids_string ; + push @all_table_ids,$table_operator_calibration_ids_string if $table_operator_calibration_ids_string ; + + my $all_table_ids_string = join(",",@all_table_ids) ; + + $trigger_jquery_raw .= qq~ + \$("$all_table_ids_string").val('') ; \$("$all_table_ids_string").trigger("chosen:updated") ; + ~ if $all_table_ids_string ; + + my $plus_button_ids_string = join(",",@plus_button_ids) ; + + if ($glod_user_level < 3 && ($quote_accepted || $quote_rejected || $quote_cancelled)) { + + } else { + + my $system_name_options = &fix_options_for_javascript($opts{"system_name_1"}) ; + my $club_name_options = &fix_options_for_javascript($opts{"club_name_1"}) ; + our $operator_options = &fix_options_for_javascript($opts{"operator_id_calibration_1"}) ; + my $event_system_ids_string = join(",",@event_system_ids) ; + my $event_club_ids_string = join(",",@event_club_ids) ; + my $event_operator_ids_string = join(",",@event_operator_ids) ; + my $daily_op_ids_string = join(",",@daily_op_ids) ; + my $overall_op_ids_string = join(",",@overall_op_ids) ; + $trigger_jquery .= qq~\$("$event_system_ids_string,$event_club_ids_string").css("width","100%");~ ; + $trigger_jquery .= qq~\$("$event_operator_ids_string").css("width","90%");~ ; + + my $table_plus_button_ids_string = join (",",@table_plus_button_ids) ; + # $table_plus_button_ids_string = "#selectCustom_operator_1_1,#selectCustom_operator_1_3,#selectCustom_operator_1_2" ; + # $table_plus_button_ids_string = "#selectCustom_operator_1_1,#selectCustom_operator_1_3,#selectCustom_operator_1_2" ; + + $trigger_jquery_raw .= qq~ + + function get_row_nr (id) { + let lastIndex = id.lastIndexOf('_'); + lastIndex = parseInt(lastIndex) ; + let row_nr = id.substring(1+lastIndex); + row_nr = parseInt(row_nr) ; + return row_nr ; + } + + function add_checkbox (row_nr,field_name,field_id,tindex,fcol) { + let checkbox = "
    " ; + return checkbox ; + } + + function add_input (row_nr,field_name,field_id,placeholder,tindex,readonly,fcol) { + let input = "
    " ; + return input ; + } + + function add_select (row_nr,field_name,field_id,placeholder,options,tindex,fcol,width,div_id,hide_div) { + let select = "
    " ; + select = select + add_select_raw(row_nr,field_name,field_id,placeholder,options,tindex,width) ; + select = select + "
    " ; + return select ; + } + + function add_select_raw (row_nr,field_name,field_id,placeholder,options,tindex,width) { + let select_raw = "
    " ; + return select_raw ; + } + + function add_event_system_extra_row (row_cnt,nr_of_active_days) { + + } + + function add_event_system_row (row_cnt,nr_of_active_days) { + + let new_row = "
    " ; + + new_row = new_row + add_select (row_cnt,"system_name_"+row_cnt,"selectSystem_name_"+row_cnt,"Select System Name "+row_cnt,"$system_name_options",-1,4,100,'','') ; + new_row = new_row + add_select (row_cnt,"club_name_"+row_cnt,"selectClub_name_"+row_cnt,"Select Club Name "+row_cnt,"$club_name_options",-1,4,100,'','') ; + new_row = new_row + add_select (row_cnt,"operator_id_calibration_"+row_cnt,"selectOperator_id_calibration_"+row_cnt,"Select Operator "+row_cnt,"$operator_options",-1,4,90,'','') ; + + // let glod_user_level = parseInt("$glod_user_level") ; + + // if (glod_user_level < 3) { return new_row ; } + + new_row = new_row +"
    " ; + + let extra_row_1,extra_row_2,extra_name_row_1,extra_name_row_2 ; + + // if (nr_of_active_days <= 6) { + + for (let col=1; col<=20; col++) { + // if (\$("#day_"+col).val()) { + // new_row = new_row + add_select (row_cnt,"custom_operator_"+row_cnt+"_"+col,"selectCustom_operator_"+row_cnt+"_"+col,"Select an Option","$operator_options",-1,1,100,"id='day_"+row_cnt+"_"+col+"'","style='display:none;'") ; + // } else { + new_row = new_row + "" ; + // } + } + + new_row = new_row+"
    " ; + extra_row_1 = "