feat: Implement account quick actions for cases and tasks, enhance account serializer, and add invoicing plan.
This commit is contained in:
parent
77c3441445
commit
ecc4a539d8
14 changed files with 574 additions and 372 deletions
|
|
@ -29,11 +29,29 @@ class AccountSerializer(serializers.ModelSerializer):
|
|||
teams = TeamsSerializer(read_only=True, many=True)
|
||||
account_attachment = AttachmentsSerializer(read_only=True, many=True)
|
||||
country_display = serializers.SerializerMethodField()
|
||||
cases = serializers.SerializerMethodField()
|
||||
tasks = serializers.SerializerMethodField()
|
||||
opportunities = serializers.SerializerMethodField()
|
||||
|
||||
@extend_schema_field(str)
|
||||
def get_country_display(self, obj):
|
||||
return obj.get_country_display() if obj.country else None
|
||||
|
||||
@extend_schema_field(list)
|
||||
def get_cases(self, obj):
|
||||
"""Return cases linked to this account"""
|
||||
return [{"id": str(c.id), "name": c.name} for c in obj.accounts_cases.all()]
|
||||
|
||||
@extend_schema_field(list)
|
||||
def get_tasks(self, obj):
|
||||
"""Return tasks linked to this account"""
|
||||
return [{"id": str(t.id), "title": t.title} for t in obj.accounts_tasks.all()]
|
||||
|
||||
@extend_schema_field(list)
|
||||
def get_opportunities(self, obj):
|
||||
"""Return opportunities linked to this account"""
|
||||
return [{"id": str(o.id), "name": o.name, "stage": o.stage, "amount": str(o.amount) if o.amount else "0"} for o in obj.opportunities.all()]
|
||||
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = (
|
||||
|
|
@ -65,6 +83,9 @@ class AccountSerializer(serializers.ModelSerializer):
|
|||
"description",
|
||||
# Related
|
||||
"account_attachment",
|
||||
"cases",
|
||||
"tasks",
|
||||
"opportunities",
|
||||
# System
|
||||
"created_by",
|
||||
"created_at",
|
||||
|
|
|
|||
|
|
@ -112,6 +112,7 @@ class AccountsListView(APIView, LimitOffsetPagination):
|
|||
context["active_accounts"] = {
|
||||
"offset": offset,
|
||||
"open_accounts": accounts_active,
|
||||
"open_accounts_count": queryset_active.count(),
|
||||
}
|
||||
|
||||
# Inactive accounts
|
||||
|
|
@ -136,6 +137,7 @@ class AccountsListView(APIView, LimitOffsetPagination):
|
|||
context["closed_accounts"] = {
|
||||
"offset": offset,
|
||||
"close_accounts": accounts_inactive,
|
||||
"close_accounts_count": queryset_inactive.count(),
|
||||
}
|
||||
context["teams"] = TeamsSerializer(
|
||||
Teams.objects.filter(org=self.request.profile.org), many=True
|
||||
|
|
|
|||
|
|
@ -27,7 +27,8 @@
|
|||
children
|
||||
} = $props();
|
||||
|
||||
let internalExpanded = $state(defaultExpanded);
|
||||
// Use a function to capture initial value (avoids Svelte warning about prop reference)
|
||||
let internalExpanded = $state((() => defaultExpanded)());
|
||||
|
||||
// Use external expanded if provided, otherwise use internal state
|
||||
const isExpanded = $derived(externalExpanded !== undefined ? externalExpanded : internalExpanded);
|
||||
|
|
|
|||
|
|
@ -67,16 +67,20 @@ export async function load({ locals, url, cookies }) {
|
|||
// Django endpoint returns separate lists
|
||||
const activeAccounts = response.active_accounts.open_accounts || [];
|
||||
const closedAccounts = response.closed_accounts.close_accounts || [];
|
||||
const activeCount = response.active_accounts.open_accounts_count || activeAccounts.length;
|
||||
const closedCount = response.closed_accounts.close_accounts_count || closedAccounts.length;
|
||||
|
||||
if (status === 'open') {
|
||||
accounts = activeAccounts;
|
||||
total = activeCount;
|
||||
} else if (status === 'closed') {
|
||||
accounts = closedAccounts;
|
||||
total = closedCount;
|
||||
} else {
|
||||
// No filter - show all accounts (both active and closed)
|
||||
accounts = [...activeAccounts, ...closedAccounts];
|
||||
total = activeCount + closedCount;
|
||||
}
|
||||
total = accounts.length;
|
||||
} else if (response.results) {
|
||||
// Standard Django pagination response
|
||||
accounts = response.results;
|
||||
|
|
@ -89,6 +93,7 @@ export async function load({ locals, url, cookies }) {
|
|||
const opportunityCount = account.opportunities?.length || 0;
|
||||
const contactCount = account.contacts?.length || 0;
|
||||
const taskCount = account.tasks?.length || 0;
|
||||
const caseCount = account.cases?.length || 0;
|
||||
|
||||
const openOpportunities =
|
||||
account.opportunities?.filter((opp) => !['CLOSED_WON', 'CLOSED_LOST'].includes(opp.stage))
|
||||
|
|
@ -143,6 +148,7 @@ export async function load({ locals, url, cookies }) {
|
|||
opportunityCount,
|
||||
contactCount,
|
||||
taskCount,
|
||||
caseCount,
|
||||
openOpportunities,
|
||||
totalOpportunityValue,
|
||||
|
||||
|
|
|
|||
|
|
@ -26,7 +26,8 @@
|
|||
UserPlus,
|
||||
Contact,
|
||||
Banknote,
|
||||
Filter
|
||||
Filter,
|
||||
CheckSquare
|
||||
} from '@lucide/svelte';
|
||||
import { PageHeader } from '$lib/components/layout';
|
||||
import { CrmDrawer } from '$lib/components/ui/crm-drawer';
|
||||
|
|
@ -708,7 +709,25 @@
|
|||
*/
|
||||
function handleAddOpportunity() {
|
||||
if (selectedAccount) {
|
||||
goto(`/opportunities/new?accountId=${selectedAccount.id}`);
|
||||
goto(`/opportunities?action=create&accountId=${selectedAccount.id}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to add case
|
||||
*/
|
||||
function handleAddCase() {
|
||||
if (selectedAccount) {
|
||||
goto(`/cases?action=create&accountId=${selectedAccount.id}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to add task
|
||||
*/
|
||||
function handleAddTask() {
|
||||
if (selectedAccount) {
|
||||
goto(`/tasks?action=create&accountId=${selectedAccount.id}`);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
|
@ -999,7 +1018,7 @@
|
|||
>
|
||||
Related
|
||||
</p>
|
||||
<div class="grid grid-cols-3 gap-2">
|
||||
<div class="grid grid-cols-4 gap-2">
|
||||
<div class="rounded-lg bg-gray-50 p-2 text-center dark:bg-gray-800">
|
||||
<div class="flex items-center justify-center gap-1 text-gray-400 dark:text-gray-500">
|
||||
<Users class="h-3.5 w-3.5" />
|
||||
|
|
@ -1027,6 +1046,15 @@
|
|||
</p>
|
||||
<p class="text-[10px] text-gray-500 dark:text-gray-400">Cases</p>
|
||||
</div>
|
||||
<div class="rounded-lg bg-gray-50 p-2 text-center dark:bg-gray-800">
|
||||
<div class="flex items-center justify-center gap-1 text-gray-400 dark:text-gray-500">
|
||||
<CheckSquare class="h-3.5 w-3.5" />
|
||||
</div>
|
||||
<p class="mt-0.5 text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||
{selectedAccount.taskCount || 0}
|
||||
</p>
|
||||
<p class="text-[10px] text-gray-500 dark:text-gray-400">Tasks</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -1048,6 +1076,16 @@
|
|||
Add Opportunity
|
||||
</Button>
|
||||
</div>
|
||||
<div class="mt-2 flex gap-2">
|
||||
<Button variant="outline" size="sm" onclick={handleAddCase} class="flex-1">
|
||||
<AlertTriangle class="mr-1.5 h-3.5 w-3.5" />
|
||||
Add Case
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onclick={handleAddTask} class="flex-1">
|
||||
<CheckSquare class="mr-1.5 h-3.5 w-3.5" />
|
||||
Add Task
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
|
|
|
|||
|
|
@ -56,8 +56,15 @@ export async function load({ url, locals, cookies }) {
|
|||
if (filters.created_at_gte) queryParams.append('created_at__gte', filters.created_at_gte);
|
||||
if (filters.created_at_lte) queryParams.append('created_at__lte', filters.created_at_lte);
|
||||
|
||||
// Only fetch cases on initial load - dropdown options loaded on-demand when drawer opens
|
||||
const casesResponse = await apiRequest(`/cases/?${queryParams.toString()}`, {}, { cookies, org });
|
||||
// Fetch cases and dropdown options in parallel
|
||||
const [casesResponse, accountsRes, usersRes, contactsRes, teamsRes, tagsRes] = await Promise.all([
|
||||
apiRequest(`/cases/?${queryParams.toString()}`, {}, { cookies, org }),
|
||||
apiRequest('/accounts/', {}, { cookies, org }).catch(() => ({})),
|
||||
apiRequest('/users/', {}, { cookies, org }).catch(() => ({})),
|
||||
apiRequest('/contacts/', {}, { cookies, org }).catch(() => ({})),
|
||||
apiRequest('/teams/', {}, { cookies, org }).catch(() => ({})),
|
||||
apiRequest('/tags/', {}, { cookies, org }).catch(() => ({}))
|
||||
]);
|
||||
|
||||
// Extract cases from response
|
||||
let cases = [];
|
||||
|
|
@ -166,6 +173,48 @@ export async function load({ url, locals, cookies }) {
|
|||
// Get total count from response
|
||||
const total = casesResponse.cases_count || casesResponse.count || transformedCases.length;
|
||||
|
||||
// Transform accounts for dropdown/lookup
|
||||
let accountsList = [];
|
||||
if (accountsRes.active_accounts?.open_accounts) {
|
||||
accountsList = accountsRes.active_accounts.open_accounts;
|
||||
} else if (accountsRes.results) {
|
||||
accountsList = accountsRes.results;
|
||||
} else if (Array.isArray(accountsRes)) {
|
||||
accountsList = accountsRes;
|
||||
}
|
||||
const accounts = accountsList.map((a) => ({ id: a.id, name: a.name }));
|
||||
|
||||
// Transform users
|
||||
const users = (usersRes.active_users?.active_users || []).map((u) => ({
|
||||
id: u.id,
|
||||
name: u.user_details?.first_name && u.user_details?.last_name
|
||||
? `${u.user_details.first_name} ${u.user_details.last_name}`
|
||||
: u.user_details?.email || u.email
|
||||
}));
|
||||
|
||||
// Transform contacts
|
||||
let contactsList = [];
|
||||
if (contactsRes.contact_obj_list) {
|
||||
contactsList = contactsRes.contact_obj_list;
|
||||
} else if (contactsRes.results) {
|
||||
contactsList = contactsRes.results;
|
||||
} else if (Array.isArray(contactsRes)) {
|
||||
contactsList = contactsRes;
|
||||
}
|
||||
const contacts = contactsList.map((c) => ({
|
||||
id: c.id,
|
||||
name: c.first_name && c.last_name
|
||||
? `${c.first_name} ${c.last_name}`
|
||||
: c.email,
|
||||
email: c.email
|
||||
}));
|
||||
|
||||
// Transform teams
|
||||
const teams = (teamsRes.teams || teamsRes.results || []).map((t) => ({ id: t.id, name: t.name }));
|
||||
|
||||
// Transform tags
|
||||
const tags = (tagsRes.tags || tagsRes.results || []).map((t) => ({ id: t.id, name: t.name }));
|
||||
|
||||
return {
|
||||
cases: transformedCases,
|
||||
pagination: {
|
||||
|
|
@ -175,14 +224,16 @@ export async function load({ url, locals, cookies }) {
|
|||
totalPages: Math.ceil(total / limit) || 1
|
||||
},
|
||||
filters,
|
||||
// Dropdown options are now lazy-loaded on client when drawer opens
|
||||
allUsers: [],
|
||||
allAccounts: [],
|
||||
allContacts: [],
|
||||
allTeams: [],
|
||||
allTags: [],
|
||||
statusOptions,
|
||||
caseTypeOptions
|
||||
caseTypeOptions,
|
||||
// Dropdown options loaded server-side
|
||||
formOptions: {
|
||||
accounts,
|
||||
users,
|
||||
contacts,
|
||||
teams,
|
||||
tags
|
||||
}
|
||||
};
|
||||
} catch (err) {
|
||||
console.error('Error loading cases from API:', err);
|
||||
|
|
|
|||
|
|
@ -34,7 +34,11 @@
|
|||
casePriorityOptions
|
||||
} from '$lib/utils/table-helpers.js';
|
||||
import { useDrawerState } from '$lib/hooks';
|
||||
import { apiRequest } from '$lib/api.js';
|
||||
|
||||
// Account from URL param (for quick action from account page)
|
||||
let accountFromUrl = $state(false);
|
||||
let accountName = $state('');
|
||||
let accountIdFromUrl = $state('');
|
||||
|
||||
/**
|
||||
* @typedef {Object} ColumnDef
|
||||
|
|
@ -159,124 +163,62 @@
|
|||
let casesData = $derived(data.cases || []);
|
||||
const pagination = $derived(data.pagination || { page: 1, limit: 10, total: 0, totalPages: 0 });
|
||||
|
||||
// Lazy-loaded dropdown options (fetched when drawer opens)
|
||||
let loadedUsers = $state(/** @type {any[]} */ ([]));
|
||||
let loadedAccounts = $state(/** @type {any[]} */ ([]));
|
||||
let loadedContacts = $state(/** @type {any[]} */ ([]));
|
||||
let loadedTeams = $state(/** @type {any[]} */ ([]));
|
||||
let loadedTags = $state(/** @type {any[]} */ ([]));
|
||||
let dropdownOptionsLoaded = $state(false);
|
||||
let dropdownOptionsLoading = $state(false);
|
||||
|
||||
// Use lazy-loaded data
|
||||
const accounts = $derived(loadedAccounts);
|
||||
const users = $derived(loadedUsers);
|
||||
const contacts = $derived(loadedContacts);
|
||||
const teams = $derived(loadedTeams);
|
||||
const tags = $derived(loadedTags);
|
||||
// Dropdown options from server (loaded with page data)
|
||||
const formOptions = $derived(data.formOptions || {});
|
||||
const accounts = $derived(formOptions.accounts || []);
|
||||
const users = $derived(formOptions.users || []);
|
||||
const contacts = $derived(formOptions.contacts || []);
|
||||
const teams = $derived(formOptions.teams || []);
|
||||
const tags = $derived(formOptions.tags || []);
|
||||
|
||||
/**
|
||||
* Fetch dropdown options for the drawer (lazy load)
|
||||
* Get account name from server-provided accounts list
|
||||
* @param {string} id
|
||||
*/
|
||||
async function loadDropdownOptions() {
|
||||
if (dropdownOptionsLoaded || dropdownOptionsLoading) return;
|
||||
|
||||
dropdownOptionsLoading = true;
|
||||
try {
|
||||
const [usersResponse, accountsResponse, contactsResponse, teamsResponse, tagsResponse] =
|
||||
await Promise.all([
|
||||
apiRequest('/users/'),
|
||||
apiRequest('/accounts/'),
|
||||
apiRequest('/contacts/'),
|
||||
apiRequest('/teams/'),
|
||||
apiRequest('/tags/').catch(() => ({ tags: [] }))
|
||||
]);
|
||||
|
||||
// Transform users
|
||||
const activeUsersList = usersResponse.active_users?.active_users || [];
|
||||
loadedUsers = activeUsersList.map((/** @type {any} */ user) => ({
|
||||
id: user.id,
|
||||
name:
|
||||
user.user_details?.first_name && user.user_details?.last_name
|
||||
? `${user.user_details.first_name} ${user.user_details.last_name}`
|
||||
: user.user_details?.email || user.email
|
||||
}));
|
||||
|
||||
// Transform accounts
|
||||
let allAccounts = [];
|
||||
if (accountsResponse.active_accounts?.open_accounts) {
|
||||
allAccounts = accountsResponse.active_accounts.open_accounts;
|
||||
} else if (accountsResponse.results) {
|
||||
allAccounts = accountsResponse.results;
|
||||
} else if (Array.isArray(accountsResponse)) {
|
||||
allAccounts = accountsResponse;
|
||||
}
|
||||
loadedAccounts = allAccounts.map((/** @type {any} */ account) => ({
|
||||
id: account.id,
|
||||
name: account.name
|
||||
}));
|
||||
|
||||
// Transform contacts
|
||||
let allContacts = [];
|
||||
if (contactsResponse.contact_obj_list) {
|
||||
allContacts = contactsResponse.contact_obj_list;
|
||||
} else if (contactsResponse.results) {
|
||||
allContacts = contactsResponse.results;
|
||||
} else if (Array.isArray(contactsResponse)) {
|
||||
allContacts = contactsResponse;
|
||||
}
|
||||
loadedContacts = allContacts.map((/** @type {any} */ contact) => ({
|
||||
id: contact.id,
|
||||
name:
|
||||
contact.first_name && contact.last_name
|
||||
? `${contact.first_name} ${contact.last_name}`
|
||||
: contact.email,
|
||||
email: contact.email
|
||||
}));
|
||||
|
||||
// Transform teams
|
||||
let allTeams = [];
|
||||
if (teamsResponse.teams) {
|
||||
allTeams = teamsResponse.teams;
|
||||
} else if (teamsResponse.results) {
|
||||
allTeams = teamsResponse.results;
|
||||
} else if (Array.isArray(teamsResponse)) {
|
||||
allTeams = teamsResponse;
|
||||
}
|
||||
loadedTeams = allTeams.map((/** @type {any} */ team) => ({
|
||||
id: team.id,
|
||||
name: team.name
|
||||
}));
|
||||
|
||||
// Transform tags
|
||||
let allTags = [];
|
||||
if (tagsResponse.tags) {
|
||||
allTags = tagsResponse.tags;
|
||||
} else if (tagsResponse.results) {
|
||||
allTags = tagsResponse.results;
|
||||
} else if (Array.isArray(tagsResponse)) {
|
||||
allTags = tagsResponse;
|
||||
}
|
||||
loadedTags = allTags.map((/** @type {any} */ tag) => ({
|
||||
id: tag.id,
|
||||
name: tag.name
|
||||
}));
|
||||
|
||||
dropdownOptionsLoaded = true;
|
||||
} catch (err) {
|
||||
console.error('Failed to load dropdown options:', err);
|
||||
} finally {
|
||||
dropdownOptionsLoading = false;
|
||||
function fetchAccountName(id) {
|
||||
const account = accounts.find((a) => a.id === id);
|
||||
if (account) {
|
||||
accountName = account.name;
|
||||
} else {
|
||||
accountName = 'Unknown Account';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear URL params for accountId and action
|
||||
*/
|
||||
function clearUrlParams() {
|
||||
const url = new URL($page.url);
|
||||
url.searchParams.delete('action');
|
||||
url.searchParams.delete('accountId');
|
||||
goto(url.pathname, { replaceState: true, invalidateAll: true });
|
||||
accountFromUrl = false;
|
||||
accountName = '';
|
||||
accountIdFromUrl = '';
|
||||
}
|
||||
|
||||
// Drawer state using hook
|
||||
const drawer = useDrawerState();
|
||||
|
||||
// Load dropdown options when drawer opens (lazy load)
|
||||
// URL sync for accountId and action params (quick action from account page)
|
||||
$effect(() => {
|
||||
if (drawer.detailOpen && !dropdownOptionsLoaded) {
|
||||
loadDropdownOptions();
|
||||
const action = $page.url.searchParams.get('action');
|
||||
const accountIdParam = $page.url.searchParams.get('accountId');
|
||||
|
||||
if (action === 'create' && !drawer.detailOpen) {
|
||||
// Handle account pre-fill from URL BEFORE opening drawer
|
||||
if (accountIdParam) {
|
||||
accountIdFromUrl = accountIdParam;
|
||||
accountFromUrl = true;
|
||||
fetchAccountName(accountIdParam);
|
||||
}
|
||||
|
||||
drawer.openCreate();
|
||||
|
||||
// Set account in form data after drawer opens
|
||||
if (accountIdParam) {
|
||||
drawerFormData.accountId = accountIdParam;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -291,10 +233,11 @@
|
|||
]);
|
||||
|
||||
// Drawer columns configuration (with icons and multiselect)
|
||||
// Account is only editable on create, read-only on edit
|
||||
// Account is only editable on create (and not when pre-filled from URL), read-only on edit
|
||||
const drawerColumns = $derived([
|
||||
{ key: 'subject', label: 'Case Title', type: 'text' },
|
||||
drawer.mode === 'create'
|
||||
// Account field: readonly when pre-filled from URL or in edit mode
|
||||
drawer.mode === 'create' && !accountFromUrl
|
||||
? {
|
||||
key: 'accountId',
|
||||
label: 'Account',
|
||||
|
|
@ -303,13 +246,21 @@
|
|||
options: accountOptions,
|
||||
emptyText: 'No account'
|
||||
}
|
||||
: {
|
||||
key: 'accountName',
|
||||
label: 'Account',
|
||||
type: 'readonly',
|
||||
icon: Building2,
|
||||
emptyText: 'No account'
|
||||
},
|
||||
: accountFromUrl
|
||||
? {
|
||||
key: 'accountDisplay',
|
||||
label: 'Account',
|
||||
type: 'readonly',
|
||||
icon: Building2,
|
||||
getValue: () => accountName || 'Loading...'
|
||||
}
|
||||
: {
|
||||
key: 'accountName',
|
||||
label: 'Account',
|
||||
type: 'readonly',
|
||||
icon: Building2,
|
||||
emptyText: 'No account'
|
||||
},
|
||||
{
|
||||
key: 'caseType',
|
||||
label: 'Type',
|
||||
|
|
@ -388,7 +339,7 @@
|
|||
drawerFormData = {
|
||||
subject: '',
|
||||
description: '',
|
||||
accountId: '',
|
||||
accountId: accountIdFromUrl || '', // Preserve account from URL if present
|
||||
accountName: '',
|
||||
assignedTo: [],
|
||||
contacts: [],
|
||||
|
|
@ -656,6 +607,10 @@
|
|||
} else {
|
||||
drawer.closeAll();
|
||||
}
|
||||
// Clear account URL params if they were set
|
||||
if (accountFromUrl) {
|
||||
clearUrlParams();
|
||||
}
|
||||
await invalidateAll();
|
||||
} else if (result.type === 'failure') {
|
||||
toast.error(result.data?.error || 'Operation failed');
|
||||
|
|
@ -912,7 +867,14 @@
|
|||
<!-- Case Drawer -->
|
||||
<CrmDrawer
|
||||
bind:open={drawer.detailOpen}
|
||||
onOpenChange={(open) => !open && drawer.closeAll()}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
drawer.closeAll();
|
||||
if (accountFromUrl) {
|
||||
clearUrlParams();
|
||||
}
|
||||
}
|
||||
}}
|
||||
data={drawerFormData}
|
||||
columns={drawerColumns}
|
||||
titleKey="subject"
|
||||
|
|
|
|||
|
|
@ -48,14 +48,21 @@ export async function load({ url, locals, cookies }) {
|
|||
if (filters.created_at_gte) queryParams.append('created_at__gte', filters.created_at_gte);
|
||||
if (filters.created_at_lte) queryParams.append('created_at__lte', filters.created_at_lte);
|
||||
|
||||
// Only fetch contacts on initial load - dropdown options loaded on-demand when drawer opens
|
||||
const contactsResponse = await apiRequest(`/contacts/?${queryParams.toString()}`, {}, { cookies, org });
|
||||
// Fetch contacts and accounts in parallel (accounts needed for quick action prefill)
|
||||
const [contactsResponse, accountsRes] = await Promise.all([
|
||||
apiRequest(`/contacts/?${queryParams.toString()}`, {}, { cookies, org }),
|
||||
apiRequest('/accounts/', {}, { cookies, org }).catch(() => ({}))
|
||||
]);
|
||||
|
||||
// Handle Django response format
|
||||
let contacts = [];
|
||||
let totalCount = 0;
|
||||
|
||||
if (contactsResponse.results) {
|
||||
if (contactsResponse.contact_obj_list) {
|
||||
// Django custom response format
|
||||
contacts = contactsResponse.contact_obj_list;
|
||||
totalCount = contactsResponse.contacts_count || contacts.length;
|
||||
} else if (contactsResponse.results) {
|
||||
// Standard Django pagination
|
||||
contacts = contactsResponse.results;
|
||||
totalCount = contactsResponse.count || 0;
|
||||
|
|
@ -140,6 +147,17 @@ export async function load({ url, locals, cookies }) {
|
|||
}
|
||||
}));
|
||||
|
||||
// Transform accounts for dropdown/lookup
|
||||
let accountsList = [];
|
||||
if (accountsRes.active_accounts?.open_accounts) {
|
||||
accountsList = accountsRes.active_accounts.open_accounts;
|
||||
} else if (accountsRes.results) {
|
||||
accountsList = accountsRes.results;
|
||||
} else if (Array.isArray(accountsRes)) {
|
||||
accountsList = accountsRes;
|
||||
}
|
||||
const accounts = accountsList.map((a) => ({ id: a.id, name: a.name }));
|
||||
|
||||
return {
|
||||
contacts: transformedContacts,
|
||||
pagination: {
|
||||
|
|
@ -151,7 +169,9 @@ export async function load({ url, locals, cookies }) {
|
|||
filters,
|
||||
// Dropdown options are now lazy-loaded on client when drawer opens
|
||||
owners: [],
|
||||
allTags: []
|
||||
allTags: [],
|
||||
// Accounts for quick action prefill lookup
|
||||
accounts
|
||||
};
|
||||
} catch (err) {
|
||||
console.error('Error loading contacts from API:', err);
|
||||
|
|
@ -164,6 +184,8 @@ export const actions = {
|
|||
create: async ({ request, locals, cookies }) => {
|
||||
try {
|
||||
const form = await request.formData();
|
||||
// Account link (from quick action)
|
||||
const accountId = form.get('accountId')?.toString().trim() || null;
|
||||
// Core fields
|
||||
const firstName = form.get('firstName')?.toString().trim();
|
||||
const lastName = form.get('lastName')?.toString().trim();
|
||||
|
|
@ -208,7 +230,8 @@ export const actions = {
|
|||
postcode: postcode || null,
|
||||
country: country || null,
|
||||
description: description || null,
|
||||
tags: tags
|
||||
tags: tags,
|
||||
account: accountId
|
||||
};
|
||||
|
||||
await apiRequest(
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@
|
|||
import { formatRelativeDate, formatPhone, getNameInitials } from '$lib/utils/formatting.js';
|
||||
import { goto } from '$app/navigation';
|
||||
import { COUNTRIES, getCountryName } from '$lib/constants/countries.js';
|
||||
import { apiRequest } from '$lib/api.js';
|
||||
import { browser } from '$app/environment';
|
||||
|
||||
// Column visibility configuration
|
||||
const STORAGE_KEY = 'contacts-column-config';
|
||||
|
|
@ -97,6 +97,14 @@
|
|||
let dropdownOptionsLoaded = $state(false);
|
||||
let dropdownOptionsLoading = $state(false);
|
||||
|
||||
// Account from URL param (for quick action from account page)
|
||||
let accountFromUrl = $state(false);
|
||||
let accountName = $state('');
|
||||
let accountId = $state('');
|
||||
|
||||
// Server-provided accounts for quick action lookup
|
||||
const accounts = $derived(data.accounts || []);
|
||||
|
||||
// Use lazy-loaded data
|
||||
const allTags = $derived(loadedTags);
|
||||
|
||||
|
|
@ -104,10 +112,12 @@
|
|||
* Fetch dropdown options for the drawer (lazy load)
|
||||
*/
|
||||
async function loadDropdownOptions() {
|
||||
if (dropdownOptionsLoaded || dropdownOptionsLoading) return;
|
||||
if (!browser || dropdownOptionsLoaded || dropdownOptionsLoading) return;
|
||||
|
||||
dropdownOptionsLoading = true;
|
||||
try {
|
||||
// Dynamic import to avoid SSR fetch warning
|
||||
const { apiRequest } = await import('$lib/api.js');
|
||||
const [ownersResponse, tagsResponse] = await Promise.all([
|
||||
apiRequest('/users/'),
|
||||
apiRequest('/tags/').catch(() => ({ tags: [] }))
|
||||
|
|
@ -135,8 +145,46 @@
|
|||
}
|
||||
}
|
||||
|
||||
// Drawer column definitions for CrmDrawer (derived to include allTags)
|
||||
/**
|
||||
* Lookup account name from server-provided accounts list
|
||||
* @param {string} id
|
||||
*/
|
||||
function fetchAccountName(id) {
|
||||
const account = accounts.find((a) => a.id === id);
|
||||
if (account) {
|
||||
accountName = account.name;
|
||||
} else {
|
||||
accountName = 'Unknown Account';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear URL params for accountId and action
|
||||
*/
|
||||
function clearUrlParams() {
|
||||
const url = new URL($page.url);
|
||||
url.searchParams.delete('action');
|
||||
url.searchParams.delete('accountId');
|
||||
goto(url.pathname, { replaceState: true, invalidateAll: true });
|
||||
accountFromUrl = false;
|
||||
accountName = '';
|
||||
accountId = '';
|
||||
}
|
||||
|
||||
// Drawer column definitions for CrmDrawer (derived to include allTags and account field)
|
||||
const drawerColumns = $derived([
|
||||
// Show account field as readonly when coming from account page
|
||||
...(accountFromUrl
|
||||
? [
|
||||
{
|
||||
key: 'accountDisplay',
|
||||
label: 'Account',
|
||||
type: 'readonly',
|
||||
icon: Building2,
|
||||
getValue: () => accountName || 'Loading...'
|
||||
}
|
||||
]
|
||||
: []),
|
||||
{ key: 'firstName', label: 'First Name', type: 'text', icon: User, placeholder: 'First name' },
|
||||
{ key: 'lastName', label: 'Last Name', type: 'text', placeholder: 'Last name' },
|
||||
{ key: 'email', label: 'Email', type: 'email', icon: Mail, placeholder: 'email@example.com' },
|
||||
|
|
@ -299,8 +347,16 @@
|
|||
$effect(() => {
|
||||
const viewId = $page.url.searchParams.get('view');
|
||||
const action = $page.url.searchParams.get('action');
|
||||
const accountIdParam = $page.url.searchParams.get('accountId');
|
||||
|
||||
if (action === 'create' && !drawerOpen) {
|
||||
// Handle account pre-fill from URL BEFORE opening drawer
|
||||
if (accountIdParam) {
|
||||
accountId = accountIdParam;
|
||||
accountFromUrl = true;
|
||||
fetchAccountName(accountIdParam);
|
||||
}
|
||||
|
||||
if (action === 'create') {
|
||||
selectedContact = null;
|
||||
drawerMode = 'create';
|
||||
drawerOpen = true;
|
||||
|
|
@ -362,7 +418,12 @@
|
|||
*/
|
||||
async function closeDrawer() {
|
||||
drawerOpen = false;
|
||||
await updateUrl(null, null);
|
||||
// Clear account URL params if they were set
|
||||
if (accountFromUrl) {
|
||||
clearUrlParams();
|
||||
} else {
|
||||
await updateUrl(null, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -371,7 +432,13 @@
|
|||
*/
|
||||
function handleDrawerChange(open) {
|
||||
drawerOpen = open;
|
||||
if (!open) updateUrl(null, null);
|
||||
if (!open) {
|
||||
if (accountFromUrl) {
|
||||
clearUrlParams();
|
||||
} else {
|
||||
updateUrl(null, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// URL-based filter state from server
|
||||
|
|
@ -453,6 +520,7 @@
|
|||
// Form data state
|
||||
let formState = $state({
|
||||
contactId: '',
|
||||
accountId: '',
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
email: '',
|
||||
|
|
@ -589,6 +657,7 @@
|
|||
if (drawerMode !== 'create') return;
|
||||
|
||||
isSubmitting = true;
|
||||
formState.accountId = accountFromUrl ? accountId : '';
|
||||
formState.firstName = drawerFormData.firstName || '';
|
||||
formState.lastName = drawerFormData.lastName || '';
|
||||
formState.email = drawerFormData.email || '';
|
||||
|
|
@ -843,6 +912,7 @@
|
|||
use:enhance={createEnhanceHandler('Contact created successfully')}
|
||||
class="hidden"
|
||||
>
|
||||
<input type="hidden" name="accountId" value={formState.accountId} />
|
||||
<input type="hidden" name="firstName" value={formState.firstName} />
|
||||
<input type="hidden" name="lastName" value={formState.lastName} />
|
||||
<input type="hidden" name="email" value={formState.email} />
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@
|
|||
} from '$lib/utils/table-helpers.js';
|
||||
import CrmTable from '$lib/components/ui/crm-table/CrmTable.svelte';
|
||||
import CrmDrawer from '$lib/components/ui/crm-drawer/CrmDrawer.svelte';
|
||||
import { apiRequest } from '$lib/api.js';
|
||||
import { browser } from '$app/environment';
|
||||
import { orgSettings } from '$lib/stores/org.js';
|
||||
|
||||
// Column visibility configuration
|
||||
|
|
@ -559,10 +559,11 @@
|
|||
* Load form options for drawer (lazy-loaded on first drawer open)
|
||||
*/
|
||||
async function loadFormOptions() {
|
||||
if (formOptionsLoaded || formOptionsLoading) return;
|
||||
if (!browser || formOptionsLoaded || formOptionsLoading) return;
|
||||
|
||||
formOptionsLoading = true;
|
||||
try {
|
||||
const { apiRequest } = await import('$lib/api.js');
|
||||
const [usersResponse, teamsResponse, contactsResponse, tagsResponse] = await Promise.all([
|
||||
apiRequest('/users/').catch(() => ({ active_users: { active_users: [] } })),
|
||||
apiRequest('/teams/').catch(() => ({ teams: [] })),
|
||||
|
|
|
|||
|
|
@ -194,7 +194,7 @@ export async function load({ locals, cookies, url }) {
|
|||
};
|
||||
|
||||
// Get total count from response
|
||||
const total = response.opportunity_count || response.count || transformedOpportunities.length;
|
||||
const total = response.opportunities_count || response.count || transformedOpportunities.length;
|
||||
|
||||
return {
|
||||
opportunities: transformedOpportunities,
|
||||
|
|
|
|||
|
|
@ -41,6 +41,11 @@
|
|||
|
||||
const STORAGE_KEY = 'opportunities-crm-columns';
|
||||
|
||||
// Account from URL param (for quick action from account page)
|
||||
let accountFromUrl = $state(false);
|
||||
let accountName = $state('');
|
||||
let accountIdFromUrl = $state('');
|
||||
|
||||
// Stage options with colors
|
||||
const stageOptions = [
|
||||
{
|
||||
|
|
@ -221,17 +226,52 @@
|
|||
}))
|
||||
);
|
||||
|
||||
/**
|
||||
* Lookup account name from server-provided accounts list
|
||||
* @param {string} id
|
||||
*/
|
||||
function fetchAccountName(id) {
|
||||
const account = formOptions.accounts.find((a) => a.id === id);
|
||||
if (account) {
|
||||
accountName = account.name;
|
||||
} else {
|
||||
accountName = 'Unknown Account';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear URL params for accountId and action
|
||||
*/
|
||||
function clearUrlParams() {
|
||||
const url = new URL($page.url);
|
||||
url.searchParams.delete('action');
|
||||
url.searchParams.delete('accountId');
|
||||
goto(url.pathname, { replaceState: true, invalidateAll: true });
|
||||
accountFromUrl = false;
|
||||
accountName = '';
|
||||
accountIdFromUrl = '';
|
||||
}
|
||||
|
||||
// Drawer column definitions for CrmDrawer (derived since some options come from data)
|
||||
const drawerColumns = $derived([
|
||||
{ key: 'name', label: 'Name', type: 'text' },
|
||||
{
|
||||
key: 'account',
|
||||
label: 'Account',
|
||||
type: 'select',
|
||||
icon: Building2,
|
||||
options: accountOptions,
|
||||
placeholder: 'Select account'
|
||||
},
|
||||
// Account field: readonly when pre-filled from URL, select otherwise
|
||||
accountFromUrl
|
||||
? {
|
||||
key: 'account',
|
||||
label: 'Account',
|
||||
type: 'readonly',
|
||||
icon: Building2,
|
||||
getValue: () => accountName || 'Loading...'
|
||||
}
|
||||
: {
|
||||
key: 'account',
|
||||
label: 'Account',
|
||||
type: 'select',
|
||||
icon: Building2,
|
||||
options: accountOptions,
|
||||
placeholder: 'Select account'
|
||||
},
|
||||
{
|
||||
key: 'stage',
|
||||
label: 'Stage',
|
||||
|
|
@ -435,7 +475,11 @@
|
|||
$effect(() => {
|
||||
if (drawerOpen) {
|
||||
if (drawerMode === 'create') {
|
||||
drawerFormData = { ...emptyOpportunity, currency: $orgSettings.default_currency || 'USD' };
|
||||
drawerFormData = {
|
||||
...emptyOpportunity,
|
||||
currency: $orgSettings.default_currency || 'USD',
|
||||
account: accountIdFromUrl || '' // Preserve account from URL if present
|
||||
};
|
||||
} else if (selectedRow) {
|
||||
// Extract IDs for multiselect fields and account select
|
||||
drawerFormData = {
|
||||
|
|
@ -511,6 +555,28 @@
|
|||
localStorage.setItem(STORAGE_KEY, JSON.stringify(visibleColumns));
|
||||
});
|
||||
|
||||
// URL sync for accountId and action params (quick action from account page)
|
||||
$effect(() => {
|
||||
const action = $page.url.searchParams.get('action');
|
||||
const accountIdParam = $page.url.searchParams.get('accountId');
|
||||
|
||||
if (action === 'create' && !drawerOpen) {
|
||||
// Handle account pre-fill from URL BEFORE opening drawer
|
||||
if (accountIdParam) {
|
||||
accountIdFromUrl = accountIdParam;
|
||||
accountFromUrl = true;
|
||||
fetchAccountName(accountIdParam);
|
||||
}
|
||||
|
||||
openCreate();
|
||||
|
||||
// Set account in form data after drawer opens
|
||||
if (accountIdParam) {
|
||||
drawerFormData.account = accountIdParam;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @param {string} key
|
||||
*/
|
||||
|
|
@ -656,6 +722,10 @@
|
|||
function closeDrawer() {
|
||||
drawerOpen = false;
|
||||
selectedRowId = null;
|
||||
// Clear account URL params if they were set
|
||||
if (accountFromUrl) {
|
||||
clearUrlParams();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -737,8 +807,10 @@
|
|||
form.append('stage', drawerFormData.stage || 'PROSPECTING');
|
||||
form.append('amount', drawerFormData.amount?.toString() || '0');
|
||||
form.append('probability', drawerFormData.probability?.toString() || '50');
|
||||
if (drawerFormData.account) {
|
||||
form.append('accountId', drawerFormData.account);
|
||||
// Use drawerFormData.account or fall back to accountIdFromUrl
|
||||
const accountId = drawerFormData.account || accountIdFromUrl;
|
||||
if (accountId) {
|
||||
form.append('accountId', accountId);
|
||||
}
|
||||
if (drawerFormData.opportunityType) {
|
||||
form.append('opportunityType', drawerFormData.opportunityType);
|
||||
|
|
|
|||
|
|
@ -55,9 +55,18 @@ export async function load({ locals, cookies, url }) {
|
|||
if (filters.due_date_gte) queryParams.append('due_date__gte', filters.due_date_gte);
|
||||
if (filters.due_date_lte) queryParams.append('due_date__lte', filters.due_date_lte);
|
||||
|
||||
// Only fetch tasks on initial page load
|
||||
// Dropdown options (users, accounts, contacts, etc.) are lazy-loaded client-side when drawer opens
|
||||
const tasksResponse = await apiRequest(`/tasks/?${queryParams.toString()}`, {}, { cookies, org });
|
||||
// Fetch tasks and dropdown options in parallel
|
||||
const [tasksResponse, usersRes, accountsRes, contactsRes, teamsRes, opportunitiesRes, casesRes, leadsRes, tagsRes] = await Promise.all([
|
||||
apiRequest(`/tasks/?${queryParams.toString()}`, {}, { cookies, org }),
|
||||
apiRequest('/users/', {}, { cookies, org }).catch(() => ({})),
|
||||
apiRequest('/accounts/', {}, { cookies, org }).catch(() => ({})),
|
||||
apiRequest('/contacts/', {}, { cookies, org }).catch(() => ({})),
|
||||
apiRequest('/teams/', {}, { cookies, org }).catch(() => ({})),
|
||||
apiRequest('/opportunities/', {}, { cookies, org }).catch(() => ({})),
|
||||
apiRequest('/cases/', {}, { cookies, org }).catch(() => ({})),
|
||||
apiRequest('/leads/', {}, { cookies, org }).catch(() => ({})),
|
||||
apiRequest('/tags/', {}, { cookies, org }).catch(() => ({}))
|
||||
]);
|
||||
|
||||
// Handle Django response structure
|
||||
// Django TaskListView returns { tasks: [...], tasks_count: ..., ... }
|
||||
|
|
@ -70,6 +79,38 @@ export async function load({ locals, cookies, url }) {
|
|||
tasks = tasksResponse.results;
|
||||
}
|
||||
|
||||
// Transform accounts first (needed for task account name lookup)
|
||||
let accountsList = [];
|
||||
if (accountsRes.active_accounts?.open_accounts) {
|
||||
accountsList = accountsRes.active_accounts.open_accounts;
|
||||
} else if (accountsRes.results) {
|
||||
accountsList = accountsRes.results;
|
||||
} else if (Array.isArray(accountsRes)) {
|
||||
accountsList = accountsRes;
|
||||
}
|
||||
const accounts = accountsList.map((a) => ({ id: a.id, name: a.name }));
|
||||
|
||||
// Transform cases, opportunities, leads early (needed for task field name lookups)
|
||||
const cases = (casesRes.cases || casesRes.results || []).map((c) => ({ id: c.id, name: c.name }));
|
||||
const opportunities = (opportunitiesRes.opportunities || opportunitiesRes.results || []).map((o) => ({ id: o.id, name: o.name }));
|
||||
const leads = (leadsRes.leads || leadsRes.results || []).map((l) => ({
|
||||
id: l.id,
|
||||
name: l.first_name || l.last_name ? `${l.first_name || ''} ${l.last_name || ''}`.trim() : l.title || 'Lead'
|
||||
}));
|
||||
|
||||
// Helper to look up related entity name from list
|
||||
const getRelatedName = (data, list, fallback) => {
|
||||
if (!data) return null;
|
||||
// If it's an object with name, use it
|
||||
if (typeof data === 'object' && data.name) {
|
||||
return { id: data.id, name: data.name };
|
||||
}
|
||||
// If it's just an ID (string), look up from list
|
||||
const id = typeof data === 'object' ? data.id : data;
|
||||
const found = list.find((item) => item.id === id);
|
||||
return { id, name: found?.name || fallback };
|
||||
};
|
||||
|
||||
// Transform Django tasks to frontend structure
|
||||
const transformedTasks = tasks.map((task) => ({
|
||||
id: task.id,
|
||||
|
|
@ -107,40 +148,17 @@ export async function load({ locals, cookies, url }) {
|
|||
name: t.name
|
||||
})),
|
||||
|
||||
// Account (FK)
|
||||
account: task.account
|
||||
? {
|
||||
id: task.account.id || task.account,
|
||||
name: task.account.name || task.account
|
||||
}
|
||||
: null,
|
||||
// Account (FK) - lookup name from accounts list if needed
|
||||
account: getRelatedName(task.account, accounts, 'Unknown Account'),
|
||||
|
||||
// Opportunity (FK)
|
||||
opportunity: task.opportunity
|
||||
? {
|
||||
id: task.opportunity.id || task.opportunity,
|
||||
name: task.opportunity.name || 'Opportunity'
|
||||
}
|
||||
: null,
|
||||
// Opportunity (FK) - lookup name from opportunities list if needed
|
||||
opportunity: getRelatedName(task.opportunity, opportunities, 'Unknown Opportunity'),
|
||||
|
||||
// Case (FK)
|
||||
case_: task.case
|
||||
? {
|
||||
id: task.case.id || task.case,
|
||||
name: task.case.name || 'Case'
|
||||
}
|
||||
: null,
|
||||
// Case (FK) - lookup name from cases list if needed
|
||||
case_: getRelatedName(task.case, cases, 'Unknown Case'),
|
||||
|
||||
// Lead (FK)
|
||||
lead: task.lead
|
||||
? {
|
||||
id: task.lead.id || task.lead,
|
||||
name:
|
||||
task.lead.first_name || task.lead.last_name
|
||||
? `${task.lead.first_name || ''} ${task.lead.last_name || ''}`.trim()
|
||||
: task.lead.title || 'Lead'
|
||||
}
|
||||
: null,
|
||||
// Lead (FK) - lookup name from leads list if needed
|
||||
lead: getRelatedName(task.lead, leads, 'Unknown Lead'),
|
||||
|
||||
// Created by
|
||||
createdBy: task.created_by
|
||||
|
|
@ -154,6 +172,33 @@ export async function load({ locals, cookies, url }) {
|
|||
// Get total count from response
|
||||
const total = tasksResponse.tasks_count || tasksResponse.count || transformedTasks.length;
|
||||
|
||||
// Transform dropdown options
|
||||
const users = (usersRes.active_users?.active_users || []).map((u) => ({
|
||||
id: u.id,
|
||||
name: u.user_details?.email || u.email
|
||||
}));
|
||||
|
||||
// accounts already transformed above for task account name lookup
|
||||
|
||||
let contactsList = [];
|
||||
if (contactsRes.contact_obj_list) {
|
||||
contactsList = contactsRes.contact_obj_list;
|
||||
} else if (contactsRes.results) {
|
||||
contactsList = contactsRes.results;
|
||||
} else if (Array.isArray(contactsRes)) {
|
||||
contactsList = contactsRes;
|
||||
}
|
||||
const contacts = contactsList.map((c) => ({
|
||||
id: c.id,
|
||||
name: c.first_name ? `${c.first_name} ${c.last_name || ''}`.trim() : c.email || 'Unknown'
|
||||
}));
|
||||
|
||||
const teams = (teamsRes.teams || teamsRes.results || []).map((t) => ({ id: t.id, name: t.name }));
|
||||
|
||||
// opportunities, cases, leads already transformed above for task field name lookups
|
||||
|
||||
const tags = (tagsRes.tags || tagsRes.results || []).map((t) => ({ id: t.id, name: t.name }));
|
||||
|
||||
return {
|
||||
tasks: transformedTasks,
|
||||
pagination: {
|
||||
|
|
@ -162,7 +207,18 @@ export async function load({ locals, cookies, url }) {
|
|||
total,
|
||||
totalPages: Math.ceil(total / limit) || 1
|
||||
},
|
||||
filters
|
||||
filters,
|
||||
// Dropdown options for drawer form
|
||||
formOptions: {
|
||||
users,
|
||||
accounts,
|
||||
contacts,
|
||||
teams,
|
||||
opportunities,
|
||||
cases,
|
||||
leads,
|
||||
tags
|
||||
}
|
||||
};
|
||||
} catch (err) {
|
||||
console.error('Error loading tasks from API:', err);
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@
|
|||
import { page } from '$app/stores';
|
||||
import { onMount, tick } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { apiRequest } from '$lib/api.js';
|
||||
import {
|
||||
Plus,
|
||||
ChevronLeft,
|
||||
|
|
@ -42,6 +41,11 @@
|
|||
import { CrmTable } from '$lib/components/ui/crm-table';
|
||||
import { formatRelativeDate } from '$lib/utils/formatting.js';
|
||||
|
||||
// Account from URL param (for quick action from account page)
|
||||
let accountFromUrl = $state(false);
|
||||
let accountNameFromUrl = $state('');
|
||||
let accountIdFromUrl = $state('');
|
||||
|
||||
// Status and priority options with colors
|
||||
const statusOptions = [
|
||||
{
|
||||
|
|
@ -272,182 +276,46 @@
|
|||
const tasks = $derived(data.tasks || []);
|
||||
const pagination = $derived(data.pagination || { page: 1, limit: 10, total: 0, totalPages: 0 });
|
||||
|
||||
// Dropdown options state - lazy loaded when drawer opens
|
||||
let accounts = $state(/** @type {any[]} */ ([]));
|
||||
let users = $state(/** @type {any[]} */ ([]));
|
||||
let contacts = $state(/** @type {any[]} */ ([]));
|
||||
let teams = $state(/** @type {any[]} */ ([]));
|
||||
let opportunities = $state(/** @type {any[]} */ ([]));
|
||||
let cases = $state(/** @type {any[]} */ ([]));
|
||||
let leads = $state(/** @type {any[]} */ ([]));
|
||||
let allTags = $state(/** @type {any[]} */ ([]));
|
||||
// Dropdown options from server (loaded with page data)
|
||||
const formOptions = $derived(data.formOptions || {});
|
||||
const accounts = $derived(formOptions.accounts || []);
|
||||
const users = $derived(formOptions.users || []);
|
||||
const contacts = $derived(formOptions.contacts || []);
|
||||
const teams = $derived(formOptions.teams || []);
|
||||
const opportunities = $derived(formOptions.opportunities || []);
|
||||
const cases = $derived(formOptions.cases || []);
|
||||
const leads = $derived(formOptions.leads || []);
|
||||
const allTags = $derived(formOptions.tags || []);
|
||||
|
||||
// Track if dropdown options have been loaded
|
||||
let dropdownOptionsLoaded = $state(false);
|
||||
let loadingDropdownOptions = $state(false);
|
||||
// Dropdown options are now loaded server-side with page data
|
||||
// No lazy loading needed
|
||||
|
||||
/**
|
||||
* Lazy load dropdown options when drawer opens
|
||||
* Cached so subsequent opens don't re-fetch
|
||||
* Get account name from server-provided accounts list
|
||||
* @param {string} id
|
||||
*/
|
||||
async function loadDropdownOptions() {
|
||||
if (dropdownOptionsLoaded || loadingDropdownOptions) return;
|
||||
|
||||
loadingDropdownOptions = true;
|
||||
try {
|
||||
// Use Promise.allSettled so partial failures don't break the whole form
|
||||
const results = await Promise.allSettled([
|
||||
apiRequest('/users/'),
|
||||
apiRequest('/accounts/'),
|
||||
apiRequest('/contacts/'),
|
||||
apiRequest('/teams/'),
|
||||
apiRequest('/opportunities/'),
|
||||
apiRequest('/cases/'),
|
||||
apiRequest('/leads/'),
|
||||
apiRequest('/tags/')
|
||||
]);
|
||||
|
||||
/**
|
||||
* Safely get result value or empty object
|
||||
* @param {PromiseSettledResult<any>} result
|
||||
* @param {string} name
|
||||
*/
|
||||
function getResult(result, name) {
|
||||
if (result.status === 'fulfilled') {
|
||||
return result.value;
|
||||
}
|
||||
console.warn(`Failed to load ${name}:`, result.reason);
|
||||
return {};
|
||||
}
|
||||
|
||||
const usersResponse = getResult(results[0], 'users');
|
||||
const accountsResponse = getResult(results[1], 'accounts');
|
||||
const contactsResponse = getResult(results[2], 'contacts');
|
||||
const teamsResponse = getResult(results[3], 'teams');
|
||||
const opportunitiesResponse = getResult(results[4], 'opportunities');
|
||||
const casesResponse = getResult(results[5], 'cases');
|
||||
const leadsResponse = getResult(results[6], 'leads');
|
||||
const tagsResponse = getResult(results[7], 'tags');
|
||||
|
||||
// Transform users list
|
||||
const activeUsersList = usersResponse.active_users?.active_users || [];
|
||||
users = activeUsersList.map((/** @type {any} */ user) => ({
|
||||
id: user.id,
|
||||
name: user.user_details?.email || user.email
|
||||
}));
|
||||
|
||||
// Transform accounts list
|
||||
let allAccounts = [];
|
||||
if (accountsResponse.active_accounts?.open_accounts) {
|
||||
allAccounts = accountsResponse.active_accounts.open_accounts;
|
||||
} else if (accountsResponse.results) {
|
||||
allAccounts = accountsResponse.results;
|
||||
} else if (Array.isArray(accountsResponse)) {
|
||||
allAccounts = accountsResponse;
|
||||
}
|
||||
accounts = allAccounts.map((/** @type {any} */ account) => ({
|
||||
id: account.id,
|
||||
name: account.name
|
||||
}));
|
||||
|
||||
// Transform contacts list
|
||||
let allContacts = [];
|
||||
if (contactsResponse.contact_obj_list) {
|
||||
allContacts = contactsResponse.contact_obj_list;
|
||||
} else if (contactsResponse.results) {
|
||||
allContacts = contactsResponse.results;
|
||||
} else if (Array.isArray(contactsResponse)) {
|
||||
allContacts = contactsResponse;
|
||||
}
|
||||
contacts = allContacts.map((/** @type {any} */ contact) => ({
|
||||
id: contact.id,
|
||||
name: contact.first_name
|
||||
? `${contact.first_name} ${contact.last_name || ''}`.trim()
|
||||
: contact.email || 'Unknown'
|
||||
}));
|
||||
|
||||
// Transform teams list
|
||||
let allTeamsList = [];
|
||||
if (teamsResponse.teams) {
|
||||
allTeamsList = teamsResponse.teams;
|
||||
} else if (teamsResponse.results) {
|
||||
allTeamsList = teamsResponse.results;
|
||||
} else if (Array.isArray(teamsResponse)) {
|
||||
allTeamsList = teamsResponse;
|
||||
}
|
||||
teams = allTeamsList.map((/** @type {any} */ team) => ({
|
||||
id: team.id,
|
||||
name: team.name
|
||||
}));
|
||||
|
||||
// Transform opportunities list
|
||||
let allOpportunitiesList = [];
|
||||
if (opportunitiesResponse.opportunities) {
|
||||
allOpportunitiesList = opportunitiesResponse.opportunities;
|
||||
} else if (opportunitiesResponse.results) {
|
||||
allOpportunitiesList = opportunitiesResponse.results;
|
||||
} else if (Array.isArray(opportunitiesResponse)) {
|
||||
allOpportunitiesList = opportunitiesResponse;
|
||||
}
|
||||
opportunities = allOpportunitiesList.map((/** @type {any} */ opp) => ({
|
||||
id: opp.id,
|
||||
name: opp.name
|
||||
}));
|
||||
|
||||
// Transform cases list
|
||||
let allCasesList = [];
|
||||
if (casesResponse.cases) {
|
||||
allCasesList = casesResponse.cases;
|
||||
} else if (casesResponse.results) {
|
||||
allCasesList = casesResponse.results;
|
||||
} else if (Array.isArray(casesResponse)) {
|
||||
allCasesList = casesResponse;
|
||||
}
|
||||
cases = allCasesList.map((/** @type {any} */ c) => ({
|
||||
id: c.id,
|
||||
name: c.name
|
||||
}));
|
||||
|
||||
// Transform leads list
|
||||
let allLeadsList = [];
|
||||
if (leadsResponse.leads) {
|
||||
allLeadsList = leadsResponse.leads;
|
||||
} else if (leadsResponse.results) {
|
||||
allLeadsList = leadsResponse.results;
|
||||
} else if (Array.isArray(leadsResponse)) {
|
||||
allLeadsList = leadsResponse;
|
||||
}
|
||||
leads = allLeadsList.map((/** @type {any} */ lead) => ({
|
||||
id: lead.id,
|
||||
name:
|
||||
lead.first_name || lead.last_name
|
||||
? `${lead.first_name || ''} ${lead.last_name || ''}`.trim()
|
||||
: lead.title || 'Lead'
|
||||
}));
|
||||
|
||||
// Transform tags list
|
||||
let allTagsList = [];
|
||||
if (tagsResponse.tags) {
|
||||
allTagsList = tagsResponse.tags;
|
||||
} else if (tagsResponse.results) {
|
||||
allTagsList = tagsResponse.results;
|
||||
} else if (Array.isArray(tagsResponse)) {
|
||||
allTagsList = tagsResponse;
|
||||
}
|
||||
allTags = allTagsList.map((/** @type {any} */ tag) => ({
|
||||
id: tag.id,
|
||||
name: tag.name
|
||||
}));
|
||||
|
||||
dropdownOptionsLoaded = true;
|
||||
} catch (err) {
|
||||
console.error('Error loading dropdown options:', err);
|
||||
toast.error('Failed to load form options');
|
||||
} finally {
|
||||
loadingDropdownOptions = false;
|
||||
function fetchAccountName(id) {
|
||||
const account = accounts.find((a) => a.id === id);
|
||||
if (account) {
|
||||
accountNameFromUrl = account.name;
|
||||
} else {
|
||||
accountNameFromUrl = 'Unknown Account';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear URL params for accountId and action
|
||||
*/
|
||||
function clearUrlParams() {
|
||||
const url = new URL($page.url);
|
||||
url.searchParams.delete('action');
|
||||
url.searchParams.delete('accountId');
|
||||
goto(url.pathname, { replaceState: true, invalidateAll: true });
|
||||
accountFromUrl = false;
|
||||
accountNameFromUrl = '';
|
||||
accountIdFromUrl = '';
|
||||
}
|
||||
|
||||
// URL-based filter state from server
|
||||
const filters = $derived(data.filters || {});
|
||||
|
||||
|
|
@ -662,6 +530,14 @@
|
|||
}
|
||||
|
||||
async function addNewTask() {
|
||||
// Check for account pre-fill from URL params
|
||||
const accountIdParam = $page.url.searchParams.get('accountId');
|
||||
if (accountIdParam && !accountFromUrl) {
|
||||
accountIdFromUrl = accountIdParam;
|
||||
accountFromUrl = true;
|
||||
fetchAccountName(accountIdParam);
|
||||
}
|
||||
|
||||
// Open the sheet for creating a new task
|
||||
selectedTaskId = null;
|
||||
formState = {
|
||||
|
|
@ -671,8 +547,8 @@
|
|||
status: 'New',
|
||||
priority: 'Medium',
|
||||
dueDate: '',
|
||||
accountId: '',
|
||||
accountName: '',
|
||||
accountId: accountIdFromUrl || '',
|
||||
accountName: accountNameFromUrl || '',
|
||||
opportunityId: '',
|
||||
opportunityName: '',
|
||||
caseId: '',
|
||||
|
|
@ -685,10 +561,17 @@
|
|||
tags: []
|
||||
};
|
||||
sheetOpen = true;
|
||||
// Lazy load dropdown options when drawer opens
|
||||
loadDropdownOptions();
|
||||
}
|
||||
|
||||
// URL sync for action param (quick action from account page)
|
||||
$effect(() => {
|
||||
const action = $page.url.searchParams.get('action');
|
||||
|
||||
if (action === 'create' && !sheetOpen) {
|
||||
addNewTask();
|
||||
}
|
||||
});
|
||||
|
||||
// Row detail sheet functions
|
||||
/**
|
||||
* @param {string} taskId
|
||||
|
|
@ -719,13 +602,15 @@
|
|||
};
|
||||
}
|
||||
sheetOpen = true;
|
||||
// Lazy load dropdown options when drawer opens
|
||||
loadDropdownOptions();
|
||||
}
|
||||
|
||||
function closeTaskSheet() {
|
||||
sheetOpen = false;
|
||||
selectedTaskId = null;
|
||||
// Clear account URL params if they were set
|
||||
if (accountFromUrl) {
|
||||
clearUrlParams();
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSelectedTask() {
|
||||
|
|
@ -941,12 +826,16 @@
|
|||
|
||||
// Drawer columns for NotionDrawer (derived to use dynamic options)
|
||||
// Parent entity fields (account, opportunity, case, lead) are only shown in edit mode
|
||||
// Exception: when creating from account quick action, show account as readonly and hide other parent fields
|
||||
const drawerColumns = $derived([
|
||||
{ key: 'subject', label: 'Subject', type: 'text', icon: FileText },
|
||||
{ key: 'status', label: 'Status', type: 'select', icon: Circle, options: statusOptions },
|
||||
{ key: 'priority', label: 'Priority', type: 'select', icon: Flag, options: priorityOptions },
|
||||
{ key: 'dueDate', label: 'Due Date', type: 'date', icon: Calendar },
|
||||
// Only show the parent entity field if one exists (read-only, only one can be associated)
|
||||
// Parent entity field handling:
|
||||
// - In edit mode: show readonly for the existing parent entity
|
||||
// - In create mode with accountFromUrl: show account as readonly only
|
||||
// - In create mode without accountFromUrl: show nothing (parent fields not available in create)
|
||||
...(selectedTaskId
|
||||
? (() => {
|
||||
const task = localTasks.find((t) => t.id === selectedTaskId);
|
||||
|
|
@ -963,7 +852,17 @@
|
|||
return [{ key: 'caseName', label: 'Case', type: 'readonly', icon: Briefcase }];
|
||||
return [];
|
||||
})()
|
||||
: []),
|
||||
: accountFromUrl
|
||||
? [
|
||||
{
|
||||
key: 'accountDisplay',
|
||||
label: 'Account',
|
||||
type: 'readonly',
|
||||
icon: Building2,
|
||||
getValue: () => accountNameFromUrl || 'Loading...'
|
||||
}
|
||||
]
|
||||
: []),
|
||||
{
|
||||
key: 'assignedTo',
|
||||
label: 'Assigned To',
|
||||
|
|
|
|||
Loading…
Reference in a new issue