Added Job detail page with a datatable displaying all Tasks related to that Job.

This commit is contained in:
rocketdebris 2025-12-23 14:48:28 -05:00
parent 49840b6c38
commit b2f77f2ca1
3 changed files with 219 additions and 22 deletions

View file

@ -1,10 +1,69 @@
import frappe, json import frappe, json
from custom_ui.db_utils import process_query_conditions, build_datatable_dict, get_count_or_filters, build_success_response from custom_ui.db_utils import process_query_conditions, build_datatable_dict, get_count_or_filters, build_success_response, build_error_response
# =============================================================================== # ===============================================================================
# JOB MANAGEMENT API METHODS # JOB MANAGEMENT API METHODS
# =============================================================================== # ===============================================================================
@frappe.whitelist()
def get_job(job_id=""):
"""Get particular Job from DB"""
print("DEBUG: Loading Job from database:", job_id)
try:
project = frappe.get_doc("Project", job_id)
return build_success_response(project)
except Exception as e:
return build_error_response(str(e), 500)
@frappe.whitelist()
def get_job_task_table_data(filters={}, sortings={}, page=1, page_size=10):
"""Get paginated job tasks table data with filtering and sorting support."""
print("DEBUG: raw task options received:", filters, sortings, page, page_size)
processed_filters, processed_sortings, is_or, page, page_size = process_query_conditions(filters, sortings, page, page_size)
if is_or:
count = frappe.db.sql(*get_count_or_filters("Task", processed_filters))[0][0]
else:
count = frappe.db.count("Task", filters=processed_filters)
print(f"DEBUG: Number of tasks returned: {count}")
tasks = frappe.db.get_all(
"Task",
fields=["*"],
filters=processed_filters if not is_or else None,
or_filters=processed_filters if is_or else None,
limit=page_size,
start=(page - 1) * page_size,
order_by=processed_sortings
)
tableRows = []
for task in tasks:
tableRow = {}
tableRow["name"] = task["name"]
tableRow["subject"] = task["subject"]
tableRow["address"] = task.get("custom_property", "")
tableRow["status"] = task.get("status", "")
tableRows.append(tableRow)
table_data_dict = build_datatable_dict(data=tableRows, count=count, page=page, page_size=page_size)
return build_success_response(table_data_dict)
@frappe.whitelist()
def get_job_task_list(job_id=""):
if job_id:
try:
tasks = frappe.get_all('Task', filters={"project": job_id})
task_docs = {task_id: frappe.get_doc(task_id) for task_id in tasks}
return build_success_response(task_docs)
except Exception as e:
return build_error_response(str(e), 500)
@frappe.whitelist() @frappe.whitelist()
def get_jobs_table_data(filters={}, sortings=[], page=1, page_size=10): def get_jobs_table_data(filters={}, sortings=[], page=1, page_size=10):
"""Get paginated job table data with filtering and sorting support.""" """Get paginated job table data with filtering and sorting support."""
@ -49,19 +108,19 @@ def upsert_job(data):
try: try:
if isinstance(data, str): if isinstance(data, str):
data = json.loads(data) data = json.loads(data)
project_id = data.get("id") project_id = data.get("id")
if not project_id: if not project_id:
return {"status": "error", "message": "Project ID is required"} return {"status": "error", "message": "Project ID is required"}
project = frappe.get_doc("Project", project_id) project = frappe.get_doc("Project", project_id)
if "scheduledDate" in data: if "scheduledDate" in data:
project.expected_start_date = data["scheduledDate"] project.expected_start_date = data["scheduledDate"]
if "foreman" in data: if "foreman" in data:
project.custom_install_crew = data["foreman"] project.custom_install_crew = data["foreman"]
project.save() project.save()
return {"status": "success", "data": project.as_dict()} return {"status": "success", "data": project.as_dict()}
except Exception as e: except Exception as e:
@ -75,16 +134,16 @@ def get_install_projects(start_date=None, end_date=None):
# If date range provided, we could filter, but for now let's fetch all open/active ones # If date range provided, we could filter, but for now let's fetch all open/active ones
# or maybe filter by status not Closed/Completed if we want active ones. # or maybe filter by status not Closed/Completed if we want active ones.
# The user said "unscheduled" are those with status "Open" (and no date). # The user said "unscheduled" are those with status "Open" (and no date).
projects = frappe.get_all("Project", fields=["*"], filters=filters) projects = frappe.get_all("Project", fields=["*"], filters=filters)
calendar_events = [] calendar_events = []
for project in projects: for project in projects:
# Determine status # Determine status
status = "unscheduled" status = "unscheduled"
if project.get("expected_start_date"): if project.get("expected_start_date"):
status = "scheduled" status = "scheduled"
# Map to calendar event format # Map to calendar event format
event = { event = {
"id": project.name, "id": project.name,
@ -101,9 +160,9 @@ def get_install_projects(start_date=None, end_date=None):
"notes": project.notes, "notes": project.notes,
"address": project.custom_installation_address "address": project.custom_installation_address
} }
calendar_events.append(event) calendar_events.append(event)
return {"status": "success", "data": calendar_events} return {"status": "success", "data": calendar_events}
except Exception as e: except Exception as e:
return {"status": "error", "message": str(e)} return {"status": "error", "message": str(e)}

View file

@ -13,9 +13,10 @@ const FRAPPE_SEND_ESTIMATE_EMAIL_METHOD = "custom_ui.api.db.estimates.send_estim
const FRAPPE_LOCK_ESTIMATE_METHOD = "custom_ui.api.db.estimates.lock_estimate"; const FRAPPE_LOCK_ESTIMATE_METHOD = "custom_ui.api.db.estimates.lock_estimate";
const FRAPPE_ESTIMATE_UPDATE_RESPONSE_METHOD = "custom_ui.api.db.estimates.manual_response"; const FRAPPE_ESTIMATE_UPDATE_RESPONSE_METHOD = "custom_ui.api.db.estimates.manual_response";
// Job methods // Job methods
const FRAPPE_GET_JOB_METHOD = "custom_ui.api.db.jobs.get_job";
const FRAPPE_GET_JOBS_METHOD = "custom_ui.api.db.jobs.get_jobs_table_data"; const FRAPPE_GET_JOBS_METHOD = "custom_ui.api.db.jobs.get_jobs_table_data";
const FRAPPE_UPSERT_JOB_METHOD = "custom_ui.api.db.jobs.upsert_job"; const FRAPPE_UPSERT_JOB_METHOD = "custom_ui.api.db.jobs.upsert_job";
const FRAPPE_GET_JOB_TASK_LIST_METHOD = "custom_ui.api.db.get_job_task_list"; const FRAPPE_GET_JOB_TASK_LIST_METHOD = "custom_ui.api.db.jobs.get_job_task_table_data";
const FRAPPE_GET_INSTALL_PROJECTS_METHOD = "custom_ui.api.db.jobs.get_install_projects"; const FRAPPE_GET_INSTALL_PROJECTS_METHOD = "custom_ui.api.db.jobs.get_install_projects";
// Invoice methods // Invoice methods
const FRAPPE_GET_INVOICES_METHOD = "custom_ui.api.db.invoices.get_invoice_table_data"; const FRAPPE_GET_INVOICES_METHOD = "custom_ui.api.db.invoices.get_invoice_table_data";
@ -273,6 +274,14 @@ class Api {
return result; return result;
} }
static async getJob(jobName) {
if (frappe.db.exists("Project", jobName)) {
const result = await this.request(FRAPPE_GET_JOB_METHOD, { jobId: jobName })
console.log(`DEBUG: API - retrieved Job ${jobName}:`, result);
return result;
}
}
static async createJob(jobData) { static async createJob(jobData) {
const payload = DataUtils.toSnakeCaseObject(jobData); const payload = DataUtils.toSnakeCaseObject(jobData);
const result = await this.request(FRAPPE_UPSERT_JOB_METHOD, { data: payload }); const result = await this.request(FRAPPE_UPSERT_JOB_METHOD, { data: payload });
@ -282,15 +291,39 @@ class Api {
static async getJobTaskList(jobName) { static async getJobTaskList(jobName) {
if (frappe.db.exists("Project", jobName)) { if (frappe.db.exists("Project", jobName)) {
const result = await request(FRAPPE_GET_JOB_TASK_LIST_METHOD, { data: jobName }) const result = await this.request(FRAPPE_GET_JOB_TASK_LIST_METHOD, { jobId: jobName })
console.log(`DEBUG: API - retrieved task list from job ${jobName}:`, result); console.log(`DEBUG: API - retrieved task list from job ${jobName}:`, result);
return result return result;
} }
else { else {
console.log(`DEBUG: API - no record found for task like from job ${jobName}: `, result); console.log(`DEBUG: API - no record found for task like from job ${jobName}: `, result);
} }
} }
static async getPaginatedJobTaskDetails(paginationParams = {}, filters = {}, sorting = null) {
const { page = 0, pageSize = 10, sortField = null, sortOrder = null } = paginationParams;
// Use sorting from the dedicated sorting parameter first, then fall back to pagination params
const actualSortField = sorting?.field || sortField;
const actualSortOrder = sorting?.order || sortOrder;
const options = {
page: page + 1, // Backend expects 1-based pages
page_size: pageSize,
filters,
sorting:
actualSortField && actualSortOrder
? `${actualSortField} ${actualSortOrder === -1 ? "desc" : "asc"}`
: null,
for_table: true,
};
console.log("DEBUG: API - Sending job task options to backend:", options);
const result = await this.request(FRAPPE_GET_JOB_TASK_LIST_METHOD, { options });
return result;
}
// ============================================================================ // ============================================================================

View file

@ -5,15 +5,39 @@
</div> </div>
<div class="info-section"> <div class="info-section">
<div class="address-info"> <div class="address-info">
<Card>
<template #header>
<div class="widget-header">
<h3>Address</h3>
</div>
</template>
<template #content>
<div class="widget-content">
{{ job.customInstallationAddress || "" }}
</div>
</template>
</Card>
</div> </div>
<div class="customer-info"> <div class="customer-info">
<Card>
<template #header>
<div class="widget-header">
<h3>Customer</h3>
</div>
</template>
<template #content>
<div class="widget-content">
{{ job.customer || "" }}
</div>
</template>
</Card>
</div> </div>
</div> </div>
<div class="task-list"> <div class="task-list">
<DataTable <DataTable
:data="tableData" :data="tableData"
:columns="columns" :columns="columns"
tableName="jobs" tableName="jobtasks"
:lazy="true" :lazy="true"
:totalRecords="totalRecords" :totalRecords="totalRecords"
:loading="isLoading" :loading="isLoading"
@ -24,8 +48,10 @@
</template> </template>
<script setup> <script setup>
import Card from "../common/Card.vue";
import DataTable from "../common/DataTable.vue"; import DataTable from "../common/DataTable.vue";
import { ref, onMounted } from "vue"; import { ref, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
import Api from "../../api"; import Api from "../../api";
import { useLoadingStore } from "../../stores/loading"; import { useLoadingStore } from "../../stores/loading";
import { usePaginationStore } from "../../stores/pagination"; import { usePaginationStore } from "../../stores/pagination";
@ -37,15 +63,23 @@ const paginationStore = usePaginationStore();
const filtersStore = useFiltersStore(); const filtersStore = useFiltersStore();
const notifications = useNotificationStore(); const notifications = useNotificationStore();
const route = useRoute();
const jobIdQuery = computed(() => route.query.jobId || "");
const isNew = computed(() => route.query.new === "true");
const tableData = ref([]); const tableData = ref([]);
const totalRecords = ref(0); const totalRecords = ref(0);
const isLoading = ref(false); const isLoading = ref(false);
const job = ref(null);
const taskList = ref(null);
const columns = [ const columns = [
{ label: "Task", fieldName: "", type: "text", sortable: true, filterable: true }, { label: "Task", fieldName: "subject", type: "text" },
{ label: "Address", fieldName: "", type: "text", sortable: true, filterable: true }, { label: "ID", fieldName: "name", type: "text", sortable: true, filterable: true },
{ label: "Category", fieldName: "", type: "text", sortable: true, filterable: true }, { label: "Category", fieldName: "", type: "text", sortable: true, filterable: true },
{ label: "Status", fieldName: "", type: "text", sortable: true, filterable: true }, { label: "Status", fieldName: "status", type: "text", sortable: true, filterable: true },
]; ];
const handleLazyLoad = async (event) => { const handleLazyLoad = async (event) => {
@ -66,7 +100,7 @@ const handleLazyLoad = async (event) => {
}; };
// Get filters (convert PrimeVue format to API format) // Get filters (convert PrimeVue format to API format)
const filters = {}; const filters = {project: jobIdQuery.value};
if (event.filters) { if (event.filters) {
Object.keys(event.filters).forEach((key) => { Object.keys(event.filters).forEach((key) => {
if (key !== "global" && event.filters[key] && event.filters[key].value) { if (key !== "global" && event.filters[key] && event.filters[key].value) {
@ -109,7 +143,7 @@ const handleLazyLoad = async (event) => {
console.log("Making API call with:", { paginationParams, filters }); console.log("Making API call with:", { paginationParams, filters });
// Call API with pagination, filters, and sorting // Call API with pagination, filters, and sorting
const result = await Api.getPaginatedJobTaskDetails(tpaginationParams, filters, sorting); const result = await Api.getPaginatedJobTaskDetails(paginationParams, filters, sorting);
// Update local state - extract from pagination structure // Update local state - extract from pagination structure
tableData.value = result.data; tableData.value = result.data;
@ -155,8 +189,79 @@ const handleLazyLoad = async (event) => {
}; };
onMounted(async () => { onMounted(async () => {
console.log("DEBUG: Query params:", route.query);
if (jobIdQuery.value) {
// Viewing existing Job
try {
job.value = await Api.getJob(jobIdQuery.value);
//taskList.value = await Api.getJobTaskList(jobIdQuery.value);
console.log("DEBUG: Loaded job:", job.value);
} catch (error) {
console.error("Error loading job from DB:", error);
}
}
// Initialize pagination and filters
paginationStore.initializeTablePagination("jobTasks", { rows: 10 });
filtersStore.initializeTableFilters("jobTasks", columns);
filtersStore.initializeTableSorting("jobsTasks");
// Load first page of tasks
const initialPagination = paginationStore.getTablePagination("jobTasks");
const initialFilters = filtersStore.getTableFilters("jobTasks");
const initialSorting = filtersStore.getTableSorting("jobTasks");
await handleLazyLoad({
page: initialPagination.page,
rows: initialPagination.rows,
first: initialPagination.first,
sortField: initialSorting.field || initialPagination.sortField,
sortOrder: initialSorting.order || initialPagination.sortOrder,
});
}); });
</script> </script>
<style scoped> <style scoped>
.info-section {
display: flex;
flex-wrap: wrap;
gap: 20px;
margin-bottom: 20px;
}
.widget-header {
display: flex;
align-items: center;
gap: 10px;
padding: 20px 20px 0;
}
.widget-icon {
color: var(--theme-primary-strong);
width: 24px;
height: 24px;
}
.widget-header h3 {
margin: 0;
color: #2c3e50;
font-size: 1.2rem;
}
.widget-content {
display: flex;
flex-direction: column;
margin: 0;
width: 200px;
align-items: center;
padding: 20px 20px 20px;
/*gap: 15px;*/
}
.job-page{
height: 100%;
margin: 20px;
gap: 20px;
background-color: transparent;
}
</style> </style>