code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
<template> <TransitionRoot :show="sidebarOpened"> <Dialog as="div" @close="sidebarOpened = false" class="fixed inset-0 z-40"> <TransitionChild as="template" enter="transition ease-in-out duration-200 transform" enter-from="-translate-x-full" enter-to="translate-x-0" leave="transition ease-in-out duration-200 transform" leave-from="translate-x-0" leave-to="-translate-x-full" > <div class="relative z-10 flex h-full w-[260px] flex-col justify-between border-r bg-gray-50 transition-all duration-300 ease-in-out" > <div><UserDropdown class="p-2" /></div> <div class="flex-1 overflow-y-auto"> <div class="mb-3 flex flex-col"> <SidebarLink id="notifications-btn" :label="__('Notifications')" :icon="NotificationsIcon" :to="{ name: 'Notifications' }" class="relative mx-2 my-0.5" > <template #right> <Badge v-if="notificationsStore().unreadNotificationsCount" :label="notificationsStore().unreadNotificationsCount" variant="subtle" /> </template> </SidebarLink> </div> <div v-for="view in allViews" :key="view.label"> <Section :label="view.name" :hideLabel="view.hideLabel" :isOpened="view.opened" > <template #header="{ opened, hide, toggle }"> <div v-if="!hide" class="ml-2 mt-4 flex h-7 w-auto cursor-pointer gap-1.5 px-1 text-base font-medium text-gray-600 opacity-100 transition-all duration-300 ease-in-out" @click="toggle()" > <FeatherIcon name="chevron-right" class="h-4 text-gray-900 transition-all duration-300 ease-in-out" :class="{ 'rotate-90': opened }" /> <span>{{ __(view.name) }}</span> </div> </template> <nav class="flex flex-col"> <SidebarLink v-for="link in view.views" :icon="link.icon" :label="__(link.label)" :to="link.to" class="mx-2 my-0.5" /> </nav> </Section> </div> </div> </div> </TransitionChild> <TransitionChild as="template" enter="transition-opacity ease-linear duration-200" enter-from="opacity-0" enter-to="opacity-100" leave="transition-opacity ease-linear duration-200" leave-from="opacity-100" leave-to="opacity-0" > <DialogOverlay class="fixed inset-0 bg-gray-600 bg-opacity-50" /> </TransitionChild> </Dialog> </TransitionRoot> </template> <script setup> import { TransitionRoot, TransitionChild, Dialog, DialogOverlay, } from '@headlessui/vue' import Section from '@/components/Section.vue' import Email2Icon from '@/components/Icons/Email2Icon.vue' import PinIcon from '@/components/Icons/PinIcon.vue' import UserDropdown from '@/components/UserDropdown.vue' import LeadsIcon from '@/components/Icons/LeadsIcon.vue' import DealsIcon from '@/components/Icons/DealsIcon.vue' import ContactsIcon from '@/components/Icons/ContactsIcon.vue' import OrganizationsIcon from '@/components/Icons/OrganizationsIcon.vue' import NoteIcon from '@/components/Icons/NoteIcon.vue' import TaskIcon from '@/components/Icons/TaskIcon.vue' import PhoneIcon from '@/components/Icons/PhoneIcon.vue' import NotificationsIcon from '@/components/Icons/NotificationsIcon.vue' import SidebarLink from '@/components/SidebarLink.vue' import { viewsStore } from '@/stores/views' import { notificationsStore } from '@/stores/notifications' import { computed, h } from 'vue' import { mobileSidebarOpened as sidebarOpened } from '@/composables/settings' const { getPinnedViews, getPublicViews } = viewsStore() const links = [ { label: 'Leads', icon: LeadsIcon, to: 'Leads', }, { label: 'Deals', icon: DealsIcon, to: 'Deals', }, { label: 'Contacts', icon: ContactsIcon, to: 'Contacts', }, { label: 'Organizations', icon: OrganizationsIcon, to: 'Organizations', }, { label: 'Notes', icon: NoteIcon, to: 'Notes', }, { label: 'Tasks', icon: TaskIcon, to: 'Tasks', }, { label: 'Call Logs', icon: PhoneIcon, to: 'Call Logs', }, { label: 'Email Templates', icon: Email2Icon, to: 'Email Templates', }, ] const allViews = computed(() => { let _views = [ { name: 'All Views', hideLabel: true, opened: true, views: links, }, ] if (getPublicViews().length) { _views.push({ name: 'Public views', opened: true, views: parseView(getPublicViews()), }) } if (getPinnedViews().length) { _views.push({ name: 'Pinned views', opened: true, views: parseView(getPinnedViews()), }) } return _views }) function parseView(views) { return views.map((view) => { return { label: view.label, icon: getIcon(view.route_name, view.icon), to: { name: view.route_name, params: { viewType: view.type || 'list' }, query: { view: view.name }, }, } }) } function getIcon(routeName, icon) { if (icon) return h('div', { class: 'size-auto' }, icon) switch (routeName) { case 'Leads': return LeadsIcon case 'Deals': return DealsIcon case 'Contacts': return ContactsIcon case 'Organizations': return OrganizationsIcon case 'Notes': return NoteIcon case 'Call Logs': return PhoneIcon default: return PinIcon } } </script>
2302_79757062/crm
frontend/src/components/Mobile/MobileSidebar.vue
Vue
agpl-3.0
6,120
<template> <Dialog v-model="show" :options="dialogOptions"> <template #body> <div class="bg-white px-4 pb-6 pt-5 sm:px-6"> <div class="mb-5 flex items-center justify-between"> <div> <h3 class="text-2xl font-semibold leading-6 text-gray-900"> {{ __(dialogOptions.title) || __('Untitled') }} </h3> </div> <div class="flex items-center gap-1"> <Button v-if="isManager()" variant="ghost" class="w-7" @click="openQuickEntryModal" > <EditIcon class="h-4 w-4" /> </Button> <Button variant="ghost" class="w-7" @click="show = false"> <FeatherIcon name="x" class="h-4 w-4" /> </Button> </div> </div> <div v-if="sections.data"> <Fields :sections="sections.data" :data="_address" /> <ErrorMessage class="mt-2" :message="error" /> </div> </div> <div class="px-4 pb-7 pt-4 sm:px-6"> <div class="space-y-2"> <Button class="w-full" v-for="action in dialogOptions.actions" :key="action.label" v-bind="action" :label="__(action.label)" :loading="loading" /> </div> </div> </template> </Dialog> <QuickEntryModal v-if="showQuickEntryModal" v-model="showQuickEntryModal" doctype="Address" /> </template> <script setup> import QuickEntryModal from '@/components/Modals/QuickEntryModal.vue' import Fields from '@/components/Fields.vue' import EditIcon from '@/components/Icons/EditIcon.vue' import { usersStore } from '@/stores/users' import { capture } from '@/telemetry' import { call, FeatherIcon, createResource, ErrorMessage } from 'frappe-ui' import { ref, nextTick, watch, computed } from 'vue' const props = defineProps({ options: { type: Object, default: { afterInsert: () => {}, }, }, }) const { isManager } = usersStore() const show = defineModel() const address = defineModel('address') const loading = ref(false) const error = ref(null) const title = ref(null) const editMode = ref(false) let _address = ref({ name: '', address_title: '', address_type: 'Billing', address_line1: '', address_line2: '', city: '', county: '', state: '', country: '', pincode: '', }) const dialogOptions = computed(() => { let title = !editMode.value ? __('New Address') : __(_address.value.address_title) let size = 'xl' let actions = [ { label: editMode.value ? __('Save') : __('Create'), variant: 'solid', onClick: () => editMode.value ? updateAddress() : createAddress.submit(), }, ] return { title, size, actions } }) const sections = createResource({ url: 'crm.fcrm.doctype.crm_fields_layout.crm_fields_layout.get_fields_layout', cache: ['quickEntryFields', 'Address'], params: { doctype: 'Address', type: 'Quick Entry' }, auto: true, }) let doc = ref({}) function updateAddress() { error.value = null const old = { ...doc.value } const newAddress = { ..._address.value } const dirty = JSON.stringify(old) !== JSON.stringify(newAddress) const values = newAddress if (!dirty) { show.value = false return } loading.value = true updateAddressValues.submit({ doctype: 'Address', name: _address.value.name, fieldname: values, }) } const updateAddressValues = createResource({ url: 'frappe.client.set_value', onSuccess(doc) { loading.value = false if (doc.name) { handleAddressUpdate(doc) } }, onError(err) { loading.value = false error.value = err }, }) const createAddress = createResource({ url: 'frappe.client.insert', makeParams() { return { doc: { doctype: 'Address', ..._address.value, }, } }, onSuccess(doc) { loading.value = false if (doc.name) { capture('address_created') handleAddressUpdate(doc) } }, onError(err) { loading.value = false error.value = err }, }) function handleAddressUpdate(doc) { show.value = false props.options.afterInsert && props.options.afterInsert(doc) } watch( () => show.value, (value) => { if (!value) return editMode.value = false nextTick(() => { // TODO: Issue with FormControl // title.value.el.focus() doc.value = address.value?.doc || address.value || {} _address.value = { ...doc.value } if (_address.value.name) { editMode.value = true } }) }, ) const showQuickEntryModal = ref(false) function openQuickEntryModal() { showQuickEntryModal.value = true nextTick(() => { show.value = false }) } </script>
2302_79757062/crm
frontend/src/components/Modals/AddressModal.vue
Vue
agpl-3.0
4,813
<template> <Dialog v-model="show" :options="{ title: __('Assign To'), size: 'xl', actions: [ { label: __('Cancel'), variant: 'subtle', onClick: () => { assignees = [...oldAssignees] show = false }, }, { label: __('Update'), variant: 'solid', onClick: () => updateAssignees(), }, ], }" @close=" () => { assignees = [...oldAssignees] } " > <template #body-content> <Link class="form-control" value="" doctype="User" @change="(option) => addValue(option) && ($refs.input.value = '')" :placeholder="__('John Doe')" :hideMe="true" > <template #item-prefix="{ option }"> <UserAvatar class="mr-2" :user="option.value" size="sm" /> </template> <template #item-label="{ option }"> <Tooltip :text="option.value"> <div class="cursor-pointer"> {{ getUser(option.value).full_name }} </div> </Tooltip> </template> </Link> <div class="mt-3 flex flex-wrap items-center gap-2"> <Tooltip :text="assignee.name" v-for="assignee in assignees" :key="assignee.name" > <Button :label="getUser(assignee.name).full_name" theme="gray" variant="outline" > <template #prefix> <UserAvatar :user="assignee.name" size="sm" /> </template> <template #suffix> <FeatherIcon v-if="assignee.name !== owner" class="h-3.5" name="x" @click.stop="removeValue(assignee.name)" /> </template> </Button> </Tooltip> </div> <ErrorMessage class="mt-2" v-if="error" :message="__(error)" /> </template> </Dialog> </template> <script setup> import UserAvatar from '@/components/UserAvatar.vue' import Link from '@/components/Controls/Link.vue' import { usersStore } from '@/stores/users' import { capture } from '@/telemetry' import { Tooltip, call } from 'frappe-ui' import { ref, computed, onMounted } from 'vue' const props = defineProps({ doc: { type: Object, default: null, }, docs: { type: Set, default: new Set(), }, doctype: { type: String, default: '', }, }) const emit = defineEmits(['reload']) const show = defineModel() const assignees = defineModel('assignees') const oldAssignees = ref([]) const error = ref('') const { getUser } = usersStore() const removeValue = (value) => { assignees.value = assignees.value.filter( (assignee) => assignee.name !== value, ) } const owner = computed(() => { if (!props.doc) return '' if (props.doctype == 'CRM Lead') return props.doc.lead_owner return props.doc.deal_owner }) const addValue = (value) => { error.value = '' let obj = { name: value, image: getUser(value).user_image, label: getUser(value).full_name, } if (!assignees.value.find((assignee) => assignee.name === value)) { assignees.value.push(obj) } } function updateAssignees() { if (assignees.value.length === 0) { error.value = 'Please select at least one assignee' return } const removedAssignees = oldAssignees.value .filter( (assignee) => !assignees.value.find((a) => a.name === assignee.name), ) .map((assignee) => assignee.name) const addedAssignees = assignees.value .filter( (assignee) => !oldAssignees.value.find((a) => a.name === assignee.name), ) .map((assignee) => assignee.name) if (removedAssignees.length) { for (let a of removedAssignees) { call('frappe.desk.form.assign_to.remove', { doctype: props.doctype, name: props.doc.name, assign_to: a, }) } } if (addedAssignees.length) { if (props.docs.size) { capture('bulk_assign_to', { doctype: props.doctype }) call('frappe.desk.form.assign_to.add_multiple', { doctype: props.doctype, name: JSON.stringify(Array.from(props.docs)), assign_to: addedAssignees, bulk_assign: true, re_assign: true, }).then(() => { emit('reload') }) } else { capture('assign_to', { doctype: props.doctype }) call('frappe.desk.form.assign_to.add', { doctype: props.doctype, name: props.doc.name, assign_to: addedAssignees, }) } } show.value = false } onMounted(() => { oldAssignees.value = [...assignees.value] }) </script>
2302_79757062/crm
frontend/src/components/Modals/AssignmentModal.vue
Vue
agpl-3.0
4,713
<template> <Dialog v-model="show"> <template #body-title> <div class="flex items-center gap-3"> <h3 class="text-2xl font-semibold leading-6 text-gray-900"> {{ __('Call Details') }} </h3> </div> </template> <template #body-content> <div class="flex flex-col gap-3.5"> <div v-for="field in detailFields" :key="field.name" class="flex gap-2 text-base text-gray-800" > <div class="grid size-7 place-content-center"> <component :is="field.icon" /> </div> <div class="flex min-h-7 w-full items-center gap-2"> <div v-if="field.name == 'receiver'" class="flex items-center gap-1" > <Avatar :image="field.value.caller.image" :label="field.value.caller.label" size="sm" /> <div class="ml-1 flex flex-col gap-1"> {{ field.value.caller.label }} </div> <FeatherIcon name="arrow-right" class="mx-1 h-4 w-4 text-gray-600" /> <Avatar :image="field.value.receiver.image" :label="field.value.receiver.label" size="sm" /> <div class="ml-1 flex flex-col gap-1"> {{ field.value.receiver.label }} </div> </div> <Tooltip v-else-if="field.tooltip" :text="field.tooltip"> {{ field.value }} </Tooltip> <div class="w-full" v-else-if="field.name == 'recording_url'"> <audio class="audio-control w-full" controls :src="field.value" ></audio> </div> <div class="w-full cursor-pointer rounded border px-2 pt-1.5 text-base text-gray-700" v-else-if="field.name == 'note'" @click="() => (showNoteModal = true)" > <FadedScrollableDiv class="max-h-24 min-h-16 overflow-y-auto"> <div v-if="field.value?.title" :class="[field.value?.content ? 'mb-1 font-bold' : '']" v-html="field.value?.title" /> <div v-if="field.value?.content" v-html="field.value?.content" /> </FadedScrollableDiv> </div> <div v-else :class="field.color ? `text-${field.color}-600` : ''"> {{ field.value }} </div> <div v-if="field.link"> <ArrowUpRightIcon class="h-4 w-4 shrink-0 cursor-pointer text-gray-600 hover:text-gray-800" @click="() => field.link()" /> </div> </div> </div> </div> </template> <template v-if=" callLog.doc?.type.label == 'Incoming' && !callLog.doc?.reference_docname " #actions > <Button class="w-full" variant="solid" :label="__('Create lead')" @click="createLead" /> </template> </Dialog> <NoteModal v-model="showNoteModal" :note="callNoteDoc?.doc" /> </template> <script setup> import ArrowUpRightIcon from '@/components/Icons/ArrowUpRightIcon.vue' import DurationIcon from '@/components/Icons/DurationIcon.vue' import ContactsIcon from '@/components/Icons/ContactsIcon.vue' import LeadsIcon from '@/components/Icons/LeadsIcon.vue' import Dealsicon from '@/components/Icons/DealsIcon.vue' import CalendarIcon from '@/components/Icons/CalendarIcon.vue' import NoteIcon from '@/components/Icons/NoteIcon.vue' import CheckCircleIcon from '@/components/Icons/CheckCircleIcon.vue' import NoteModal from '@/components/Modals/NoteModal.vue' import FadedScrollableDiv from '@/components/FadedScrollableDiv.vue' import { FeatherIcon, Avatar, Tooltip, createDocumentResource, call, } from 'frappe-ui' import { getCallLogDetail } from '@/utils/callLog' import { ref, computed, h, watch } from 'vue' import { useRouter } from 'vue-router' const props = defineProps({ name: { type: String, default: {}, }, }) const show = defineModel() const showNoteModal = ref(false) const router = useRouter() const callNoteDoc = ref(null) const callLog = ref({}) const detailFields = computed(() => { if (!callLog.value.doc) return [] let details = [ { icon: h(FeatherIcon, { name: callLog.value.doc.type.icon, class: 'h-3.5 w-3.5', }), name: 'type', value: callLog.value.doc.type.label + ' Call', }, { icon: ContactsIcon, name: 'receiver', value: { receiver: callLog.value.doc.receiver, caller: callLog.value.doc.caller, }, }, { icon: callLog.value.doc.reference_doctype == 'CRM Lead' ? LeadsIcon : Dealsicon, name: 'reference_doctype', value: callLog.value.doc.reference_doctype == 'CRM Lead' ? 'Lead' : 'Deal', link: () => { if (callLog.value.doc.reference_doctype == 'CRM Lead') { router.push({ name: 'Lead', params: { leadId: callLog.value.doc.reference_docname }, }) } else { router.push({ name: 'Deal', params: { dealId: callLog.value.doc.reference_docname }, }) } }, condition: () => callLog.value.doc.reference_docname, }, { icon: CalendarIcon, name: 'creation', value: callLog.value.doc.creation.label, tooltip: callLog.value.doc.creation.label, }, { icon: DurationIcon, name: 'duration', value: callLog.value.doc.duration.label, }, { icon: CheckCircleIcon, name: 'status', value: callLog.value.doc.status.label, color: callLog.value.doc.status.color, }, { icon: h(FeatherIcon, { name: 'play-circle', class: 'h-4 w-4 mt-2', }), name: 'recording_url', value: callLog.value.doc.recording_url, }, { icon: NoteIcon, name: 'note', value: callNoteDoc.value?.doc, }, ] return details .filter((detail) => detail.value) .filter((detail) => (detail.condition ? detail.condition() : true)) }) function createLead() { call('crm.fcrm.doctype.crm_call_log.crm_call_log.create_lead_from_call_log', { call_log: callLog.value.doc, }).then((d) => { if (d) { router.push({ name: 'Lead', params: { leadId: d } }) } }) } watch(show, (val) => { if (val) { callLog.value = createDocumentResource({ doctype: 'CRM Call Log', name: props.name, fields: [ 'name', 'caller', 'receiver', 'duration', 'type', 'status', 'from', 'to', 'note', 'recording_url', 'reference_doctype', 'reference_docname', 'creation', ], cache: ['call_log', props.name], auto: true, transform: (doc) => { for (const key in doc) { doc[key] = getCallLogDetail(key, doc) } return doc }, onSuccess: (doc) => { if (!doc.note) { callNoteDoc.value = null return } callNoteDoc.value = createDocumentResource({ doctype: 'FCRM Note', name: doc.note, fields: ['title', 'content'], cache: ['note', doc.note], auto: true, }) }, }) } }) </script> <style scoped> .audio-control { height: 36px; outline: none; border-radius: 10px; cursor: pointer; background-color: rgb(237, 237, 237); } audio::-webkit-media-controls-panel { background-color: rgb(237, 237, 237) !important; } .audio-control::-webkit-media-controls-panel { background-color: white; } </style>
2302_79757062/crm
frontend/src/components/Modals/CallLogModal.vue
Vue
agpl-3.0
8,028
<template> <Dialog v-model="show" :options="dialogOptions"> <template #body> <div class="bg-white px-4 pb-6 pt-5 sm:px-6"> <div class="mb-5 flex items-center justify-between"> <div> <h3 class="text-2xl font-semibold leading-6 text-gray-900"> {{ __(dialogOptions.title) || __('Untitled') }} </h3> </div> <div class="flex items-center gap-1"> <Button v-if="isManager() || detailMode" variant="ghost" class="w-7" @click="detailMode ? (detailMode = false) : openQuickEntryModal()" > <EditIcon class="h-4 w-4" /> </Button> <Button variant="ghost" class="w-7" @click="show = false"> <FeatherIcon name="x" class="h-4 w-4" /> </Button> </div> </div> <div> <div v-if="detailMode" class="flex flex-col gap-3.5"> <div v-for="field in detailFields" :key="field.name" class="flex h-7 items-center gap-2 text-base text-gray-800" > <div class="grid w-7 place-content-center"> <component :is="field.icon" /> </div> <div v-if="field.type == 'dropdown'"> <Dropdown :options="field.options" class="form-control -ml-2 mr-2 w-full flex-1" > <template #default="{ open }"> <Button variant="ghost" :label="contact.data[field.name]" class="dropdown-button w-full justify-between truncate hover:bg-white" > <div class="truncate">{{ contact.data[field.name] }}</div> <template #suffix> <FeatherIcon :name="open ? 'chevron-up' : 'chevron-down'" class="h-4 text-gray-600" /> </template> </Button> </template> </Dropdown> </div> <div v-else>{{ field.value }}</div> </div> </div> <Fields v-else-if="filteredSections" :sections="filteredSections" :data="_contact" /> </div> </div> <div v-if="!detailMode" class="px-4 pb-7 pt-4 sm:px-6"> <div class="space-y-2"> <Button class="w-full" v-for="action in dialogOptions.actions" :key="action.label" v-bind="action" > {{ __(action.label) }} </Button> </div> </div> </template> </Dialog> <AddressModal v-model="showAddressModal" v-model:address="_address" /> </template> <script setup> import Fields from '@/components/Fields.vue' import AddressModal from '@/components/Modals/AddressModal.vue' import ContactIcon from '@/components/Icons/ContactIcon.vue' import GenderIcon from '@/components/Icons/GenderIcon.vue' import Email2Icon from '@/components/Icons/Email2Icon.vue' import PhoneIcon from '@/components/Icons/PhoneIcon.vue' import OrganizationsIcon from '@/components/Icons/OrganizationsIcon.vue' import AddressIcon from '@/components/Icons/AddressIcon.vue' import CertificateIcon from '@/components/Icons/CertificateIcon.vue' import EditIcon from '@/components/Icons/EditIcon.vue' import Dropdown from '@/components/frappe-ui/Dropdown.vue' import { usersStore } from '@/stores/users' import { capture } from '@/telemetry' import { call, createResource } from 'frappe-ui' import { ref, nextTick, watch, computed } from 'vue' import { createToast } from '@/utils' import { useRouter } from 'vue-router' const props = defineProps({ contact: { type: Object, default: {}, }, options: { type: Object, default: { redirect: true, detailMode: false, afterInsert: () => {}, }, }, }) const { isManager } = usersStore() const router = useRouter() const show = defineModel() const detailMode = ref(false) const editMode = ref(false) let _contact = ref({}) let _address = ref({}) const showAddressModal = ref(false) async function updateContact() { if (!dirty.value) { show.value = false return } const values = { ..._contact.value } let name = await callSetValue(values) handleContactUpdate({ name }) } async function callSetValue(values) { const d = await call('frappe.client.set_value', { doctype: 'Contact', name: props.contact.data.name, fieldname: values, }) return d.name } async function callInsertDoc() { if (_contact.value.email_id) { _contact.value.email_ids = [{ email_id: _contact.value.email_id }] delete _contact.value.email_id } if (_contact.value.actual_mobile_no) { _contact.value.phone_nos = [{ phone: _contact.value.actual_mobile_no }] delete _contact.value.actual_mobile_no } const doc = await call('frappe.client.insert', { doc: { doctype: 'Contact', ..._contact.value, }, }) if (doc.name) { capture('contact_created') handleContactUpdate(doc) } } function handleContactUpdate(doc) { props.contact?.reload?.() if (doc.name && props.options.redirect) { router.push({ name: 'Contact', params: { contactId: doc.name }, }) } show.value = false props.options.afterInsert && props.options.afterInsert(doc) } const dialogOptions = computed(() => { let title = !editMode.value ? 'New Contact' : _contact.value.full_name let size = detailMode.value ? '' : 'xl' let actions = detailMode.value ? [] : [ { label: editMode.value ? 'Save' : 'Create', variant: 'solid', disabled: !dirty.value, onClick: () => (editMode.value ? updateContact() : callInsertDoc()), }, ] return { title, size, actions } }) const detailFields = computed(() => { let details = [ { icon: ContactIcon, name: 'full_name', value: (_contact.value.salutation ? _contact.value.salutation + '. ' : '') + _contact.value.full_name, }, { icon: GenderIcon, name: 'gender', value: _contact.value.gender, }, { icon: Email2Icon, name: 'email_id', value: _contact.value.email_id, }, { icon: PhoneIcon, name: 'mobile_no', value: _contact.value.actual_mobile_no, }, { icon: OrganizationsIcon, name: 'company_name', value: _contact.value.company_name, }, { icon: CertificateIcon, name: 'designation', value: _contact.value.designation, }, { icon: AddressIcon, name: 'address', value: _contact.value.address, }, ] return details.filter((detail) => detail.value) }) const sections = createResource({ url: 'crm.fcrm.doctype.crm_fields_layout.crm_fields_layout.get_fields_layout', cache: ['quickEntryFields', 'Contact'], params: { doctype: 'Contact', type: 'Quick Entry' }, auto: true, }) const filteredSections = computed(() => { let allSections = sections.data || [] if (!allSections.length) return [] allSections.forEach((s) => { s.fields.forEach((field) => { if (field.name == 'email_id') { field.type = props.contact?.data?.name ? 'Dropdown' : 'Data' field.options = props.contact.data?.email_ids?.map((email) => { return { name: email.name, value: email.email_id, selected: email.email_id === props.contact.data.email_id, placeholder: 'john@doe.com', onClick: () => { _contact.value.email_id = email.email_id setAsPrimary('email', email.email_id) }, onSave: (option, isNew) => { if (isNew) { createNew('email', option.value) if (props.contact.data.email_ids.length === 1) { _contact.value.email_id = option.value } } else { editOption('Contact Email', option.name, option.value) } }, onDelete: async (option, isNew) => { props.contact.data.email_ids = props.contact.data.email_ids.filter( (email) => email.name !== option.name, ) !isNew && (await deleteOption('Contact Email', option.name)) if (_contact.value.email_id === option.value) { if (props.contact.data.email_ids.length === 0) { _contact.value.email_id = '' } else { _contact.value.email_id = props.contact.data.email_ids.find( (email) => email.is_primary, )?.email_id } } }, } }) || [] field.create = () => { props.contact.data?.email_ids?.push({ name: 'new-1', value: '', selected: false, isNew: true, }) } } else if ( field.name == 'mobile_no' || field.name == 'actual_mobile_no' ) { field.type = props.contact?.data?.name ? 'Dropdown' : 'Data' field.name = 'actual_mobile_no' field.options = props.contact.data?.phone_nos?.map((phone) => { return { name: phone.name, value: phone.phone, selected: phone.phone === props.contact.data.actual_mobile_no, onClick: () => { _contact.value.actual_mobile_no = phone.phone _contact.value.mobile_no = phone.phone setAsPrimary('mobile_no', phone.phone) }, onSave: (option, isNew) => { if (isNew) { createNew('phone', option.value) if (props.contact.data.phone_nos.length === 1) { _contact.value.actual_mobile_no = option.value } } else { editOption('Contact Phone', option.name, option.value) } }, onDelete: async (option, isNew) => { props.contact.data.phone_nos = props.contact.data.phone_nos.filter( (phone) => phone.name !== option.name, ) !isNew && (await deleteOption('Contact Phone', option.name)) if (_contact.value.actual_mobile_no === option.value) { if (props.contact.data.phone_nos.length === 0) { _contact.value.actual_mobile_no = '' } else { _contact.value.actual_mobile_no = props.contact.data.phone_nos.find( (phone) => phone.is_primary_mobile_no, )?.phone } } }, } }) || [] field.create = () => { props.contact.data?.phone_nos?.push({ name: 'new-1', value: '', selected: false, isNew: true, }) } } else if (field.name == 'address') { field.create = (value, close) => { _contact.value.address = value _address.value = {} showAddressModal.value = true close() } field.edit = async (addr) => { _address.value = await call('frappe.client.get', { doctype: 'Address', name: addr, }) showAddressModal.value = true } } }) }) return allSections }) async function setAsPrimary(field, value) { let d = await call('crm.api.contact.set_as_primary', { contact: props.contact.data.name, field, value, }) if (d) { props.contact.reload() createToast({ title: 'Contact updated', icon: 'check', iconClasses: 'text-green-600', }) } } async function createNew(field, value) { let d = await call('crm.api.contact.create_new', { contact: props.contact.data.name, field, value, }) if (d) { props.contact.reload() createToast({ title: 'Contact updated', icon: 'check', iconClasses: 'text-green-600', }) } } async function editOption(doctype, name, value) { let d = await call('frappe.client.set_value', { doctype, name, fieldname: doctype == 'Contact Phone' ? 'phone' : 'email', value, }) if (d) { props.contact.reload() createToast({ title: 'Contact updated', icon: 'check', iconClasses: 'text-green-600', }) } } async function deleteOption(doctype, name) { await call('frappe.client.delete', { doctype, name, }) await props.contact.reload() createToast({ title: 'Contact updated', icon: 'check', iconClasses: 'text-green-600', }) } const dirty = computed(() => { return JSON.stringify(props.contact.data) !== JSON.stringify(_contact.value) }) watch( () => show.value, (value) => { if (!value) return detailMode.value = props.options.detailMode editMode.value = false nextTick(() => { _contact.value = { ...props.contact.data } if (_contact.value.name) { editMode.value = true } }) }, ) const showQuickEntryModal = defineModel('quickEntry') function openQuickEntryModal() { showQuickEntryModal.value = true nextTick(() => { show.value = false }) } </script> <style scoped> :deep(:has(> .dropdown-button)) { width: 100%; } </style>
2302_79757062/crm
frontend/src/components/Modals/ContactModal.vue
Vue
agpl-3.0
13,844
<template> <Dialog v-model="show" :options="{ size: '3xl' }"> <template #body> <div class="bg-white px-4 pb-6 pt-5 sm:px-6"> <div class="mb-5 flex items-center justify-between"> <div> <h3 class="text-2xl font-semibold leading-6 text-gray-900"> {{ __('Create Deal') }} </h3> </div> <div class="flex items-center gap-1"> <Button v-if="isManager()" variant="ghost" class="w-7" @click="openQuickEntryModal" > <EditIcon class="h-4 w-4" /> </Button> <Button variant="ghost" class="w-7" @click="show = false"> <FeatherIcon name="x" class="h-4 w-4" /> </Button> </div> </div> <div> <div class="mb-4 grid grid-cols-1 gap-4 sm:grid-cols-3"> <div class="flex items-center gap-3 text-sm text-gray-600"> <div>{{ __('Choose Existing Organization') }}</div> <Switch v-model="chooseExistingOrganization" /> </div> <div class="flex items-center gap-3 text-sm text-gray-600"> <div>{{ __('Choose Existing Contact') }}</div> <Switch v-model="chooseExistingContact" /> </div> </div> <Fields v-if="filteredSections" class="border-t pt-4" :sections="filteredSections" :data="deal" /> <ErrorMessage class="mt-4" v-if="error" :message="__(error)" /> </div> </div> <div class="px-4 pb-7 pt-4 sm:px-6"> <div class="flex flex-row-reverse gap-2"> <Button variant="solid" :label="__('Create')" :loading="isDealCreating" @click="createDeal" /> </div> </div> </template> </Dialog> </template> <script setup> import EditIcon from '@/components/Icons/EditIcon.vue' import Fields from '@/components/Fields.vue' import { usersStore } from '@/stores/users' import { statusesStore } from '@/stores/statuses' import { capture } from '@/telemetry' import { Switch, createResource } from 'frappe-ui' import { computed, ref, reactive, onMounted, nextTick } from 'vue' import { useRouter } from 'vue-router' const props = defineProps({ defaults: Object, }) const { getUser, isManager } = usersStore() const { getDealStatus, statusOptions } = statusesStore() const show = defineModel() const router = useRouter() const error = ref(null) const deal = reactive({ organization: '', organization_name: '', website: '', no_of_employees: '', territory: '', annual_revenue: '', industry: '', contact: '', salutation: '', first_name: '', last_name: '', email: '', mobile_no: '', gender: '', status: '', deal_owner: '', }) const isDealCreating = ref(false) const chooseExistingContact = ref(false) const chooseExistingOrganization = ref(false) const sections = createResource({ url: 'crm.fcrm.doctype.crm_fields_layout.crm_fields_layout.get_fields_layout', cache: ['quickEntryFields', 'CRM Deal'], params: { doctype: 'CRM Deal', type: 'Quick Entry' }, auto: true, transform: (data) => { return data.forEach((section) => { section.fields.forEach((field) => { if (field.name == 'status') { field.type = 'Select' field.options = dealStatuses.value field.prefix = getDealStatus(deal.status).iconColorClass } else if (field.name == 'deal_owner') { field.type = 'User' } }) }) }, }) const filteredSections = computed(() => { let allSections = sections.data || [] if (!allSections.length) return [] let _filteredSections = [] if (chooseExistingOrganization.value) { _filteredSections.push( allSections.find((s) => s.label === 'Select Organization'), ) } else { _filteredSections.push( allSections.find((s) => s.label === 'Organization Details'), ) } if (chooseExistingContact.value) { _filteredSections.push( allSections.find((s) => s.label === 'Select Contact'), ) } else { _filteredSections.push( allSections.find((s) => s.label === 'Contact Details'), ) } allSections.forEach((s) => { if ( ![ 'Select Organization', 'Organization Details', 'Select Contact', 'Contact Details', ].includes(s.label) ) { _filteredSections.push(s) } }) return _filteredSections }) const dealStatuses = computed(() => { let statuses = statusOptions('deal') if (!deal.status) { deal.status = statuses[0].value } return statuses }) function createDeal() { if (deal.website && !deal.website.startsWith('http')) { deal.website = 'https://' + deal.website } createResource({ url: 'crm.fcrm.doctype.crm_deal.crm_deal.create_deal', params: { args: deal }, auto: true, validate() { error.value = null if (deal.annual_revenue) { deal.annual_revenue = deal.annual_revenue.replace(/,/g, '') if (isNaN(deal.annual_revenue)) { error.value = __('Annual Revenue should be a number') return error.value } } if (deal.mobile_no && isNaN(deal.mobile_no.replace(/[-+() ]/g, ''))) { error.value = __('Mobile No should be a number') return error.value } if (deal.email && !deal.email.includes('@')) { error.value = __('Invalid Email') return error.value } if (!deal.status) { error.value = __('Status is required') return error.value } isDealCreating.value = true }, onSuccess(name) { capture('deal_created') isDealCreating.value = false show.value = false router.push({ name: 'Deal', params: { dealId: name } }) }, onError(err) { isDealCreating.value = false if (!err.messages) { error.value = err.message return } error.value = err.messages.join('\n') }, }) } const showQuickEntryModal = defineModel('quickEntry') function openQuickEntryModal() { showQuickEntryModal.value = true nextTick(() => { show.value = false }) } onMounted(() => { Object.assign(deal, props.defaults) if (!deal.deal_owner) { deal.deal_owner = getUser().name } if (!deal.status && dealStatuses.value[0].value) { deal.status = dealStatuses.value[0].value } }) </script>
2302_79757062/crm
frontend/src/components/Modals/DealModal.vue
Vue
agpl-3.0
6,513
<template> <Dialog v-model="show" :options="{ title: __('Bulk Edit') }"> <template #body-content> <div class="mb-4"> <div class="mb-1.5 text-sm text-gray-600">{{ __('Field') }}</div> <Autocomplete :value="field.label" :options="fields.data" @change="(e) => changeField(e)" :placeholder="__('Source')" /> </div> <div> <div class="mb-1.5 text-sm text-gray-600">{{ __('Value') }}</div> <component :is="getValueComponent(field)" :value="newValue" size="md" @change="(v) => updateValue(v)" :placeholder="__('Contact Us')" /> </div> </template> <template #actions> <Button class="w-full" variant="solid" @click="updateValues" :loading="loading" :label="__('Update {0} Records', [recordCount])" /> </template> </Dialog> </template> <script setup> import Link from '@/components/Controls/Link.vue' import Autocomplete from '@/components/frappe-ui/Autocomplete.vue' import { capture } from '@/telemetry' import { FormControl, call, createResource, TextEditor, DatePicker } from 'frappe-ui' import { ref, computed, onMounted, h } from 'vue' const typeCheck = ['Check'] const typeLink = ['Link', 'Dynamic Link'] const typeNumber = ['Float', 'Int', 'Currency', 'Percent'] const typeSelect = ['Select'] const typeEditor = ['Text Editor'] const typeDate = ['Date', 'Datetime'] const props = defineProps({ doctype: { type: String, required: true, }, selectedValues: { type: Set, required: true, }, }) const show = defineModel() const emit = defineEmits(['reload']) const fields = createResource({ url: 'crm.api.doc.get_fields', cache: ['fields', props.doctype], params: { doctype: props.doctype, }, transform: (data) => { return data.filter((f) => f.hidden == 0 && f.read_only == 0) } }) onMounted(() => { if (fields.data?.length) return fields.fetch() }) const recordCount = computed(() => props.selectedValues?.size || 0) const field = ref({ label: '', type: '', value: '', options: '', }) const newValue = ref('') const loading = ref(false) function updateValues() { let fieldVal = newValue.value if (field.value.type == 'Check') { fieldVal = fieldVal == 'Yes' ? 1 : 0 } loading.value = true call( 'frappe.desk.doctype.bulk_update.bulk_update.submit_cancel_or_update_docs', { doctype: props.doctype, docnames: Array.from(props.selectedValues), action: 'update', data: { [field.value.value]: fieldVal || null, }, } ).then(() => { field.value = { label: '', type: '', value: '', options: '', } newValue.value = '' loading.value = false show.value = false capture('bulk_update', { doctype: props.doctype }) emit('reload') }) } function changeField(f) { newValue.value = '' if (!f) return field.value = f } function updateValue(v) { let value = v.target ? v.target.value : v newValue.value = value } function getSelectOptions(options) { return options.split('\n') } function getValueComponent(f) { const { type, options } = f if (typeSelect.includes(type) || typeCheck.includes(type)) { const _options = type == 'Check' ? ['Yes', 'No'] : getSelectOptions(options) return h(FormControl, { type: 'select', options: _options.map((o) => ({ label: o, value: o, })), modelValue: newValue.value, }) } else if (typeLink.includes(type)) { if (type == 'Dynamic Link') { return h(FormControl, { type: 'text' }) } return h(Link, { class: 'form-control', doctype: options }) } else if (typeNumber.includes(type)) { return h(FormControl, { type: 'number' }) } else if (typeDate.includes(type)) { return h(DatePicker) } else if (typeEditor.includes(type)) { return h(TextEditor, { variant: 'outline', editorClass: '!prose-sm overflow-auto min-h-[80px] max-h-80 py-1.5 px-2 rounded border border-gray-300 bg-white hover:border-gray-400 hover:shadow-sm focus:bg-white focus:border-gray-500 focus:shadow-sm focus:ring-0 focus-visible:ring-2 focus-visible:ring-gray-400 text-gray-800 transition-colors', bubbleMenu: true, content: newValue.value, }) } else { return h(FormControl, { type: 'text' }) } } </script>
2302_79757062/crm
frontend/src/components/Modals/EditValueModal.vue
Vue
agpl-3.0
4,453
<template> <Dialog v-model="show" :options="{ title: editMode ? __(emailTemplate.name) : __('Create Email Template'), size: 'xl', actions: [ { label: editMode ? __('Update') : __('Create'), variant: 'solid', onClick: () => (editMode ? updateEmailTemplate() : callInsertDoc()), }, ], }" > <template #body-content> <div class="flex flex-col gap-4"> <div class="flex sm:flex-row flex-col gap-4"> <div class="flex-1"> <div class="mb-1.5 text-sm text-gray-600"> {{ __('Name') }} <span class="text-red-500">*</span> </div> <TextInput ref="nameRef" variant="outline" v-model="_emailTemplate.name" :placeholder="__('Payment Reminder')" /> </div> <div class="flex-1"> <div class="mb-1.5 text-sm text-gray-600">{{ __('Doctype') }}</div> <Select variant="outline" v-model="_emailTemplate.reference_doctype" :options="['CRM Deal', 'CRM Lead']" :placeholder="__('CRM Deal')" /> </div> </div> <div> <div class="mb-1.5 text-sm text-gray-600"> {{ __('Subject') }} <span class="text-red-500">*</span> </div> <TextInput ref="subjectRef" variant="outline" v-model="_emailTemplate.subject" :placeholder="__('Payment Reminder from Frappé - (#{{ name }})')" /> </div> <div> <div class="mb-1.5 text-sm text-gray-600"> {{ __('Content') }} <span class="text-red-500">*</span> </div> <FormControl v-if="_emailTemplate.use_html" type="textarea" variant="outline" ref="content" :rows="10" v-model="_emailTemplate.response_html" :placeholder=" __( '<p>Dear {{ lead_name }},</p>\n\n<p>This is a reminder for the payment of {{ grand_total }}.</p>\n\n<p>Thanks,</p>\n<p>Frappé</p>' ) " /> <TextEditor v-else variant="outline" ref="content" editor-class="!prose-sm overflow-auto min-h-[180px] max-h-80 py-1.5 px-2 rounded border border-gray-300 bg-white hover:border-gray-400 hover:shadow-sm focus:bg-white focus:border-gray-500 focus:shadow-sm focus:ring-0 focus-visible:ring-2 focus-visible:ring-gray-400 text-gray-800 transition-colors" :bubbleMenu="true" :content="_emailTemplate.response" @change="(val) => (_emailTemplate.response = val)" :placeholder=" __( 'Dear {{ lead_name }}, \n\nThis is a reminder for the payment of {{ grand_total }}. \n\nThanks, \nFrappé' ) " /> </div> <div> <Checkbox v-model="_emailTemplate.enabled" :label="__('Enabled')" /> </div> <div> <Checkbox v-model="_emailTemplate.use_html" :label="__('Use HTML')" /> </div> <ErrorMessage :message="__(errorMessage)" /> </div> </template> </Dialog> </template> <script setup> import { capture } from '@/telemetry' import { Checkbox, Select, TextEditor, call } from 'frappe-ui' import { ref, nextTick, watch } from 'vue' const props = defineProps({ emailTemplate: { type: Object, default: {}, }, }) const show = defineModel() const emailTemplates = defineModel('reloadEmailTemplates') const errorMessage = ref('') const emit = defineEmits(['after']) const subjectRef = ref(null) const nameRef = ref(null) const editMode = ref(false) let _emailTemplate = ref({}) async function updateEmailTemplate() { if (!validate()) return const old = { ...props.emailTemplate } const newEmailTemplate = { ..._emailTemplate.value } const nameChanged = old.name !== newEmailTemplate.name delete old.name delete newEmailTemplate.name const otherFieldChanged = JSON.stringify(old) !== JSON.stringify(newEmailTemplate) const values = newEmailTemplate if (!nameChanged && !otherFieldChanged) { show.value = false return } let name if (nameChanged) { name = await callRenameDoc() } if (otherFieldChanged) { name = await callSetValue(values) } handleEmailTemplateUpdate({ name }) } async function callRenameDoc() { const d = await call('frappe.client.rename_doc', { doctype: 'Email Template', old_name: props.emailTemplate.name, new_name: _emailTemplate.value.name, }) return d } async function callSetValue(values) { const d = await call('frappe.client.set_value', { doctype: 'Email Template', name: _emailTemplate.value.name, fieldname: values, }) return d.name } async function callInsertDoc() { if (!validate()) return const doc = await call('frappe.client.insert', { doc: { doctype: 'Email Template', ..._emailTemplate.value, }, }) if (doc.name) { capture('email_template_created', { doctype: doc.reference_doctype }) handleEmailTemplateUpdate(doc) } } function handleEmailTemplateUpdate(doc) { emailTemplates.value?.reload() show.value = false } function validate() { if (!_emailTemplate.value.name) { errorMessage.value = 'Name is required' return false } if (!_emailTemplate.value.subject) { errorMessage.value = 'Subject is required' return false } if ( !_emailTemplate.value.response || _emailTemplate.value.response === '<p></p>' ) { errorMessage.value = 'Content is required' return false } return true } watch( () => show.value, (value) => { if (!value) return editMode.value = false errorMessage.value = '' nextTick(() => { if (_emailTemplate.value.name) { subjectRef.value.el.focus() } else { nameRef.value.el.focus() } _emailTemplate.value = { ...props.emailTemplate } if (_emailTemplate.value.name) { editMode.value = true } }) } ) </script>
2302_79757062/crm
frontend/src/components/Modals/EmailTemplateModal.vue
Vue
agpl-3.0
6,241
<template> <Dialog v-model="show" :options="{ title: __('Email Templates'), size: '4xl' }" > <template #body-content> <TextInput ref="searchInput" v-model="search" type="text" :placeholder="__('Payment Reminder')" > <template #prefix> <FeatherIcon name="search" class="h-4 w-4 text-gray-500" /> </template> </TextInput> <div v-if="filteredTemplates.length" class="mt-2 grid max-h-[560px] sm:grid-cols-3 gris-cols-1 gap-2 overflow-y-auto" > <div v-for="template in filteredTemplates" :key="template.name" class="flex h-56 cursor-pointer flex-col gap-2 rounded-lg border p-3 hover:bg-gray-100" @click="emit('apply', template)" > <div class="border-b pb-2 text-base font-semibold"> {{ template.name }} </div> <div v-if="template.subject" class="text-sm text-gray-600"> {{ __('Subject: {0}', [template.subject]) }} </div> <TextEditor v-if="template.use_html && template.response_html" :content="template.response_html" :editable="false" editor-class="!prose-sm max-w-none !text-sm text-gray-600 focus:outline-none" class="flex-1 overflow-hidden" /> <TextEditor v-else-if="template.response" :content="template.response" :editable="false" editor-class="!prose-sm max-w-none !text-sm text-gray-600 focus:outline-none" class="flex-1 overflow-hidden" /> </div> </div> <div v-else class="mt-2"> <div class="flex h-56 flex-col items-center justify-center"> <div class="text-lg text-gray-500"> {{ __('No templates found') }} </div> <Button :label="__('Create New')" class="mt-4" @click=" () => { show = false emailTemplate = { reference_doctype: props.doctype, enabled: 1, } showEmailTemplateModal = true } " /> </div> </div> </template> </Dialog> <EmailTemplateModal v-model="showEmailTemplateModal" :emailTemplate="emailTemplate" /> </template> <script setup> import EmailTemplateModal from '@/components/Modals/EmailTemplateModal.vue' import { TextEditor, createListResource } from 'frappe-ui' import { ref, computed, nextTick, watch, onMounted } from 'vue' const props = defineProps({ doctype: { type: String, default: '', }, }) const show = defineModel() const searchInput = ref('') const showEmailTemplateModal = ref(false) const emailTemplate = ref({}) const emit = defineEmits(['apply']) const search = ref('') const templates = createListResource({ type: 'list', doctype: 'Email Template', cache: ['emailTemplates', props.doctype], fields: [ 'name', 'enabled', 'use_html', 'reference_doctype', 'subject', 'response', 'response_html', 'modified', 'owner', ], filters: { enabled: 1, reference_doctype: props.doctype }, orderBy: 'modified desc', pageLength: 99999, }) onMounted(() => { if (templates.data == null) { templates.fetch() } }) const filteredTemplates = computed(() => { return ( templates.data?.filter((template) => { return ( template.name.toLowerCase().includes(search.value.toLowerCase()) || template.subject.toLowerCase().includes(search.value.toLowerCase()) ) }) ?? [] ) }) watch(show, (value) => value && nextTick(() => searchInput.value?.el?.focus())) </script>
2302_79757062/crm
frontend/src/components/Modals/EmailTemplateSelectorModal.vue
Vue
agpl-3.0
3,786
<template> <Dialog v-model="show" :options="{ size: '3xl' }"> <template #body> <div class="bg-white px-4 pb-6 pt-5 sm:px-6"> <div class="mb-5 flex items-center justify-between"> <div> <h3 class="text-2xl font-semibold leading-6 text-gray-900"> {{ __('Create Lead') }} </h3> </div> <div class="flex items-center gap-1"> <Button v-if="isManager()" variant="ghost" class="w-7" @click="openQuickEntryModal" > <EditIcon class="h-4 w-4" /> </Button> <Button variant="ghost" class="w-7" @click="show = false"> <FeatherIcon name="x" class="h-4 w-4" /> </Button> </div> </div> <div> <Fields v-if="sections.data" :sections="sections.data" :data="lead" /> <ErrorMessage class="mt-4" v-if="error" :message="__(error)" /> </div> </div> <div class="px-4 pb-7 pt-4 sm:px-6"> <div class="flex flex-row-reverse gap-2"> <Button variant="solid" :label="__('Create')" :loading="isLeadCreating" @click="createNewLead" /> </div> </div> </template> </Dialog> </template> <script setup> import EditIcon from '@/components/Icons/EditIcon.vue' import Fields from '@/components/Fields.vue' import { usersStore } from '@/stores/users' import { statusesStore } from '@/stores/statuses' import { capture } from '@/telemetry' import { createResource } from 'frappe-ui' import { computed, onMounted, ref, reactive, nextTick } from 'vue' import { useRouter } from 'vue-router' const props = defineProps({ defaults: Object, }) const { getUser, isManager } = usersStore() const { getLeadStatus, statusOptions } = statusesStore() const show = defineModel() const router = useRouter() const error = ref(null) const isLeadCreating = ref(false) const sections = createResource({ url: 'crm.fcrm.doctype.crm_fields_layout.crm_fields_layout.get_fields_layout', cache: ['quickEntryFields', 'CRM Lead'], params: { doctype: 'CRM Lead', type: 'Quick Entry' }, auto: true, transform: (data) => { return data.forEach((section) => { section.fields.forEach((field) => { if (field.name == 'status') { field.type = 'Select' field.options = leadStatuses.value field.prefix = getLeadStatus(lead.status).iconColorClass } else if (field.name == 'lead_owner') { field.type = 'User' } }) }) }, }) const lead = reactive({ salutation: '', first_name: '', last_name: '', email: '', mobile_no: '', gender: '', organization: '', website: '', no_of_employees: '', territory: '', annual_revenue: '', industry: '', status: '', lead_owner: '', }) const createLead = createResource({ url: 'frappe.client.insert', makeParams(values) { return { doc: { doctype: 'CRM Lead', ...values, }, } }, }) const leadStatuses = computed(() => { let statuses = statusOptions('lead') if (!lead.status) { lead.status = statuses[0].value } return statuses }) function createNewLead() { if (lead.website && !lead.website.startsWith('http')) { lead.website = 'https://' + lead.website } createLead.submit(lead, { validate() { error.value = null if (!lead.first_name) { error.value = __('First Name is mandatory') return error.value } if (lead.annual_revenue) { lead.annual_revenue = lead.annual_revenue.replace(/,/g, '') if (isNaN(lead.annual_revenue)) { error.value = __('Annual Revenue should be a number') return error.value } } if (lead.mobile_no && isNaN(lead.mobile_no.replace(/[-+() ]/g, ''))) { error.value = __('Mobile No should be a number') return error.value } if (lead.email && !lead.email.includes('@')) { error.value = __('Invalid Email') return error.value } if (!lead.status) { error.value = __('Status is required') return error.value } isLeadCreating.value = true }, onSuccess(data) { capture('lead_created') isLeadCreating.value = false show.value = false router.push({ name: 'Lead', params: { leadId: data.name } }) }, onError(err) { isLeadCreating.value = false if (!err.messages) { error.value = err.message return } error.value = err.messages.join('\n') }, }) } const showQuickEntryModal = defineModel('quickEntry') function openQuickEntryModal() { showQuickEntryModal.value = true nextTick(() => { show.value = false }) } onMounted(() => { Object.assign(lead, props.defaults) if (!lead.lead_owner) { lead.lead_owner = getUser().name } if (!lead.status && leadStatuses.value[0].value) { lead.status = leadStatuses.value[0].value } }) </script>
2302_79757062/crm
frontend/src/components/Modals/LeadModal.vue
Vue
agpl-3.0
5,075
<template> <Dialog v-model="show" :options="{ size: 'xl', actions: [ { label: editMode ? __('Update') : __('Create'), variant: 'solid', onClick: () => updateNote(), }, ], }" > <template #body-title> <div class="flex items-center gap-3"> <h3 class="text-2xl font-semibold leading-6 text-gray-900"> {{ editMode ? __('Edit Note') : __('Create Note') }} </h3> <Button v-if="_note?.reference_docname" variant="outline" size="sm" :label=" _note.reference_doctype == 'CRM Deal' ? __('Open Deal') : __('Open Lead') " @click="redirect()" > <template #suffix> <ArrowUpRightIcon class="h-4 w-4" /> </template> </Button> </div> </template> <template #body-content> <div class="flex flex-col gap-4"> <div> <div class="mb-1.5 text-sm text-gray-600">{{ __('Title') }}</div> <TextInput ref="title" variant="outline" v-model="_note.title" :placeholder="__('Call with John Doe')" /> </div> <div> <div class="mb-1.5 text-sm text-gray-600">{{ __('Content') }}</div> <TextEditor variant="outline" ref="content" editor-class="!prose-sm overflow-auto min-h-[180px] max-h-80 py-1.5 px-2 rounded border border-gray-300 bg-white hover:border-gray-400 hover:shadow-sm focus:bg-white focus:border-gray-500 focus:shadow-sm focus:ring-0 focus-visible:ring-2 focus-visible:ring-gray-400 text-gray-800 transition-colors" :bubbleMenu="true" :content="_note.content" @change="(val) => (_note.content = val)" :placeholder=" __('Took a call with John Doe and discussed the new project.') " /> </div> </div> </template> </Dialog> </template> <script setup> import ArrowUpRightIcon from '@/components/Icons/ArrowUpRightIcon.vue' import { capture } from '@/telemetry' import { TextEditor, call } from 'frappe-ui' import { ref, nextTick, watch } from 'vue' import { useRouter } from 'vue-router' const props = defineProps({ note: { type: Object, default: {}, }, doctype: { type: String, default: 'CRM Lead', }, doc: { type: String, default: '', }, }) const show = defineModel() const notes = defineModel('reloadNotes') const emit = defineEmits(['after']) const router = useRouter() const title = ref(null) const editMode = ref(false) let _note = ref({}) async function updateNote() { if ( props.note.title === _note.value.title && props.note.content === _note.value.content ) return if (_note.value.name) { let d = await call('frappe.client.set_value', { doctype: 'FCRM Note', name: _note.value.name, fieldname: _note.value, }) if (d.name) { notes.value?.reload() emit('after', d) } } else { let d = await call('frappe.client.insert', { doc: { doctype: 'FCRM Note', title: _note.value.title, content: _note.value.content, reference_doctype: props.doctype, reference_docname: props.doc || '', }, }) if (d.name) { capture('note_created') notes.value?.reload() emit('after', d, true) } } show.value = false } function redirect() { if (!props.note?.reference_docname) return let name = props.note.reference_doctype == 'CRM Deal' ? 'Deal' : 'Lead' let params = { leadId: props.note.reference_docname } if (name == 'Deal') { params = { dealId: props.note.reference_docname } } router.push({ name: name, params: params }) } watch( () => show.value, (value) => { if (!value) return editMode.value = false nextTick(() => { title.value.el.focus() _note.value = { ...props.note } if (_note.value.title || _note.value.content) { editMode.value = true } }) } ) </script>
2302_79757062/crm
frontend/src/components/Modals/NoteModal.vue
Vue
agpl-3.0
4,144
<template> <Dialog v-model="show" :options="dialogOptions"> <template #body> <div class="bg-white px-4 pb-6 pt-5 sm:px-6"> <div class="mb-5 flex items-center justify-between"> <div> <h3 class="text-2xl font-semibold leading-6 text-gray-900"> {{ __(dialogOptions.title) || __('Untitled') }} </h3> </div> <div class="flex items-center gap-1"> <Button v-if="isManager() || detailMode" variant="ghost" class="w-7" @click="detailMode ? (detailMode = false) : openQuickEntryModal()" > <EditIcon class="h-4 w-4" /> </Button> <Button variant="ghost" class="w-7" @click="show = false"> <FeatherIcon name="x" class="h-4 w-4" /> </Button> </div> </div> <div> <div v-if="detailMode" class="flex flex-col gap-3.5"> <div class="flex h-7 items-center gap-2 text-base text-gray-800" v-for="field in fields" :key="field.name" > <div class="grid w-7 place-content-center"> <component :is="field.icon" /> </div> <div>{{ field.value }}</div> </div> </div> <Fields v-else-if="filteredSections" :sections="filteredSections" :data="_organization" /> </div> </div> <div v-if="!detailMode" class="px-4 pb-7 pt-4 sm:px-6"> <div class="space-y-2"> <Button class="w-full" v-for="action in dialogOptions.actions" :key="action.label" v-bind="action" :label="__(action.label)" :loading="loading" /> </div> </div> </template> </Dialog> <AddressModal v-model="showAddressModal" v-model:address="_address" /> </template> <script setup> import Fields from '@/components/Fields.vue' import AddressModal from '@/components/Modals/AddressModal.vue' import EditIcon from '@/components/Icons/EditIcon.vue' import MoneyIcon from '@/components/Icons/MoneyIcon.vue' import WebsiteIcon from '@/components/Icons/WebsiteIcon.vue' import OrganizationsIcon from '@/components/Icons/OrganizationsIcon.vue' import TerritoryIcon from '@/components/Icons/TerritoryIcon.vue' import { usersStore } from '@/stores/users' import { formatNumberIntoCurrency } from '@/utils' import { capture } from '@/telemetry' import { call, FeatherIcon, createResource } from 'frappe-ui' import { ref, nextTick, watch, computed, h } from 'vue' import { useRouter } from 'vue-router' const props = defineProps({ options: { type: Object, default: { redirect: true, detailMode: false, afterInsert: () => {}, }, }, }) const { isManager } = usersStore() const router = useRouter() const show = defineModel() const organization = defineModel('organization') const loading = ref(false) const title = ref(null) const detailMode = ref(false) const editMode = ref(false) let _address = ref({}) let _organization = ref({ organization_name: '', website: '', annual_revenue: '', no_of_employees: '1-10', industry: '', }) const showAddressModal = ref(false) let doc = ref({}) async function updateOrganization() { const old = { ...doc.value } const newOrg = { ..._organization.value } const nameChanged = old.organization_name !== newOrg.organization_name delete old.organization_name delete newOrg.organization_name const otherFieldChanged = JSON.stringify(old) !== JSON.stringify(newOrg) const values = newOrg if (!nameChanged && !otherFieldChanged) { show.value = false return } let name loading.value = true if (nameChanged) { name = await callRenameDoc() } if (otherFieldChanged) { name = await callSetValue(values) } handleOrganizationUpdate({ name }, nameChanged) } async function callRenameDoc() { const d = await call('frappe.client.rename_doc', { doctype: 'CRM Organization', old_name: doc.value?.organization_name, new_name: _organization.value.organization_name, }) loading.value = false return d } async function callSetValue(values) { const d = await call('frappe.client.set_value', { doctype: 'CRM Organization', name: _organization.value.name, fieldname: values, }) loading.value = false return d.name } async function callInsertDoc() { const doc = await call('frappe.client.insert', { doc: { doctype: 'CRM Organization', ..._organization.value, }, }) loading.value = false if (doc.name) { capture('organization_created') handleOrganizationUpdate(doc) } } function handleOrganizationUpdate(doc, renamed = false) { if (doc.name && (props.options.redirect || renamed)) { router.push({ name: 'Organization', params: { organizationId: doc.name }, }) } else { organization.value.reload?.() } show.value = false props.options.afterInsert && props.options.afterInsert(doc) } const dialogOptions = computed(() => { let title = !editMode.value ? __('New Organization') : __(_organization.value.organization_name) let size = detailMode.value ? '' : 'xl' let actions = detailMode.value ? [] : [ { label: editMode.value ? __('Save') : __('Create'), variant: 'solid', onClick: () => editMode.value ? updateOrganization() : callInsertDoc(), }, ] return { title, size, actions } }) const fields = computed(() => { let details = [ { icon: OrganizationsIcon, name: 'organization_name', value: _organization.value.organization_name, }, { icon: WebsiteIcon, name: 'website', value: _organization.value.website, }, { icon: TerritoryIcon, name: 'territory', value: _organization.value.territory, }, { icon: MoneyIcon, name: 'annual_revenue', value: formatNumberIntoCurrency( _organization.value.annual_revenue, _organization.value.currency, ), }, { icon: h(FeatherIcon, { name: 'hash', class: 'h-4 w-4' }), name: 'no_of_employees', value: _organization.value.no_of_employees, }, { icon: h(FeatherIcon, { name: 'briefcase', class: 'h-4 w-4' }), name: 'industry', value: _organization.value.industry, }, ] return details.filter((field) => field.value) }) const sections = createResource({ url: 'crm.fcrm.doctype.crm_fields_layout.crm_fields_layout.get_fields_layout', cache: ['quickEntryFields', 'CRM Organization'], params: { doctype: 'CRM Organization', type: 'Quick Entry' }, auto: true, }) const filteredSections = computed(() => { let allSections = sections.data || [] if (!allSections.length) return [] allSections.forEach((s) => { s.fields.forEach((field) => { if (field.name == 'address') { field.create = (value, close) => { _organization.value.address = value _address.value = {} showAddressModal.value = true close() } field.edit = async (addr) => { _address.value = await call('frappe.client.get', { doctype: 'Address', name: addr, }) showAddressModal.value = true } } }) }) return allSections }) watch( () => show.value, (value) => { if (!value) return editMode.value = false detailMode.value = props.options.detailMode nextTick(() => { // TODO: Issue with FormControl // title.value.el.focus() doc.value = organization.value?.doc || organization.value || {} _organization.value = { ...doc.value } if (_organization.value.name) { editMode.value = true } }) }, ) const showQuickEntryModal = defineModel('quickEntry') function openQuickEntryModal() { showQuickEntryModal.value = true nextTick(() => { show.value = false }) } </script>
2302_79757062/crm
frontend/src/components/Modals/OrganizationModal.vue
Vue
agpl-3.0
8,113
<template> <Dialog v-model="show" :options="{ size: '3xl' }"> <template #body-title> <h3 class="flex items-center gap-2 text-2xl font-semibold leading-6 text-gray-900" > <div>{{ __('Edit Quick Entry Layout') }}</div> <Badge v-if="dirty" :label="__('Not Saved')" variant="subtle" theme="orange" /> </h3> </template> <template #body-content> <div class="flex flex-col gap-3"> <div class="flex justify-between gap-2"> <FormControl type="select" class="w-1/4" v-model="_doctype" :options="[ 'CRM Lead', 'CRM Deal', 'Contact', 'CRM Organization', 'Address', ]" @change="reload" /> <Switch v-model="preview" :label="preview ? __('Hide preview') : __('Show preview')" size="sm" /> </div> <div v-if="sections?.data"> <QuickEntryLayoutBuilder v-if="!preview" :sections="sections.data" :doctype="_doctype" /> <Fields v-else :sections="sections.data" :data="{}" /> </div> </div> </template> <template #actions> <div class="flex flex-row-reverse gap-2"> <Button :loading="loading" :label="__('Save')" variant="solid" @click="saveChanges" /> <Button :label="__('Reset')" @click="reload" /> </div> </template> </Dialog> </template> <script setup> import Fields from '@/components/Fields.vue' import QuickEntryLayoutBuilder from '@/components/QuickEntryLayoutBuilder.vue' import { useDebounceFn } from '@vueuse/core' import { capture } from '@/telemetry' import { Dialog, Badge, Switch, call, createResource } from 'frappe-ui' import { ref, watch, onMounted, nextTick } from 'vue' const props = defineProps({ doctype: { type: String, default: 'CRM Lead', }, }) const show = defineModel() const _doctype = ref(props.doctype) const loading = ref(false) const dirty = ref(false) const preview = ref(false) function getParams() { return { doctype: _doctype.value, type: 'Quick Entry' } } const sections = createResource({ url: 'crm.fcrm.doctype.crm_fields_layout.crm_fields_layout.get_fields_layout', cache: ['quick-entry-sections', _doctype.value], params: getParams(), onSuccess(data) { sections.originalData = JSON.parse(JSON.stringify(data)) }, }) watch( () => sections?.data, () => { dirty.value = JSON.stringify(sections?.data) !== JSON.stringify(sections?.originalData) }, { deep: true }, ) onMounted(() => useDebounceFn(reload, 100)()) function reload() { nextTick(() => { sections.params = getParams() sections.reload() }) } function saveChanges() { let _sections = JSON.parse(JSON.stringify(sections.data)) _sections.forEach((section) => { if (!section.fields) return section.fields = section.fields.map( (field) => field.fieldname || field.name, ) }) loading.value = true call( 'crm.fcrm.doctype.crm_fields_layout.crm_fields_layout.save_fields_layout', { doctype: _doctype.value, type: 'Quick Entry', layout: JSON.stringify(_sections), }, ).then(() => { loading.value = false show.value = false capture('quick_entry_layout_builder', { doctype: _doctype.value }) }) } </script>
2302_79757062/crm
frontend/src/components/Modals/QuickEntryModal.vue
Vue
agpl-3.0
3,531
<template> <Dialog v-model="show" :options="{ size: 'xl', actions: [ { label: editMode ? __('Update') : __('Create'), variant: 'solid', onClick: () => updateTask(), }, ], }" > <template #body-title> <div class="flex items-center gap-3"> <h3 class="text-2xl font-semibold leading-6 text-gray-900"> {{ editMode ? __('Edit Task') : __('Create Task') }} </h3> <Button v-if="task?.reference_docname" variant="outline" size="sm" :label=" task.reference_doctype == 'CRM Deal' ? __('Open Deal') : __('Open Lead') " @click="redirect()" > <template #suffix> <ArrowUpRightIcon class="h-4 w-4" /> </template> </Button> </div> </template> <template #body-content> <div class="flex flex-col gap-4"> <div> <div class="mb-1.5 text-sm text-gray-600">{{ __('Title') }}</div> <TextInput ref="title" variant="outline" v-model="_task.title" :placeholder="__('Call with John Doe')" /> </div> <div> <div class="mb-1.5 text-sm text-gray-600"> {{ __('Description') }} </div> <TextEditor variant="outline" ref="description" editor-class="!prose-sm overflow-auto min-h-[80px] max-h-80 py-1.5 px-2 rounded border border-gray-300 bg-white hover:border-gray-400 hover:shadow-sm focus:bg-white focus:border-gray-500 focus:shadow-sm focus:ring-0 focus-visible:ring-2 focus-visible:ring-gray-400 text-gray-800 transition-colors" :bubbleMenu="true" :content="_task.description" @change="(val) => (_task.description = val)" :placeholder=" __('Took a call with John Doe and discussed the new project.') " /> </div> <div class="flex flex-wrap items-center gap-2"> <Dropdown :options="taskStatusOptions(updateTaskStatus)"> <Button :label="_task.status" class="w-full justify-between"> <template #prefix> <TaskStatusIcon :status="_task.status" /> </template> </Button> </Dropdown> <Link class="form-control" :value="getUser(_task.assigned_to).full_name" doctype="User" @change="(option) => (_task.assigned_to = option)" :placeholder="__('John Doe')" :hideMe="true" > <template #prefix> <UserAvatar class="mr-2 !h-4 !w-4" :user="_task.assigned_to" /> </template> <template #item-prefix="{ option }"> <UserAvatar class="mr-2" :user="option.value" size="sm" /> </template> <template #item-label="{ option }"> <Tooltip :text="option.value"> <div class="cursor-pointer"> {{ getUser(option.value).full_name }} </div> </Tooltip> </template> </Link> <DateTimePicker class="datepicker w-36" v-model="_task.due_date" :placeholder="__('01/04/2024 11:30 PM')" input-class="border-none" /> <Dropdown :options="taskPriorityOptions(updateTaskPriority)"> <Button :label="_task.priority" class="w-full justify-between"> <template #prefix> <TaskPriorityIcon :priority="_task.priority" /> </template> </Button> </Dropdown> </div> </div> </template> </Dialog> </template> <script setup> import TaskStatusIcon from '@/components/Icons/TaskStatusIcon.vue' import TaskPriorityIcon from '@/components/Icons/TaskPriorityIcon.vue' import ArrowUpRightIcon from '@/components/Icons/ArrowUpRightIcon.vue' import UserAvatar from '@/components/UserAvatar.vue' import Link from '@/components/Controls/Link.vue' import { taskStatusOptions, taskPriorityOptions } from '@/utils' import { usersStore } from '@/stores/users' import { capture } from '@/telemetry' import { TextEditor, Dropdown, Tooltip, call, DateTimePicker } from 'frappe-ui' import { ref, watch, nextTick, onMounted } from 'vue' import { useRouter } from 'vue-router' const props = defineProps({ task: { type: Object, default: {}, }, doctype: { type: String, default: 'CRM Lead', }, doc: { type: String, default: '', }, }) const show = defineModel() const tasks = defineModel('reloadTasks') const emit = defineEmits(['updateTask']) const router = useRouter() const { getUser } = usersStore() const title = ref(null) const editMode = ref(false) const _task = ref({ title: '', description: '', assigned_to: '', due_date: '', status: 'Backlog', priority: 'Low', reference_doctype: props.doctype, reference_docname: null, }) function updateTaskStatus(status) { _task.value.status = status } function updateTaskPriority(priority) { _task.value.priority = priority } function redirect() { if (!props.task?.reference_docname) return let name = props.task.reference_doctype == 'CRM Deal' ? 'Deal' : 'Lead' let params = { leadId: props.task.reference_docname } if (name == 'Deal') { params = { dealId: props.task.reference_docname } } router.push({ name: name, params: params }) } async function updateTask() { if (!_task.value.assigned_to) { _task.value.assigned_to = getUser().name } if (_task.value.name) { let d = await call('frappe.client.set_value', { doctype: 'CRM Task', name: _task.value.name, fieldname: _task.value, }) if (d.name) { tasks.value.reload() } } else { let d = await call('frappe.client.insert', { doc: { doctype: 'CRM Task', reference_doctype: props.doctype, reference_docname: props.doc || null, ..._task.value, }, }) if (d.name) { capture('task_created') tasks.value.reload() } } show.value = false } function render() { editMode.value = false nextTick(() => { title.value?.el?.focus?.() _task.value = { ...props.task } if (_task.value.title) { editMode.value = true } }) } onMounted(() => show.value && render()) watch(show, (value) => { if (!value) return render() }) </script> <style scoped> :deep(.datepicker svg) { width: 0.875rem; height: 0.875rem; } </style>
2302_79757062/crm
frontend/src/components/Modals/TaskModal.vue
Vue
agpl-3.0
6,641
<template> <Dialog v-model="show" :options="{ title: editMode ? __('Edit View') : duplicateMode ? __('Duplicate View') : __('Create View'), actions: [ { label: editMode ? __('Save Changes') : duplicateMode ? __('Duplicate') : __('Create'), variant: 'solid', onClick: () => (editMode ? update() : create()), }, ], }" > <template #body-content> <div class="mb-1.5 block text-base text-gray-600"> {{ __('View Name') }} </div> <div class="flex gap-2"> <IconPicker v-model="view.icon" v-slot="{ togglePopover }"> <Button variant="outline" size="md" class="flex size-8 text-2xl leading-none" :label="view.icon" @click="togglePopover" /> </IconPicker> <TextInput class="flex-1" variant="outline" size="md" type="text" :placeholder="__('My Open Deals')" v-model="view.label" /> </div> </template> </Dialog> </template> <script setup> import IconPicker from '@/components/IconPicker.vue' import { call, TextInput } from 'frappe-ui' import { ref, watch, nextTick } from 'vue' const props = defineProps({ doctype: { type: String, required: true, }, options: { type: Object, default: { afterCreate: () => {}, afterUpdate: () => {}, }, }, }) const show = defineModel() const view = defineModel('view') const editMode = ref(false) const duplicateMode = ref(false) const _view = ref({ name: '', label: '', type: 'list', icon: '', filters: {}, order_by: 'modified desc', columns: '', rows: '', }) async function create() { view.value.doctype = props.doctype let v = await call( 'crm.fcrm.doctype.crm_view_settings.crm_view_settings.create', { view: view.value } ) show.value = false props.options.afterCreate?.(v) } async function update() { view.value.doctype = props.doctype await call('crm.fcrm.doctype.crm_view_settings.crm_view_settings.update', { view: view.value, }) show.value = false props.options.afterUpdate?.(view.value) } watch(show, (value) => { if (!value) return editMode.value = false duplicateMode.value = false nextTick(() => { _view.value = { ...view.value } if (_view.value.mode === 'edit') { editMode.value = true } else if (_view.value.mode === 'duplicate') { duplicateMode.value = true } }) }) </script>
2302_79757062/crm
frontend/src/components/Modals/ViewModal.vue
Vue
agpl-3.0
2,620
<template> <Dialog v-model="show" :options="{ title: __('WhatsApp Templates'), size: '4xl' }" > <template #body-content> <TextInput ref="searchInput" v-model="search" type="text" :placeholder="__('Welcome Message')" > <template #prefix> <FeatherIcon name="search" class="h-4 w-4 text-gray-500" /> </template> </TextInput> <div v-if="filteredTemplates.length" class="mt-2 grid max-h-[560px] grid-cols-1 gap-2 overflow-y-auto sm:grid-cols-3" > <div v-for="template in filteredTemplates" :key="template.name" class="flex h-56 cursor-pointer flex-col gap-2 rounded-lg border p-3 hover:bg-gray-100" @click="emit('send', template.name)" > <div class="border-b pb-2 text-base font-semibold"> {{ template.name }} </div> <TextEditor v-if="template.template" :content="template.template" :editable="false" editor-class="!prose-sm max-w-none !text-sm text-gray-600 focus:outline-none" class="flex-1 overflow-hidden" /> </div> </div> <div v-else class="mt-2"> <div class="flex h-56 flex-col items-center justify-center"> <div class="text-lg text-gray-500"> {{ __('No templates found') }} </div> <Button :label="__('Create New')" class="mt-4" @click="newWhatsappTemplate" /> </div> </div> </template> </Dialog> </template> <script setup> import { TextEditor, createListResource } from 'frappe-ui' import { ref, computed, nextTick, watch, onMounted } from 'vue' const props = defineProps({ doctype: String, }) const show = defineModel() const searchInput = ref('') const emit = defineEmits(['send']) const search = ref('') const templates = createListResource({ type: 'list', doctype: 'WhatsApp Templates', cache: ['whatsappTemplates'], fields: ['name', 'template', 'footer'], filters: { status: 'APPROVED', for_doctype: ['in', [props.doctype, '']] }, orderBy: 'modified desc', pageLength: 99999, }) onMounted(() => { if (templates.data == null) { templates.fetch() } }) const filteredTemplates = computed(() => { return ( templates.data?.filter((template) => { return template.name.toLowerCase().includes(search.value.toLowerCase()) }) ?? [] ) }) function newWhatsappTemplate() { show.value = false window.open('/app/whatsapp-templates/new') } watch(show, (value) => value && nextTick(() => searchInput.value?.el?.focus())) </script>
2302_79757062/crm
frontend/src/components/Modals/WhatsappTemplateSelectorModal.vue
Vue
agpl-3.0
2,701
<template> <div v-if="avatars?.length" class="mr-1.5 flex cursor-pointer items-center" :class="[ avatars?.length > 1 ? 'flex-row-reverse' : 'truncate [&>div]:truncate', ]" > <Tooltip v-if="avatars?.length == 1" :text="avatars[0].name"> <div class="flex items-center gap-2 text-base"> <Avatar shape="circle" :image="avatars[0].image" :label="avatars[0].label" :size="size" /> <div class="truncate">{{ avatars[0].label }}</div> </div> </Tooltip> <Tooltip v-else :text="avatar.name" v-for="avatar in reverseAvatars" :key="avatar.name" > <Avatar class="user-avatar -mr-1.5 transform ring-2 ring-white transition hover:z-10 hover:scale-110" shape="circle" :image="avatar.image" :label="avatar.label" :size="size" :data-name="avatar.name" /> </Tooltip> </div> </template> <script setup> import { Avatar, Tooltip } from 'frappe-ui' import { computed } from 'vue' const props = defineProps({ avatars: { type: Array, default: [], }, size: { type: String, default: 'md', }, }) const reverseAvatars = computed(() => props.avatars.reverse()) </script>
2302_79757062/crm
frontend/src/components/MultipleAvatar.vue
Vue
agpl-3.0
1,273
<template> <Popover v-slot="{ open }"> <PopoverButton as="div" ref="reference" @click="updatePosition" @focusin="updatePosition" @keydown="updatePosition" v-slot="{ open }" > <slot name="target" v-bind="{ open }" /> </PopoverButton> <div v-show="open"> <PopoverPanel v-slot="{ open, close }" ref="popover" static class="z-[100]" > <slot name="body" v-bind="{ open, close }" /> </PopoverPanel> </div> </Popover> </template> <script setup> import { Popover, PopoverButton, PopoverPanel } from '@headlessui/vue' import { createPopper } from '@popperjs/core' import { nextTick, ref, onBeforeUnmount } from 'vue' const props = defineProps({ placement: { type: String, default: 'bottom-start', }, }) const reference = ref(null) const popover = ref(null) let popper = ref(null) function setupPopper() { if (!popper.value) { popper.value = createPopper(reference.value.el, popover.value.el, { placement: props.placement, }) } else { popper.value.update() } } function updatePosition() { nextTick(() => setupPopper()) } onBeforeUnmount(() => { popper.value?.destroy() }) </script>
2302_79757062/crm
frontend/src/components/NestedPopover.vue
Vue
agpl-3.0
1,243
<template> <div v-if="notificationsStore().visible" ref="target" class="absolute z-20 h-screen bg-white transition-all duration-300 ease-in-out" :style="{ 'box-shadow': '8px 0px 8px rgba(0, 0, 0, 0.1)', 'max-width': '350px', 'min-width': '350px', left: 'calc(100% + 1px)', }" > <div class="flex h-screen flex-col"> <div class="z-20 flex items-center justify-between border-b bg-white px-5 py-2.5" > <div class="text-base font-medium">{{ __('Notifications') }}</div> <div class="flex gap-1"> <Tooltip :text="__('Mark all as read')"> <div> <Button variant="ghost" @click="() => markAllAsRead()"> <template #icon> <MarkAsDoneIcon class="h-4 w-4" /> </template> </Button> </div> </Tooltip> <Tooltip :text="__('Close')"> <div> <Button variant="ghost" @click="() => toggleNotificationPanel()"> <template #icon> <FeatherIcon name="x" class="h-4 w-4" /> </template> </Button> </div> </Tooltip> </div> </div> <div v-if="notificationsStore().allNotifications?.length" class="divide-y overflow-auto text-base" > <RouterLink v-for="n in notificationsStore().allNotifications" :key="n.comment" :to="getRoute(n)" class="flex cursor-pointer items-start gap-2.5 px-4 py-2.5 hover:bg-gray-100" @click="markAsRead(n.comment || n.notification_type_doc)" > <div class="mt-1 flex items-center gap-2.5"> <div class="size-[5px] rounded-full" :class="[n.read ? 'bg-transparent' : 'bg-gray-900']" /> <WhatsAppIcon v-if="n.type == 'WhatsApp'" class="size-7" /> <UserAvatar v-else :user="n.from_user.name" size="lg" /> </div> <div> <div v-if="n.notification_text" v-html="n.notification_text" /> <div v-else class="mb-2 space-x-1 leading-5 text-gray-600"> <span class="font-medium text-gray-900"> {{ n.from_user.full_name }} </span> <span> {{ __('mentioned you in {0}', [n.reference_doctype]) }} </span> <span class="font-medium text-gray-900"> {{ n.reference_name }} </span> </div> <div class="text-sm text-gray-600"> {{ __(timeAgo(n.creation)) }} </div> </div> </RouterLink> </div> <div v-else class="flex flex-1 flex-col items-center justify-center gap-2" > <NotificationsIcon class="h-20 w-20 text-gray-300" /> <div class="text-lg font-medium text-gray-500"> {{ __('No new notifications') }} </div> </div> </div> </div> </template> <script setup> import WhatsAppIcon from '@/components/Icons/WhatsAppIcon.vue' import MarkAsDoneIcon from '@/components/Icons/MarkAsDoneIcon.vue' import NotificationsIcon from '@/components/Icons/NotificationsIcon.vue' import UserAvatar from '@/components/UserAvatar.vue' import { notificationsStore } from '@/stores/notifications' import { globalStore } from '@/stores/global' import { timeAgo } from '@/utils' import { onClickOutside } from '@vueuse/core' import { capture } from '@/telemetry' import { Tooltip } from 'frappe-ui' import { ref, onMounted, onBeforeUnmount } from 'vue' const { $socket } = globalStore() const target = ref(null) onClickOutside( target, () => { if (notificationsStore().visible) { toggleNotificationPanel() } }, { ignore: ['#notifications-btn'], }, ) function toggleNotificationPanel() { notificationsStore().toggle() } function markAsRead(doc) { capture('notification_mark_as_read') notificationsStore().mark_doc_as_read(doc) } function markAllAsRead() { capture('notification_mark_all_as_read') notificationsStore().mark_as_read.reload() } onBeforeUnmount(() => { $socket.off('crm_notification') }) onMounted(() => { $socket.on('crm_notification', () => { notificationsStore().notifications.reload() }) }) function getRoute(notification) { let params = { leadId: notification.reference_name, } if (notification.route_name === 'Deal') { params = { dealId: notification.reference_name, } } return { name: notification.route_name, params: params, hash: '#' + notification.comment || notification.notification_type_doc, } } onMounted(() => {}) </script>
2302_79757062/crm
frontend/src/components/Notifications.vue
Vue
agpl-3.0
4,741
<template> <div> <Draggable :list="sections" item-key="label" class="flex flex-col gap-5.5"> <template #item="{ element: section }"> <div class="flex flex-col gap-1.5 p-2.5 bg-gray-50 rounded"> <div class="flex items-center justify-between"> <div class="flex h-7 max-w-fit cursor-pointer items-center gap-2 text-base font-medium leading-4" > <div v-if="!section.editingLabel" :class="section.hideLabel ? 'text-gray-400' : ''" > {{ __(section.label) || __('Untitled') }} </div> <div v-else class="flex gap-2 items-center"> <Input v-model="section.label" @keydown.enter="section.editingLabel = false" @blur="section.editingLabel = false" @click.stop /> <Button v-if="section.editingLabel" icon="check" variant="ghost" @click="section.editingLabel = false" /> </div> </div> <Dropdown :options="getOptions(section)"> <template #default> <Button variant="ghost"> <FeatherIcon name="more-horizontal" class="h-4" /> </Button> </template> </Dropdown> </div> <Draggable :list="section.fields" group="fields" item-key="label" class="grid gap-1.5" :class=" section.columns ? 'grid-cols-' + section.columns : 'grid-cols-3' " handle=".cursor-grab" > <template #item="{ element: field }"> <div class="px-2.5 py-2 border rounded text-base bg-white text-gray-800 flex items-center leading-4 justify-between gap-2" > <div class="flex items-center gap-2"> <DragVerticalIcon class="h-3.5 cursor-grab" /> <div>{{ field.label }}</div> </div> <Button variant="ghost" class="!size-4 rounded-sm" icon="x" @click=" section.fields.splice(section.fields.indexOf(field), 1) " /> </div> </template> </Draggable> <Autocomplete v-if="fields.data" value="" :options="fields.data" @change="(e) => addField(section, e)" > <template #target="{ togglePopover }"> <div class="gap-2 w-full"> <Button class="w-full !h-8 !border-gray-200 hover:!border-gray-300" variant="outline" @click="togglePopover()" :label="__('Add Field')" > <template #prefix> <FeatherIcon name="plus" class="h-4" /> </template> </Button> </div> </template> <template #item-label="{ option }"> <div class="flex flex-col gap-1"> <div>{{ option.label }}</div> <div class="text-gray-500 text-sm"> {{ `${option.fieldname} - ${option.fieldtype}` }} </div> </div> </template> </Autocomplete> </div> </template> </Draggable> <div class="mt-5.5"> <Button class="w-full h-8" variant="subtle" :label="__('Add Section')" @click=" sections.push({ label: __('New Section'), opened: true, fields: [], }) " > <template #prefix> <FeatherIcon name="plus" class="h-4" /> </template> </Button> </div> </div> </template> <script setup> import Autocomplete from '@/components/frappe-ui/Autocomplete.vue' import DragVerticalIcon from '@/components/Icons/DragVerticalIcon.vue' import Draggable from 'vuedraggable' import { Dropdown, createResource } from 'frappe-ui' import { computed, watch } from 'vue' const props = defineProps({ sections: Object, doctype: String, }) const restrictedFieldTypes = [ 'Table', 'Geolocation', 'Attach', 'Attach Image', 'HTML', 'Signature', ] const params = computed(() => { return { doctype: props.doctype, restricted_fieldtypes: restrictedFieldTypes, as_array: true, } }) const fields = createResource({ url: 'crm.api.doc.get_fields_meta', params: params.value, cache: ['fieldsMeta', props.doctype], auto: true, }) function addField(section, field) { if (!field) return section.fields.push(field) } function getOptions(section) { return [ { label: 'Edit', icon: 'edit', onClick: () => (section.editingLabel = true), condition: () => section.editable !== false, }, { label: section.hideLabel ? 'Show Label' : 'Hide Label', icon: section.hideLabel ? 'eye' : 'eye-off', onClick: () => (section.hideLabel = !section.hideLabel), }, { label: section.hideBorder ? 'Show Border' : 'Hide Border', icon: 'minus', onClick: () => (section.hideBorder = !section.hideBorder), }, { label: 'Add Column', icon: 'columns', onClick: () => (section.columns = section.columns ? section.columns + 1 : 4), condition: () => !section.columns || section.columns < 4, }, { label: 'Remove Column', icon: 'columns', onClick: () => (section.columns = section.columns ? section.columns - 1 : 2), condition: () => !section.columns || section.columns > 1, }, { label: 'Remove Section', icon: 'trash-2', onClick: () => props.sections.splice(props.sections.indexOf(section), 1), condition: () => section.editable !== false, }, ] } watch( () => props.doctype, () => fields.fetch(params.value), { immediate: true }, ) </script>
2302_79757062/crm
frontend/src/components/QuickEntryLayoutBuilder.vue
Vue
agpl-3.0
6,223
<template> <FormControl v-if="filter.type == 'Check'" :label="filter.label" type="checkbox" v-model="filter.value" @change.stop="updateFilter(filter, $event.target.checked)" /> <FormControl v-else-if="filter.type === 'Select'" class="form-control cursor-pointer [&_select]:cursor-pointer" type="select" v-model="filter.value" :options="filter.options" :placeholder="filter.label" @change.stop="updateFilter(filter, $event.target.value)" /> <Link v-else-if="filter.type === 'Link'" :value="filter.value" :doctype="filter.options" :placeholder="filter.label" @change="(data) => updateFilter(filter, data)" /> <component v-else-if="['Date', 'Datetime'].includes(filter.type)" class="border-none" :is="filter.type === 'Date' ? DatePicker : DateTimePicker" :value="filter.value" @change="(v) => updateFilter(filter, v)" :placeholder="filter.label" /> <TextInput v-else v-model="filter.value" type="text" :placeholder="filter.label" @input.stop="debouncedFn(filter, $event.target.value)" /> </template> <script setup> import Link from '@/components/Controls/Link.vue' import { TextInput, FormControl, DatePicker, DateTimePicker } from 'frappe-ui' import { useDebounceFn } from '@vueuse/core' const props = defineProps({ filter: { type: Object, required: true, }, }) const emit = defineEmits(['applyQuickFilter']) const debouncedFn = useDebounceFn((f, value) => { emit('applyQuickFilter', f, value) }, 500) function updateFilter(f, value) { emit('applyQuickFilter', f, value) } </script>
2302_79757062/crm
frontend/src/components/QuickFilterField.vue
Vue
agpl-3.0
1,633
<template> <div class="relative" :style="{ width: `${sidebarWidth}px` }"> <slot v-bind="{ sidebarResizing, sidebarWidth }" /> <div class="absolute left-0 z-10 h-full w-1 cursor-col-resize bg-gray-300 opacity-0 transition-opacity hover:opacity-100" :class="{ 'opacity-100': sidebarResizing }" @mousedown="startResize" /> </div> </template> <script setup> import { ref } from 'vue' const props = defineProps({ defaultWidth: { type: Number, default: 352, }, minWidth: { type: Number, default: 16 * 16, }, maxWidth: { type: Number, default: 30 * 16, }, side: { type: String, default: 'left', }, parent: { type: Object, default: null, }, }) const sidebarResizing = ref(false) const sidebarWidth = ref(props.defaultWidth) function startResize() { document.addEventListener('mousemove', resize) document.addEventListener('mouseup', () => { document.body.classList.remove('select-none') document.body.classList.remove('cursor-col-resize') document.querySelectorAll('.select-text1').forEach((el) => { el.classList.remove('select-text1') el.classList.add('select-text') }) localStorage.setItem('sidebarWidth', sidebarWidth.value) sidebarResizing.value = false document.removeEventListener('mousemove', resize) }) } function resize(e) { sidebarResizing.value = true document.body.classList.add('select-none') document.body.classList.add('cursor-col-resize') document.querySelectorAll('.select-text').forEach((el) => { el.classList.remove('select-text') el.classList.add('select-text1') }) sidebarWidth.value = props.side == 'left' ? e.clientX : window.innerWidth - e.clientX let gap = props.parent ? distance() : 0 sidebarWidth.value = sidebarWidth.value - gap // snap to props.defaultWidth let range = [props.defaultWidth - 10, props.defaultWidth + 10] if (sidebarWidth.value > range[0] && sidebarWidth.value < range[1]) { sidebarWidth.value = props.defaultWidth } if (sidebarWidth.value < props.minWidth) { sidebarWidth.value = props.minWidth } if (sidebarWidth.value > props.maxWidth) { sidebarWidth.value = props.maxWidth } } function distance() { if (!props.parent) return 0 const rect = props.parent.getBoundingClientRect() return window.innerWidth - rect[props.side] } </script>
2302_79757062/crm
frontend/src/components/Resizer.vue
Vue
agpl-3.0
2,383
<template> <div class="flex flex-col gap-1.5 border-b sm:px-6 py-3 px-4"> <div v-for="s in slaSection" :key="s.label" class="flex items-center gap-2 text-base leading-5" > <div class="sm:w-[106px] w-36 text-sm text-gray-600"> {{ __(s.label) }} </div> <div class="grid min-h-[28px] items-center"> <Tooltip v-if="s.tooltipText" :text="__(s.tooltipText)"> <div class="ml-2 cursor-pointer"> <Badge v-if="s.type == 'Badge'" class="-ml-1" :label="s.value" variant="subtle" :theme="s.color" /> <div v-else>{{ s.value }}</div> </div> </Tooltip> <Dropdown class="form-control" v-if="s.type == 'Select'" :options="s.options" > <template #default="{ open }"> <Button :label="s.value"> <template #suffix> <FeatherIcon :name="open ? 'chevron-up' : 'chevron-down'" class="h-4" /> </template> </Button> </template> </Dropdown> </div> </div> </div> </template> <script setup> import { Dropdown, Tooltip } from 'frappe-ui' import { timeAgo, dateFormat, formatTime, dateTooltipFormat } from '@/utils' import { statusesStore } from '@/stores/statuses' import { capture } from '@/telemetry' import { computed, defineModel } from 'vue' const data = defineModel() const emit = defineEmits(['updateField']) const { communicationStatuses } = statusesStore() let slaSection = computed(() => { let sections = [] let status = data.value.sla_status let tooltipText = status let color = data.value.sla_status == 'Failed' ? 'red' : data.value.sla_status == 'Fulfilled' ? 'green' : 'orange' if (status == 'First Response Due') { status = timeAgo(data.value.response_by) if (status == 'just now') { status = 'In less than a minute' } tooltipText = dateFormat(data.value.response_by, dateTooltipFormat) if (new Date(data.value.response_by) < new Date()) { color = 'red' if (status == __('In less than a minute')) { status = 'less than a minute ago' } } } else if (['Fulfilled', 'Failed'].includes(status)) { status = __(status) + ' in ' + formatTime(data.value.first_response_time) tooltipText = dateFormat(data.value.first_responded_on, dateTooltipFormat) } sections.push( ...[ { label: 'First Response', type: 'Badge', value: __(status), tooltipText: tooltipText, color: color, }, { label: 'Status', value: data.value.communication_status, type: 'Select', options: communicationStatuses.data?.map((status) => ({ label: status.name, value: status.name, onClick: () => { capture('sla_status_change') emit('updateField', 'communication_status', status.name) }, })), }, ], ) return sections }) </script> <style scoped> :deep(.form-control button) { border-color: transparent; background: white; } </style>
2302_79757062/crm
frontend/src/components/SLASection.vue
Vue
agpl-3.0
3,275
<template> <slot name="header" v-bind="{ opened, hide, open, close, toggle }"> <div v-if="!hide" class="flex items-center justify-between"> <div class="flex h-7 max-w-fit cursor-pointer items-center gap-2 pl-2 pr-3 text-base font-semibold leading-5" @click="toggle()" > <FeatherIcon name="chevron-right" class="h-4 text-gray-900 transition-all duration-300 ease-in-out" :class="{ 'rotate-90': opened }" /> {{ __(label) || __('Untitled') }} </div> <slot name="actions"></slot> </div> </slot> <transition enter-active-class="duration-300 ease-in" leave-active-class="duration-300 ease-[cubic-bezier(0, 1, 0.5, 1)]" enter-to-class="max-h-[200px] overflow-hidden" leave-from-class="max-h-[200px] overflow-hidden" enter-from-class="max-h-0 overflow-hidden" leave-to-class="max-h-0 overflow-hidden" > <div v-if="opened"> <slot v-bind="{ opened, open, close, toggle }" /> </div> </transition> </template> <script setup> import { ref } from 'vue' const props = defineProps({ label: { type: String, default: '', }, hideLabel: { type: Boolean, default: false, }, isOpened: { type: Boolean, default: true, }, }) function toggle() { opened.value = !opened.value } function open() { opened.value = true } function close() { opened.value = false } let opened = ref(props.isOpened) let hide = ref(props.hideLabel) </script>
2302_79757062/crm
frontend/src/components/Section.vue
Vue
agpl-3.0
1,504
<template> <FadedScrollableDiv class="flex flex-col gap-1.5 overflow-y-auto" :class="[isLastSection ? '' : 'max-h-[300px]']" > <div v-for="field in _fields" :key="field.label" :class="[field.hidden && 'hidden']" class="section-field flex items-center gap-2 px-3 leading-5 first:mt-3" > <Tooltip :text="__(field.label)" :hoverDelay="1"> <div class="sm:w-[106px] w-36 shrink-0 truncate text-sm text-gray-600"> <span>{{ __(field.label) }}</span> <span class="text-red-500">{{ field.reqd ? ' *' : '' }}</span> </div> </Tooltip> <div class="grid min-h-[28px] flex-1 items-center overflow-hidden text-base" > <div v-if="field.read_only && field.type !== 'checkbox'" class="flex h-7 cursor-pointer items-center px-2 py-1 text-gray-600" > <Tooltip :text="__(field.tooltip)"> <div>{{ data[field.name] }}</div> </Tooltip> </div> <FormControl v-else-if="field.type == 'checkbox'" class="form-control" :type="field.type" v-model="data[field.name]" @change.stop="emit('update', field.name, $event.target.checked)" :disabled="Boolean(field.read_only)" /> <FormControl v-else-if=" ['email', 'number', 'date', 'password', 'textarea'].includes( field.type, ) " class="form-control" :class="{ '[&_input]:text-gray-500': field.type === 'date' && !data[field.name], }" :type="field.type" :value="data[field.name]" :placeholder="field.placeholder" :debounce="500" @change.stop="emit('update', field.name, $event.target.value)" /> <FormControl v-else-if="field.type === 'select'" class="form-control cursor-pointer [&_select]:cursor-pointer" type="select" :value="data[field.name]" :options="field.options" :debounce="500" @change.stop="emit('update', field.name, $event.target.value)" /> <Link v-else-if="['lead_owner', 'deal_owner'].includes(field.name)" class="form-control" :value="data[field.name] && getUser(data[field.name]).full_name" doctype="User" @change="(data) => emit('update', field.name, data)" :placeholder="'Select' + ' ' + field.label + '...'" :hideMe="true" > <template v-if="data[field.name]" #prefix> <UserAvatar class="mr-1.5" :user="data[field.name]" size="sm" /> </template> <template #item-prefix="{ option }"> <UserAvatar class="mr-1.5" :user="option.value" size="sm" /> </template> <template #item-label="{ option }"> <Tooltip :text="option.value"> <div class="cursor-pointer"> {{ getUser(option.value).full_name }} </div> </Tooltip> </template> </Link> <Link v-else-if="field.type === 'link'" class="form-control select-text" :value="data[field.name]" :doctype="field.doctype" :placeholder="field.placeholder" @change="(data) => emit('update', field.name, data)" :onCreate="field.create" /> <FormControl v-else class="form-control" type="text" :value="data[field.name]" :placeholder="field.placeholder" :debounce="500" @change.stop="emit('update', field.name, $event.target.value)" /> </div> <ArrowUpRightIcon v-if="field.type === 'link' && field.link && data[field.name]" class="h-4 w-4 shrink-0 cursor-pointer text-gray-600 hover:text-gray-800" @click="field.link(data[field.name])" /> </div> </FadedScrollableDiv> </template> <script setup> import FadedScrollableDiv from '@/components/FadedScrollableDiv.vue' import ArrowUpRightIcon from '@/components/Icons/ArrowUpRightIcon.vue' import Link from '@/components/Controls/Link.vue' import UserAvatar from '@/components/UserAvatar.vue' import { usersStore } from '@/stores/users' import { Tooltip } from 'frappe-ui' import { computed } from 'vue' const props = defineProps({ fields: { type: Object, required: true, }, isLastSection: { type: Boolean, default: false, }, }) const { getUser } = usersStore() const emit = defineEmits(['update']) const data = defineModel() const _fields = computed(() => { let all_fields = [] props.fields?.forEach((field) => { let df = field.all_properties if (df?.depends_on) evaluate_depends_on(df.depends_on, field) all_fields.push({ ...field, placeholder: field.placeholder || field.label, }) }) return all_fields }) function evaluate_depends_on(expression, field) { if (expression.substr(0, 5) == 'eval:') { try { let out = evaluate(expression.substr(5), { doc: data.value }) if (!out) { field.hidden = true } } catch (e) { console.error(e) } } } function evaluate(code, context = {}) { let variable_names = Object.keys(context) let variables = Object.values(context) code = `let out = ${code}; return out` try { let expression_function = new Function(...variable_names, code) return expression_function(...variables) } catch (error) { console.log('Error evaluating the following expression:') console.error(code) throw error } } </script> <style scoped> .form-control { margin: 2px; } :deep(.form-control input:not([type='checkbox'])), :deep(.form-control select), :deep(.form-control textarea), :deep(.form-control button) { border-color: transparent; background: white; } :deep(.form-control button) { gap: 0; } :deep(.form-control [type='checkbox']) { margin-left: 9px; cursor: pointer; } :deep(.form-control button > div) { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } :deep(.form-control button svg) { color: white; width: 0; } </style>
2302_79757062/crm
frontend/src/components/SectionFields.vue
Vue
agpl-3.0
6,228
<template> <SettingsPage doctype="ERPNext CRM Settings" :title="__('ERPNext Settings')" :successMessage="__('ERPNext Settings updated')" class="p-8" /> </template> <script setup> import SettingsPage from '@/components/Settings/SettingsPage.vue' </script>
2302_79757062/crm
frontend/src/components/Settings/ERPNextSettings.vue
Vue
agpl-3.0
274
<template> <div class="flex h-full flex-col gap-8 p-8"> <h2 class="flex gap-2 text-xl font-semibold leading-none h-5"> {{ __('Send Invites To') }} </h2> <div class="flex-1 overflow-y-auto"> <label class="block text-xs text-gray-600 mb-1.5"> {{ __('Invite by email') }} </label> <MultiValueInput v-model="invitees" :validate="validateEmail" :error-message=" (value) => __('{0} is an invalid email address', [value]) " /> <FormControl type="select" class="mt-4" v-model="role" variant="outline" :label="__('Invite as')" :options="[ { label: __('Regular Access'), value: 'Sales User' }, { label: __('Manager Access'), value: 'Sales Manager' }, ]" :description="description" /> <ErrorMessage class="mt-2" v-if="error" :message="error" /> <template v-if="pendingInvitations.data?.length && !invitees.length"> <div class="mt-6 flex items-center justify-between py-4 text-base font-semibold" > <div>{{ __('Pending Invites') }}</div> </div> <ul class="flex flex-col gap-1"> <li class="flex items-center justify-between px-2 py-1 rounded-lg bg-gray-50" v-for="user in pendingInvitations.data" :key="user.name" > <div class="text-base"> <span class="text-gray-900"> {{ user.email }} </span> <span class="text-gray-600"> ({{ roleMap[user.role] }}) </span> </div> <div> <Tooltip text="Delete Invitation"> <Button icon="x" variant="ghost" :loading=" pendingInvitations.delete.loading && pendingInvitations.delete.params.name === user.name " @click="pendingInvitations.delete.submit(user.name)" /> </Tooltip> </div> </li> </ul> </template> </div> <div class="flex flex-row-reverse"> <Button :label="__('Send Invites')" variant="solid" @click="inviteByEmail.submit()" :loading="inviteByEmail.loading" /> </div> </div> </template> <script setup> import MultiValueInput from '@/components/Controls/MultiValueInput.vue' import { validateEmail, convertArrayToString } from '@/utils' import { createListResource, createResource, FormControl, Tooltip, } from 'frappe-ui' import { ref, computed } from 'vue' const invitees = ref([]) const role = ref('Sales User') const error = ref(null) const description = computed(() => { return { 'Sales Manager': 'Can manage and invite new members, and create public & private views (reports).', 'Sales User': 'Can work with leads and deals and create private views (reports).', }[role.value] }) const roleMap = { 'Sales User': __('Regular Access'), 'Sales Manager': __('Manager Access'), } const inviteByEmail = createResource({ url: 'crm.api.invite_by_email', makeParams() { return { emails: convertArrayToString(invitees.value), role: role.value, } }, onSuccess() { invitees.value = [] role.value = 'Sales User' error.value = null pendingInvitations.reload() }, onError(error) { error.value = error }, }) const pendingInvitations = createListResource({ type: 'list', doctype: 'CRM Invitation', filters: { status: 'Pending' }, fields: ['name', 'email', 'role'], auto: true, }) </script>
2302_79757062/crm
frontend/src/components/Settings/InviteMemberPage.vue
Vue
agpl-3.0
3,698
<template> <FileUploader @success="(file) => setUserImage(file.file_url)" :validateFile="validateFile" > <template v-slot="{ file, progress, error, uploading, openFileSelector }"> <div class="flex flex-col items-center"> <button class="group relative rounded-full border-2" @click="openFileSelector" > <div class="absolute inset-0 grid place-items-center rounded-full bg-gray-400/20 text-base text-gray-600 transition-opacity" :class="[ uploading ? 'opacity-100' : 'opacity-0 group-hover:opacity-100', 'drop-shadow-sm', ]" > <span class="inline-block rounded-md bg-gray-900/60 px-2 py-1 text-white" > {{ uploading ? `Uploading ${progress}%` : profile.user_image ? 'Change Image' : 'Upload Image' }} </span> </div> <img v-if="profile.user_image" class="h-64 w-64 rounded-full object-cover" :src="profile.user_image" alt="Profile Photo" /> <div v-else class="h-64 w-64 rounded-full bg-gray-100"></div> </button> <ErrorMessage class="mt-4" :message="error" /> <div class="mt-4 flex items-center gap-4"> <Button v-if="profile.user_image" @click="setUserImage(null)"> Remove </Button> </div> </div> </template> </FileUploader> </template> <script setup> import { FileUploader } from 'frappe-ui' const profile = defineModel() function setUserImage(url) { profile.value.user_image = url } function validateFile(file) { let extn = file.name.split('.').pop().toLowerCase() if (!['png', 'jpg'].includes(extn)) { return 'Only PNG and JPG images are allowed' } } </script>
2302_79757062/crm
frontend/src/components/Settings/ProfileImageEditor.vue
Vue
agpl-3.0
1,948
<template> <div v-if="profile" class="flex w-full items-center justify-between p-12 pt-14"> <div class="flex items-center gap-4"> <Avatar class="!size-16" :image="profile.user_image" :label="profile.full_name" /> <div class="flex flex-col gap-1"> <span class="text-2xl font-semibold">{{ profile.full_name }}</span> <span class="text-base text-gray-700">{{ profile.email }}</span> </div> </div> <Button :label="__('Edit profile')" @click="showProfileModal = true" /> <Dialog :options="{ title: __('Edit Profile') }" v-model="showProfileModal" @after-leave="editingProfilePhoto = false" > <template #body-content> <div v-if="user" class="space-y-4"> <ProfileImageEditor v-model="profile" v-if="editingProfilePhoto" /> <template v-else> <div class="flex items-center gap-4"> <Avatar size="lg" :image="profile.user_image" :label="profile.full_name" /> <Button :label="__('Edit Profile Photo')" @click="editingProfilePhoto = true" /> </div> <FormControl label="First Name" v-model="profile.first_name" /> <FormControl label="Last Name" v-model="profile.last_name" /> </template> </div> </template> <template #actions> <Button v-if="editingProfilePhoto" class="mb-2 w-full" @click="editingProfilePhoto = false" :label="__('Back')" /> <Button variant="solid" class="w-full" :loading="loading" @click="updateUser" :label="__('Save')" /> </template> </Dialog> </div> </template> <script setup> import ProfileImageEditor from '@/components/Settings/ProfileImageEditor.vue' import { usersStore } from '@/stores/users' import { Dialog, Avatar, createResource } from 'frappe-ui' import { ref, computed, onMounted } from 'vue' const { getUser, users } = usersStore() const user = computed(() => getUser() || {}) const showProfileModal = ref(false) const editingProfilePhoto = ref(false) const profile = ref({}) const loading = ref(false) function updateUser() { loading.value = true const fieldname = { first_name: profile.value.first_name, last_name: profile.value.last_name, user_image: profile.value.user_image, } createResource({ url: 'frappe.client.set_value', params: { doctype: 'User', name: user.value.name, fieldname, }, auto: true, onSuccess: () => { loading.value = false showProfileModal.value = false users.reload() }, }) } onMounted(() => { profile.value = { ...user.value } }) </script>
2302_79757062/crm
frontend/src/components/Settings/ProfileSettings.vue
Vue
agpl-3.0
2,864
<template> <Dialog v-model="show" :options="{ size: '5xl' }"> <template #body> <div class="flex h-[calc(100vh_-_8rem)]"> <div class="flex w-52 shrink-0 flex-col bg-gray-50 p-2"> <h1 class="mb-3 px-2 pt-2 text-lg font-semibold"> {{ __('Settings') }} </h1> <div v-for="tab in tabs"> <div v-if="!tab.hideLabel" class="mb-2 mt-3 flex cursor-pointer gap-1.5 px-1 text-base font-medium text-gray-600 transition-all duration-300 ease-in-out" > <span>{{ __(tab.label) }}</span> </div> <nav class="space-y-1"> <SidebarLink v-for="i in tab.items" :icon="i.icon" :label="__(i.label)" class="w-full" :class=" activeTab?.label == i.label ? 'bg-white shadow-sm' : 'hover:bg-gray-100' " @click="activeTab = i" /> </nav> </div> </div> <div class="flex flex-1 flex-col overflow-y-auto"> <component :is="activeTab.component" v-if="activeTab" /> </div> </div> </template> </Dialog> </template> <script setup> import ContactsIcon from '@/components/Icons/ContactsIcon.vue' import WhatsAppIcon from '@/components/Icons/WhatsAppIcon.vue' import ERPNextIcon from '@/components/Icons/ERPNextIcon.vue' import PhoneIcon from '@/components/Icons/PhoneIcon.vue' import InviteMemberPage from '@/components/Settings/InviteMemberPage.vue' import ProfileSettings from '@/components/Settings/ProfileSettings.vue' import WhatsAppSettings from '@/components/Settings/WhatsAppSettings.vue' import ERPNextSettings from '@/components/Settings/ERPNextSettings.vue' import TwilioSettings from '@/components/Settings/TwilioSettings.vue' import SidebarLink from '@/components/SidebarLink.vue' import { isWhatsappInstalled } from '@/composables/settings' import { Dialog } from 'frappe-ui' import { ref, markRaw, computed, h } from 'vue' const show = defineModel() const tabs = computed(() => { let _tabs = [ { label: __('Settings'), hideLabel: true, items: [ { label: __('Profile'), icon: ContactsIcon, component: markRaw(ProfileSettings), }, { label: __('Invite Members'), icon: 'user-plus', component: markRaw(InviteMemberPage), }, ], }, { label: __('Integrations'), items: [ { label: __('Twilio'), icon: PhoneIcon, component: markRaw(TwilioSettings), }, { label: __('WhatsApp'), icon: WhatsAppIcon, component: markRaw(WhatsAppSettings), condition: () => isWhatsappInstalled.value, }, { label: __('ERPNext'), icon: ERPNextIcon, component: markRaw(ERPNextSettings), }, ], }, ] return _tabs.map((tab) => { tab.items = tab.items.filter((item) => { if (item.condition) { return item.condition() } return true }) return tab }) }) const activeTab = ref(tabs.value[0].items[0]) </script>
2302_79757062/crm
frontend/src/components/Settings/SettingsModal.vue
Vue
agpl-3.0
3,307
<template> <div class="flex h-full flex-col gap-8"> <h2 class="flex gap-2 text-xl font-semibold leading-none h-5"> <div>{{ title || __(doctype) }}</div> <Badge v-if="data.isDirty" :label="__('Not Saved')" variant="subtle" theme="orange" /> </h2> <div v-if="!data.get.loading" class="flex-1 overflow-y-auto"> <Fields v-if="data?.doc && sections" :sections="sections" :data="data.doc" /> <ErrorMessage class="mt-2" :message="error" /> </div> <div v-else class="flex flex-1 items-center justify-center"> <Spinner class="size-8" /> </div> <div class="flex flex-row-reverse"> <Button :loading="data.save.loading" :label="__('Update')" variant="solid" @click="update" /> </div> </div> </template> <script setup> import Fields from '@/components/Fields.vue' import { createDocumentResource, createResource, Spinner, Badge, ErrorMessage, } from 'frappe-ui' import { evaluate_depends_on_value, createToast } from '@/utils' import { ref, computed } from 'vue' const props = defineProps({ doctype: { type: String, required: true, }, title: { type: String, default: '', }, successMessage: { type: String, default: 'Updated Successfully', }, }) const fields = createResource({ url: 'crm.api.doc.get_fields', cache: ['fields', props.doctype], params: { doctype: props.doctype, allow_all_fieldtypes: true, }, auto: true, }) const error = ref(null) const data = createDocumentResource({ doctype: props.doctype, name: props.doctype, fields: ['*'], cache: props.doctype, auto: true, setValue: { onSuccess: () => { error.value = null createToast({ title: __('Success'), text: __(props.successMessage), icon: 'check', iconClasses: 'text-green-600', }) }, onError: (err) => { createToast({ title: __('Error'), text: err.message + ': ' + err.messages[0], icon: 'x', iconClasses: 'text-red-600', }) }, }, }) const sections = computed(() => { if (!fields.data) return [] let _sections = [] let fieldsData = fields.data if (fieldsData[0].type !== 'Section Break') { _sections.push({ label: 'General', hideLabel: true, columns: 1, fields: [], }) } fieldsData.forEach((field) => { if (field.type === 'Section Break') { _sections.push({ label: field.value, hideLabel: true, columns: 1, fields: [], }) } else if (field.type === 'Column Break') { _sections[_sections.length - 1].columns += 1 } else { _sections[_sections.length - 1].fields.push({ ...field, display_via_depends_on: evaluate_depends_on_value( field.depends_on, data.doc, ), mandatory_via_depends_on: evaluate_depends_on_value( field.mandatory_depends_on, data.doc, ), name: field.value, }) } }) return _sections }) function update() { error.value = null if (validateMandatoryFields()) return data.save.submit() } function validateMandatoryFields() { for (let section of sections.value) { for (let field of section.fields) { if ( (field.mandatory || (field.mandatory_depends_on && field.mandatory_via_depends_on)) && !data.doc[field.name] ) { error.value = __('{0} is mandatory', [__(field.label)]) return true } } } return false } </script>
2302_79757062/crm
frontend/src/components/Settings/SettingsPage.vue
Vue
agpl-3.0
3,645
<template> <div> <Draggable :list="sections" item-key="label" class="flex flex-col gap-5.5"> <template #item="{ element: section }"> <div class="flex flex-col gap-3"> <div class="flex items-center justify-between rounded px-2.5 py-2 bg-gray-50" > <div class="flex max-w-fit cursor-pointer items-center gap-2 text-base leading-4" @click="section.opened = !section.opened" > <FeatherIcon name="chevron-right" class="h-4 text-gray-900 transition-all duration-300 ease-in-out" :class="{ 'rotate-90': section.opened }" /> <div v-if="!section.editingLabel"> {{ __(section.label) || __('Untitled') }} </div> <div v-else class="flex gap-2 items-center"> <Input v-model="section.label" @keydown.enter="section.editingLabel = false" @blur="section.editingLabel = false" @click.stop /> <Button v-if="section.editingLabel" icon="check" class="!size-4 rounded-sm" variant="ghost" @click.stop="section.editingLabel = false" /> </div> </div> <div class="flex gap-1 items-center"> <Button v-if="!section.editingLabel" class="!size-4 rounded-sm" variant="ghost" @click="section.editingLabel = true" > <EditIcon class="h-3.5" /> </Button> <Button v-if="section.editable !== false" class="!size-4 rounded-sm" icon="x" variant="ghost" @click="sections.splice(sections.indexOf(section), 1)" /> </div> </div> <div v-show="section.opened"> <Draggable :list="section.fields" group="fields" item-key="label" class="flex flex-col gap-1.5" handle=".cursor-grab" > <template #item="{ element: field }"> <div class="px-2.5 py-2 border rounded text-base leading-4 text-gray-800 flex items-center justify-between gap-2" > <div class="flex items-center gap-2"> <DragVerticalIcon class="h-3.5 cursor-grab" /> <div>{{ field.label }}</div> </div> <Button variant="ghost" icon="x" class="!size-4 rounded-sm" @click=" section.fields.splice(section.fields.indexOf(field), 1) " /> </div> </template> </Draggable> <Autocomplete v-if="fields.data && section.editable !== false" value="" :options="fields.data" @change="(e) => addField(section, e)" > <template #target="{ togglePopover }"> <Button class="w-full h-8 mt-1.5 !border-gray-200 hover:!border-gray-300" variant="outline" @click="togglePopover()" :label="__('Add Field')" > <template #prefix> <FeatherIcon name="plus" class="h-4" /> </template> </Button> </template> <template #item-label="{ option }"> <div class="flex flex-col gap-1"> <div>{{ option.label }}</div> <div class="text-gray-500 text-sm"> {{ `${option.fieldname} - ${option.fieldtype}` }} </div> </div> </template> </Autocomplete> <div v-else class="flex justify-center items-center border rounded border-dashed p-3" > <div class="text-sm text-gray-500"> {{ __('This section is not editable') }} </div> </div> </div> </div> </template> </Draggable> <div class="mt-5.5"> <Button class="w-full h-8" variant="subtle" :label="__('Add Section')" @click=" sections.push({ label: __('New Section'), opened: true, fields: [] }) " > <template #prefix> <FeatherIcon name="plus" class="h-4" /> </template> </Button> </div> </div> </template> <script setup> import EditIcon from '@/components/Icons/EditIcon.vue' import Autocomplete from '@/components/frappe-ui/Autocomplete.vue' import DragVerticalIcon from '@/components/Icons/DragVerticalIcon.vue' import Draggable from 'vuedraggable' import { Input, createResource } from 'frappe-ui' import { computed, watch } from 'vue' const props = defineProps({ sections: Object, doctype: String, }) const restrictedFieldTypes = [ 'Table', 'Geolocation', 'Attach', 'Attach Image', 'HTML', 'Signature', ] const params = computed(() => { return { doctype: props.doctype, restricted_fieldtypes: restrictedFieldTypes, as_array: true, } }) const fields = createResource({ url: 'crm.api.doc.get_fields_meta', params: params.value, cache: ['fieldsMeta', props.doctype], auto: true, }) function addField(section, field) { if (!field) return section.fields.push(field) } watch( () => props.doctype, () => fields.fetch(params.value), { immediate: true }, ) </script>
2302_79757062/crm
frontend/src/components/Settings/SidePanelLayoutBuilder.vue
Vue
agpl-3.0
5,893
<template> <Dialog v-model="show" :options="{ size: '3xl' }"> <template #body-title> <h3 class="flex items-center gap-2 text-2xl font-semibold leading-6 text-gray-900" > <div>{{ __('Edit Field Layout') }}</div> <Badge v-if="dirty" :label="__('Not Saved')" variant="subtle" theme="orange" /> </h3> </template> <template #body-content> <div class="flex flex-col gap-5.5"> <div class="flex justify-between gap-2"> <FormControl type="select" class="w-1/4" v-model="_doctype" :options="['CRM Lead', 'CRM Deal']" @change="reload" /> <Switch v-model="preview" :label="preview ? __('Hide preview') : __('Show preview')" size="sm" /> </div> <div v-if="sections.data" class="flex gap-4"> <SidePanelLayoutBuilder class="flex flex-1 flex-col pr-2" :sections="sections.data" :doctype="_doctype" /> <div v-if="preview" class="flex flex-1 flex-col border rounded"> <div v-for="(section, i) in sections.data" :key="section.label" class="flex flex-col py-1.5 px-1" :class="{ 'border-b': i !== sections.data.length - 1 }" > <Section :is-opened="section.opened" :label="section.label"> <SectionFields :fields="section.fields" :isLastSection="i == section.data.length - 1" v-model="data" /> </Section> </div> </div> <div v-else class="flex flex-1 justify-center items-center text-gray-600 bg-gray-50 rounded border border-gray-50" > {{ __('Toggle on for preview') }} </div> </div> </div> </template> <template #actions> <div class="flex flex-row-reverse gap-2"> <Button :loading="loading" :label="__('Save')" variant="solid" @click="saveChanges" /> <Button :label="__('Reset')" @click="reload" /> </div> </template> </Dialog> </template> <script setup> import Section from '@/components/Section.vue' import SectionFields from '@/components/SectionFields.vue' import SidePanelLayoutBuilder from '@/components/Settings/SidePanelLayoutBuilder.vue' import { useDebounceFn } from '@vueuse/core' import { capture } from '@/telemetry' import { Dialog, Badge, Switch, call, createResource } from 'frappe-ui' import { ref, watch, onMounted, nextTick } from 'vue' const props = defineProps({ doctype: { type: String, default: 'CRM Lead', }, }) const emit = defineEmits(['reload']) const show = defineModel() const _doctype = ref(props.doctype) const loading = ref(false) const dirty = ref(false) const preview = ref(false) const data = ref({}) function getParams() { return { doctype: _doctype.value, type: 'Side Panel' } } const sections = createResource({ url: 'crm.fcrm.doctype.crm_fields_layout.crm_fields_layout.get_fields_layout', cache: ['sidebar-sections', _doctype.value], params: getParams(), onSuccess(data) { sections.originalData = JSON.parse(JSON.stringify(data)) }, }) watch( () => sections?.data, () => { dirty.value = JSON.stringify(sections?.data) !== JSON.stringify(sections?.originalData) }, { deep: true }, ) onMounted(() => useDebounceFn(reload, 100)()) function reload() { nextTick(() => { sections.params = getParams() sections.reload() }) } function saveChanges() { let _sections = JSON.parse(JSON.stringify(sections.data)) _sections.forEach((section) => { if (!section.fields) return section.fields = section.fields.map( (field) => field.fieldname || field.name, ) }) loading.value = true call( 'crm.fcrm.doctype.crm_fields_layout.crm_fields_layout.save_fields_layout', { doctype: _doctype.value, type: 'Side Panel', layout: JSON.stringify(_sections), }, ).then(() => { loading.value = false show.value = false capture('side_panel_layout_builder', { doctype: _doctype.value }) emit('reload') }) } </script>
2302_79757062/crm
frontend/src/components/Settings/SidePanelModal.vue
Vue
agpl-3.0
4,370
<template> <SettingsPage doctype="Twilio Settings" class="p-8" /> </template> <script setup> import SettingsPage from '@/components/Settings/SettingsPage.vue' </script>
2302_79757062/crm
frontend/src/components/Settings/TwilioSettings.vue
Vue
agpl-3.0
171
<template> <SettingsPage doctype="WhatsApp Settings" class="p-8" /> </template> <script setup> import SettingsPage from '@/components/Settings/SettingsPage.vue' </script>
2302_79757062/crm
frontend/src/components/Settings/WhatsAppSettings.vue
Vue
agpl-3.0
172
<template> <button class="flex h-7 cursor-pointer items-center rounded text-gray-700 duration-300 ease-in-out focus:outline-none focus:transition-none focus-visible:rounded focus-visible:ring-2 focus-visible:ring-gray-400" :class="isActive ? 'bg-white shadow-sm' : 'hover:bg-gray-100'" @click="handleClick" > <div class="flex w-full items-center justify-between duration-300 ease-in-out" :class="isCollapsed ? 'ml-[3px] p-1' : 'px-2 py-1'" > <div class="flex items-center truncate"> <Tooltip :text="label" placement="right" :disabled="!isCollapsed"> <slot name="icon"> <span class="grid flex-shrink-0 place-items-center"> <FeatherIcon v-if="typeof icon == 'string'" :name="icon" class="size-4 text-gray-700" /> <component v-else :is="icon" class="size-4 text-gray-700" /> </span> </slot> </Tooltip> <Tooltip :text="label" placement="right" :disabled="isCollapsed" :hoverDelay="1.5" > <span class="flex-1 flex-shrink-0 truncate text-sm duration-300 ease-in-out" :class=" isCollapsed ? 'ml-0 w-0 overflow-hidden opacity-0' : 'ml-2 w-auto opacity-100' " > {{ label }} </span> </Tooltip> </div> <slot name="right" /> </div> </button> </template> <script setup> import { Tooltip } from 'frappe-ui' import { computed } from 'vue' import { useRouter, useRoute } from 'vue-router' import { isMobileView, mobileSidebarOpened } from '@/composables/settings' const router = useRouter() const route = useRoute() const props = defineProps({ icon: { type: [Object, String], }, label: { type: String, default: '', }, to: { type: [Object, String], default: '', }, isCollapsed: { type: Boolean, default: false, }, }) function handleClick() { if (!props.to) return if (typeof props.to === 'object') { router.push(props.to) } else { router.push({ name: props.to }) } if (isMobileView.value) { mobileSidebarOpened.value = false } } let isActive = computed(() => { if (route.query.view) { return route.query.view == props.to?.query?.view } return route.name === props.to }) </script>
2302_79757062/crm
frontend/src/components/SidebarLink.vue
Vue
agpl-3.0
2,444
<template> <Autocomplete v-if="!sortValues?.size" :options="options" value="" :placeholder="__('First Name')" @change="(e) => setSort(e)" > <template #target="{ togglePopover }"> <Button :label="__('Sort')" @click="togglePopover()"> <template v-if="hideLabel"> <SortIcon class="h-4" /> </template> <template v-if="!hideLabel && !sortValues?.size" #prefix> <SortIcon class="h-4" /> </template> </Button> </template> </Autocomplete> <NestedPopover v-else> <template #target="{ open }"> <Button v-if="sortValues.size > 1" :label="__('Sort')"> <template v-if="hideLabel"> <SortIcon class="h-4" /> </template> <template v-if="!hideLabel" #prefix><SortIcon class="h-4" /></template> <template v-if="sortValues?.size" #suffix> <div class="flex h-5 w-5 items-center justify-center rounded bg-gray-900 pt-[1px] text-2xs font-medium text-white" > {{ sortValues.size }} </div> </template> </Button> <div v-else class="flex items-center justify-center"> <Button v-if="sortValues.size" class="rounded-r-none border-r" @click.stop=" () => { Array.from(sortValues)[0].direction = Array.from(sortValues)[0].direction == 'asc' ? 'desc' : 'asc' apply() } " > <AscendingIcon v-if="Array.from(sortValues)[0].direction == 'asc'" class="h-4" /> <DesendingIcon v-else class="h-4" /> </Button> <Button :label="getSortLabel()" :class="sortValues.size ? 'rounded-l-none' : ''" > <template v-if="!hideLabel && !sortValues?.size" #prefix> <SortIcon class="h-4" /> </template> <template v-if="sortValues?.size" #suffix> <FeatherIcon :name="open ? 'chevron-up' : 'chevron-down'" class="h-4 text-gray-600" /> </template> </Button> </div> </template> <template #body="{ close }"> <div class="my-2 rounded-lg border border-gray-100 bg-white shadow-xl"> <div class="min-w-60 p-2"> <div v-if="sortValues?.size" id="sort-list" class="mb-3 flex flex-col gap-2" > <div v-for="(sort, i) in sortValues" :key="sort.fieldname" class="flex items-center gap-1" > <div class="handle flex h-7 w-7 items-center justify-center"> <DragIcon class="h-4 w-4 cursor-grab text-gray-600" /> </div> <div class="flex"> <Button size="md" class="rounded-r-none border-r" @click=" () => { sort.direction = sort.direction == 'asc' ? 'desc' : 'asc' apply() } " > <AscendingIcon v-if="sort.direction == 'asc'" class="h-4" /> <DesendingIcon v-else class="h-4" /> </Button> <Autocomplete class="!w-32" :value="sort.fieldname" :options="sortOptions.data" @change="(e) => updateSort(e, i)" :placeholder="__('First Name')" > <template #target="{ togglePopover, selectedValue, displayValue }" > <Button class="flex w-full items-center justify-between rounded-l-none !text-gray-600" size="md" @click="togglePopover()" > {{ displayValue(selectedValue) }} <template #suffix> <FeatherIcon name="chevron-down" class="h-4 text-gray-600" /> </template> </Button> </template> </Autocomplete> </div> <Button variant="ghost" icon="x" @click="removeSort(i)" /> </div> </div> <div v-else class="mb-3 flex h-7 items-center px-3 text-sm text-gray-600" > {{ __('Empty - Choose a field to sort by') }} </div> <div class="flex items-center justify-between gap-2"> <Autocomplete :options="options" value="" :placeholder="__('First Name')" @change="(e) => setSort(e)" > <template #target="{ togglePopover }"> <Button class="!text-gray-600" variant="ghost" @click="togglePopover()" :label="__('Add Sort')" > <template #prefix> <FeatherIcon name="plus" class="h-4" /> </template> </Button> </template> </Autocomplete> <Button v-if="sortValues?.size" class="!text-gray-600" variant="ghost" :label="__('Clear Sort')" @click="clearSort(close)" /> </div> </div> </div> </template> </NestedPopover> </template> <script setup> import AscendingIcon from '@/components/Icons/AscendingIcon.vue' import DesendingIcon from '@/components/Icons/DesendingIcon.vue' import NestedPopover from '@/components/NestedPopover.vue' import SortIcon from '@/components/Icons/SortIcon.vue' import DragIcon from '@/components/Icons/DragIcon.vue' import Autocomplete from '@/components/frappe-ui/Autocomplete.vue' import { useSortable } from '@vueuse/integrations/useSortable' import { createResource } from 'frappe-ui' import { computed, nextTick, onMounted } from 'vue' const props = defineProps({ doctype: { type: String, required: true, }, hideLabel: { type: Boolean, default: false, }, }) const emit = defineEmits(['update']) const list = defineModel() const sortOptions = createResource({ url: 'crm.api.doc.sort_options', cache: ['sortOptions', props.doctype], params: { doctype: props.doctype, }, }) onMounted(() => { if (sortOptions.data?.length) return sortOptions.fetch() }) const sortValues = computed({ get: () => { if (!list.value?.data) return new Set() let allSortValues = list.value?.params?.order_by if (!allSortValues || !sortOptions.data) return new Set() if (allSortValues.trim() === 'modified desc') return new Set() allSortValues = allSortValues.split(', ').map((sortValue) => { const [fieldname, direction] = sortValue.split(' ') return { fieldname, direction } }) return new Set(allSortValues) }, set: (value) => { list.value.params.order_by = convertToString(value) }, }) const options = computed(() => { if (!sortOptions.data) return [] if (!sortValues.value.size) return sortOptions.data const selectedOptions = [...sortValues.value].map((sort) => sort.fieldname) restartSort() return sortOptions.data.filter((option) => { return !selectedOptions.includes(option.value) }) }) const sortSortable = useSortable('#sort-list', sortValues, { handle: '.handle', animation: 200, onEnd: () => apply(), }) function getSortLabel() { if (!sortValues.value.size) return __('Sort') let values = Array.from(sortValues.value) let label = sortOptions.data?.find( (option) => option.value === values[0].fieldname )?.label return label || sort.fieldname } function setSort(data) { sortValues.value.add({ fieldname: data.value, direction: 'asc' }) restartSort() apply() } function updateSort(data, index) { let oldSort = Array.from(sortValues.value)[index] sortValues.value.delete(oldSort) sortValues.value.add({ fieldname: data.value, direction: oldSort.direction, }) apply() } function removeSort(index) { sortValues.value.delete(Array.from(sortValues.value)[index]) apply() } function clearSort(close) { sortValues.value.clear() apply() close() } function apply() { nextTick(() => { emit('update', convertToString(sortValues.value)) }) } function convertToString(values) { let _sortValues = '' values.forEach((f) => { _sortValues += `${f.fieldname} ${f.direction}, ` }) _sortValues = _sortValues.slice(0, -2) return _sortValues } function restartSort() { sortSortable.stop() sortSortable.start() } </script>
2302_79757062/crm
frontend/src/components/SortBy.vue
Vue
agpl-3.0
8,865
<template> <Avatar :label="getUser(user).full_name" :image="getUser(user).user_image" v-bind="$attrs" /> </template> <script setup> import { usersStore } from '@/stores/users' import { Avatar } from 'frappe-ui' const props = defineProps({ user: { type: String, default: null, }, }) const { getUser } = usersStore() </script>
2302_79757062/crm
frontend/src/components/UserAvatar.vue
Vue
agpl-3.0
355
<template> <Dropdown :options="dropdownOptions" v-bind="$attrs"> <template v-slot="{ open }"> <button class="flex h-12 items-center rounded-md py-2 duration-300 ease-in-out" :class=" isCollapsed ? 'w-auto px-0' : open ? 'w-52 bg-white px-2 shadow-sm' : 'w-52 px-2 hover:bg-gray-200' " > <CRMLogo class="size-8 flex-shrink-0 rounded" /> <div class="flex flex-1 flex-col text-left duration-300 ease-in-out" :class=" isCollapsed ? 'ml-0 w-0 overflow-hidden opacity-0' : 'ml-2 w-auto opacity-100' " > <div class="text-base font-medium leading-none text-gray-900"> {{ __('CRM') }} </div> <div class="mt-1 text-sm leading-none text-gray-700"> {{ user.full_name }} </div> </div> <div class="duration-300 ease-in-out" :class=" isCollapsed ? 'ml-0 w-0 overflow-hidden opacity-0' : 'ml-2 w-auto opacity-100' " > <FeatherIcon name="chevron-down" class="size-4 text-gray-600" aria-hidden="true" /> </div> </button> </template> </Dropdown> <SettingsModal v-if="showSettingsModal" v-model="showSettingsModal" /> </template> <script setup> import SettingsModal from '@/components/Settings/SettingsModal.vue' import CRMLogo from '@/components/Icons/CRMLogo.vue' import Apps from '@/components/Apps.vue' import { sessionStore } from '@/stores/session' import { usersStore } from '@/stores/users' import { Dropdown } from 'frappe-ui' import { computed, ref, markRaw} from 'vue' const props = defineProps({ isCollapsed: { type: Boolean, default: false, }, }) const { logout } = sessionStore() const { getUser } = usersStore() const user = computed(() => getUser() || {}) const showSettingsModal = ref(false) let dropdownOptions = ref([ { group: 'Manage', hideLabel: true, items: [ { component: markRaw(Apps), }, { icon: 'life-buoy', label: computed(() => __('Support')), onClick: () => window.open('https://t.me/frappecrm', '_blank'), }, { icon: 'book-open', label: computed(() => __('Docs')), onClick: () => window.open('https://docs.frappe.io/crm', '_blank'), }, ], }, { group: 'Others', hideLabel: true, items: [ { icon: 'settings', label: computed(() => __('Settings')), onClick: () => (showSettingsModal.value = true), }, { icon: 'log-out', label: computed(() => __('Log out')), onClick: () => logout.submit(), }, ], }, ]) </script>
2302_79757062/crm
frontend/src/components/UserDropdown.vue
Vue
agpl-3.0
2,875
<template> <div class="flex items-center"> <router-link :to="{ name: routeName }" class="px-0.5 py-1 text-lg font-medium focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-400 text-gray-600 hover:text-gray-700" > {{ __(routeName) }} </router-link> <span class="mx-0.5 text-base text-gray-500" aria-hidden="true"> / </span> <Dropdown v-if="viewControls" :options="viewControls.viewsDropdownOptions"> <template #default="{ open }"> <Button variant="ghost" class="text-lg font-medium text-nowrap" :label="__(viewControls.currentView.label)" > <template #prefix> <Icon :icon="viewControls.currentView.icon" class="h-4" /> </template> <template #suffix> <FeatherIcon :name="open ? 'chevron-up' : 'chevron-down'" class="h-4 text-gray-800" /> </template> </Button> </template> <template #item="{ item, active }"> <button :class="[ active ? 'bg-gray-100' : 'text-gray-800', 'group flex gap-4 h-7 w-full justify-between items-center rounded px-2 text-base', ]" @click="item.onClick" > <div class="flex items-center"> <FeatherIcon v-if="item.icon && typeof item.icon === 'string'" :name="item.icon" class="mr-2 h-4 w-4 flex-shrink-0 text-gray-700" aria-hidden="true" /> <component class="mr-2 h-4 w-4 flex-shrink-0 text-gray-700" v-else-if="item.icon" :is="item.icon" /> <span class="whitespace-nowrap"> {{ item.label }} </span> </div> <div v-if="item.name" class="flex flex-row-reverse gap-2 items-center min-w-11" > <Dropdown :class="active ? 'block' : 'hidden'" placement="right-start" :options="viewControls.viewActions(item)" > <template #default="{ togglePopover }"> <Button variant="ghost" class="!size-5" icon="more-horizontal" @click.stop="togglePopover()" /> </template> </Dropdown> <FeatherIcon v-if="isCurrentView(item)" name="check" class="size-4 text-gray-700" /> </div> </button> </template> </Dropdown> </div> </template> <script setup> import Icon from '@/components/Icon.vue' import Dropdown from '@/components/frappe-ui/Dropdown.vue' const props = defineProps({ routeName: { type: String, required: true, }, }) const viewControls = defineModel() const isCurrentView = (item) => { return item.name === viewControls.value.currentView.name } </script>
2302_79757062/crm
frontend/src/components/ViewBreadcrumbs.vue
Vue
agpl-3.0
3,028
<template> <div v-if="isMobileView" class="flex flex-col justify-between gap-2 sm:px-5 px-3 py-4" > <div class="flex flex-col gap-2"> <div class="flex items-center justify-between gap-2 overflow-x-auto"> <div class="flex gap-2"> <Filter v-model="list" :doctype="doctype" :default_filters="filters" @update="updateFilter" /> <GroupBy v-if="route.params.viewType === 'group_by'" v-model="list" :doctype="doctype" :hideLabel="isMobileView" @update="updateGroupBy" /> </div> <div class="flex gap-2"> <Button :label="__('Refresh')" @click="reload()" :loading="isLoading"> <template #icon> <RefreshIcon class="h-4 w-4" /> </template> </Button> <SortBy v-if="route.params.viewType !== 'kanban'" v-model="list" :doctype="doctype" @update="updateSort" :hideLabel="isMobileView" /> <KanbanSettings v-if="route.params.viewType === 'kanban'" v-model="list" :doctype="doctype" @update="updateKanbanSettings" /> <ColumnSettings v-else-if="!options.hideColumnsButton" v-model="list" :doctype="doctype" :hideLabel="isMobileView" @update="(isDefault) => updateColumns(isDefault)" /> </div> </div> <div v-if="viewUpdated && route.query.view && (!view.public || isManager())" class="flex flex-row-reverse items-center gap-2 border-r pr-2" > <Button :label="__('Cancel')" @click="cancelChanges" /> <Button :label="__('Save Changes')" @click="saveView" /> </div> </div> </div> <div v-else class="flex items-center justify-between gap-2 px-5 py-4"> <FadedScrollableDiv class="flex flex-1 items-center overflow-x-auto -ml-1" orientation="horizontal" > <div v-for="filter in quickFilterList" :key="filter.name" class="m-1 min-w-36" > <QuickFilterField :filter="filter" @applyQuickFilter="(f, v) => applyQuickFilter(f, v)" /> </div> </FadedScrollableDiv> <div class="-ml-2 h-[70%] border-l" /> <div class="flex items-center gap-2"> <div v-if="viewUpdated && route.query.view && (!view.public || isManager())" class="flex items-center gap-2 border-r pr-2" > <Button :label="__('Cancel')" @click="cancelChanges" /> <Button :label="__('Save Changes')" @click="saveView" /> </div> <div class="flex items-center gap-2"> <Button :label="__('Refresh')" @click="reload()" :loading="isLoading"> <template #icon> <RefreshIcon class="h-4 w-4" /> </template> </Button> <GroupBy v-if="route.params.viewType === 'group_by'" v-model="list" :doctype="doctype" @update="updateGroupBy" /> <Filter v-model="list" :doctype="doctype" :default_filters="filters" @update="updateFilter" /> <SortBy v-if="route.params.viewType !== 'kanban'" v-model="list" :doctype="doctype" @update="updateSort" /> <KanbanSettings v-if="route.params.viewType === 'kanban'" v-model="list" :doctype="doctype" @update="updateKanbanSettings" /> <ColumnSettings v-else-if="!options.hideColumnsButton" v-model="list" :doctype="doctype" @update="(isDefault) => updateColumns(isDefault)" /> <Dropdown v-if=" !options.hideColumnsButton && route.params.viewType !== 'kanban' " :options="[ { group: __('Options'), hideLabel: true, items: [ { label: __('Export'), icon: () => h(FeatherIcon, { name: 'download', class: 'h-4 w-4' }), onClick: () => (showExportDialog = true), }, ], }, ]" > <template #default> <Button icon="more-horizontal" /> </template> </Dropdown> </div> </div> </div> <ViewModal v-model="showViewModal" v-model:view="viewModalObj" :doctype="doctype" :options="{ afterCreate: async (v) => { await reloadView() viewUpdated = false router.push({ name: route.name, params: { viewType: v.type || 'list' }, query: { view: v.name }, }) }, afterUpdate: () => { viewUpdated = false reloadView() list.reload() }, }" /> <Dialog v-model="showExportDialog" :options="{ title: __('Export'), actions: [ { label: __('Download'), variant: 'solid', onClick: () => exportRows(), }, ], }" > <template #body-content> <FormControl variant="outline" :label="__('Export Type')" type="select" :options="[ { label: __('Excel'), value: 'Excel', }, { label: __('CSV'), value: 'CSV', }, ]" v-model="export_type" :placeholder="__('Excel')" /> <div class="mt-3"> <FormControl type="checkbox" :label="__('Export All {0} Record(s)', [list.data.total_count])" v-model="export_all" /> </div> </template> </Dialog> </template> <script setup> import ListIcon from '@/components/Icons/ListIcon.vue' import KanbanIcon from '@/components/Icons/KanbanIcon.vue' import GroupByIcon from '@/components/Icons/GroupByIcon.vue' import QuickFilterField from '@/components/QuickFilterField.vue' import RefreshIcon from '@/components/Icons/RefreshIcon.vue' import EditIcon from '@/components/Icons/EditIcon.vue' import DuplicateIcon from '@/components/Icons/DuplicateIcon.vue' import PinIcon from '@/components/Icons/PinIcon.vue' import UnpinIcon from '@/components/Icons/UnpinIcon.vue' import ViewModal from '@/components/Modals/ViewModal.vue' import SortBy from '@/components/SortBy.vue' import Filter from '@/components/Filter.vue' import GroupBy from '@/components/GroupBy.vue' import FadedScrollableDiv from '@/components/FadedScrollableDiv.vue' import ColumnSettings from '@/components/ColumnSettings.vue' import KanbanSettings from '@/components/Kanban/KanbanSettings.vue' import { globalStore } from '@/stores/global' import { viewsStore } from '@/stores/views' import { usersStore } from '@/stores/users' import { isEmoji } from '@/utils' import { createResource, Dropdown, call, FeatherIcon, usePageMeta, } from 'frappe-ui' import { computed, ref, onMounted, watch, h, markRaw } from 'vue' import { useRouter, useRoute } from 'vue-router' import { useDebounceFn } from '@vueuse/core' import { isMobileView } from '@/composables/settings' import _ from 'lodash' const props = defineProps({ doctype: { type: String, required: true, }, filters: { type: Object, default: {}, }, options: { type: Object, default: { hideColumnsButton: false, defaultViewName: '', allowedViews: ['list'], }, }, }) const { $dialog } = globalStore() const { reload: reloadView, getView } = viewsStore() const { isManager } = usersStore() const list = defineModel() const loadMore = defineModel('loadMore') const resizeColumn = defineModel('resizeColumn') const updatedPageCount = defineModel('updatedPageCount') const route = useRoute() const router = useRouter() const defaultParams = ref('') const viewUpdated = ref(false) const showViewModal = ref(false) function getViewType() { let viewType = route.params.viewType || 'list' let types = { list: { name: 'list', label: __('List'), icon: markRaw(ListIcon), }, group_by: { name: 'group_by', label: __('Group By'), icon: markRaw(GroupByIcon), }, kanban: { name: 'kanban', label: __('Kanban'), icon: markRaw(KanbanIcon), }, } return types[viewType] } const currentView = computed(() => { let _view = getView(route.query.view, route.params.viewType, props.doctype) return { name: _view?.name || getViewType().name, label: _view?.label || props.options?.defaultViewName || getViewType().label, icon: _view?.icon || getViewType().icon, is_default: !_view || _view.is_default, } }) usePageMeta(() => { let label = currentView.value.label if (currentView.value.is_default) { let routeName = route.name label = `${routeName} - ${label}` } return { title: label, emoji: isEmoji(currentView.value.icon) ? currentView.value.icon : '', } }) const view = ref({ name: '', label: '', type: 'list', icon: '', filters: {}, order_by: 'modified desc', column_field: 'status', title_field: '', kanban_columns: '', kanban_fields: '', columns: '', rows: '', load_default_columns: false, pinned: false, public: false, }) const pageLength = computed(() => list.value?.data?.page_length) const pageLengthCount = computed(() => list.value?.data?.page_length_count) watch(loadMore, (value) => { if (!value) return updatePageLength(value, true) }) watch(resizeColumn, (value) => { if (!value) return updateColumns() }) watch(updatedPageCount, (value) => { if (!value) return updatePageLength(value) }) function getParams() { let _view = getView(route.query.view, route.params.viewType, props.doctype) const view_name = _view?.name || '' const view_type = _view?.type || route.params.viewType || 'list' const filters = (_view?.filters && JSON.parse(_view.filters)) || {} const order_by = _view?.order_by || 'modified desc' const group_by_field = _view?.group_by_field || 'owner' const columns = _view?.columns || '' const rows = _view?.rows || '' const column_field = _view?.column_field || 'status' const title_field = _view?.title_field || '' const kanban_columns = _view?.kanban_columns || '' const kanban_fields = _view?.kanban_fields || '' view.value = { name: view_name, label: _view?.label || getViewType().label, type: view_type, icon: _view?.icon || '', filters: filters, order_by: order_by, group_by_field: group_by_field, column_field: column_field, title_field: title_field, kanban_columns: kanban_columns, kanban_fields: kanban_fields, columns: columns, rows: rows, route_name: _view?.route_name || route.name, load_default_columns: _view?.row || true, pinned: _view?.pinned || false, public: _view?.public || false, } return { doctype: props.doctype, filters: filters, order_by: order_by, default_filters: props.filters, view: { custom_view_name: view_name, view_type: view_type, group_by_field: group_by_field, }, column_field: column_field, title_field: title_field, kanban_columns: kanban_columns, kanban_fields: kanban_fields, columns: columns, rows: rows, page_length: pageLength.value, page_length_count: pageLengthCount.value, } } list.value = createResource({ url: 'crm.api.doc.get_data', params: getParams(), cache: [props.doctype, route.query.view, route.params.viewType], onSuccess(data) { let cv = getView(route.query.view, route.params.viewType, props.doctype) let params = list.value.params ? list.value.params : getParams() defaultParams.value = { doctype: props.doctype, filters: params.filters, order_by: params.order_by, default_filters: props.filters, view: { custom_view_name: cv?.name || '', view_type: cv?.type || route.params.viewType || 'list', group_by_field: params?.view?.group_by_field || 'owner', }, column_field: data.column_field, title_field: data.title_field, kanban_columns: data.kanban_columns, kanban_fields: data.kanban_fields, columns: data.columns, rows: data.rows, page_length: params.page_length, page_length_count: params.page_length_count, } }, }) onMounted(() => useDebounceFn(reload, 100)()) const isLoading = computed(() => list.value?.loading) function reload() { list.value.params = getParams() list.value.reload() } const showExportDialog = ref(false) const export_type = ref('Excel') const export_all = ref(false) async function exportRows() { let fields = JSON.stringify(list.value.data.columns.map((f) => f.key)) let filters = JSON.stringify(list.value.params.filters) let order_by = list.value.params.order_by let page_length = list.value.params.page_length if (export_all.value) { page_length = list.value.data.total_count } window.location.href = `/api/method/frappe.desk.reportview.export_query?file_format_type=${export_type.value}&title=${props.doctype}&doctype=${props.doctype}&fields=${fields}&filters=${filters}&order_by=${order_by}&page_length=${page_length}&start=0&view=Report&with_comment_count=1` showExportDialog.value = false export_all.value = false export_type.value = 'Excel' } let defaultViews = [] let allowedViews = props.options.allowedViews || ['list'] if (allowedViews.includes('list')) { defaultViews.push({ name: 'list', label: __(props.options?.defaultViewName) || __('List'), icon: markRaw(ListIcon), onClick() { viewUpdated.value = false router.push({ name: route.name }) }, }) } if (allowedViews.includes('kanban')) { defaultViews.push({ name: 'kanban', label: __(props.options?.defaultViewName) || __('Kanban'), icon: markRaw(KanbanIcon), onClick() { viewUpdated.value = false router.push({ name: route.name, params: { viewType: 'kanban' } }) }, }) } if (allowedViews.includes('group_by')) { defaultViews.push({ name: 'group_by', label: __(props.options?.defaultViewName) || __('Group By'), icon: markRaw(GroupByIcon), onClick() { viewUpdated.value = false router.push({ name: route.name, params: { viewType: 'group_by' } }) }, }) } function getIcon(icon, type) { if (isEmoji(icon)) { return h('div', icon) } else if (!icon && type === 'group_by') { return markRaw(GroupByIcon) } else if (!icon && type === 'kanban') { return markRaw(KanbanIcon) } return icon || markRaw(ListIcon) } const viewsDropdownOptions = computed(() => { let _views = [ { group: __('Default Views'), hideLabel: true, items: defaultViews, }, ] if (list.value?.data?.views) { list.value.data.views.forEach((view) => { view.name = view.name view.label = __(view.label) view.type = view.type || 'list' view.icon = getIcon(view.icon, view.type) view.filters = typeof view.filters == 'string' ? JSON.parse(view.filters) : view.filters view.onClick = () => { viewUpdated.value = false router.push({ name: route.name, params: { viewType: view.type }, query: { view: view.name }, }) } }) let publicViews = list.value.data.views.filter((v) => v.public) let savedViews = list.value.data.views.filter( (v) => !v.pinned && !v.public && !v.is_default, ) let pinnedViews = list.value.data.views.filter((v) => v.pinned) savedViews.length && _views.push({ group: __('Saved Views'), items: savedViews, }) publicViews.length && _views.push({ group: __('Public Views'), items: publicViews, }) pinnedViews.length && _views.push({ group: __('Pinned Views'), items: pinnedViews, }) } _views.push({ group: __('Actions'), hideLabel: true, items: [ { label: __('Create View'), icon: 'plus', onClick: () => createView(), }, ], }) return _views }) const quickFilterList = computed(() => { let filters = [{ name: 'name', label: __('ID') }] if (quickFilters.data) { filters.push(...quickFilters.data) } filters.forEach((filter) => { filter['value'] = filter.type == 'Check' ? false : '' if (list.value.params?.filters[filter.name]) { let value = list.value.params.filters[filter.name] if (Array.isArray(value)) { if ( (['Check', 'Select', 'Link', 'Date', 'Datetime'].includes( filter.type, ) && value[0]?.toLowerCase() == 'like') || value[0]?.toLowerCase() != 'like' ) return filter['value'] = value[1]?.replace(/%/g, '') } else { filter['value'] = value.replace(/%/g, '') } } }) return filters }) const quickFilters = createResource({ url: 'crm.api.doc.get_quick_filters', params: { doctype: props.doctype }, cache: ['Quick Filters', props.doctype], auto: true, }) function applyQuickFilter(filter, value) { let filters = { ...list.value.params.filters } let field = filter.name if (value) { if (['Check', 'Select', 'Link', 'Date', 'Datetime'].includes(filter.type)) { filters[field] = value } else { filters[field] = ['LIKE', `%${value}%`] } filter['value'] = value } else { delete filters[field] filter['value'] = '' } updateFilter(filters) } function updateFilter(filters) { viewUpdated.value = true if (!defaultParams.value) { defaultParams.value = getParams() } list.value.params = defaultParams.value list.value.params.filters = filters view.value.filters = filters list.value.reload() if (!route.query.view) { create_or_update_default_view() } } function updateSort(order_by) { viewUpdated.value = true if (!defaultParams.value) { defaultParams.value = getParams() } list.value.params = defaultParams.value list.value.params.order_by = order_by view.value.order_by = order_by list.value.reload() if (!route.query.view) { create_or_update_default_view() } } function updateGroupBy(group_by_field) { viewUpdated.value = true if (!defaultParams.value) { defaultParams.value = getParams() } list.value.params = defaultParams.value list.value.params.view.group_by_field = group_by_field view.value.group_by_field = group_by_field list.value.reload() if (!route.query.view) { create_or_update_default_view() } } function updateColumns(obj) { if (!obj) { obj = { columns: list.value.data.columns, rows: list.value.data.rows, isDefault: false, } } if (!defaultParams.value) { defaultParams.value = getParams() } defaultParams.value.columns = view.value.columns = obj.isDefault ? '' : obj.columns defaultParams.value.rows = view.value.rows = obj.isDefault ? '' : obj.rows view.value.load_default_columns = obj.isDefault if (obj.reset) { defaultParams.value.columns = getParams().columns defaultParams.value.rows = getParams().rows } if (obj.reload) { list.value.params = defaultParams.value list.value.reload() } viewUpdated.value = true if (!route.query.view) { create_or_update_default_view() } } async function updateKanbanSettings(data) { if (data.item && data.to) { await call('frappe.client.set_value', { doctype: props.doctype, name: data.item, fieldname: view.value.column_field, value: data.to, }) } let isDirty = viewUpdated.value viewUpdated.value = true if (!defaultParams.value) { defaultParams.value = getParams() } list.value.params = defaultParams.value if (data.kanban_columns) { list.value.params.kanban_columns = data.kanban_columns view.value.kanban_columns = data.kanban_columns } if (data.kanban_fields) { list.value.params.kanban_fields = data.kanban_fields view.value.kanban_fields = data.kanban_fields } if (data.column_field && data.column_field != view.value.column_field) { list.value.params.column_field = data.column_field view.value.column_field = data.column_field list.value.params.kanban_columns = '' view.value.kanban_columns = '' } if (data.title_field && data.title_field != view.value.title_field) { list.value.params.title_field = data.title_field view.value.title_field = data.title_field } list.value.reload() if (!route.query.view) { create_or_update_default_view() } else if (!data.column_field) { if (isDirty) { $dialog({ title: __('Unsaved Changes'), message: __('You have unsaved changes. Do you want to save them?'), variant: 'danger', actions: [ { label: __('Update'), variant: 'solid', onClick: (close) => { update_custom_view() close() }, }, ], }) } else { update_custom_view() } } } function loadMoreKanban(columnName) { let columns = list.value.data.kanban_columns || '[]' if (typeof columns === 'string') { columns = JSON.parse(columns) } let column = columns.find((c) => c.name == columnName) if (!column.page_length) { column.page_length = 40 } else { column.page_length += 20 } list.value.params.kanban_columns = columns view.value.kanban_columns = columns list.value.reload() } function create_or_update_default_view() { if (route.query.view) return view.value.doctype = props.doctype call( 'crm.fcrm.doctype.crm_view_settings.crm_view_settings.create_or_update_default_view', { view: view.value, }, ).then(() => { reloadView() view.value = { label: view.value.label, type: view.value.type || 'list', icon: view.value.icon, name: view.value.name, filters: defaultParams.value.filters, order_by: defaultParams.value.order_by, group_by_field: defaultParams.value.view?.group_by_field, column_field: defaultParams.value.column_field, title_field: defaultParams.value.title_field, kanban_columns: defaultParams.value.kanban_columns, kanban_fields: defaultParams.value.kanban_fields, columns: defaultParams.value.columns, rows: defaultParams.value.rows, route_name: route.name, load_default_columns: view.value.load_default_columns, } viewUpdated.value = false }) } function update_custom_view() { viewUpdated.value = false view.value = { doctype: props.doctype, label: view.value.label, type: view.value.type || 'list', icon: view.value.icon, name: view.value.name, filters: defaultParams.value.filters, order_by: defaultParams.value.order_by, group_by_field: defaultParams.value.view.group_by_field, column_field: defaultParams.value.column_field, title_field: defaultParams.value.title_field, kanban_columns: defaultParams.value.kanban_columns, kanban_fields: defaultParams.value.kanban_fields, columns: defaultParams.value.columns, rows: defaultParams.value.rows, route_name: route.name, load_default_columns: view.value.load_default_columns, } call('crm.fcrm.doctype.crm_view_settings.crm_view_settings.update', { view: view.value, }).then(() => reloadView()) } function updatePageLength(value, loadMore = false) { if (!defaultParams.value) { defaultParams.value = getParams() } list.value.params = defaultParams.value if (loadMore) { list.value.params.page_length += list.value.params.page_length_count } else { if ( value == list.value.params.page_length && value == list.value.params.page_length_count ) return list.value.params.page_length = value list.value.params.page_length_count = value } list.value.reload() } // View Actions const viewActions = (view) => { let isDefault = typeof view.name === 'string' let _view = getView(view.name) let actions = [ { group: __('Default Views'), hideLabel: true, items: [ { label: __('Duplicate'), icon: () => h(DuplicateIcon, { class: 'h-4 w-4' }), onClick: () => duplicateView(_view), }, ], }, ] if (!isDefault && (!_view.public || isManager())) { actions[0].items.push({ label: __('Edit'), icon: () => h(EditIcon, { class: 'h-4 w-4' }), onClick: () => editView(_view), }) if (!_view.public) { actions[0].items.push({ label: _view.pinned ? __('Unpin View') : __('Pin View'), icon: () => h(_view.pinned ? UnpinIcon : PinIcon, { class: 'h-4 w-4' }), onClick: () => pinView(_view), }) } if (isManager()) { actions[0].items.push({ label: _view.public ? __('Make Private') : __('Make Public'), icon: () => h(FeatherIcon, { name: _view.public ? 'lock' : 'unlock', class: 'h-4 w-4', }), onClick: () => publicView(_view), }) } actions.push({ group: __('Delete View'), hideLabel: true, items: [ { label: __('Delete'), icon: 'trash-2', onClick: () => $dialog({ title: __('Delete View'), message: __('Are you sure you want to delete "{0}" view?', [ _view.label, ]), variant: 'danger', actions: [ { label: __('Delete'), variant: 'solid', theme: 'red', onClick: (close) => deleteView(_view, close), }, ], }), }, ], }) } return actions } const viewModalObj = ref({}) function createView() { view.value.name = '' view.value.label = '' view.value.icon = '' viewModalObj.value = view.value viewModalObj.value.mode = 'create' showViewModal.value = true } function duplicateView(v) { v.label = v.label + __(' (New)') viewModalObj.value = v viewModalObj.value.mode = 'duplicate' showViewModal.value = true } function editView(v) { viewModalObj.value = v viewModalObj.value.mode = 'edit' showViewModal.value = true } function publicView(v) { call('crm.fcrm.doctype.crm_view_settings.crm_view_settings.public', { name: v.name, value: !v.public, }).then(() => { v.public = !v.public reloadView() list.value.reload() }) } function pinView(v) { call('crm.fcrm.doctype.crm_view_settings.crm_view_settings.pin', { name: v.name, value: !v.pinned, }).then(() => { v.pinned = !v.pinned reloadView() list.value.reload() }) } function deleteView(v, close) { call('crm.fcrm.doctype.crm_view_settings.crm_view_settings.delete', { name: v.name, }).then(() => { router.push({ name: route.name }) reloadView() list.value.reload() }) close() } function cancelChanges() { reload() viewUpdated.value = false } function saveView() { view.value = { label: view.value.label, type: view.value.type || 'list', icon: view.value.icon, name: view.value.name, filters: defaultParams.value.filters, order_by: defaultParams.value.order_by, group_by_field: defaultParams.value.view.group_by_field, column_field: defaultParams.value.column_field, title_field: defaultParams.value.title_field, kanban_columns: defaultParams.value.kanban_columns, kanban_fields: defaultParams.value.kanban_fields, columns: defaultParams.value.columns, rows: defaultParams.value.rows, route_name: route.name, load_default_columns: view.value.load_default_columns, } viewModalObj.value = view.value viewModalObj.value.mode = 'edit' showViewModal.value = true } function applyFilter({ event, idx, column, item, firstColumn }) { let restrictedFieldtypes = ['Duration', 'Datetime', 'Time'] if (restrictedFieldtypes.includes(column.type) || idx === 0) return if (idx === 1 && firstColumn.key == '_liked_by') return event.stopPropagation() event.preventDefault() let filters = { ...list.value.params.filters } let value = item.name || item.label || item if (value) { filters[column.key] = value } else { delete filters[column.key] } if (column.key == '_assign') { if (item.length > 1) { let target = event.target.closest('.user-avatar') if (target) { let name = target.getAttribute('data-name') filters['_assign'] = ['LIKE', `%${name}%`] } } else { filters['_assign'] = ['LIKE', `%${item[0].name}%`] } } updateFilter(filters) } function applyLikeFilter() { let filters = { ...list.value.params.filters } if (!filters._liked_by) { filters['_liked_by'] = ['LIKE', '%@me%'] } else { delete filters['_liked_by'] } updateFilter(filters) } function likeDoc({ name, liked }) { createResource({ url: 'frappe.desk.like.toggle_like', params: { doctype: props.doctype, name: name, add: liked ? 'No' : 'Yes' }, auto: true, onSuccess: () => reload(), }) } defineExpose({ applyFilter, applyLikeFilter, likeDoc, updateKanbanSettings, loadMoreKanban, viewActions, viewsDropdownOptions, currentView, }) // Watchers watch( () => getView(route.query.view, route.params.viewType, props.doctype), (value, old_value) => { if (_.isEqual(value, old_value)) return reload() }, { deep: true }, ) watch([() => route, () => route.params.viewType], (value, old_value) => { if (value[0] === old_value[0] && value[1] === value[0]) return reload() }) </script>
2302_79757062/crm
frontend/src/components/ViewControls.vue
Vue
agpl-3.0
29,972
<template> <Combobox v-model="selectedValue" nullable v-slot="{ open: isComboboxOpen }"> <Popover class="w-full" v-model:show="showOptions"> <template #target="{ open: openPopover, togglePopover }"> <slot name="target" v-bind="{ open: openPopover, togglePopover, isOpen: showOptions, selectedValue, displayValue, }" > <div class="w-full"> <button class="flex w-full items-center justify-between focus:outline-none" :class="inputClasses" @click="() => togglePopover()" > <div class="flex items-center"> <slot name="prefix" /> <span class="overflow-hidden text-ellipsis whitespace-nowrap text-base leading-5" v-if="selectedValue" > {{ displayValue(selectedValue) }} </span> <span class="text-base leading-5 text-gray-500" v-else> {{ placeholder || '' }} </span> </div> <FeatherIcon name="chevron-down" class="h-4 w-4 text-gray-600" aria-hidden="true" /> </button> </div> </slot> </template> <template #body="{ isOpen }"> <div v-show="isOpen"> <div class="mt-1 rounded-lg bg-white py-1 text-base shadow-2xl"> <div class="relative px-1.5 pt-0.5"> <ComboboxInput ref="search" class="form-input w-full" type="text" @change=" (e) => { query = e.target.value } " :value="query" autocomplete="off" placeholder="Search" /> <button class="absolute right-1.5 inline-flex h-7 w-7 items-center justify-center" @click="selectedValue = null" > <FeatherIcon name="x" class="w-4" /> </button> </div> <ComboboxOptions class="my-1 max-h-[12rem] overflow-y-auto px-1.5" static > <div class="mt-1.5" v-for="group in groups" :key="group.key" v-show="group.items.length > 0" > <div v-if="group.group && !group.hideLabel" class="px-2.5 py-1.5 text-sm font-medium text-gray-500" > {{ group.group }} </div> <ComboboxOption as="template" v-for="option in group.items" :key="option.value" :value="option" v-slot="{ active, selected }" > <li :class="[ 'flex items-center rounded px-2.5 py-1.5 text-base', { 'bg-gray-100': active }, ]" > <slot name="item-prefix" v-bind="{ active, selected, option }" /> <slot name="item-label" v-bind="{ active, selected, option }" > {{ option.label }} </slot> </li> </ComboboxOption> </div> <li v-if="groups.length == 0" class="mt-1.5 rounded-md px-2.5 py-1.5 text-base text-gray-600" > No results found </li> </ComboboxOptions> <div v-if="slots.footer" class="border-t p-1.5 pb-0.5"> <slot name="footer" v-bind="{ value: search?.el._value, close }" ></slot> </div> </div> </div> </template> </Popover> </Combobox> </template> <script setup> import { Combobox, ComboboxInput, ComboboxOptions, ComboboxOption, } from '@headlessui/vue' import { Popover, Button, FeatherIcon } from 'frappe-ui' import { ref, computed, useAttrs, useSlots, watch, nextTick } from 'vue' const props = defineProps({ modelValue: { type: String, default: '', }, options: { type: Array, default: () => [], }, size: { type: String, default: 'md', }, variant: { type: String, default: 'subtle', }, placeholder: { type: String, default: '', }, disabled: { type: Boolean, default: false, }, filterable: { type: Boolean, default: true, }, }) const emit = defineEmits(['update:modelValue', 'update:query', 'change']) const query = ref('') const showOptions = ref(false) const search = ref(null) const attrs = useAttrs() const slots = useSlots() const valuePropPassed = computed(() => 'value' in attrs) const selectedValue = computed({ get() { return valuePropPassed.value ? attrs.value : props.modelValue }, set(val) { query.value = '' if (val) { showOptions.value = false } emit(valuePropPassed.value ? 'change' : 'update:modelValue', val) }, }) function close() { showOptions.value = false } const groups = computed(() => { if (!props.options || props.options.length == 0) return [] let groups = props.options[0]?.group ? props.options : [{ group: '', items: props.options }] return groups .map((group, i) => { return { key: i, group: group.group, hideLabel: group.hideLabel || false, items: props.filterable ? filterOptions(group.items) : group.items, } }) .filter((group) => group.items.length > 0) }) function filterOptions(options) { if (!query.value) { return options } return options.filter((option) => { let searchTexts = [option.label, option.value] return searchTexts.some((text) => (text || '').toString().toLowerCase().includes(query.value.toLowerCase()) ) }) } function displayValue(option) { if (typeof option === 'string') { let allOptions = groups.value.flatMap((group) => group.items) let selectedOption = allOptions.find((o) => o.value === option) return selectedOption?.label || option } return option?.label } watch(query, (q) => { emit('update:query', q) }) watch(showOptions, (val) => { if (val) { nextTick(() => { search.value.el.focus() }) } }) const textColor = computed(() => { return props.disabled ? 'text-gray-600' : 'text-gray-800' }) const inputClasses = computed(() => { let sizeClasses = { sm: 'text-base rounded h-7', md: 'text-base rounded h-8', lg: 'text-lg rounded-md h-10', xl: 'text-xl rounded-md h-10', }[props.size] let paddingClasses = { sm: 'py-1.5 px-2', md: 'py-1.5 px-2.5', lg: 'py-1.5 px-3', xl: 'py-1.5 px-3', }[props.size] let variant = props.disabled ? 'disabled' : props.variant let variantClasses = { subtle: 'border border-gray-100 bg-gray-100 placeholder-gray-500 hover:border-gray-200 hover:bg-gray-200 focus:bg-white focus:border-gray-500 focus:shadow-sm focus:ring-0 focus-visible:ring-2 focus-visible:ring-gray-400', outline: 'border border-gray-300 bg-white placeholder-gray-500 hover:border-gray-400 hover:shadow-sm focus:bg-white focus:border-gray-500 focus:shadow-sm focus:ring-0 focus-visible:ring-2 focus-visible:ring-gray-400', disabled: [ 'border bg-gray-50 placeholder-gray-400', props.variant === 'outline' ? 'border-gray-300' : 'border-transparent', ], }[variant] return [ sizeClasses, paddingClasses, variantClasses, textColor.value, 'transition-colors w-full', ] }) defineExpose({ query }) </script>
2302_79757062/crm
frontend/src/components/frappe-ui/Autocomplete.vue
Vue
agpl-3.0
8,055
<template> <Menu as="div" class="relative inline-block text-left" v-slot="{ open }"> <Popover :transition="dropdownTransition" :show="open" :placement="popoverPlacement" > <template #target="{ togglePopover }"> <MenuButton as="template"> <slot v-if="$slots.default" v-bind="{ open, togglePopover }" /> <Button v-else :active="open" v-bind="button"> {{ button ? button?.label || null : 'Options' }} </Button> </MenuButton> </template> <template #body> <div class="rounded-lg bg-white shadow-2xl ring-1 ring-black ring-opacity-5 focus:outline-none" :class="{ 'mt-2': ['bottom', 'left', 'right'].includes(placement), 'ml-2': placement == 'right-start', }" > <MenuItems class="min-w-40 divide-y divide-gray-100" :class="{ 'left-0 origin-top-left': placement == 'left', 'right-0 origin-top-right': placement == 'right', 'inset-x-0 origin-top': placement == 'center', 'mt-0 origin-top-right': placement == 'right-start', }" > <div v-for="group in groups" :key="group.key" class="p-1.5"> <div v-if="group.group && !group.hideLabel" class="flex h-7 items-center px-2 text-sm font-medium text-gray-500" > {{ group.group }} </div> <MenuItem v-for="item in group.items" :key="item.label" v-slot="{ active }" > <slot name="item" v-bind="{ item, active }"> <component v-if="item.component" :is="item.component" :active="active" /> <button v-else :class="[ active ? 'bg-gray-100' : 'text-gray-800', 'group flex h-7 w-full items-center rounded px-2 text-base', ]" @click="item.onClick" > <FeatherIcon v-if="item.icon && typeof item.icon === 'string'" :name="item.icon" class="mr-2 h-4 w-4 flex-shrink-0 text-gray-700" aria-hidden="true" /> <component class="mr-2 h-4 w-4 flex-shrink-0 text-gray-700" v-else-if="item.icon" :is="item.icon" /> <span class="whitespace-nowrap"> {{ item.label }} </span> </button> </slot> </MenuItem> </div> </MenuItems> <div v-if="slots.footer" class="border-t p-1.5"> <slot name="footer"></slot> </div> </div> </template> </Popover> </Menu> </template> <script setup> import { Menu, MenuButton, MenuItems, MenuItem } from '@headlessui/vue' import { Popover, Button, FeatherIcon } from 'frappe-ui' import { computed, useSlots } from 'vue' import { useRouter } from 'vue-router' const props = defineProps({ button: { type: Object, default: null, }, options: { type: Array, default: () => [], }, placement: { type: String, default: 'left', }, }) const router = useRouter() const slots = useSlots() const dropdownTransition = { enterActiveClass: 'transition duration-100 ease-out', enterFromClass: 'transform scale-95 opacity-0', enterToClass: 'transform scale-100 opacity-100', leaveActiveClass: 'transition duration-75 ease-in', leaveFromClass: 'transform scale-100 opacity-100', leaveToClass: 'transform scale-95 opacity-0', } const groups = computed(() => { let groups = props.options[0]?.group ? props.options : [{ group: '', items: props.options }] return groups.map((group, i) => { return { key: i, group: group.group, hideLabel: group.hideLabel || false, items: filterOptions(group.items), } }) }) const popoverPlacement = computed(() => { if (props.placement === 'left') return 'bottom-start' if (props.placement === 'right') return 'bottom-end' if (props.placement === 'center') return 'bottom-center' if (props.placement === 'right-start') return 'right-start' return 'bottom' }) function normalizeDropdownItem(option) { let onClick = option.onClick || null if (!onClick && option.route && router) { onClick = () => router.push(option.route) } return { name: option.name, label: option.label, icon: option.icon, group: option.group, component: option.component, onClick, } } function filterOptions(options) { return (options || []) .filter(Boolean) .filter((option) => (option.condition ? option.condition() : true)) .map((option) => normalizeDropdownItem(option)) } </script>
2302_79757062/crm
frontend/src/components/frappe-ui/Dropdown.vue
Vue
agpl-3.0
5,120
<template> <div ref="reference"> <div ref="target" :class="['flex', $attrs.class]" @click="updatePosition" @focusin="updatePosition" @keydown="updatePosition" @mouseover="onMouseover" @mouseleave="onMouseleave" > <slot name="target" v-bind="{ togglePopover, updatePosition, open, close, isOpen }" /> </div> <teleport to="#frappeui-popper-root"> <div ref="popover" class="relative z-[100]" :class="[popoverContainerClass, popoverClass]" :style="{ minWidth: targetWidth ? targetWidth + 'px' : null }" @mouseover="pointerOverTargetOrPopup = true" @mouseleave="onMouseleave" > <transition v-bind="popupTransition"> <div v-show="isOpen"> <slot name="body" v-bind="{ togglePopover, updatePosition, open, close, isOpen }" > <div class="rounded-lg border border-gray-100 bg-white shadow-xl"> <slot name="body-main" v-bind="{ togglePopover, updatePosition, open, close, isOpen, }" /> </div> </slot> </div> </transition> </div> </teleport> </div> </template> <script> import { createPopper } from '@popperjs/core' export default { name: 'Popover', inheritAttrs: false, props: { show: { default: undefined, }, trigger: { type: String, default: 'click', // click, hover }, hoverDelay: { type: Number, default: 0, }, leaveDelay: { type: Number, default: 0, }, placement: { type: String, default: 'bottom-start', }, popoverClass: [String, Object, Array], transition: { default: null, }, hideOnBlur: { default: true, }, }, emits: ['open', 'close', 'update:show'], expose: ['open', 'close'], data() { return { popoverContainerClass: 'body-container', showPopup: false, targetWidth: null, pointerOverTargetOrPopup: false, } }, watch: { show(val) { if (val) { this.open() } else { this.close() } }, }, created() { if (typeof window === 'undefined') return if (!document.getElementById('frappeui-popper-root')) { const root = document.createElement('div') root.id = 'frappeui-popper-root' document.body.appendChild(root) } }, mounted() { this.listener = (e) => { const clickedElement = e.target const reference = this.$refs.reference const popoverBody = this.$refs.popover const insideClick = clickedElement === reference || clickedElement === popoverBody || reference?.contains(clickedElement) || popoverBody?.contains(clickedElement) if (insideClick) { return } const root = document.getElementById('frappeui-popper-root') const insidePopoverRoot = root.contains(clickedElement) if (!insidePopoverRoot) { return this.close() } const bodyClass = `.${this.popoverContainerClass}` const clickedElementBody = clickedElement?.closest(bodyClass) const currentPopoverBody = reference?.closest(bodyClass) const isSiblingClicked = clickedElementBody && currentPopoverBody && clickedElementBody === currentPopoverBody if (isSiblingClicked) { this.close() } } if (this.hideOnBlur) { document.addEventListener('click', this.listener) document.addEventListener('mousedown', this.listener) } this.$nextTick(() => { this.targetWidth = this.$refs['target'].clientWidth }) }, beforeDestroy() { this.popper && this.popper.destroy() document.removeEventListener('click', this.listener) document.removeEventListener('mousedown', this.listener) }, computed: { showPropPassed() { return this.show != null }, isOpen: { get() { if (this.showPropPassed) { return this.show } return this.showPopup }, set(val) { val = Boolean(val) if (this.showPropPassed) { this.$emit('update:show', val) } else { this.showPopup = val } if (val === false) { this.$emit('close') } else if (val === true) { this.$emit('open') } }, }, popupTransition() { let templates = { default: { enterActiveClass: 'transition duration-150 ease-out', enterFromClass: 'translate-y-1 opacity-0', enterToClass: 'translate-y-0 opacity-100', leaveActiveClass: 'transition duration-150 ease-in', leaveFromClass: 'translate-y-0 opacity-100', leaveToClass: 'translate-y-1 opacity-0', }, } if (typeof this.transition === 'string') { return templates[this.transition] } return this.transition }, }, methods: { setupPopper() { if (!this.popper) { this.popper = createPopper(this.$refs.reference, this.$refs.popover, { placement: this.placement, }) } else { this.updatePosition() } }, updatePosition() { this.popper && this.popper.update() }, togglePopover(flag) { if (flag instanceof Event) { flag = null } if (flag == null) { flag = !this.isOpen } flag = Boolean(flag) if (flag) { this.open() } else { this.close() } }, open() { this.isOpen = true this.$nextTick(() => this.setupPopper()) }, close() { this.isOpen = false }, onMouseover() { this.pointerOverTargetOrPopup = true if (this.leaveTimer) { clearTimeout(this.leaveTimer) this.leaveTimer = null } if (this.trigger === 'hover') { if (this.hoverDelay) { this.hoverTimer = setTimeout(() => { if (this.pointerOverTargetOrPopup) { this.open() } }, Number(this.hoverDelay) * 1000) } else { this.open() } } }, onMouseleave(e) { this.pointerOverTargetOrPopup = false if (this.hoverTimer) { clearTimeout(this.hoverTimer) this.hoverTimer = null } if (this.trigger === 'hover') { if (this.leaveTimer) { clearTimeout(this.leaveTimer) } if (this.leaveDelay) { this.leaveTimer = setTimeout(() => { if (!this.pointerOverTargetOrPopup) { this.close() } }, Number(this.leaveDelay) * 1000) } else { if (!this.pointerOverTargetOrPopup) { this.close() } } } }, }, } </script>
2302_79757062/crm
frontend/src/components/frappe-ui/Popover.vue
Vue
agpl-3.0
7,043
import { createResource } from 'frappe-ui' import { computed, ref } from 'vue' export const whatsappEnabled = ref(false) export const isWhatsappInstalled = ref(false) createResource({ url: 'crm.api.whatsapp.is_whatsapp_enabled', cache: 'Is Whatsapp Enabled', auto: true, onSuccess: (data) => { whatsappEnabled.value = Boolean(data) }, }) createResource({ url: 'crm.api.whatsapp.is_whatsapp_installed', cache: 'Is Whatsapp Installed', auto: true, onSuccess: (data) => { isWhatsappInstalled.value = Boolean(data) }, }) export const callEnabled = ref(false) createResource({ url: 'crm.integrations.twilio.api.is_enabled', cache: 'Is Twilio Enabled', auto: true, onSuccess: (data) => { callEnabled.value = Boolean(data) }, }) export const mobileSidebarOpened = ref(false) export const isMobileView = computed(() => window.innerWidth < 768)
2302_79757062/crm
frontend/src/composables/settings.js
JavaScript
agpl-3.0
882
import { getCurrentInstance } from 'vue' export function is_twilio_enabled() { const app = getCurrentInstance() return app.appContext.config.globalProperties.is_twilio_enabled }
2302_79757062/crm
frontend/src/composables/twilio.js
JavaScript
agpl-3.0
183
@import './assets/Inter/inter.css'; @import 'frappe-ui/src/style.css'; @layer components { .prose-f { @apply break-all max-w-none prose prose-code:break-all prose-code:whitespace-pre-wrap prose-img:border prose-img:rounded-lg prose-sm prose-table:table-fixed prose-td:border prose-td:border-gray-300 prose-td:p-2 prose-td:relative prose-th:bg-gray-100 prose-th:border prose-th:border-gray-300 prose-th:p-2 prose-th:relative } }
2302_79757062/crm
frontend/src/index.css
CSS
agpl-3.0
468
import './index.css' import { createApp } from 'vue' import { createPinia } from 'pinia' import { createDialog } from './utils/dialogs' import { initSocket } from './socket' import router from './router' import translationPlugin from './translation' import { posthogPlugin } from './telemetry' import App from './App.vue' import { FrappeUI, Button, Input, TextInput, FormControl, ErrorMessage, Dialog, Alert, Badge, setConfig, frappeRequest, FeatherIcon, } from 'frappe-ui' let globalComponents = { Button, TextInput, Input, FormControl, ErrorMessage, Dialog, Alert, Badge, FeatherIcon, } // create a pinia instance let pinia = createPinia() let app = createApp(App) setConfig('resourceFetcher', frappeRequest) app.use(FrappeUI) app.use(pinia) app.use(router) app.use(translationPlugin) app.use(posthogPlugin) for (let key in globalComponents) { app.component(key, globalComponents[key]) } app.config.globalProperties.$dialog = createDialog let socket if (import.meta.env.DEV) { frappeRequest({ url: '/api/method/crm.www.crm.get_context_for_dev' }).then( (values) => { for (let key in values) { window[key] = values[key] } socket = initSocket() app.config.globalProperties.$socket = socket app.mount('#app') }, ) } else { socket = initSocket() app.config.globalProperties.$socket = socket app.mount('#app') } if (import.meta.env.DEV) { window.$dialog = createDialog }
2302_79757062/crm
frontend/src/main.js
JavaScript
agpl-3.0
1,479
<template> <LayoutHeader> <template #left-header> <ViewBreadcrumbs v-model="viewControls" routeName="Call Logs" /> </template> <template #right-header> <CustomActions v-if="callLogsListView?.customListActions" :actions="callLogsListView.customListActions" /> </template> </LayoutHeader> <ViewControls ref="viewControls" v-model="callLogs" v-model:loadMore="loadMore" v-model:resizeColumn="triggerResize" v-model:updatedPageCount="updatedPageCount" doctype="CRM Call Log" /> <CallLogsListView ref="callLogsListView" v-if="callLogs.data && rows.length" v-model="callLogs.data.page_length_count" v-model:list="callLogs" :rows="rows" :columns="callLogs.data.columns" :options="{ showTooltip: false, resizeColumn: true, rowCount: callLogs.data.row_count, totalCount: callLogs.data.total_count, }" @showCallLog="showCallLog" @loadMore="() => loadMore++" @columnWidthUpdated="() => triggerResize++" @updatePageCount="(count) => (updatedPageCount = count)" @applyFilter="(data) => viewControls.applyFilter(data)" @applyLikeFilter="(data) => viewControls.applyLikeFilter(data)" @likeDoc="(data) => viewControls.likeDoc(data)" /> <div v-else-if="callLogs.data" class="flex h-full items-center justify-center" > <div class="flex flex-col items-center gap-3 text-xl font-medium text-gray-500" > <PhoneIcon class="h-10 w-10" /> <span>{{ __('No {0} Found', [__('Logs')]) }}</span> </div> </div> <CallLogModal v-model="showCallLogModal" :name="selectedCallLog" /> </template> <script setup> import ViewBreadcrumbs from '@/components/ViewBreadcrumbs.vue' import CustomActions from '@/components/CustomActions.vue' import PhoneIcon from '@/components/Icons/PhoneIcon.vue' import LayoutHeader from '@/components/LayoutHeader.vue' import ViewControls from '@/components/ViewControls.vue' import CallLogsListView from '@/components/ListViews/CallLogsListView.vue' import CallLogModal from '@/components/Modals/CallLogModal.vue' import { getCallLogDetail } from '@/utils/callLog' import { computed, ref } from 'vue' const callLogsListView = ref(null) // callLogs data is loaded in the ViewControls component const callLogs = ref({}) const loadMore = ref(1) const triggerResize = ref(1) const updatedPageCount = ref(20) const viewControls = ref(null) const rows = computed(() => { if ( !callLogs.value?.data?.data || !['list', 'group_by'].includes(callLogs.value.data.view_type) ) return [] return callLogs.value?.data.data.map((callLog) => { let _rows = {} callLogs.value?.data.rows.forEach((row) => { _rows[row] = getCallLogDetail(row, callLog) }) return _rows }) }) const showCallLogModal = ref(false) const selectedCallLog = ref(null) function showCallLog(name) { selectedCallLog.value = name showCallLogModal.value = true } </script>
2302_79757062/crm
frontend/src/pages/CallLogs.vue
Vue
agpl-3.0
2,985
<template> <LayoutHeader v-if="contact.data"> <template #left-header> <Breadcrumbs :items="breadcrumbs"> <template #prefix="{ item }"> <Icon v-if="item.icon" :icon="item.icon" class="mr-2 h-4" /> </template> </Breadcrumbs> </template> </LayoutHeader> <div v-if="contact.data" class="flex h-full flex-col overflow-hidden"> <FileUploader @success="changeContactImage" :validateFile="validateFile"> <template #default="{ openFileSelector, error }"> <div class="flex items-start justify-start gap-6 p-5 sm:items-center"> <div class="group relative h-24 w-24"> <Avatar size="3xl" class="h-24 w-24" :label="contact.data.full_name" :image="contact.data.image" /> <component :is="contact.data.image ? Dropdown : 'div'" v-bind=" contact.data.image ? { options: [ { icon: 'upload', label: contact.data.image ? __('Change image') : __('Upload image'), onClick: openFileSelector, }, { icon: 'trash-2', label: __('Remove image'), onClick: () => changeContactImage(''), }, ], } : { onClick: openFileSelector } " class="!absolute bottom-0 left-0 right-0" > <div class="z-1 absolute bottom-0 left-0 right-0 flex h-14 cursor-pointer items-center justify-center rounded-b-full bg-black bg-opacity-40 pt-3 opacity-0 duration-300 ease-in-out group-hover:opacity-100" style=" -webkit-clip-path: inset(12px 0 0 0); clip-path: inset(12px 0 0 0); " > <CameraIcon class="h-6 w-6 cursor-pointer text-white" /> </div> </component> </div> <div class="flex flex-col gap-2 truncate sm:gap-0.5"> <div class="truncate text-3xl font-semibold"> <span v-if="contact.data.salutation"> {{ contact.data.salutation + '. ' }} </span> <span>{{ contact.data.full_name }}</span> </div> <div class="flex flex-col flex-wrap gap-3 text-base text-gray-700 sm:flex-row sm:items-center sm:gap-2" > <div v-if="contact.data.email_id" class="flex items-center gap-1.5" > <Email2Icon class="h-4 w-4" /> <span class="">{{ contact.data.email_id }}</span> </div> <span v-if="contact.data.email_id" class="hidden text-3xl leading-[0] text-gray-600 sm:flex" > &middot; </span> <component :is="callEnabled ? Tooltip : 'div'" :text="__('Make Call')" v-if="contact.data.actual_mobile_no" > <div class="flex items-center gap-1.5" :class="callEnabled ? 'cursor-pointer' : ''" @click=" callEnabled && makeCall(contact.data.actual_mobile_no) " > <PhoneIcon class="h-4 w-4" /> <span class="">{{ contact.data.actual_mobile_no }}</span> </div> </component> <span v-if="contact.data.actual_mobile_no" class="hidden text-3xl leading-[0] text-gray-600 sm:flex" > &middot; </span> <div v-if="contact.data.company_name" class="flex items-center gap-1.5" > <Avatar size="xs" :label="contact.data.company_name" :image=" getOrganization(contact.data.company_name) ?.organization_logo " /> <span class="">{{ contact.data.company_name }}</span> </div> <span v-if="contact.data.company_name" class="hidden text-3xl leading-[0] text-gray-600 sm:flex" > &middot; </span> <Button v-if=" contact.data.email_id || contact.data.mobile_no || contact.data.company_name " variant="ghost" :label="__('More')" class="w-fit cursor-pointer hover:text-gray-900 sm:-ml-1" @click=" () => { detailMode = true showContactModal = true } " /> </div> <div class="mt-2 flex gap-1.5"> <Button :label="__('Edit')" size="sm" @click=" () => { detailMode = false showContactModal = true } " > <template #prefix> <EditIcon class="h-4 w-4" /> </template> </Button> <Button :label="__('Delete')" theme="red" size="sm" @click="deleteContact" > <template #prefix> <FeatherIcon name="trash-2" class="h-4 w-4" /> </template> </Button> </div> <ErrorMessage :message="__(error)" /> </div> </div> </template> </FileUploader> <Tabs class="overflow-hidden" v-model="tabIndex" :tabs="tabs"> <template #tab="{ tab, selected }"> <button class="group flex items-center gap-2 border-b border-transparent py-2.5 text-base text-gray-600 duration-300 ease-in-out hover:border-gray-400 hover:text-gray-900" :class="{ 'text-gray-900': selected }" > <component v-if="tab.icon" :is="tab.icon" class="h-5" /> {{ __(tab.label) }} <Badge class="group-hover:bg-gray-900" :class="[selected ? 'bg-gray-900' : 'bg-gray-600']" variant="solid" theme="gray" size="sm" > {{ tab.count }} </Badge> </button> </template> <template #default="{ tab }"> <DealsListView v-if="tab.label === 'Deals' && rows.length" class="mt-4" :rows="rows" :columns="columns" :options="{ selectable: false, showTooltip: false }" /> <div v-if="!rows.length" class="grid flex-1 place-items-center text-xl font-medium text-gray-500" > <div class="flex flex-col items-center justify-center space-y-3"> <component :is="tab.icon" class="!h-10 !w-10" /> <div>{{ __('No {0} Found', [__(tab.label)]) }}</div> </div> </div> </template> </Tabs> </div> <ContactModal v-model="showContactModal" v-model:quickEntry="showQuickEntryModal" :contact="contact" :options="{ detailMode }" /> <QuickEntryModal v-if="showQuickEntryModal" v-model="showQuickEntryModal" doctype="Contact" /> </template> <script setup> import Icon from '@/components/Icon.vue' import Dropdown from '@/components/frappe-ui/Dropdown.vue' import LayoutHeader from '@/components/LayoutHeader.vue' import Email2Icon from '@/components/Icons/Email2Icon.vue' import PhoneIcon from '@/components/Icons/PhoneIcon.vue' import EditIcon from '@/components/Icons/EditIcon.vue' import CameraIcon from '@/components/Icons/CameraIcon.vue' import DealsIcon from '@/components/Icons/DealsIcon.vue' import DealsListView from '@/components/ListViews/DealsListView.vue' import ContactModal from '@/components/Modals/ContactModal.vue' import QuickEntryModal from '@/components/Modals/QuickEntryModal.vue' import { dateFormat, dateTooltipFormat, timeAgo, formatNumberIntoCurrency, } from '@/utils' import { getView } from '@/utils/view' import { globalStore } from '@/stores/global.js' import { usersStore } from '@/stores/users.js' import { organizationsStore } from '@/stores/organizations.js' import { statusesStore } from '@/stores/statuses' import { callEnabled } from '@/composables/settings' import { Breadcrumbs, Avatar, FileUploader, Tooltip, Tabs, call, createResource, usePageMeta, } from 'frappe-ui' import { ref, computed, h } from 'vue' import { useRoute, useRouter } from 'vue-router' const { $dialog, makeCall } = globalStore() const { getUser } = usersStore() const { getOrganization } = organizationsStore() const { getDealStatus } = statusesStore() const props = defineProps({ contactId: { type: String, required: true, }, }) const route = useRoute() const router = useRouter() const showContactModal = ref(false) const showQuickEntryModal = ref(false) const detailMode = ref(false) const contact = createResource({ url: 'crm.api.contact.get_contact', cache: ['contact', props.contactId], params: { name: props.contactId, }, auto: true, transform: (data) => { return { ...data, actual_mobile_no: data.mobile_no, mobile_no: data.mobile_no, } }, }) const breadcrumbs = computed(() => { let items = [{ label: __('Contacts'), route: { name: 'Contacts' } }] if (route.query.view || route.query.viewType) { let view = getView(route.query.view, route.query.viewType, 'Contact') if (view) { items.push({ label: __(view.label), icon: view.icon, route: { name: 'Contacts', params: { viewType: route.query.viewType }, query: { view: route.query.view }, }, }) } } items.push({ label: contact.data?.full_name, route: { name: 'Contact', params: { contactId: props.contactId } }, }) return items }) usePageMeta(() => { return { title: contact.data?.full_name || contact.data?.name, } }) function validateFile(file) { let extn = file.name.split('.').pop().toLowerCase() if (!['png', 'jpg', 'jpeg'].includes(extn)) { return __('Only PNG and JPG images are allowed') } } async function changeContactImage(file) { await call('frappe.client.set_value', { doctype: 'Contact', name: props.contactId, fieldname: 'image', value: file?.file_url || '', }) contact.reload() } async function deleteContact() { $dialog({ title: __('Delete contact'), message: __('Are you sure you want to delete this contact?'), actions: [ { label: __('Delete'), theme: 'red', variant: 'solid', async onClick(close) { await call('frappe.client.delete', { doctype: 'Contact', name: props.contactId, }) close() router.push({ name: 'Contacts' }) }, }, ], }) } const tabIndex = ref(0) const tabs = [ { label: 'Deals', icon: h(DealsIcon, { class: 'h-4 w-4' }), count: computed(() => deals.data?.length), }, ] const deals = createResource({ url: 'crm.api.contact.get_linked_deals', cache: ['deals', props.contactId], params: { contact: props.contactId, }, auto: true, }) const rows = computed(() => { if (!deals.data || deals.data == []) return [] return deals.data.map((row) => getDealRowObject(row)) }) const columns = computed(() => dealColumns) function getDealRowObject(deal) { return { name: deal.name, organization: { label: deal.organization, logo: getOrganization(deal.organization)?.organization_logo, }, annual_revenue: formatNumberIntoCurrency( deal.annual_revenue, deal.currency, ), status: { label: deal.status, color: getDealStatus(deal.status)?.iconColorClass, }, email: deal.email, mobile_no: deal.mobile_no, deal_owner: { label: deal.deal_owner && getUser(deal.deal_owner).full_name, ...(deal.deal_owner && getUser(deal.deal_owner)), }, modified: { label: dateFormat(deal.modified, dateTooltipFormat), timeAgo: __(timeAgo(deal.modified)), }, } } const dealColumns = [ { label: __('Organization'), key: 'organization', width: '11rem', }, { label: __('Amount'), key: 'annual_revenue', width: '9rem', }, { label: __('Status'), key: 'status', width: '10rem', }, { label: __('Email'), key: 'email', width: '12rem', }, { label: __('Mobile no'), key: 'mobile_no', width: '11rem', }, { label: __('Deal owner'), key: 'deal_owner', width: '10rem', }, { label: __('Last modified'), key: 'modified', width: '8rem', }, ] </script> <style scoped> :deep(.form-control input), :deep(.form-control select), :deep(.form-control button) { border-color: transparent; background: white; } :deep(.form-control button) { gap: 0; } :deep(.form-control button > div) { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } :deep(.form-control button svg) { color: white; width: 0; } :deep(:has(> .dropdown-button)) { width: 100%; } :deep(.dropdown-button > button > span) { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } </style>
2302_79757062/crm
frontend/src/pages/Contact.vue
Vue
agpl-3.0
13,925
<template> <LayoutHeader> <template #left-header> <ViewBreadcrumbs v-model="viewControls" routeName="Contacts" /> </template> <template #right-header> <CustomActions v-if="contactsListView?.customListActions" :actions="contactsListView.customListActions" /> <Button variant="solid" :label="__('Create')" @click="showContactModal = true" > <template #prefix><FeatherIcon name="plus" class="h-4" /></template> </Button> </template> </LayoutHeader> <ViewControls ref="viewControls" v-model="contacts" v-model:loadMore="loadMore" v-model:resizeColumn="triggerResize" v-model:updatedPageCount="updatedPageCount" doctype="Contact" /> <ContactsListView ref="contactsListView" v-if="contacts.data && rows.length" v-model="contacts.data.page_length_count" v-model:list="contacts" :rows="rows" :columns="contacts.data.columns" :options="{ showTooltip: false, resizeColumn: true, rowCount: contacts.data.row_count, totalCount: contacts.data.total_count, }" @loadMore="() => loadMore++" @columnWidthUpdated="() => triggerResize++" @updatePageCount="(count) => (updatedPageCount = count)" @applyFilter="(data) => viewControls.applyFilter(data)" @applyLikeFilter="(data) => viewControls.applyLikeFilter(data)" @likeDoc="(data) => viewControls.likeDoc(data)" /> <div v-else-if="contacts.data" class="flex h-full items-center justify-center" > <div class="flex flex-col items-center gap-3 text-xl font-medium text-gray-500" > <ContactsIcon class="h-10 w-10" /> <span>{{ __('No {0} Found', [__('Contacts')]) }}</span> <Button :label="__('Create')" @click="showContactModal = true"> <template #prefix><FeatherIcon name="plus" class="h-4" /></template> </Button> </div> </div> <ContactModal v-model="showContactModal" v-model:quickEntry="showQuickEntryModal" :contact="{}" /> <QuickEntryModal v-if="showQuickEntryModal" v-model="showQuickEntryModal" doctype="Contact" /> </template> <script setup> import ViewBreadcrumbs from '@/components/ViewBreadcrumbs.vue' import CustomActions from '@/components/CustomActions.vue' import ContactsIcon from '@/components/Icons/ContactsIcon.vue' import LayoutHeader from '@/components/LayoutHeader.vue' import ContactModal from '@/components/Modals/ContactModal.vue' import QuickEntryModal from '@/components/Modals/QuickEntryModal.vue' import ContactsListView from '@/components/ListViews/ContactsListView.vue' import ViewControls from '@/components/ViewControls.vue' import { organizationsStore } from '@/stores/organizations.js' import { dateFormat, dateTooltipFormat, timeAgo } from '@/utils' import { ref, computed } from 'vue' const { getOrganization } = organizationsStore() const showContactModal = ref(false) const showQuickEntryModal = ref(false) const contactsListView = ref(null) // contacts data is loaded in the ViewControls component const contacts = ref({}) const loadMore = ref(1) const triggerResize = ref(1) const updatedPageCount = ref(20) const viewControls = ref(null) const rows = computed(() => { if ( !contacts.value?.data?.data || !['list', 'group_by'].includes(contacts.value.data.view_type) ) return [] return contacts.value?.data.data.map((contact) => { let _rows = {} contacts.value?.data.rows.forEach((row) => { _rows[row] = contact[row] if (row == 'full_name') { _rows[row] = { label: contact.full_name, image_label: contact.full_name, image: contact.image, } } else if (row == 'company_name') { _rows[row] = { label: contact.company_name, logo: getOrganization(contact.company_name)?.organization_logo, } } else if (['modified', 'creation'].includes(row)) { _rows[row] = { label: dateFormat(contact[row], dateTooltipFormat), timeAgo: __(timeAgo(contact[row])), } } }) return _rows }) }) </script>
2302_79757062/crm
frontend/src/pages/Contacts.vue
Vue
agpl-3.0
4,151
<template> <LayoutHeader> <template #left-header> <Breadcrumbs :items="breadcrumbs" /> </template> </LayoutHeader> </template> <script setup> import LayoutHeader from '@/components/LayoutHeader.vue' import { Breadcrumbs } from 'frappe-ui' let title = 'Dashboard' const breadcrumbs = [{ label: title, route: { name: 'Dashboard' } }] </script>
2302_79757062/crm
frontend/src/pages/Dashboard.vue
Vue
agpl-3.0
361
<template> <LayoutHeader v-if="deal.data"> <template #left-header> <Breadcrumbs :items="breadcrumbs"> <template #prefix="{ item }"> <Icon v-if="item.icon" :icon="item.icon" class="mr-2 h-4" /> </template> </Breadcrumbs> </template> <template #right-header> <CustomActions v-if="customActions" :actions="customActions" /> <component :is="deal.data._assignedTo?.length == 1 ? 'Button' : 'div'"> <MultipleAvatar :avatars="deal.data._assignedTo" @click="showAssignmentModal = true" /> </component> <Dropdown :options="statusOptions('deal', updateField, customStatuses)"> <template #default="{ open }"> <Button :label="deal.data.status" :class="getDealStatus(deal.data.status).colorClass" > <template #prefix> <IndicatorIcon /> </template> <template #suffix> <FeatherIcon :name="open ? 'chevron-up' : 'chevron-down'" class="h-4" /> </template> </Button> </template> </Dropdown> </template> </LayoutHeader> <div v-if="deal.data" class="flex h-full overflow-hidden"> <Tabs v-model="tabIndex" v-slot="{ tab }" :tabs="tabs"> <Activities ref="activities" doctype="CRM Deal" :title="tab.name" v-model:reload="reload" v-model:tabIndex="tabIndex" v-model="deal" /> </Tabs> <Resizer side="right" class="flex flex-col justify-between border-l"> <div class="flex h-10.5 cursor-copy items-center border-b px-5 py-2.5 text-lg font-medium" @click="copyToClipboard(deal.data.name)" > {{ __(deal.data.name) }} </div> <div class="flex items-center justify-start gap-5 border-b p-5"> <Tooltip :text="__('Organization logo')"> <div class="group relative size-12"> <Avatar size="3xl" class="size-12" :label="organization.data?.name || __('Untitled')" :image="organization.data?.organization_logo" /> </div> </Tooltip> <div class="flex flex-col gap-2.5 truncate"> <Tooltip :text="organization.data?.name || __('Set an organization')"> <div class="truncate text-2xl font-medium"> {{ organization.data?.name || __('Untitled') }} </div> </Tooltip> <div class="flex gap-1.5"> <Tooltip v-if="callEnabled" :text="__('Make a call')"> <Button class="h-7 w-7" @click="triggerCall"> <PhoneIcon class="h-4 w-4" /> </Button> </Tooltip> <Tooltip :text="__('Send an email')"> <Button class="h-7 w-7"> <Email2Icon class="h-4 w-4" @click=" deal.data.email ? openEmailBox() : errorMessage(__('No email set')) " /> </Button> </Tooltip> <Tooltip :text="__('Go to website')"> <Button class="h-7 w-7"> <LinkIcon class="h-4 w-4" @click=" deal.data.website ? openWebsite(deal.data.website) : errorMessage(__('No website set')) " /> </Button> </Tooltip> </div> </div> </div> <SLASection v-if="deal.data.sla_status" v-model="deal.data" @updateField="updateField" /> <div v-if="fieldsLayout.data" class="flex flex-1 flex-col justify-between overflow-hidden" > <div class="flex flex-col overflow-y-auto"> <div v-for="(section, i) in fieldsLayout.data" :key="section.label" class="section flex flex-col p-3" :class="{ 'border-b': i !== fieldsLayout.data.length - 1 }" > <Section :is-opened="section.opened" :label="section.label"> <template #actions> <div v-if="section.contacts" class="pr-2"> <Link value="" doctype="Contact" @change="(e) => addContact(e)" :onCreate=" (value, close) => { _contact = { first_name: value, company_name: deal.data.organization, } showContactModal = true close() } " > <template #target="{ togglePopover }"> <Button class="h-7 px-3" variant="ghost" icon="plus" @click="togglePopover()" /> </template> </Link> </div> <Button v-else-if=" ((!section.contacts && i == 1) || i == 0) && isManager() " variant="ghost" class="w-7 mr-2" @click="showSidePanelModal = true" > <EditIcon class="h-4 w-4" /> </Button> </template> <SectionFields v-if="section.fields" :fields="section.fields" :isLastSection="i == fieldsLayout.data.length - 1" v-model="deal.data" @update="updateField" /> <div v-else> <div v-if=" dealContacts?.loading && dealContacts?.data?.length == 0 " class="flex min-h-20 flex-1 items-center justify-center gap-3 text-base text-gray-500" > <LoadingIndicator class="h-4 w-4" /> <span>{{ __('Loading...') }}</span> </div> <div v-else-if="dealContacts?.data?.length" v-for="(contact, i) in dealContacts.data" :key="contact.name" > <div class="px-2 pb-2.5" :class="[i == 0 ? 'pt-5' : 'pt-2.5']" > <Section :is-opened="contact.opened"> <template #header="{ opened, toggle }"> <div class="flex cursor-pointer items-center justify-between gap-2 pr-1 text-base leading-5 text-gray-700" > <div class="flex h-7 items-center gap-2 truncate" @click="toggle()" > <Avatar :label="contact.full_name" :image="contact.image" size="md" /> <div class="truncate"> {{ contact.full_name }} </div> <Badge v-if="contact.is_primary" class="ml-2" variant="outline" :label="__('Primary')" theme="green" /> </div> <div class="flex items-center"> <Dropdown :options="contactOptions(contact)"> <Button icon="more-horizontal" class="text-gray-600" variant="ghost" /> </Dropdown> <Button variant="ghost" @click=" router.push({ name: 'Contact', params: { contactId: contact.name }, }) " > <ArrowUpRightIcon class="h-4 w-4" /> </Button> <Button variant="ghost" @click="toggle()"> <FeatherIcon name="chevron-right" class="h-4 w-4 text-gray-900 transition-all duration-300 ease-in-out" :class="{ 'rotate-90': opened }" /> </Button> </div> </div> </template> <div class="flex flex-col gap-1.5 text-base text-gray-800" > <div class="flex items-center gap-3 pb-1.5 pl-1 pt-4"> <Email2Icon class="h-4 w-4" /> {{ contact.email }} </div> <div class="flex items-center gap-3 p-1 py-1.5"> <PhoneIcon class="h-4 w-4" /> {{ contact.mobile_no }} </div> </div> </Section> </div> <div v-if="i != dealContacts.data.length - 1" class="mx-2 h-px border-t border-gray-200" /> </div> <div v-else class="flex h-20 items-center justify-center text-base text-gray-600" > {{ __('No contacts added') }} </div> </div> </Section> </div> </div> </div> </Resizer> </div> <OrganizationModal v-model="showOrganizationModal" v-model:organization="_organization" :options="{ redirect: false, afterInsert: (doc) => updateField('organization', doc.name), }" /> <ContactModal v-model="showContactModal" :contact="_contact" :options="{ redirect: false, afterInsert: (doc) => addContact(doc.name), }" /> <AssignmentModal v-if="showAssignmentModal" v-model="showAssignmentModal" v-model:assignees="deal.data._assignedTo" :doc="deal.data" doctype="CRM Deal" /> <SidePanelModal v-if="showSidePanelModal" v-model="showSidePanelModal" doctype="CRM Deal" @reload="() => fieldsLayout.reload()" /> </template> <script setup> import Icon from '@/components/Icon.vue' import Resizer from '@/components/Resizer.vue' import LoadingIndicator from '@/components/Icons/LoadingIndicator.vue' import EditIcon from '@/components/Icons/EditIcon.vue' import ActivityIcon from '@/components/Icons/ActivityIcon.vue' import EmailIcon from '@/components/Icons/EmailIcon.vue' import Email2Icon from '@/components/Icons/Email2Icon.vue' import CommentIcon from '@/components/Icons/CommentIcon.vue' import PhoneIcon from '@/components/Icons/PhoneIcon.vue' import TaskIcon from '@/components/Icons/TaskIcon.vue' import NoteIcon from '@/components/Icons/NoteIcon.vue' import WhatsAppIcon from '@/components/Icons/WhatsAppIcon.vue' import IndicatorIcon from '@/components/Icons/IndicatorIcon.vue' import LinkIcon from '@/components/Icons/LinkIcon.vue' import ArrowUpRightIcon from '@/components/Icons/ArrowUpRightIcon.vue' import SuccessIcon from '@/components/Icons/SuccessIcon.vue' import LayoutHeader from '@/components/LayoutHeader.vue' import Activities from '@/components/Activities/Activities.vue' import OrganizationModal from '@/components/Modals/OrganizationModal.vue' import AssignmentModal from '@/components/Modals/AssignmentModal.vue' import MultipleAvatar from '@/components/MultipleAvatar.vue' import ContactModal from '@/components/Modals/ContactModal.vue' import SidePanelModal from '@/components/Settings/SidePanelModal.vue' import Link from '@/components/Controls/Link.vue' import Section from '@/components/Section.vue' import SectionFields from '@/components/SectionFields.vue' import SLASection from '@/components/SLASection.vue' import CustomActions from '@/components/CustomActions.vue' import { openWebsite, createToast, setupAssignees, setupCustomizations, errorMessage, copyToClipboard, } from '@/utils' import { getView } from '@/utils/view' import { globalStore } from '@/stores/global' import { statusesStore } from '@/stores/statuses' import { usersStore } from '@/stores/users' import { whatsappEnabled, callEnabled } from '@/composables/settings' import { createResource, Dropdown, Tooltip, Avatar, Tabs, Breadcrumbs, call, usePageMeta, } from 'frappe-ui' import { ref, computed, h, onMounted, onBeforeUnmount } from 'vue' import { useRoute, useRouter } from 'vue-router' const { $dialog, $socket, makeCall } = globalStore() const { statusOptions, getDealStatus } = statusesStore() const { isManager } = usersStore() const route = useRoute() const router = useRouter() const props = defineProps({ dealId: { type: String, required: true, }, }) const customActions = ref([]) const customStatuses = ref([]) const deal = createResource({ url: 'crm.fcrm.doctype.crm_deal.api.get_deal', params: { name: props.dealId }, cache: ['deal', props.dealId], onSuccess: async (data) => { organization.update({ params: { doctype: 'CRM Organization', name: data.organization }, }) organization.fetch() let obj = { doc: data, $dialog, $socket, router, updateField, createToast, deleteDoc: deleteDeal, resource: { deal, dealContacts, fieldsLayout, }, call, } setupAssignees(data) let customization = await setupCustomizations(data, obj) customActions.value = customization.actions || [] customStatuses.value = customization.statuses || [] }, }) const organization = createResource({ url: 'frappe.client.get', onSuccess: (data) => (deal.data._organizationObj = data), }) onMounted(() => { $socket.on('crm_customer_created', () => { createToast({ title: __('Customer created successfully'), icon: 'check', iconClasses: 'text-green-600', }) }) if (deal.data) { organization.data = deal.data._organizationObj return } deal.fetch() }) onBeforeUnmount(() => { $socket.off('crm_customer_created') }) const reload = ref(false) const showOrganizationModal = ref(false) const showAssignmentModal = ref(false) const showSidePanelModal = ref(false) const _organization = ref({}) function updateDeal(fieldname, value, callback) { value = Array.isArray(fieldname) ? '' : value if (validateRequired(fieldname, value)) return createResource({ url: 'frappe.client.set_value', params: { doctype: 'CRM Deal', name: props.dealId, fieldname, value, }, auto: true, onSuccess: () => { deal.reload() reload.value = true createToast({ title: __('Deal updated'), icon: 'check', iconClasses: 'text-green-600', }) callback?.() }, onError: (err) => { createToast({ title: __('Error updating deal'), text: __(err.messages?.[0]), icon: 'x', iconClasses: 'text-red-600', }) }, }) } function validateRequired(fieldname, value) { let meta = deal.data.fields_meta || {} if (meta[fieldname]?.reqd && !value) { createToast({ title: __('Error Updating Deal'), text: __('{0} is a required field', [meta[fieldname].label]), icon: 'x', iconClasses: 'text-red-600', }) return true } return false } const breadcrumbs = computed(() => { let items = [{ label: __('Deals'), route: { name: 'Deals' } }] if (route.query.view || route.query.viewType) { let view = getView(route.query.view, route.query.viewType, 'CRM Deal') if (view) { items.push({ label: __(view.label), icon: view.icon, route: { name: 'Deals', params: { viewType: route.query.viewType }, query: { view: route.query.view }, }, }) } } items.push({ label: organization.data?.name || __('Untitled'), route: { name: 'Deal', params: { dealId: deal.data.name } }, }) return items }) usePageMeta(() => { return { title: organization.data?.name || deal.data?.name, } }) const tabIndex = ref(0) const tabs = computed(() => { let tabOptions = [ { name: 'Activity', label: __('Activity'), icon: ActivityIcon, }, { name: 'Emails', label: __('Emails'), icon: EmailIcon, }, { name: 'Comments', label: __('Comments'), icon: CommentIcon, }, { name: 'Calls', label: __('Calls'), icon: PhoneIcon, condition: () => callEnabled.value, }, { name: 'Tasks', label: __('Tasks'), icon: TaskIcon, }, { name: 'Notes', label: __('Notes'), icon: NoteIcon, }, { name: 'WhatsApp', label: __('WhatsApp'), icon: WhatsAppIcon, condition: () => whatsappEnabled.value, }, ] return tabOptions.filter((tab) => (tab.condition ? tab.condition() : true)) }) const fieldsLayout = createResource({ url: 'crm.api.doc.get_sidebar_fields', cache: ['fieldsLayout', props.dealId], params: { doctype: 'CRM Deal', name: props.dealId }, auto: true, transform: (data) => getParsedFields(data), }) function getParsedFields(sections) { sections.forEach((section) => { if (section.name == 'contacts_section') return section.fields.forEach((field) => { if (field.name == 'organization') { field.create = (value, close) => { _organization.value.organization_name = value showOrganizationModal.value = true close() } field.link = (org) => router.push({ name: 'Organization', params: { organizationId: org }, }) } }) }) return sections } const showContactModal = ref(false) const _contact = ref({}) function contactOptions(contact) { let options = [ { label: __('Remove'), icon: 'trash-2', onClick: () => removeContact(contact.name), }, ] if (!contact.is_primary) { options.push({ label: __('Set as Primary Contact'), icon: h(SuccessIcon, { class: 'h-4 w-4' }), onClick: () => setPrimaryContact(contact), }) } return options } async function addContact(contact) { let d = await call('crm.fcrm.doctype.crm_deal.crm_deal.add_contact', { deal: props.dealId, contact, }) if (d) { dealContacts.reload() createToast({ title: __('Contact added'), icon: 'check', iconClasses: 'text-green-600', }) } } async function removeContact(contact) { let d = await call('crm.fcrm.doctype.crm_deal.crm_deal.remove_contact', { deal: props.dealId, contact, }) if (d) { dealContacts.reload() createToast({ title: __('Contact removed'), icon: 'check', iconClasses: 'text-green-600', }) } } async function setPrimaryContact(contact) { let d = await call('crm.fcrm.doctype.crm_deal.crm_deal.set_primary_contact', { deal: props.dealId, contact, }) if (d) { dealContacts.reload() createToast({ title: __('Primary contact set'), icon: 'check', iconClasses: 'text-green-600', }) } } const dealContacts = createResource({ url: 'crm.fcrm.doctype.crm_deal.api.get_deal_contacts', params: { name: props.dealId }, cache: ['deal_contacts', props.dealId], auto: true, transform: (data) => { data.forEach((contact) => { contact.opened = false }) return data }, }) function triggerCall() { let primaryContact = dealContacts.data?.find((c) => c.is_primary) let mobile_no = primaryContact.mobile_no || null if (!primaryContact) { errorMessage(__('No primary contact set')) return } if (!mobile_no) { errorMessage(__('No mobile number set')) return } makeCall(mobile_no) } function updateField(name, value, callback) { updateDeal(name, value, () => { deal.data[name] = value callback?.() }) } async function deleteDeal(name) { await call('frappe.client.delete', { doctype: 'CRM Deal', name, }) router.push({ name: 'Deals' }) } const activities = ref(null) function openEmailBox() { activities.value.emailBox.show = true } </script> <style scoped> :deep(.section:has(.section-field.hidden)) { display: none; } :deep(.section:has(.section-field:not(.hidden))) { display: flex; } </style>
2302_79757062/crm
frontend/src/pages/Deal.vue
Vue
agpl-3.0
21,328
<template> <LayoutHeader> <template #left-header> <ViewBreadcrumbs v-model="viewControls" routeName="Deals" /> </template> <template #right-header> <CustomActions v-if="dealsListView?.customListActions" :actions="dealsListView.customListActions" /> <Button variant="solid" :label="__('Create')" @click="showDealModal = true" > <template #prefix><FeatherIcon name="plus" class="h-4" /></template> </Button> </template> </LayoutHeader> <ViewControls ref="viewControls" v-model="deals" v-model:loadMore="loadMore" v-model:resizeColumn="triggerResize" v-model:updatedPageCount="updatedPageCount" doctype="CRM Deal" :options="{ allowedViews: ['list', 'group_by', 'kanban'], }" /> <KanbanView v-if="route.params.viewType == 'kanban'" v-model="deals" :options="{ getRoute: (row) => ({ name: 'Deal', params: { dealId: row.name }, query: { view: route.query.view, viewType: route.params.viewType }, }), onNewClick: (column) => onNewClick(column), }" @update="(data) => viewControls.updateKanbanSettings(data)" @loadMore="(columnName) => viewControls.loadMoreKanban(columnName)" > <template #title="{ titleField, itemName }"> <div class="flex gap-2 items-center"> <div v-if="titleField === 'status'"> <IndicatorIcon :class="getRow(itemName, titleField).color" /> </div> <div v-else-if=" titleField === 'organization' && getRow(itemName, titleField).label " > <Avatar class="flex items-center" :image="getRow(itemName, titleField).logo" :label="getRow(itemName, titleField).label" size="sm" /> </div> <div v-else-if=" titleField === 'deal_owner' && getRow(itemName, titleField).full_name " > <Avatar class="flex items-center" :image="getRow(itemName, titleField).user_image" :label="getRow(itemName, titleField).full_name" size="sm" /> </div> <div v-if=" [ 'modified', 'creation', 'first_response_time', 'first_responded_on', 'response_by', ].includes(titleField) " class="truncate text-base" > <Tooltip :text="getRow(itemName, titleField).label"> <div>{{ getRow(itemName, titleField).timeAgo }}</div> </Tooltip> </div> <div v-else-if="titleField === 'sla_status'" class="truncate text-base"> <Badge v-if="getRow(itemName, titleField).value" :variant="'subtle'" :theme="getRow(itemName, titleField).color" size="md" :label="getRow(itemName, titleField).value" /> </div> <div v-else-if="getRow(itemName, titleField).label" class="truncate text-base" > {{ getRow(itemName, titleField).label }} </div> <div class="text-gray-500" v-else>{{ __('No Title') }}</div> </div> </template> <template #fields="{ fieldName, itemName }"> <div v-if="getRow(itemName, fieldName).label" class="truncate flex items-center gap-2" > <div v-if="fieldName === 'status'"> <IndicatorIcon :class="getRow(itemName, fieldName).color" /> </div> <div v-else-if="fieldName === 'organization'"> <Avatar v-if="getRow(itemName, fieldName).label" class="flex items-center" :image="getRow(itemName, fieldName).logo" :label="getRow(itemName, fieldName).label" size="xs" /> </div> <div v-else-if="fieldName === 'deal_owner'"> <Avatar v-if="getRow(itemName, fieldName).full_name" class="flex items-center" :image="getRow(itemName, fieldName).user_image" :label="getRow(itemName, fieldName).full_name" size="xs" /> </div> <div v-if=" [ 'modified', 'creation', 'first_response_time', 'first_responded_on', 'response_by', ].includes(fieldName) " class="truncate text-base" > <Tooltip :text="getRow(itemName, fieldName).label"> <div>{{ getRow(itemName, fieldName).timeAgo }}</div> </Tooltip> </div> <div v-else-if="fieldName === 'sla_status'" class="truncate text-base"> <Badge v-if="getRow(itemName, fieldName).value" :variant="'subtle'" :theme="getRow(itemName, fieldName).color" size="md" :label="getRow(itemName, fieldName).value" /> </div> <div v-else-if="fieldName === '_assign'" class="flex items-center"> <MultipleAvatar :avatars="getRow(itemName, fieldName).label" size="xs" /> </div> <div v-else class="truncate text-base"> {{ getRow(itemName, fieldName).label }} </div> </div> </template> <template #actions="{ itemName }"> <div class="flex gap-2 items-center justify-between"> <div class="text-gray-600 flex items-center gap-1.5"> <EmailAtIcon class="h-4 w-4" /> <span v-if="getRow(itemName, '_email_count').label"> {{ getRow(itemName, '_email_count').label }} </span> <span class="text-3xl leading-[0]"> &middot; </span> <NoteIcon class="h-4 w-4" /> <span v-if="getRow(itemName, '_note_count').label"> {{ getRow(itemName, '_note_count').label }} </span> <span class="text-3xl leading-[0]"> &middot; </span> <TaskIcon class="h-4 w-4" /> <span v-if="getRow(itemName, '_task_count').label"> {{ getRow(itemName, '_task_count').label }} </span> <span class="text-3xl leading-[0]"> &middot; </span> <CommentIcon class="h-4 w-4" /> <span v-if="getRow(itemName, '_comment_count').label"> {{ getRow(itemName, '_comment_count').label }} </span> </div> <Dropdown class="flex items-center gap-2" :options="actions(itemName)" variant="ghost" @click.stop.prevent > <Button icon="plus" variant="ghost" /> </Dropdown> </div> </template> </KanbanView> <DealsListView ref="dealsListView" v-else-if="deals.data && rows.length" v-model="deals.data.page_length_count" v-model:list="deals" :rows="rows" :columns="deals.data.columns" :options="{ showTooltip: false, resizeColumn: true, rowCount: deals.data.row_count, totalCount: deals.data.total_count, }" @loadMore="() => loadMore++" @columnWidthUpdated="() => triggerResize++" @updatePageCount="(count) => (updatedPageCount = count)" @applyFilter="(data) => viewControls.applyFilter(data)" @applyLikeFilter="(data) => viewControls.applyLikeFilter(data)" @likeDoc="(data) => viewControls.likeDoc(data)" /> <div v-else-if="deals.data" class="flex h-full items-center justify-center"> <div class="flex flex-col items-center gap-3 text-xl font-medium text-gray-500" > <DealsIcon class="h-10 w-10" /> <span>{{ __('No {0} Found', [__('Deals')]) }}</span> <Button :label="__('Create')" @click="showDealModal = true"> <template #prefix><FeatherIcon name="plus" class="h-4" /></template> </Button> </div> </div> <DealModal v-if="showDealModal" v-model="showDealModal" v-model:quickEntry="showQuickEntryModal" :defaults="defaults" /> <NoteModal v-if="showNoteModal" v-model="showNoteModal" :note="note" doctype="CRM Deal" :doc="docname" /> <TaskModal v-if="showTaskModal" v-model="showTaskModal" :task="task" doctype="CRM Deal" :doc="docname" /> <QuickEntryModal v-if="showQuickEntryModal" v-model="showQuickEntryModal" doctype="CRM Deal" /> </template> <script setup> import ViewBreadcrumbs from '@/components/ViewBreadcrumbs.vue' import MultipleAvatar from '@/components/MultipleAvatar.vue' import CustomActions from '@/components/CustomActions.vue' import EmailAtIcon from '@/components/Icons/EmailAtIcon.vue' import PhoneIcon from '@/components/Icons/PhoneIcon.vue' import NoteIcon from '@/components/Icons/NoteIcon.vue' import TaskIcon from '@/components/Icons/TaskIcon.vue' import CommentIcon from '@/components/Icons/CommentIcon.vue' import IndicatorIcon from '@/components/Icons/IndicatorIcon.vue' import DealsIcon from '@/components/Icons/DealsIcon.vue' import LayoutHeader from '@/components/LayoutHeader.vue' import DealsListView from '@/components/ListViews/DealsListView.vue' import KanbanView from '@/components/Kanban/KanbanView.vue' import DealModal from '@/components/Modals/DealModal.vue' import NoteModal from '@/components/Modals/NoteModal.vue' import TaskModal from '@/components/Modals/TaskModal.vue' import QuickEntryModal from '@/components/Modals/QuickEntryModal.vue' import ViewControls from '@/components/ViewControls.vue' import { globalStore } from '@/stores/global' import { usersStore } from '@/stores/users' import { organizationsStore } from '@/stores/organizations' import { statusesStore } from '@/stores/statuses' import { callEnabled } from '@/composables/settings' import { dateFormat, dateTooltipFormat, timeAgo, website, formatNumberIntoCurrency, formatTime, } from '@/utils' import { Tooltip, Avatar, Dropdown } from 'frappe-ui' import { useRoute } from 'vue-router' import { ref, reactive, computed, h } from 'vue' const { makeCall } = globalStore() const { getUser } = usersStore() const { getOrganization } = organizationsStore() const { getDealStatus } = statusesStore() const route = useRoute() const dealsListView = ref(null) const showDealModal = ref(false) const showQuickEntryModal = ref(false) const defaults = reactive({}) // deals data is loaded in the ViewControls component const deals = ref({}) const loadMore = ref(1) const triggerResize = ref(1) const updatedPageCount = ref(20) const viewControls = ref(null) function getRow(name, field) { function getValue(value) { if (value && typeof value === 'object' && !Array.isArray(value)) { return value } return { label: value } } return getValue(rows.value?.find((row) => row.name == name)[field]) } // Rows const rows = computed(() => { if (!deals.value?.data?.data) return [] if (deals.value.data.view_type === 'group_by') { if (!deals.value?.data.group_by_field?.name) return [] return getGroupedByRows( deals.value?.data.data, deals.value?.data.group_by_field, ) } else if (deals.value.data.view_type === 'kanban') { return getKanbanRows(deals.value.data.data) } else { return parseRows(deals.value?.data.data) } }) function getGroupedByRows(listRows, groupByField) { let groupedRows = [] groupByField.options?.forEach((option) => { let filteredRows = [] if (!option) { filteredRows = listRows.filter((row) => !row[groupByField.name]) } else { filteredRows = listRows.filter((row) => row[groupByField.name] == option) } let groupDetail = { label: groupByField.label, group: option || __(' '), collapsed: false, rows: parseRows(filteredRows), } if (groupByField.name == 'status') { groupDetail.icon = () => h(IndicatorIcon, { class: getDealStatus(option)?.iconColorClass, }) } groupedRows.push(groupDetail) }) return groupedRows || listRows } function getKanbanRows(data) { let _rows = [] data.forEach((column) => { column.data?.forEach((row) => { _rows.push(row) }) }) return parseRows(_rows) } function parseRows(rows) { return rows.map((deal) => { let _rows = {} deals.value.data.rows.forEach((row) => { _rows[row] = deal[row] if (row == 'organization') { _rows[row] = { label: deal.organization, logo: getOrganization(deal.organization)?.organization_logo, } } else if (row === 'website') { _rows[row] = website(deal.website) } else if (row == 'annual_revenue') { _rows[row] = formatNumberIntoCurrency( deal.annual_revenue, deal.currency, ) } else if (row == 'status') { _rows[row] = { label: deal.status, color: getDealStatus(deal.status)?.iconColorClass, } } else if (row == 'sla_status') { let value = deal.sla_status let tooltipText = value let color = deal.sla_status == 'Failed' ? 'red' : deal.sla_status == 'Fulfilled' ? 'green' : 'orange' if (value == 'First Response Due') { value = __(timeAgo(deal.response_by)) tooltipText = dateFormat(deal.response_by, dateTooltipFormat) if (new Date(deal.response_by) < new Date()) { color = 'red' } } _rows[row] = { label: tooltipText, value: value, color: color, } } else if (row == 'deal_owner') { _rows[row] = { label: deal.deal_owner && getUser(deal.deal_owner).full_name, ...(deal.deal_owner && getUser(deal.deal_owner)), } } else if (row == '_assign') { let assignees = JSON.parse(deal._assign || '[]') if (!assignees.length && deal.deal_owner) { assignees = [deal.deal_owner] } _rows[row] = assignees.map((user) => ({ name: user, image: getUser(user).user_image, label: getUser(user).full_name, })) } else if (['modified', 'creation'].includes(row)) { _rows[row] = { label: dateFormat(deal[row], dateTooltipFormat), timeAgo: __(timeAgo(deal[row])), } } else if ( ['first_response_time', 'first_responded_on', 'response_by'].includes( row, ) ) { let field = row == 'response_by' ? 'response_by' : 'first_responded_on' _rows[row] = { label: deal[field] ? dateFormat(deal[field], dateTooltipFormat) : '', timeAgo: deal[row] ? row == 'first_response_time' ? formatTime(deal[row]) : __(timeAgo(deal[row])) : '', } } }) _rows['_email_count'] = deal._email_count _rows['_note_count'] = deal._note_count _rows['_task_count'] = deal._task_count _rows['_comment_count'] = deal._comment_count return _rows }) } function onNewClick(column) { let column_field = deals.value.params.column_field if (column_field) { defaults[column_field] = column.column.name } showDealModal.value = true } function actions(itemName) { let mobile_no = getRow(itemName, 'mobile_no')?.label || '' let actions = [ { icon: h(PhoneIcon, { class: 'h-4 w-4' }), label: __('Make a Call'), onClick: () => makeCall(mobile_no), condition: () => mobile_no && callEnabled.value, }, { icon: h(NoteIcon, { class: 'h-4 w-4' }), label: __('New Note'), onClick: () => showNote(itemName), }, { icon: h(TaskIcon, { class: 'h-4 w-4' }), label: __('New Task'), onClick: () => showTask(itemName), }, ] return actions.filter((action) => action.condition ? action.condition() : true, ) } const docname = ref('') const showNoteModal = ref(false) const note = ref({ title: '', content: '', }) function showNote(name) { docname.value = name showNoteModal.value = true } const showTaskModal = ref(false) const task = ref({ title: '', description: '', assigned_to: '', due_date: '', priority: 'Low', status: 'Backlog', }) function showTask(name) { docname.value = name showTaskModal.value = true } </script>
2302_79757062/crm
frontend/src/pages/Deals.vue
Vue
agpl-3.0
16,377
<template> <div> <h1>Email Templates</h1> <p>Here is a list of email templates</p> </div> </template>
2302_79757062/crm
frontend/src/pages/EmailTemplate.vue
Vue
agpl-3.0
114
<template> <LayoutHeader> <template #left-header> <ViewBreadcrumbs v-model="viewControls" routeName="Email Templates" /> </template> <template #right-header> <CustomActions v-if="emailTemplatesListView?.customListActions" :actions="emailTemplatesListView.customListActions" /> <Button variant="solid" :label="__('Create')" @click="() => showEmailTemplate()" > <template #prefix><FeatherIcon name="plus" class="h-4" /></template> </Button> </template> </LayoutHeader> <ViewControls ref="viewControls" v-model="emailTemplates" v-model:loadMore="loadMore" v-model:resizeColumn="triggerResize" v-model:updatedPageCount="updatedPageCount" doctype="Email Template" /> <EmailTemplatesListView ref="emailTemplatesListView" v-if="emailTemplates.data && rows.length" v-model="emailTemplates.data.page_length_count" v-model:list="emailTemplates" :rows="rows" :columns="emailTemplates.data.columns" :options="{ showTooltip: false, resizeColumn: true, rowCount: emailTemplates.data.row_count, totalCount: emailTemplates.data.total_count, }" @loadMore="() => loadMore++" @columnWidthUpdated="() => triggerResize++" @updatePageCount="(count) => (updatedPageCount = count)" @showEmailTemplate="showEmailTemplate" @applyFilter="(data) => viewControls.applyFilter(data)" @applyLikeFilter="(data) => viewControls.applyLikeFilter(data)" @likeDoc="(data) => viewControls.likeDoc(data)" /> <div v-else-if="emailTemplates.data" class="flex h-full items-center justify-center" > <div class="flex flex-col items-center gap-3 text-xl font-medium text-gray-500" > <Email2Icon class="h-10 w-10" /> <span>{{ __('No {0} Found', [__('Email Templates')]) }}</span> <Button :label="__('Create')" @click="() => showEmailTemplate()"> <template #prefix><FeatherIcon name="plus" class="h-4" /></template> </Button> </div> </div> <EmailTemplateModal v-model="showEmailTemplateModal" v-model:reloadEmailTemplates="emailTemplates" :emailTemplate="emailTemplate" /> </template> <script setup> import ViewBreadcrumbs from '@/components/ViewBreadcrumbs.vue' import CustomActions from '@/components/CustomActions.vue' import Email2Icon from '@/components/Icons/Email2Icon.vue' import LayoutHeader from '@/components/LayoutHeader.vue' import ViewControls from '@/components/ViewControls.vue' import EmailTemplatesListView from '@/components/ListViews/EmailTemplatesListView.vue' import EmailTemplateModal from '@/components/Modals/EmailTemplateModal.vue' import { dateFormat, dateTooltipFormat, timeAgo } from '@/utils' import { computed, ref } from 'vue' const emailTemplatesListView = ref(null) // emailTemplates data is loaded in the ViewControls component const emailTemplates = ref({}) const loadMore = ref(1) const triggerResize = ref(1) const updatedPageCount = ref(20) const viewControls = ref(null) const rows = computed(() => { if ( !emailTemplates.value?.data?.data || !['list', 'group_by'].includes(emailTemplates.value.data.view_type) ) return [] return emailTemplates.value?.data.data.map((emailTemplate) => { let _rows = {} emailTemplates.value?.data.rows.forEach((row) => { _rows[row] = emailTemplate[row] if (['modified', 'creation'].includes(row)) { _rows[row] = { label: dateFormat(emailTemplate[row], dateTooltipFormat), timeAgo: timeAgo(emailTemplate[row]), } } }) return _rows }) }) const showEmailTemplateModal = ref(false) const emailTemplate = ref({}) function showEmailTemplate(name) { if (!name) { emailTemplate.value = { subject: '', response: '', response_html: '', name: '', enabled: 1, use_html: 0, owner: '', reference_doctype: 'CRM Deal', } } else { let et = rows.value?.find((row) => row.name === name) emailTemplate.value = { subject: et.subject, response: et.response, response_html: et.response_html, name: et.name, enabled: et.enabled, use_html: et.use_html, owner: et.owner, reference_doctype: et.reference_doctype, } } showEmailTemplateModal.value = true } </script>
2302_79757062/crm
frontend/src/pages/EmailTemplates.vue
Vue
agpl-3.0
4,384
<template> <div class="grid h-full place-items-center px-4 py-20 text-center text-lg text-gray-600" > <div class="space-y-2"> <div>Invalid page or not permitted to access</div> <Button :route="{ name: 'Leads' }"> <template #prefix><LeadsIcon class="w-4" /></template> Leads </Button> </div> </div> </template> <script setup> import LeadsIcon from '@/components/Icons/LeadsIcon.vue' </script>
2302_79757062/crm
frontend/src/pages/InvalidPage.vue
Vue
agpl-3.0
445
<template> <LayoutHeader v-if="lead.data"> <template #left-header> <Breadcrumbs :items="breadcrumbs"> <template #prefix="{ item }"> <Icon v-if="item.icon" :icon="item.icon" class="mr-2 h-4" /> </template> </Breadcrumbs> </template> <template #right-header> <CustomActions v-if="customActions" :actions="customActions" /> <component :is="lead.data._assignedTo?.length == 1 ? 'Button' : 'div'"> <MultipleAvatar :avatars="lead.data._assignedTo" @click="showAssignmentModal = true" /> </component> <Dropdown :options="statusOptions('lead', updateField, customStatuses)"> <template #default="{ open }"> <Button :label="lead.data.status" :class="getLeadStatus(lead.data.status).colorClass" > <template #prefix> <IndicatorIcon /> </template> <template #suffix> <FeatherIcon :name="open ? 'chevron-up' : 'chevron-down'" class="h-4" /> </template> </Button> </template> </Dropdown> <Button :label="__('Convert to Deal')" variant="solid" @click="showConvertToDealModal = true" /> </template> </LayoutHeader> <div v-if="lead?.data" class="flex h-full overflow-hidden"> <Tabs v-model="tabIndex" v-slot="{ tab }" :tabs="tabs"> <Activities ref="activities" doctype="CRM Lead" :title="tab.name" :tabs="tabs" v-model:reload="reload" v-model:tabIndex="tabIndex" v-model="lead" /> </Tabs> <Resizer class="flex flex-col justify-between border-l" side="right"> <div class="flex h-10.5 cursor-copy items-center border-b px-5 py-2.5 text-lg font-medium" @click="copyToClipboard(lead.data.name)" > {{ __(lead.data.name) }} </div> <FileUploader @success="(file) => updateField('image', file.file_url)" :validateFile="validateFile" > <template #default="{ openFileSelector, error }"> <div class="flex items-center justify-start gap-5 border-b p-5"> <div class="group relative size-12"> <Avatar size="3xl" class="size-12" :label="lead.data.first_name || __('Untitled')" :image="lead.data.image" /> <component :is="lead.data.image ? Dropdown : 'div'" v-bind=" lead.data.image ? { options: [ { icon: 'upload', label: lead.data.image ? __('Change image') : __('Upload image'), onClick: openFileSelector, }, { icon: 'trash-2', label: __('Remove image'), onClick: () => updateField('image', ''), }, ], } : { onClick: openFileSelector } " class="!absolute bottom-0 left-0 right-0" > <div class="z-1 absolute bottom-0.5 left-0 right-0.5 flex h-9 cursor-pointer items-center justify-center rounded-b-full bg-black bg-opacity-40 pt-3 opacity-0 duration-300 ease-in-out group-hover:opacity-100" style=" -webkit-clip-path: inset(12px 0 0 0); clip-path: inset(12px 0 0 0); " > <CameraIcon class="size-4 cursor-pointer text-white" /> </div> </component> </div> <div class="flex flex-col gap-2.5 truncate"> <Tooltip :text="lead.data.lead_name || __('Set first name')"> <div class="truncate text-2xl font-medium"> {{ lead.data.lead_name || __('Untitled') }} </div> </Tooltip> <div class="flex gap-1.5"> <Tooltip v-if="callEnabled" :text="__('Make a call')"> <Button class="h-7 w-7" @click=" () => lead.data.mobile_no ? makeCall(lead.data.mobile_no) : errorMessage(__('No phone number set')) " > <PhoneIcon class="h-4 w-4" /> </Button> </Tooltip> <Tooltip :text="__('Send an email')"> <Button class="h-7 w-7"> <Email2Icon class="h-4 w-4" @click=" lead.data.email ? openEmailBox() : errorMessage(__('No email set')) " /> </Button> </Tooltip> <Tooltip :text="__('Go to website')"> <Button class="h-7 w-7"> <LinkIcon class="h-4 w-4" @click=" lead.data.website ? openWebsite(lead.data.website) : errorMessage(__('No website set')) " /> </Button> </Tooltip> </div> <ErrorMessage :message="__(error)" /> </div> </div> </template> </FileUploader> <SLASection v-if="lead.data.sla_status" v-model="lead.data" @updateField="updateField" /> <div v-if="fieldsLayout.data" class="flex flex-1 flex-col justify-between overflow-hidden" > <div class="flex flex-col overflow-y-auto"> <div v-for="(section, i) in fieldsLayout.data" :key="section.label" class="flex flex-col p-3" :class="{ 'border-b': i !== fieldsLayout.data.length - 1 }" > <Section :is-opened="section.opened" :label="section.label"> <SectionFields :fields="section.fields" :isLastSection="i == fieldsLayout.data.length - 1" v-model="lead.data" @update="updateField" /> <template v-if="i == 0 && isManager()" #actions> <Button variant="ghost" class="w-7 mr-2" @click="showSidePanelModal = true" > <EditIcon class="h-4 w-4" /> </Button> </template> </Section> </div> </div> </div> </Resizer> </div> <AssignmentModal v-if="showAssignmentModal" v-model="showAssignmentModal" v-model:assignees="lead.data._assignedTo" :doc="lead.data" doctype="CRM Lead" /> <Dialog v-model="showConvertToDealModal" :options="{ title: __('Convert to Deal'), size: 'xl', actions: [ { label: __('Convert'), variant: 'solid', onClick: convertToDeal, }, ], }" > <template #body-content> <div class="mb-4 flex items-center gap-2 text-gray-600"> <OrganizationsIcon class="h-4 w-4" /> <label class="block text-base">{{ __('Organization') }}</label> </div> <div class="ml-6"> <div class="flex items-center justify-between text-base"> <div>{{ __('Choose Existing') }}</div> <Switch v-model="existingOrganizationChecked" /> </div> <Link v-if="existingOrganizationChecked" class="form-control mt-2.5" variant="outline" size="md" :value="existingOrganization" doctype="CRM Organization" @change="(data) => (existingOrganization = data)" /> <div v-else class="mt-2.5 text-base"> {{ __( 'New organization will be created based on the data in details section', ) }} </div> </div> <div class="mb-4 mt-6 flex items-center gap-2 text-gray-600"> <ContactsIcon class="h-4 w-4" /> <label class="block text-base">{{ __('Contact') }}</label> </div> <div class="ml-6"> <div class="flex items-center justify-between text-base"> <div>{{ __('Choose Existing') }}</div> <Switch v-model="existingContactChecked" /> </div> <Link v-if="existingContactChecked" class="form-control mt-2.5" variant="outline" size="md" :value="existingContact" doctype="Contact" @change="(data) => (existingContact = data)" /> <div v-else class="mt-2.5 text-base"> {{ __("New contact will be created based on the person's details") }} </div> </div> </template> </Dialog> <SidePanelModal v-if="showSidePanelModal" v-model="showSidePanelModal" @reload="() => fieldsLayout.reload()" /> </template> <script setup> import Icon from '@/components/Icon.vue' import Resizer from '@/components/Resizer.vue' import EditIcon from '@/components/Icons/EditIcon.vue' import ActivityIcon from '@/components/Icons/ActivityIcon.vue' import EmailIcon from '@/components/Icons/EmailIcon.vue' import Email2Icon from '@/components/Icons/Email2Icon.vue' import CommentIcon from '@/components/Icons/CommentIcon.vue' import PhoneIcon from '@/components/Icons/PhoneIcon.vue' import TaskIcon from '@/components/Icons/TaskIcon.vue' import NoteIcon from '@/components/Icons/NoteIcon.vue' import WhatsAppIcon from '@/components/Icons/WhatsAppIcon.vue' import IndicatorIcon from '@/components/Icons/IndicatorIcon.vue' import CameraIcon from '@/components/Icons/CameraIcon.vue' import LinkIcon from '@/components/Icons/LinkIcon.vue' import OrganizationsIcon from '@/components/Icons/OrganizationsIcon.vue' import ContactsIcon from '@/components/Icons/ContactsIcon.vue' import LayoutHeader from '@/components/LayoutHeader.vue' import Activities from '@/components/Activities/Activities.vue' import AssignmentModal from '@/components/Modals/AssignmentModal.vue' import SidePanelModal from '@/components/Settings/SidePanelModal.vue' import MultipleAvatar from '@/components/MultipleAvatar.vue' import Link from '@/components/Controls/Link.vue' import Section from '@/components/Section.vue' import SectionFields from '@/components/SectionFields.vue' import SLASection from '@/components/SLASection.vue' import CustomActions from '@/components/CustomActions.vue' import { openWebsite, createToast, setupAssignees, setupCustomizations, errorMessage, copyToClipboard, } from '@/utils' import { getView } from '@/utils/view' import { globalStore } from '@/stores/global' import { contactsStore } from '@/stores/contacts' import { statusesStore } from '@/stores/statuses' import { usersStore } from '@/stores/users' import { whatsappEnabled, callEnabled } from '@/composables/settings' import { capture } from '@/telemetry' import { createResource, FileUploader, Dropdown, Tooltip, Avatar, Tabs, Switch, Breadcrumbs, call, usePageMeta, } from 'frappe-ui' import { ref, computed, onMounted, watch } from 'vue' import { useRouter, useRoute } from 'vue-router' const { $dialog, $socket, makeCall } = globalStore() const { getContactByName, contacts } = contactsStore() const { statusOptions, getLeadStatus } = statusesStore() const { isManager } = usersStore() const route = useRoute() const router = useRouter() const props = defineProps({ leadId: { type: String, required: true, }, }) const customActions = ref([]) const customStatuses = ref([]) const lead = createResource({ url: 'crm.fcrm.doctype.crm_lead.api.get_lead', params: { name: props.leadId }, cache: ['lead', props.leadId], onSuccess: async (data) => { let obj = { doc: data, $dialog, $socket, router, updateField, createToast, deleteDoc: deleteLead, resource: { lead, fieldsLayout, }, call, } setupAssignees(data) let customization = await setupCustomizations(data, obj) customActions.value = customization.actions || [] customStatuses.value = customization.statuses || [] }, }) onMounted(() => { if (lead.data) return lead.fetch() }) const reload = ref(false) const showAssignmentModal = ref(false) const showSidePanelModal = ref(false) function updateLead(fieldname, value, callback) { value = Array.isArray(fieldname) ? '' : value if (!Array.isArray(fieldname) && validateRequired(fieldname, value)) return createResource({ url: 'frappe.client.set_value', params: { doctype: 'CRM Lead', name: props.leadId, fieldname, value, }, auto: true, onSuccess: () => { lead.reload() reload.value = true createToast({ title: __('Lead updated'), icon: 'check', iconClasses: 'text-green-600', }) callback?.() }, onError: (err) => { createToast({ title: __('Error updating lead'), text: __(err.messages?.[0]), icon: 'x', iconClasses: 'text-red-600', }) }, }) } function validateRequired(fieldname, value) { let meta = lead.data.fields_meta || {} if (meta[fieldname]?.reqd && !value) { createToast({ title: __('Error Updating Lead'), text: __('{0} is a required field', [meta[fieldname].label]), icon: 'x', iconClasses: 'text-red-600', }) return true } return false } const breadcrumbs = computed(() => { let items = [{ label: __('Leads'), route: { name: 'Leads' } }] if (route.query.view || route.query.viewType) { let view = getView(route.query.view, route.query.viewType, 'CRM Lead') if (view) { items.push({ label: __(view.label), icon: view.icon, route: { name: 'Leads', params: { viewType: route.query.viewType }, query: { view: route.query.view }, }, }) } } items.push({ label: lead.data.lead_name || __('Untitled'), route: { name: 'Lead', params: { leadId: lead.data.name } }, }) return items }) usePageMeta(() => { return { title: lead.data?.lead_name || lead.data?.name, } }) const tabIndex = ref(0) const tabs = computed(() => { let tabOptions = [ { name: 'Activity', label: __('Activity'), icon: ActivityIcon, }, { name: 'Emails', label: __('Emails'), icon: EmailIcon, }, { name: 'Comments', label: __('Comments'), icon: CommentIcon, }, { name: 'Calls', label: __('Calls'), icon: PhoneIcon, condition: () => callEnabled.value, }, { name: 'Tasks', label: __('Tasks'), icon: TaskIcon, }, { name: 'Notes', label: __('Notes'), icon: NoteIcon, }, { name: 'WhatsApp', label: __('WhatsApp'), icon: WhatsAppIcon, condition: () => whatsappEnabled.value, }, ] return tabOptions.filter((tab) => (tab.condition ? tab.condition() : true)) }) watch(tabs, (value) => { if (value && route.params.tabName) { let index = value.findIndex( (tab) => tab.name.toLowerCase() === route.params.tabName.toLowerCase(), ) if (index !== -1) { tabIndex.value = index } } }) function validateFile(file) { let extn = file.name.split('.').pop().toLowerCase() if (!['png', 'jpg', 'jpeg'].includes(extn)) { return __('Only PNG and JPG images are allowed') } } const fieldsLayout = createResource({ url: 'crm.api.doc.get_sidebar_fields', cache: ['fieldsLayout', props.leadId], params: { doctype: 'CRM Lead', name: props.leadId }, auto: true, }) function updateField(name, value, callback) { updateLead(name, value, () => { lead.data[name] = value callback?.() }) } async function deleteLead(name) { await call('frappe.client.delete', { doctype: 'CRM Lead', name, }) router.push({ name: 'Leads' }) } // Convert to Deal const showConvertToDealModal = ref(false) const existingContactChecked = ref(false) const existingOrganizationChecked = ref(false) const existingContact = ref('') const existingOrganization = ref('') async function convertToDeal(updated) { let valueUpdated = false if (existingContactChecked.value && !existingContact.value) { createToast({ title: __('Error'), text: __('Please select an existing contact'), icon: 'x', iconClasses: 'text-red-600', }) return } if (existingOrganizationChecked.value && !existingOrganization.value) { createToast({ title: __('Error'), text: __('Please select an existing organization'), icon: 'x', iconClasses: 'text-red-600', }) return } if (existingContactChecked.value && existingContact.value) { lead.data.salutation = getContactByName(existingContact.value).salutation lead.data.first_name = getContactByName(existingContact.value).first_name lead.data.last_name = getContactByName(existingContact.value).last_name lead.data.email_id = getContactByName(existingContact.value).email_id lead.data.mobile_no = getContactByName(existingContact.value).mobile_no existingContactChecked.value = false valueUpdated = true } if (existingOrganizationChecked.value && existingOrganization.value) { lead.data.organization = existingOrganization.value existingOrganizationChecked.value = false valueUpdated = true } if (valueUpdated) { updateLead( { salutation: lead.data.salutation, first_name: lead.data.first_name, last_name: lead.data.last_name, email_id: lead.data.email_id, mobile_no: lead.data.mobile_no, organization: lead.data.organization, }, '', () => convertToDeal(true), ) showConvertToDealModal.value = false } else { let deal = await call( 'crm.fcrm.doctype.crm_lead.crm_lead.convert_to_deal', { lead: lead.data.name, }, ) if (deal) { capture('convert_lead_to_deal') if (updated) { await contacts.reload() } router.push({ name: 'Deal', params: { dealId: deal } }) } } } const activities = ref(null) function openEmailBox() { activities.value.emailBox.show = true } </script>
2302_79757062/crm
frontend/src/pages/Lead.vue
Vue
agpl-3.0
18,925
<template> <LayoutHeader> <template #left-header> <ViewBreadcrumbs v-model="viewControls" routeName="Leads" /> </template> <template #right-header> <CustomActions v-if="leadsListView?.customListActions" :actions="leadsListView.customListActions" /> <Button variant="solid" :label="__('Create')" @click="showLeadModal = true" > <template #prefix><FeatherIcon name="plus" class="h-4" /></template> </Button> </template> </LayoutHeader> <ViewControls ref="viewControls" v-model="leads" v-model:loadMore="loadMore" v-model:resizeColumn="triggerResize" v-model:updatedPageCount="updatedPageCount" doctype="CRM Lead" :filters="{ converted: 0 }" :options="{ allowedViews: ['list', 'group_by', 'kanban'], }" /> <KanbanView v-if="route.params.viewType == 'kanban'" v-model="leads" :options="{ getRoute: (row) => ({ name: 'Lead', params: { leadId: row.name }, query: { view: route.query.view, viewType: route.params.viewType }, }), onNewClick: (column) => onNewClick(column), }" @update="(data) => viewControls.updateKanbanSettings(data)" @loadMore="(columnName) => viewControls.loadMoreKanban(columnName)" > <template #title="{ titleField, itemName }"> <div class="flex items-center gap-2"> <div v-if="titleField === 'status'"> <IndicatorIcon :class="getRow(itemName, titleField).color" /> </div> <div v-else-if=" titleField === 'organization' && getRow(itemName, titleField).label " > <Avatar class="flex items-center" :image="getRow(itemName, titleField).logo" :label="getRow(itemName, titleField).label" size="sm" /> </div> <div v-else-if=" titleField === 'lead_name' && getRow(itemName, titleField).label " > <Avatar class="flex items-center" :image="getRow(itemName, titleField).image" :label="getRow(itemName, titleField).image_label" size="sm" /> </div> <div v-else-if=" titleField === 'lead_owner' && getRow(itemName, titleField).full_name " > <Avatar class="flex items-center" :image="getRow(itemName, titleField).user_image" :label="getRow(itemName, titleField).full_name" size="sm" /> </div> <div v-else-if="titleField === 'mobile_no'"> <PhoneIcon class="h-4 w-4" /> </div> <div v-if=" [ 'modified', 'creation', 'first_response_time', 'first_responded_on', 'response_by', ].includes(titleField) " class="truncate text-base" > <Tooltip :text="getRow(itemName, titleField).label"> <div>{{ getRow(itemName, titleField).timeAgo }}</div> </Tooltip> </div> <div v-else-if="titleField === 'sla_status'" class="truncate text-base"> <Badge v-if="getRow(itemName, titleField).value" :variant="'subtle'" :theme="getRow(itemName, titleField).color" size="md" :label="getRow(itemName, titleField).value" /> </div> <div v-else-if="getRow(itemName, titleField).label" class="truncate text-base" > {{ getRow(itemName, titleField).label }} </div> <div class="text-gray-500" v-else>{{ __('No Title') }}</div> </div> </template> <template #fields="{ fieldName, itemName }"> <div v-if="getRow(itemName, fieldName).label" class="truncate flex items-center gap-2" > <div v-if="fieldName === 'status'"> <IndicatorIcon :class="getRow(itemName, fieldName).color" /> </div> <div v-else-if=" fieldName === 'organization' && getRow(itemName, fieldName).label " > <Avatar class="flex items-center" :image="getRow(itemName, fieldName).logo" :label="getRow(itemName, fieldName).label" size="xs" /> </div> <div v-else-if="fieldName === 'lead_name'"> <Avatar v-if="getRow(itemName, fieldName).label" class="flex items-center" :image="getRow(itemName, fieldName).image" :label="getRow(itemName, fieldName).image_label" size="xs" /> </div> <div v-else-if="fieldName === 'lead_owner'"> <Avatar v-if="getRow(itemName, fieldName).full_name" class="flex items-center" :image="getRow(itemName, fieldName).user_image" :label="getRow(itemName, fieldName).full_name" size="xs" /> </div> <div v-if=" [ 'modified', 'creation', 'first_response_time', 'first_responded_on', 'response_by', ].includes(fieldName) " class="truncate text-base" > <Tooltip :text="getRow(itemName, fieldName).label"> <div>{{ getRow(itemName, fieldName).timeAgo }}</div> </Tooltip> </div> <div v-else-if="fieldName === 'sla_status'" class="truncate text-base"> <Badge v-if="getRow(itemName, fieldName).value" :variant="'subtle'" :theme="getRow(itemName, fieldName).color" size="md" :label="getRow(itemName, fieldName).value" /> </div> <div v-else-if="fieldName === '_assign'" class="flex items-center"> <MultipleAvatar :avatars="getRow(itemName, fieldName).label" size="xs" /> </div> <div v-else class="truncate text-base"> {{ getRow(itemName, fieldName).label }} </div> </div> </template> <template #actions="{ itemName }"> <div class="flex gap-2 items-center justify-between"> <div class="text-gray-600 flex items-center gap-1.5"> <EmailAtIcon class="h-4 w-4" /> <span v-if="getRow(itemName, '_email_count').label"> {{ getRow(itemName, '_email_count').label }} </span> <span class="text-3xl leading-[0]"> &middot; </span> <NoteIcon class="h-4 w-4" /> <span v-if="getRow(itemName, '_note_count').label"> {{ getRow(itemName, '_note_count').label }} </span> <span class="text-3xl leading-[0]"> &middot; </span> <TaskIcon class="h-4 w-4" /> <span v-if="getRow(itemName, '_task_count').label"> {{ getRow(itemName, '_task_count').label }} </span> <span class="text-3xl leading-[0]"> &middot; </span> <CommentIcon class="h-4 w-4" /> <span v-if="getRow(itemName, '_comment_count').label"> {{ getRow(itemName, '_comment_count').label }} </span> </div> <Dropdown class="flex items-center gap-2" :options="actions(itemName)" variant="ghost" @click.stop.prevent > <Button icon="plus" variant="ghost" /> </Dropdown> </div> </template> </KanbanView> <LeadsListView ref="leadsListView" v-else-if="leads.data && rows.length" v-model="leads.data.page_length_count" v-model:list="leads" :rows="rows" :columns="leads.data.columns" :options="{ showTooltip: false, resizeColumn: true, rowCount: leads.data.row_count, totalCount: leads.data.total_count, }" @loadMore="() => loadMore++" @columnWidthUpdated="() => triggerResize++" @updatePageCount="(count) => (updatedPageCount = count)" @applyFilter="(data) => viewControls.applyFilter(data)" @applyLikeFilter="(data) => viewControls.applyLikeFilter(data)" @likeDoc="(data) => viewControls.likeDoc(data)" /> <div v-else-if="leads.data" class="flex h-full items-center justify-center"> <div class="flex flex-col items-center gap-3 text-xl font-medium text-gray-500" > <LeadsIcon class="h-10 w-10" /> <span>{{ __('No {0} Found', [__('Leads')]) }}</span> <Button :label="__('Create')" @click="showLeadModal = true"> <template #prefix><FeatherIcon name="plus" class="h-4" /></template> </Button> </div> </div> <LeadModal v-if="showLeadModal" v-model="showLeadModal" v-model:quickEntry="showQuickEntryModal" :defaults="defaults" /> <NoteModal v-if="showNoteModal" v-model="showNoteModal" :note="note" doctype="CRM Lead" :doc="docname" /> <TaskModal v-if="showTaskModal" v-model="showTaskModal" :task="task" doctype="CRM Lead" :doc="docname" /> <QuickEntryModal v-if="showQuickEntryModal" v-model="showQuickEntryModal" /> </template> <script setup> import ViewBreadcrumbs from '@/components/ViewBreadcrumbs.vue' import MultipleAvatar from '@/components/MultipleAvatar.vue' import CustomActions from '@/components/CustomActions.vue' import EmailAtIcon from '@/components/Icons/EmailAtIcon.vue' import PhoneIcon from '@/components/Icons/PhoneIcon.vue' import NoteIcon from '@/components/Icons/NoteIcon.vue' import TaskIcon from '@/components/Icons/TaskIcon.vue' import CommentIcon from '@/components/Icons/CommentIcon.vue' import IndicatorIcon from '@/components/Icons/IndicatorIcon.vue' import LeadsIcon from '@/components/Icons/LeadsIcon.vue' import LayoutHeader from '@/components/LayoutHeader.vue' import LeadsListView from '@/components/ListViews/LeadsListView.vue' import KanbanView from '@/components/Kanban/KanbanView.vue' import LeadModal from '@/components/Modals/LeadModal.vue' import NoteModal from '@/components/Modals/NoteModal.vue' import TaskModal from '@/components/Modals/TaskModal.vue' import QuickEntryModal from '@/components/Modals/QuickEntryModal.vue' import ViewControls from '@/components/ViewControls.vue' import { globalStore } from '@/stores/global' import { usersStore } from '@/stores/users' import { statusesStore } from '@/stores/statuses' import { callEnabled } from '@/composables/settings' import { dateFormat, dateTooltipFormat, timeAgo, website, formatTime, } from '@/utils' import { Avatar, Tooltip, Dropdown } from 'frappe-ui' import { useRoute } from 'vue-router' import { ref, computed, reactive, h } from 'vue' const { makeCall } = globalStore() const { getUser } = usersStore() const { getLeadStatus } = statusesStore() const route = useRoute() const leadsListView = ref(null) const showLeadModal = ref(false) const showQuickEntryModal = ref(false) const defaults = reactive({}) // leads data is loaded in the ViewControls component const leads = ref({}) const loadMore = ref(1) const triggerResize = ref(1) const updatedPageCount = ref(20) const viewControls = ref(null) function getRow(name, field) { function getValue(value) { if (value && typeof value === 'object' && !Array.isArray(value)) { return value } return { label: value } } return getValue(rows.value?.find((row) => row.name == name)[field]) } // Rows const rows = computed(() => { if (!leads.value?.data?.data) return [] if (leads.value.data.view_type === 'group_by') { if (!leads.value?.data.group_by_field?.name) return [] return getGroupedByRows( leads.value?.data.data, leads.value?.data.group_by_field, ) } else if (leads.value.data.view_type === 'kanban') { return getKanbanRows(leads.value.data.data) } else { return parseRows(leads.value?.data.data) } }) function getGroupedByRows(listRows, groupByField) { let groupedRows = [] groupByField.options?.forEach((option) => { let filteredRows = [] if (!option) { filteredRows = listRows.filter((row) => !row[groupByField.name]) } else { filteredRows = listRows.filter((row) => row[groupByField.name] == option) } let groupDetail = { label: groupByField.label, group: option || __(' '), collapsed: false, rows: parseRows(filteredRows), } if (groupByField.name == 'status') { groupDetail.icon = () => h(IndicatorIcon, { class: getLeadStatus(option)?.iconColorClass, }) } groupedRows.push(groupDetail) }) return groupedRows || listRows } function getKanbanRows(data) { let _rows = [] data.forEach((column) => { column.data?.forEach((row) => { _rows.push(row) }) }) return parseRows(_rows) } function parseRows(rows) { return rows.map((lead) => { let _rows = {} leads.value?.data.rows.forEach((row) => { _rows[row] = lead[row] if (row == 'lead_name') { _rows[row] = { label: lead.lead_name, image: lead.image, image_label: lead.first_name, } } else if (row == 'organization') { _rows[row] = lead.organization } else if (row === 'website') { _rows[row] = website(lead.website) } else if (row == 'status') { _rows[row] = { label: lead.status, color: getLeadStatus(lead.status)?.iconColorClass, } } else if (row == 'sla_status') { let value = lead.sla_status let tooltipText = value let color = lead.sla_status == 'Failed' ? 'red' : lead.sla_status == 'Fulfilled' ? 'green' : 'orange' if (value == 'First Response Due') { value = __(timeAgo(lead.response_by)) tooltipText = dateFormat(lead.response_by, dateTooltipFormat) if (new Date(lead.response_by) < new Date()) { color = 'red' } } _rows[row] = { label: tooltipText, value: value, color: color, } } else if (row == 'lead_owner') { _rows[row] = { label: lead.lead_owner && getUser(lead.lead_owner).full_name, ...(lead.lead_owner && getUser(lead.lead_owner)), } } else if (row == '_assign') { let assignees = JSON.parse(lead._assign || '[]') if (!assignees.length && lead.lead_owner) { assignees = [lead.lead_owner] } _rows[row] = assignees.map((user) => ({ name: user, image: getUser(user).user_image, label: getUser(user).full_name, })) } else if (['modified', 'creation'].includes(row)) { _rows[row] = { label: dateFormat(lead[row], dateTooltipFormat), timeAgo: __(timeAgo(lead[row])), } } else if ( ['first_response_time', 'first_responded_on', 'response_by'].includes( row, ) ) { let field = row == 'response_by' ? 'response_by' : 'first_responded_on' _rows[row] = { label: lead[field] ? dateFormat(lead[field], dateTooltipFormat) : '', timeAgo: lead[row] ? row == 'first_response_time' ? formatTime(lead[row]) : __(timeAgo(lead[row])) : '', } } }) _rows['_email_count'] = lead._email_count _rows['_note_count'] = lead._note_count _rows['_task_count'] = lead._task_count _rows['_comment_count'] = lead._comment_count return _rows }) } function onNewClick(column) { let column_field = leads.value.params.column_field if (column_field) { defaults[column_field] = column.column.name } showLeadModal.value = true } function actions(itemName) { let mobile_no = getRow(itemName, 'mobile_no')?.label || '' let actions = [ { icon: h(PhoneIcon, { class: 'h-4 w-4' }), label: __('Make a Call'), onClick: () => makeCall(mobile_no), condition: () => mobile_no && callEnabled.value, }, { icon: h(NoteIcon, { class: 'h-4 w-4' }), label: __('New Note'), onClick: () => showNote(itemName), }, { icon: h(TaskIcon, { class: 'h-4 w-4' }), label: __('New Task'), onClick: () => showTask(itemName), }, ] return actions.filter((action) => action.condition ? action.condition() : true, ) } const docname = ref('') const showNoteModal = ref(false) const note = ref({ title: '', content: '', }) function showNote(name) { docname.value = name showNoteModal.value = true } const showTaskModal = ref(false) const task = ref({ title: '', description: '', assigned_to: '', due_date: '', priority: 'Low', status: 'Backlog', }) function showTask(name) { docname.value = name showTaskModal.value = true } </script>
2302_79757062/crm
frontend/src/pages/Leads.vue
Vue
agpl-3.0
16,974
<template> <LayoutHeader v-if="deal.data"> <header class="relative flex h-12 items-center justify-between gap-2 py-2.5 pl-5" > <Breadcrumbs :items="breadcrumbs"> <template #prefix="{ item }"> <Icon v-if="item.icon" :icon="item.icon" class="mr-2 h-4" /> </template> </Breadcrumbs> <div class="absolute right-0"> <Dropdown :options="statusOptions('deal', updateField, customStatuses)"> <template #default="{ open }"> <Button :label="deal.data.status" :class="getDealStatus(deal.data.status).colorClass" > <template #prefix> <IndicatorIcon /> </template> <template #suffix> <FeatherIcon :name="open ? 'chevron-up' : 'chevron-down'" class="h-4" /> </template> </Button> </template> </Dropdown> </div> </header> </LayoutHeader> <div v-if="deal.data" class="flex h-12 items-center justify-between gap-2 border-b px-3 py-2.5" > <component :is="deal.data._assignedTo?.length == 1 ? 'Button' : 'div'"> <MultipleAvatar :avatars="deal.data._assignedTo" @click="showAssignmentModal = true" /> </component> <div class="flex items-center gap-2"> <CustomActions v-if="customActions" :actions="customActions" /> </div> </div> <div v-if="deal.data" class="flex h-full overflow-hidden"> <Tabs v-model="tabIndex" v-slot="{ tab }" :tabs="tabs" tablistClass="!px-3" class="overflow-auto" > <div v-if="tab.name == 'Details'"> <SLASection v-if="deal.data.sla_status" v-model="deal.data" @updateField="updateField" /> <div v-if="fieldsLayout.data" class="flex flex-1 flex-col justify-between overflow-hidden" > <div class="flex flex-col overflow-y-auto"> <div v-for="(section, i) in fieldsLayout.data" :key="section.label" class="flex flex-col px-2 py-3 sm:p-3" :class="{ 'border-b': i !== fieldsLayout.data.length - 1 }" > <Section :is-opened="section.opened" :label="section.label"> <template #actions> <div v-if="section.contacts" class="pr-2"> <Link value="" doctype="Contact" @change="(e) => addContact(e)" :onCreate=" (value, close) => { _contact = { first_name: value, company_name: deal.data.organization, } showContactModal = true close() } " > <template #target="{ togglePopover }"> <Button class="h-7 px-3" variant="ghost" icon="plus" @click="togglePopover()" /> </template> </Link> </div> </template> <SectionFields v-if="section.fields" :fields="section.fields" :isLastSection="i == fieldsLayout.data.length - 1" v-model="deal.data" @update="updateField" /> <div v-else> <div v-if=" dealContacts?.loading && dealContacts?.data?.length == 0 " class="flex min-h-20 flex-1 items-center justify-center gap-3 text-base text-gray-500" > <LoadingIndicator class="h-4 w-4" /> <span>{{ __('Loading...') }}</span> </div> <div v-else-if="section.contacts.length" v-for="(contact, i) in section.contacts" :key="contact.name" > <div class="px-2 pb-2.5" :class="[i == 0 ? 'pt-5' : 'pt-2.5']" > <Section :is-opened="contact.opened"> <template #header="{ opened, toggle }"> <div class="flex cursor-pointer items-center justify-between gap-2 pr-1 text-base leading-5 text-gray-700" > <div class="flex h-7 items-center gap-2 truncate" @click="toggle()" > <Avatar :label="contact.full_name" :image="contact.image" size="md" /> <div class="truncate"> {{ contact.full_name }} </div> <Badge v-if="contact.is_primary" class="ml-2" variant="outline" :label="__('Primary')" theme="green" /> </div> <div class="flex items-center"> <Dropdown :options="contactOptions(contact.name)"> <Button icon="more-horizontal" class="text-gray-600" variant="ghost" /> </Dropdown> <Button variant="ghost" @click=" router.push({ name: 'Contact', params: { contactId: contact.name }, }) " > <ArrowUpRightIcon class="h-4 w-4" /> </Button> <Button variant="ghost" @click="toggle()"> <FeatherIcon name="chevron-right" class="h-4 w-4 text-gray-900 transition-all duration-300 ease-in-out" :class="{ 'rotate-90': opened }" /> </Button> </div> </div> </template> <div class="flex flex-col gap-1.5 text-base text-gray-800" > <div class="flex items-center gap-3 pb-1.5 pl-1 pt-4"> <Email2Icon class="h-4 w-4" /> {{ contact.email }} </div> <div class="flex items-center gap-3 p-1 py-1.5"> <PhoneIcon class="h-4 w-4" /> {{ contact.mobile_no }} </div> </div> </Section> </div> <div v-if="i != section.contacts.length - 1" class="mx-2 h-px border-t border-gray-200" /> </div> <div v-else class="flex h-20 items-center justify-center text-base text-gray-600" > {{ __('No contacts added') }} </div> </div> </Section> </div> </div> </div> </div> <Activities v-else doctype="CRM Deal" :title="tab.name" v-model:reload="reload" v-model:tabIndex="tabIndex" v-model="deal" /> </Tabs> </div> <OrganizationModal v-model="showOrganizationModal" v-model:organization="_organization" :options="{ redirect: false, afterInsert: (doc) => updateField('organization', doc.name), }" /> <ContactModal v-model="showContactModal" :contact="_contact" :options="{ redirect: false, afterInsert: (doc) => addContact(doc.name), }" /> <AssignmentModal v-if="showAssignmentModal" v-model="showAssignmentModal" v-model:assignees="deal.data._assignedTo" :doc="deal.data" doctype="CRM Deal" /> </template> <script setup> import Icon from '@/components/Icon.vue' import DetailsIcon from '@/components/Icons/DetailsIcon.vue' import LoadingIndicator from '@/components/Icons/LoadingIndicator.vue' import ActivityIcon from '@/components/Icons/ActivityIcon.vue' import EmailIcon from '@/components/Icons/EmailIcon.vue' import Email2Icon from '@/components/Icons/Email2Icon.vue' import CommentIcon from '@/components/Icons/CommentIcon.vue' import PhoneIcon from '@/components/Icons/PhoneIcon.vue' import TaskIcon from '@/components/Icons/TaskIcon.vue' import NoteIcon from '@/components/Icons/NoteIcon.vue' import WhatsAppIcon from '@/components/Icons/WhatsAppIcon.vue' import IndicatorIcon from '@/components/Icons/IndicatorIcon.vue' import ArrowUpRightIcon from '@/components/Icons/ArrowUpRightIcon.vue' import SuccessIcon from '@/components/Icons/SuccessIcon.vue' import LayoutHeader from '@/components/LayoutHeader.vue' import Activities from '@/components/Activities/Activities.vue' import OrganizationModal from '@/components/Modals/OrganizationModal.vue' import AssignmentModal from '@/components/Modals/AssignmentModal.vue' import MultipleAvatar from '@/components/MultipleAvatar.vue' import ContactModal from '@/components/Modals/ContactModal.vue' import Link from '@/components/Controls/Link.vue' import Section from '@/components/Section.vue' import SectionFields from '@/components/SectionFields.vue' import SLASection from '@/components/SLASection.vue' import CustomActions from '@/components/CustomActions.vue' import { createToast, setupAssignees, setupCustomizations } from '@/utils' import { getView } from '@/utils/view' import { globalStore } from '@/stores/global' import { statusesStore } from '@/stores/statuses' import { whatsappEnabled, callEnabled, isMobileView, } from '@/composables/settings' import { createResource, Dropdown, Avatar, Tabs, Breadcrumbs, call, } from 'frappe-ui' import { ref, computed, h, onMounted } from 'vue' import { useRoute, useRouter } from 'vue-router' const { $dialog, $socket } = globalStore() const { statusOptions, getDealStatus } = statusesStore() const route = useRoute() const router = useRouter() const props = defineProps({ dealId: { type: String, required: true, }, }) const customActions = ref([]) const customStatuses = ref([]) const deal = createResource({ url: 'crm.fcrm.doctype.crm_deal.api.get_deal', params: { name: props.dealId }, cache: ['deal', props.dealId], onSuccess: async (data) => { organization.update({ params: { doctype: 'CRM Organization', name: data.organization }, }) organization.fetch() let obj = { doc: data, $dialog, $socket, router, updateField, createToast, deleteDoc: deleteDeal, resource: { deal, dealContacts, fieldsLayout, }, call, } setupAssignees(data) let customization = await setupCustomizations(data, obj) customActions.value = customization.actions || [] customStatuses.value = customization.statuses || [] }, }) const organization = createResource({ url: 'frappe.client.get', onSuccess: (data) => (deal.data._organizationObj = data), }) onMounted(() => { if (deal.data) return deal.fetch() }) const reload = ref(false) const showOrganizationModal = ref(false) const showAssignmentModal = ref(false) const _organization = ref({}) function updateDeal(fieldname, value, callback) { value = Array.isArray(fieldname) ? '' : value if (validateRequired(fieldname, value)) return createResource({ url: 'frappe.client.set_value', params: { doctype: 'CRM Deal', name: props.dealId, fieldname, value, }, auto: true, onSuccess: () => { deal.reload() reload.value = true createToast({ title: __('Deal updated'), icon: 'check', iconClasses: 'text-green-600', }) callback?.() }, onError: (err) => { createToast({ title: __('Error updating deal'), text: __(err.messages?.[0]), icon: 'x', iconClasses: 'text-red-600', }) }, }) } function validateRequired(fieldname, value) { let meta = deal.data.fields_meta || {} if (meta[fieldname]?.reqd && !value) { createToast({ title: __('Error Updating Deal'), text: __('{0} is a required field', [meta[fieldname].label]), icon: 'x', iconClasses: 'text-red-600', }) return true } return false } const breadcrumbs = computed(() => { let items = [{ label: __('Deals'), route: { name: 'Deals' } }] if (route.query.view || route.query.viewType) { let view = getView(route.query.view, route.query.viewType, 'CRM Deal') if (view) { items.push({ label: __(view.label), icon: view.icon, route: { name: 'Deals', params: { viewType: route.query.viewType }, query: { view: route.query.view }, }, }) } } items.push({ label: organization.data?.name || __('Untitled'), route: { name: 'Deal', params: { dealId: deal.data.name } }, }) return items }) const tabIndex = ref(0) const tabs = computed(() => { let tabOptions = [ { name: 'Details', label: __('Details'), icon: DetailsIcon, condition: () => isMobileView.value, }, { name: 'Activity', label: __('Activity'), icon: ActivityIcon, }, { name: 'Emails', label: __('Emails'), icon: EmailIcon, }, { name: 'Comments', label: __('Comments'), icon: CommentIcon, }, { name: 'Calls', label: __('Calls'), icon: PhoneIcon, condition: () => callEnabled.value, }, { name: 'Tasks', label: __('Tasks'), icon: TaskIcon, }, { name: 'Notes', label: __('Notes'), icon: NoteIcon, }, { name: 'WhatsApp', label: __('WhatsApp'), icon: WhatsAppIcon, condition: () => whatsappEnabled.value, }, ] return tabOptions.filter((tab) => (tab.condition ? tab.condition() : true)) }) const fieldsLayout = createResource({ url: 'crm.api.doc.get_sidebar_fields', cache: ['fieldsLayout', props.dealId], params: { doctype: 'CRM Deal', name: props.dealId }, auto: true, transform: (data) => getParsedFields(data), }) function getParsedFields(sections) { sections.forEach((section) => { if (section.name == 'contacts_section') return section.fields.forEach((field) => { if (field.name == 'organization') { field.create = (value, close) => { _organization.value.organization_name = value showOrganizationModal.value = true close() } field.link = (org) => router.push({ name: 'Organization', params: { organizationId: org }, }) } }) }) return sections } const showContactModal = ref(false) const _contact = ref({}) function contactOptions(contact) { let options = [ { label: __('Delete'), icon: 'trash-2', onClick: () => removeContact(contact), }, ] if (!contact.is_primary) { options.push({ label: __('Set as Primary Contact'), icon: h(SuccessIcon, { class: 'h-4 w-4' }), onClick: () => setPrimaryContact(contact), }) } return options } async function addContact(contact) { let d = await call('crm.fcrm.doctype.crm_deal.crm_deal.add_contact', { deal: props.dealId, contact, }) if (d) { dealContacts.reload() createToast({ title: __('Contact added'), icon: 'check', iconClasses: 'text-green-600', }) } } async function removeContact(contact) { let d = await call('crm.fcrm.doctype.crm_deal.crm_deal.remove_contact', { deal: props.dealId, contact, }) if (d) { dealContacts.reload() createToast({ title: __('Contact removed'), icon: 'check', iconClasses: 'text-green-600', }) } } async function setPrimaryContact(contact) { let d = await call('crm.fcrm.doctype.crm_deal.crm_deal.set_primary_contact', { deal: props.dealId, contact, }) if (d) { dealContacts.reload() createToast({ title: __('Primary contact set'), icon: 'check', iconClasses: 'text-green-600', }) } } const dealContacts = createResource({ url: 'crm.fcrm.doctype.crm_deal.api.get_deal_contacts', params: { name: props.dealId }, cache: ['deal_contacts', props.dealId], auto: true, onSuccess: (data) => { let contactSection = fieldsLayout.data?.find( (section) => section.name == 'contacts_section', ) if (!contactSection) return contactSection.contacts = data.map((contact) => { return { name: contact.name, full_name: contact.full_name, email: contact.email, mobile_no: contact.mobile_no, image: contact.image, is_primary: contact.is_primary, opened: false, } }) }, }) function updateField(name, value, callback) { updateDeal(name, value, () => { deal.data[name] = value callback?.() }) } async function deleteDeal(name) { await call('frappe.client.delete', { doctype: 'CRM Deal', name, }) router.push({ name: 'Deals' }) } </script>
2302_79757062/crm
frontend/src/pages/MobileDeal.vue
Vue
agpl-3.0
18,522
<template> <LayoutHeader v-if="lead.data"> <header class="relative flex h-12 items-center justify-between gap-2 py-2.5 pl-5" > <Breadcrumbs :items="breadcrumbs"> <template #prefix="{ item }"> <Icon v-if="item.icon" :icon="item.icon" class="mr-2 h-4" /> </template> </Breadcrumbs> <div class="absolute right-0"> <Dropdown :options="statusOptions('lead', updateField, customStatuses)"> <template #default="{ open }"> <Button :label="lead.data.status" :class="getLeadStatus(lead.data.status).colorClass" > <template #prefix> <IndicatorIcon /> </template> <template #suffix> <FeatherIcon :name="open ? 'chevron-up' : 'chevron-down'" class="h-4" /> </template> </Button> </template> </Dropdown> </div> </header> </LayoutHeader> <div v-if="lead.data" class="flex h-12 items-center justify-between gap-2 border-b px-3 py-2.5" > <component :is="lead.data._assignedTo?.length == 1 ? 'Button' : 'div'"> <MultipleAvatar :avatars="lead.data._assignedTo" @click="showAssignmentModal = true" /> </component> <div class="flex items-center gap-2"> <CustomActions v-if="customActions" :actions="customActions" /> <Button :label="__('Convert')" variant="solid" @click="showConvertToDealModal = true" /> </div> </div> <div v-if="lead?.data" class="flex h-full overflow-hidden"> <Tabs v-model="tabIndex" v-slot="{ tab }" :tabs="tabs" tablistClass="!px-3" class="overflow-auto" > <div v-if="tab.name == 'Details'"> <SLASection v-if="lead.data.sla_status" v-model="lead.data" @updateField="updateField" /> <div v-if="fieldsLayout.data" class="flex flex-1 flex-col justify-between overflow-hidden" > <div class="flex flex-col overflow-y-auto"> <div v-for="(section, i) in fieldsLayout.data" :key="section.label" class="flex flex-col px-2 py-3 sm:p-3" :class="{ 'border-b': i !== fieldsLayout.data.length - 1 }" > <Section :is-opened="section.opened" :label="section.label"> <SectionFields :fields="section.fields" :isLastSection="i == fieldsLayout.data.length - 1" v-model="lead.data" @update="updateField" /> </Section> </div> </div> </div> </div> <Activities v-else doctype="CRM Lead" :title="tab.name" :tabs="tabs" v-model:reload="reload" v-model:tabIndex="tabIndex" v-model="lead" /> </Tabs> </div> <AssignmentModal v-if="showAssignmentModal" v-model="showAssignmentModal" v-model:assignees="lead.data._assignedTo" :doc="lead.data" doctype="CRM Lead" /> <Dialog v-model="showConvertToDealModal" :options="{ title: __('Convert to Deal'), size: 'xl', actions: [ { label: __('Convert'), variant: 'solid', onClick: convertToDeal, }, ], }" > <template #body-content> <div class="mb-4 flex items-center gap-2 text-gray-600"> <OrganizationsIcon class="h-4 w-4" /> <label class="block text-base">{{ __('Organization') }}</label> </div> <div class="ml-6"> <div class="flex items-center justify-between text-base"> <div>{{ __('Choose Existing') }}</div> <Switch v-model="existingOrganizationChecked" /> </div> <Link v-if="existingOrganizationChecked" class="form-control mt-2.5" variant="outline" size="md" :value="existingOrganization" doctype="CRM Organization" @change="(data) => (existingOrganization = data)" /> <div v-else class="mt-2.5 text-base"> {{ __( 'New organization will be created based on the data in details section', ) }} </div> </div> <div class="mb-4 mt-6 flex items-center gap-2 text-gray-600"> <ContactsIcon class="h-4 w-4" /> <label class="block text-base">{{ __('Contact') }}</label> </div> <div class="ml-6"> <div class="flex items-center justify-between text-base"> <div>{{ __('Choose Existing') }}</div> <Switch v-model="existingContactChecked" /> </div> <Link v-if="existingContactChecked" class="form-control mt-2.5" variant="outline" size="md" :value="existingContact" doctype="Contact" @change="(data) => (existingContact = data)" /> <div v-else class="mt-2.5 text-base"> {{ __("New contact will be created based on the person's details") }} </div> </div> </template> </Dialog> </template> <script setup> import Icon from '@/components/Icon.vue' import DetailsIcon from '@/components/Icons/DetailsIcon.vue' import ActivityIcon from '@/components/Icons/ActivityIcon.vue' import EmailIcon from '@/components/Icons/EmailIcon.vue' import CommentIcon from '@/components/Icons/CommentIcon.vue' import PhoneIcon from '@/components/Icons/PhoneIcon.vue' import TaskIcon from '@/components/Icons/TaskIcon.vue' import NoteIcon from '@/components/Icons/NoteIcon.vue' import WhatsAppIcon from '@/components/Icons/WhatsAppIcon.vue' import IndicatorIcon from '@/components/Icons/IndicatorIcon.vue' import OrganizationsIcon from '@/components/Icons/OrganizationsIcon.vue' import ContactsIcon from '@/components/Icons/ContactsIcon.vue' import LayoutHeader from '@/components/LayoutHeader.vue' import Activities from '@/components/Activities/Activities.vue' import AssignmentModal from '@/components/Modals/AssignmentModal.vue' import MultipleAvatar from '@/components/MultipleAvatar.vue' import Link from '@/components/Controls/Link.vue' import Section from '@/components/Section.vue' import SectionFields from '@/components/SectionFields.vue' import SLASection from '@/components/SLASection.vue' import CustomActions from '@/components/CustomActions.vue' import { createToast, setupAssignees, setupCustomizations } from '@/utils' import { getView } from '@/utils/view' import { globalStore } from '@/stores/global' import { contactsStore } from '@/stores/contacts' import { statusesStore } from '@/stores/statuses' import { whatsappEnabled, callEnabled, isMobileView, } from '@/composables/settings' import { createResource, Dropdown, Tabs, Switch, Breadcrumbs, call, } from 'frappe-ui' import { ref, computed, onMounted, watch } from 'vue' import { useRouter, useRoute } from 'vue-router' const { $dialog, $socket } = globalStore() const { getContactByName, contacts } = contactsStore() const { statusOptions, getLeadStatus } = statusesStore() const route = useRoute() const router = useRouter() const props = defineProps({ leadId: { type: String, required: true, }, }) const customActions = ref([]) const customStatuses = ref([]) const lead = createResource({ url: 'crm.fcrm.doctype.crm_lead.api.get_lead', params: { name: props.leadId }, cache: ['lead', props.leadId], onSuccess: async (data) => { let obj = { doc: data, $dialog, $socket, router, updateField, createToast, deleteDoc: deleteLead, resource: { lead, fieldsLayout, }, call, } setupAssignees(data) let customization = await setupCustomizations(data, obj) customActions.value = customization.actions || [] customStatuses.value = customization.statuses || [] }, }) onMounted(() => { if (lead.data) return lead.fetch() }) const reload = ref(false) const showAssignmentModal = ref(false) function updateLead(fieldname, value, callback) { value = Array.isArray(fieldname) ? '' : value if (!Array.isArray(fieldname) && validateRequired(fieldname, value)) return createResource({ url: 'frappe.client.set_value', params: { doctype: 'CRM Lead', name: props.leadId, fieldname, value, }, auto: true, onSuccess: () => { lead.reload() reload.value = true createToast({ title: __('Lead updated'), icon: 'check', iconClasses: 'text-green-600', }) callback?.() }, onError: (err) => { createToast({ title: __('Error updating lead'), text: __(err.messages?.[0]), icon: 'x', iconClasses: 'text-red-600', }) }, }) } function validateRequired(fieldname, value) { let meta = lead.data.fields_meta || {} if (meta[fieldname]?.reqd && !value) { createToast({ title: __('Error Updating Lead'), text: __('{0} is a required field', [meta[fieldname].label]), icon: 'x', iconClasses: 'text-red-600', }) return true } return false } const breadcrumbs = computed(() => { let items = [{ label: __('Leads'), route: { name: 'Leads' } }] if (route.query.view || route.query.viewType) { let view = getView(route.query.view, route.query.viewType, 'CRM Lead') if (view) { items.push({ label: __(view.label), icon: view.icon, route: { name: 'Leads', params: { viewType: route.query.viewType }, query: { view: route.query.view }, }, }) } } items.push({ label: lead.data.lead_name || __('Untitled'), route: { name: 'Lead', params: { leadId: lead.data.name } }, }) return items }) const tabIndex = ref(0) const tabs = computed(() => { let tabOptions = [ { name: 'Details', label: __('Details'), icon: DetailsIcon, condition: () => isMobileView.value, }, { name: 'Activity', label: __('Activity'), icon: ActivityIcon, }, { name: 'Emails', label: __('Emails'), icon: EmailIcon, }, { name: 'Comments', label: __('Comments'), icon: CommentIcon, }, { name: 'Calls', label: __('Calls'), icon: PhoneIcon, condition: () => callEnabled.value, }, { name: 'Tasks', label: __('Tasks'), icon: TaskIcon, }, { name: 'Notes', label: __('Notes'), icon: NoteIcon, }, { name: 'WhatsApp', label: __('WhatsApp'), icon: WhatsAppIcon, condition: () => whatsappEnabled.value, }, ] return tabOptions.filter((tab) => (tab.condition ? tab.condition() : true)) }) watch(tabs, (value) => { if (value && route.params.tabName) { let index = value.findIndex( (tab) => tab.name.toLowerCase() === route.params.tabName.toLowerCase(), ) if (index !== -1) { tabIndex.value = index } } }) const fieldsLayout = createResource({ url: 'crm.api.doc.get_sidebar_fields', cache: ['fieldsLayout', props.leadId], params: { doctype: 'CRM Lead', name: props.leadId }, auto: true, }) function updateField(name, value, callback) { updateLead(name, value, () => { lead.data[name] = value callback?.() }) } async function deleteLead(name) { await call('frappe.client.delete', { doctype: 'CRM Lead', name, }) router.push({ name: 'Leads' }) } // Convert to Deal const showConvertToDealModal = ref(false) const existingContactChecked = ref(false) const existingOrganizationChecked = ref(false) const existingContact = ref('') const existingOrganization = ref('') async function convertToDeal(updated) { let valueUpdated = false if (existingContactChecked.value && !existingContact.value) { createToast({ title: __('Error'), text: __('Please select an existing contact'), icon: 'x', iconClasses: 'text-red-600', }) return } if (existingOrganizationChecked.value && !existingOrganization.value) { createToast({ title: __('Error'), text: __('Please select an existing organization'), icon: 'x', iconClasses: 'text-red-600', }) return } if (existingContactChecked.value && existingContact.value) { lead.data.salutation = getContactByName(existingContact.value).salutation lead.data.first_name = getContactByName(existingContact.value).first_name lead.data.last_name = getContactByName(existingContact.value).last_name lead.data.email_id = getContactByName(existingContact.value).email_id lead.data.mobile_no = getContactByName(existingContact.value).mobile_no existingContactChecked.value = false valueUpdated = true } if (existingOrganizationChecked.value && existingOrganization.value) { lead.data.organization = existingOrganization.value existingOrganizationChecked.value = false valueUpdated = true } if (valueUpdated) { updateLead( { salutation: lead.data.salutation, first_name: lead.data.first_name, last_name: lead.data.last_name, email_id: lead.data.email_id, mobile_no: lead.data.mobile_no, organization: lead.data.organization, }, '', () => convertToDeal(true), ) showConvertToDealModal.value = false } else { let deal = await call( 'crm.fcrm.doctype.crm_lead.crm_lead.convert_to_deal', { lead: lead.data.name, }, ) if (deal) { if (updated) { await contacts.reload() } router.push({ name: 'Deal', params: { dealId: deal } }) } } } </script>
2302_79757062/crm
frontend/src/pages/MobileLead.vue
Vue
agpl-3.0
13,888
<template> <LayoutHeader> <template #left-header> <Breadcrumbs :items="[ { label: __('Notifications'), route: { name: 'Notifications' } }, ]" /> </template> <template #right-header> <Tooltip :text="__('Mark all as read')"> <div> <Button :label="__('Mark all as read')" @click="() => notificationsStore().mark_as_read.reload()" > <template #prefix> <MarkAsDoneIcon class="h-4 w-4" /> </template> </Button> </div> </Tooltip> </template> </LayoutHeader> <div class="flex flex-col overflow-hidden"> <div v-if="notificationsStore().allNotifications?.length" class="divide-y overflow-y-auto text-base" > <RouterLink v-for="n in notificationsStore().allNotifications" :key="n.comment" :to="getRoute(n)" class="flex cursor-pointer items-start gap-3 px-2.5 py-3 hover:bg-gray-100" @click="mark_as_read(n.comment || n.notification_type_doc)" > <div class="mt-1 flex items-center gap-2.5"> <div class="size-[5px] rounded-full" :class="[n.read ? 'bg-transparent' : 'bg-gray-900']" /> <WhatsAppIcon v-if="n.type == 'WhatsApp'" class="size-7" /> <UserAvatar v-else :user="n.from_user.name" size="lg" /> </div> <div> <div v-if="n.notification_text" v-html="n.notification_text" /> <div v-else class="mb-2 space-x-1 leading-5 text-gray-600"> <span class="font-medium text-gray-900"> {{ n.from_user.full_name }} </span> <span> {{ __('mentioned you in {0}', [n.reference_doctype]) }} </span> <span class="font-medium text-gray-900"> {{ n.reference_name }} </span> </div> <div class="text-sm text-gray-600"> {{ __(timeAgo(n.creation)) }} </div> </div> </RouterLink> </div> <div v-else class="flex flex-1 flex-col items-center justify-center gap-2"> <NotificationsIcon class="h-20 w-20 text-gray-300" /> <div class="text-lg font-medium text-gray-500"> {{ __('No new notifications') }} </div> </div> </div> </template> <script setup> import LayoutHeader from '@/components/LayoutHeader.vue' import WhatsAppIcon from '@/components/Icons/WhatsAppIcon.vue' import MarkAsDoneIcon from '@/components/Icons/MarkAsDoneIcon.vue' import NotificationsIcon from '@/components/Icons/NotificationsIcon.vue' import UserAvatar from '@/components/UserAvatar.vue' import { notificationsStore } from '@/stores/notifications' import { globalStore } from '@/stores/global' import { timeAgo } from '@/utils' import { Breadcrumbs, Tooltip } from 'frappe-ui' import { onMounted, onBeforeUnmount } from 'vue' const { $socket } = globalStore() function mark_as_read(doc) { notificationsStore().mark_doc_as_read(doc) } onBeforeUnmount(() => { $socket.off('crm_notification') }) onMounted(() => { $socket.on('crm_notification', () => { notificationsStore().notifications.reload() }) }) function getRoute(notification) { let params = { leadId: notification.reference_name, } if (notification.route_name === 'Deal') { params = { dealId: notification.reference_name, } } return { name: notification.route_name, params: params, hash: '#' + notification.comment || notification.notification_type_doc, } } </script>
2302_79757062/crm
frontend/src/pages/MobileNotification.vue
Vue
agpl-3.0
3,591
<template> <LayoutHeader> <template #left-header> <ViewBreadcrumbs v-model="viewControls" routeName="Notes" /> </template> <template #right-header> <Button variant="solid" :label="__('Create')" @click="createNote"> <template #prefix><FeatherIcon name="plus" class="h-4" /></template> </Button> </template> </LayoutHeader> <ViewControls ref="viewControls" v-model="notes" v-model:loadMore="loadMore" v-model:updatedPageCount="updatedPageCount" doctype="FCRM Note" :options="{ hideColumnsButton: true, defaultViewName: __('Notes View'), }" /> <div class="flex-1 overflow-y-auto"> <div v-if="notes.data?.data?.length" class="grid grid-cols-1 gap-2 px-3 pb-2 sm:grid-cols-4 sm:gap-4 sm:px-5 sm:pb-3" > <div v-for="note in notes.data.data" class="group flex h-56 cursor-pointer flex-col justify-between gap-2 rounded-lg border px-5 py-4 shadow-sm hover:bg-gray-50" @click="editNote(note)" > <div class="flex items-center justify-between"> <div class="truncate text-lg font-medium"> {{ note.title }} </div> <Dropdown :options="[ { label: __('Delete'), icon: 'trash-2', onClick: () => deleteNote(note.name), }, ]" @click.stop > <Button icon="more-horizontal" variant="ghosted" class="hover:bg-white" /> </Dropdown> </div> <TextEditor v-if="note.content" :content="note.content" :editable="false" editor-class="!prose-sm max-w-none !text-sm text-gray-600 focus:outline-none" class="flex-1 overflow-hidden" /> <div class="mt-2 flex items-center justify-between gap-2"> <div class="flex items-center gap-2"> <UserAvatar :user="note.owner" size="xs" /> <div class="text-sm text-gray-800"> {{ getUser(note.owner).full_name }} </div> </div> <Tooltip :text="dateFormat(note.modified, dateTooltipFormat)"> <div class="text-sm text-gray-700"> {{ __(timeAgo(note.modified)) }} </div> </Tooltip> </div> </div> </div> </div> <ListFooter v-if="notes.data?.data?.length" class="border-t px-3 py-2 sm:px-5" v-model="notes.data.page_length_count" :options="{ rowCount: notes.data.row_count, totalCount: notes.data.total_count, }" @loadMore="() => loadMore++" /> <div v-else class="flex h-full items-center justify-center"> <div class="flex flex-col items-center gap-3 text-xl font-medium text-gray-500" > <NoteIcon class="h-10 w-10" /> <span>{{ __('No {0} Found', [__('Notes')]) }}</span> <Button :label="__('Create')" @click="createNote"> <template #prefix><FeatherIcon name="plus" class="h-4" /></template> </Button> </div> </div> <NoteModal v-model="showNoteModal" v-model:reloadNotes="notes" :note="currentNote" /> </template> <script setup> import ViewBreadcrumbs from '@/components/ViewBreadcrumbs.vue' import LayoutHeader from '@/components/LayoutHeader.vue' import UserAvatar from '@/components/UserAvatar.vue' import NoteIcon from '@/components/Icons/NoteIcon.vue' import NoteModal from '@/components/Modals/NoteModal.vue' import ViewControls from '@/components/ViewControls.vue' import { usersStore } from '@/stores/users' import { timeAgo, dateFormat, dateTooltipFormat } from '@/utils' import { TextEditor, call, Dropdown, Tooltip, ListFooter } from 'frappe-ui' import { ref, watch } from 'vue' const { getUser } = usersStore() const showNoteModal = ref(false) const currentNote = ref(null) const notes = ref({}) const loadMore = ref(1) const updatedPageCount = ref(20) const viewControls = ref(null) watch( () => notes.value?.data?.page_length_count, (val, old_value) => { if (!val || val === old_value) return updatedPageCount.value = val }, ) function createNote() { currentNote.value = { title: '', content: '', } showNoteModal.value = true } function editNote(note) { currentNote.value = note showNoteModal.value = true } async function deleteNote(name) { await call('frappe.client.delete', { doctype: 'FCRM Note', name, }) notes.value.reload() } </script>
2302_79757062/crm
frontend/src/pages/Notes.vue
Vue
agpl-3.0
4,541
<template> <LayoutHeader v-if="organization.doc"> <template #left-header> <Breadcrumbs :items="breadcrumbs"> <template #prefix="{ item }"> <Icon v-if="item.icon" :icon="item.icon" class="mr-2 h-4" /> </template> </Breadcrumbs> </template> </LayoutHeader> <div v-if="organization.doc" class="flex flex-1 flex-col overflow-hidden"> <FileUploader @success="changeOrganizationImage" :validateFile="validateFile" > <template #default="{ openFileSelector, error }"> <div class="flex items-start justify-start gap-6 p-5 sm:items-center"> <div class="group relative h-24 w-24"> <Avatar size="3xl" :image="organization.doc.organization_logo" :label="organization.doc.name" class="!h-24 !w-24" /> <component :is="organization.doc.organization_logo ? Dropdown : 'div'" v-bind=" organization.doc.organization_logo ? { options: [ { icon: 'upload', label: organization.doc.organization_logo ? __('Change image') : __('Upload image'), onClick: openFileSelector, }, { icon: 'trash-2', label: __('Remove image'), onClick: () => changeOrganizationImage(''), }, ], } : { onClick: openFileSelector } " class="!absolute bottom-0 left-0 right-0" > <div class="z-1 absolute bottom-0 left-0 right-0 flex h-13 cursor-pointer items-center justify-center rounded-b-full bg-black bg-opacity-40 pt-3 opacity-0 duration-300 ease-in-out group-hover:opacity-100" style=" -webkit-clip-path: inset(12px 0 0 0); clip-path: inset(12px 0 0 0); " > <CameraIcon class="h-6 w-6 cursor-pointer text-white" /> </div> </component> </div> <div class="flex flex-col justify-center gap-2 sm:gap-0.5"> <div class="text-3xl font-semibold text-gray-900"> {{ organization.doc.name }} </div> <div class="flex flex-col flex-wrap gap-3 text-base text-gray-700 sm:flex-row sm:items-center sm:gap-2" > <div v-if="organization.doc.website" class="flex items-center gap-1.5" > <WebsiteIcon class="h-4 w-4" /> <span class="">{{ website(organization.doc.website) }}</span> </div> <span v-if="organization.doc.website" class="hidden text-3xl leading-[0] text-gray-600 sm:flex" > &middot; </span> <div v-if="organization.doc.industry" class="flex items-center gap-1.5" > <FeatherIcon name="briefcase" class="h-4 w-4" /> <span class="">{{ organization.doc.industry }}</span> </div> <span v-if="organization.doc.industry" class="hidden text-3xl leading-[0] text-gray-600 sm:flex" > &middot; </span> <div v-if="organization.doc.territory" class="flex items-center gap-1.5" > <TerritoryIcon class="h-4 w-4" /> <span class="">{{ organization.doc.territory }}</span> </div> <span v-if="organization.doc.territory" class="hidden text-3xl leading-[0] text-gray-600 sm:flex" > &middot; </span> <div v-if="organization.doc.annual_revenue" class="flex items-center gap-1.5" > <MoneyIcon class="size-4" /> <span class="">{{ formatNumberIntoCurrency( organization.doc.annual_revenue, organization.doc.currency, ) }}</span> </div> <span v-if="organization.doc.annual_revenue" class="hidden text-3xl leading-[0] text-gray-600 sm:flex" > &middot; </span> <Button v-if=" organization.doc.website || organization.doc.industry || organization.doc.territory || organization.doc.annual_revenue " variant="ghost" :label="__('More')" class="w-fit cursor-pointer hover:text-gray-900 sm:-ml-1" @click=" () => { detailMode = true showOrganizationModal = true } " /> </div> <div class="mt-2 flex gap-1.5"> <Button :label="__('Edit')" size="sm" @click=" () => { detailMode = false showOrganizationModal = true } " > <template #prefix> <EditIcon class="h-4 w-4" /> </template> </Button> <Button :label="__('Delete')" theme="red" size="sm" @click="deleteOrganization" > <template #prefix> <FeatherIcon name="trash-2" class="h-4 w-4" /> </template> </Button> </div> <ErrorMessage class="mt-2" :message="__(error)" /> </div> </div> </template> </FileUploader> <Tabs v-model="tabIndex" :tabs="tabs"> <template #tab="{ tab, selected }"> <button class="group flex items-center gap-2 border-b border-transparent py-2.5 text-base text-gray-600 duration-300 ease-in-out hover:border-gray-400 hover:text-gray-900" :class="{ 'text-gray-900': selected }" > <component v-if="tab.icon" :is="tab.icon" class="h-5" /> {{ __(tab.label) }} <Badge class="group-hover:bg-gray-900" :class="[selected ? 'bg-gray-900' : 'bg-gray-600']" variant="solid" theme="gray" size="sm" > {{ tab.count }} </Badge> </button> </template> <template #default="{ tab }"> <DealsListView class="mt-4" v-if="tab.label === 'Deals' && rows.length" :rows="rows" :columns="columns" :options="{ selectable: false, showTooltip: false }" /> <ContactsListView class="mt-4" v-if="tab.label === 'Contacts' && rows.length" :rows="rows" :columns="columns" :options="{ selectable: false, showTooltip: false }" /> <div v-if="!rows.length" class="grid flex-1 place-items-center text-xl font-medium text-gray-500" > <div class="flex flex-col items-center justify-center space-y-3"> <component :is="tab.icon" class="!h-10 !w-10" /> <div>{{ __('No {0} Found', [__(tab.label)]) }}</div> </div> </div> </template> </Tabs> </div> <OrganizationModal v-model="showOrganizationModal" v-model:quickEntry="showQuickEntryModal" v-model:organization="organization" :options="{ detailMode }" /> <QuickEntryModal v-if="showQuickEntryModal" v-model="showQuickEntryModal" doctype="CRM Organization" /> </template> <script setup> import Icon from '@/components/Icon.vue' import LayoutHeader from '@/components/LayoutHeader.vue' import OrganizationModal from '@/components/Modals/OrganizationModal.vue' import QuickEntryModal from '@/components/Modals/QuickEntryModal.vue' import DealsListView from '@/components/ListViews/DealsListView.vue' import ContactsListView from '@/components/ListViews/ContactsListView.vue' import WebsiteIcon from '@/components/Icons/WebsiteIcon.vue' import TerritoryIcon from '@/components/Icons/TerritoryIcon.vue' import MoneyIcon from '@/components/Icons/MoneyIcon.vue' import EditIcon from '@/components/Icons/EditIcon.vue' import CameraIcon from '@/components/Icons/CameraIcon.vue' import DealsIcon from '@/components/Icons/DealsIcon.vue' import ContactsIcon from '@/components/Icons/ContactsIcon.vue' import { globalStore } from '@/stores/global' import { usersStore } from '@/stores/users' import { statusesStore } from '@/stores/statuses' import { getView } from '@/utils/view' import { dateFormat, dateTooltipFormat, timeAgo, formatNumberIntoCurrency, } from '@/utils' import { Breadcrumbs, Avatar, FileUploader, Dropdown, Tabs, call, createListResource, createDocumentResource, usePageMeta, } from 'frappe-ui' import { h, computed, ref } from 'vue' import { useRoute, useRouter } from 'vue-router' const props = defineProps({ organizationId: { type: String, required: true, }, }) const { $dialog } = globalStore() const { getDealStatus } = statusesStore() const showOrganizationModal = ref(false) const showQuickEntryModal = ref(false) const detailMode = ref(false) const route = useRoute() const router = useRouter() const organization = createDocumentResource({ doctype: 'CRM Organization', name: props.organizationId, cache: ['organization', props.organizationId], fields: ['*'], auto: true, }) const breadcrumbs = computed(() => { let items = [{ label: __('Organizations'), route: { name: 'Organizations' } }] if (route.query.view || route.query.viewType) { let view = getView( route.query.view, route.query.viewType, 'CRM Organization', ) if (view) { items.push({ label: __(view.label), icon: view.icon, route: { name: 'Organizations', params: { viewType: route.query.viewType }, query: { view: route.query.view }, }, }) } } items.push({ label: props.organizationId, route: { name: 'Organization', params: { organizationId: props.organizationId }, }, }) return items }) usePageMeta(() => { return { title: props.organizationId, } }) function validateFile(file) { let extn = file.name.split('.').pop().toLowerCase() if (!['png', 'jpg', 'jpeg'].includes(extn)) { return __('Only PNG and JPG images are allowed') } } async function changeOrganizationImage(file) { await call('frappe.client.set_value', { doctype: 'CRM Organization', name: props.organizationId, fieldname: 'organization_logo', value: file?.file_url || '', }) organization.reload() } async function deleteOrganization() { $dialog({ title: __('Delete organization'), message: __('Are you sure you want to delete this organization?'), actions: [ { label: __('Delete'), theme: 'red', variant: 'solid', async onClick(close) { await call('frappe.client.delete', { doctype: 'CRM Organization', name: props.organizationId, }) close() router.push({ name: 'Organizations' }) }, }, ], }) } function website(url) { return url && url.replace(/^(?:https?:\/\/)?(?:www\.)?/i, '') } const tabIndex = ref(0) const tabs = [ { label: 'Deals', icon: h(DealsIcon, { class: 'h-4 w-4' }), count: computed(() => deals.data?.length), }, { label: 'Contacts', icon: h(ContactsIcon, { class: 'h-4 w-4' }), count: computed(() => contacts.data?.length), }, ] const { getUser } = usersStore() const deals = createListResource({ type: 'list', doctype: 'CRM Deal', cache: ['deals', props.organizationId], fields: [ 'name', 'organization', 'currency', 'annual_revenue', 'status', 'email', 'mobile_no', 'deal_owner', 'modified', ], filters: { organization: props.organizationId, }, orderBy: 'modified desc', pageLength: 20, auto: true, }) const contacts = createListResource({ type: 'list', doctype: 'Contact', cache: ['contacts', props.organizationId], fields: [ 'name', 'full_name', 'image', 'email_id', 'mobile_no', 'company_name', 'modified', ], filters: { company_name: props.organizationId, }, orderBy: 'modified desc', pageLength: 20, auto: true, }) const rows = computed(() => { let list = [] list = !tabIndex.value ? deals : contacts if (!list.data) return [] return list.data.map((row) => { return !tabIndex.value ? getDealRowObject(row) : getContactRowObject(row) }) }) const columns = computed(() => { return tabIndex.value === 0 ? dealColumns : contactColumns }) function getDealRowObject(deal) { return { name: deal.name, organization: { label: deal.organization, logo: props.organization?.organization_logo, }, annual_revenue: formatNumberIntoCurrency( deal.annual_revenue, deal.currency, ), status: { label: deal.status, color: getDealStatus(deal.status)?.iconColorClass, }, email: deal.email, mobile_no: deal.mobile_no, deal_owner: { label: deal.deal_owner && getUser(deal.deal_owner).full_name, ...(deal.deal_owner && getUser(deal.deal_owner)), }, modified: { label: dateFormat(deal.modified, dateTooltipFormat), timeAgo: __(timeAgo(deal.modified)), }, } } function getContactRowObject(contact) { return { name: contact.name, full_name: { label: contact.full_name, image_label: contact.full_name, image: contact.image, }, email: contact.email_id, mobile_no: contact.mobile_no, company_name: { label: contact.company_name, logo: props.organization?.organization_logo, }, modified: { label: dateFormat(contact.modified, dateTooltipFormat), timeAgo: __(timeAgo(contact.modified)), }, } } const dealColumns = [ { label: __('Organization'), key: 'organization', width: '11rem', }, { label: __('Amount'), key: 'annual_revenue', width: '9rem', }, { label: __('Status'), key: 'status', width: '10rem', }, { label: __('Email'), key: 'email', width: '12rem', }, { label: __('Mobile no'), key: 'mobile_no', width: '11rem', }, { label: __('Deal owner'), key: 'deal_owner', width: '10rem', }, { label: __('Last modified'), key: 'modified', width: '8rem', }, ] const contactColumns = [ { label: __('Name'), key: 'full_name', width: '17rem', }, { label: __('Email'), key: 'email', width: '12rem', }, { label: __('Phone'), key: 'mobile_no', width: '12rem', }, { label: __('Organization'), key: 'company_name', width: '12rem', }, { label: __('Last modified'), key: 'modified', width: '8rem', }, ] </script>
2302_79757062/crm
frontend/src/pages/Organization.vue
Vue
agpl-3.0
15,670
<template> <LayoutHeader> <template #left-header> <ViewBreadcrumbs v-model="viewControls" routeName="Organizations" /> </template> <template #right-header> <CustomActions v-if="organizationsListView?.customListActions" :actions="organizationsListView.customListActions" /> <Button variant="solid" :label="__('Create')" @click="showOrganizationModal = true" > <template #prefix><FeatherIcon name="plus" class="h-4" /></template> </Button> </template> </LayoutHeader> <ViewControls ref="viewControls" v-model="organizations" v-model:loadMore="loadMore" v-model:resizeColumn="triggerResize" v-model:updatedPageCount="updatedPageCount" doctype="CRM Organization" /> <OrganizationsListView ref="organizationsListView" v-if="organizations.data && rows.length" v-model="organizations.data.page_length_count" v-model:list="organizations" :rows="rows" :columns="organizations.data.columns" :options="{ showTooltip: false, resizeColumn: true, rowCount: organizations.data.row_count, totalCount: organizations.data.total_count, }" @loadMore="() => loadMore++" @columnWidthUpdated="() => triggerResize++" @updatePageCount="(count) => (updatedPageCount = count)" @applyFilter="(data) => viewControls.applyFilter(data)" @applyLikeFilter="(data) => viewControls.applyLikeFilter(data)" @likeDoc="(data) => viewControls.likeDoc(data)" /> <div v-else-if="organizations.data" class="flex h-full items-center justify-center" > <div class="flex flex-col items-center gap-3 text-xl font-medium text-gray-500" > <OrganizationsIcon class="h-10 w-10" /> <span>{{ __('No {0} Found', [__('Organizations')]) }}</span> <Button :label="__('Create')" @click="showOrganizationModal = true"> <template #prefix><FeatherIcon name="plus" class="h-4" /></template> </Button> </div> </div> <OrganizationModal v-model="showOrganizationModal" v-model:quickEntry="showQuickEntryModal" /> <QuickEntryModal v-if="showQuickEntryModal" v-model="showQuickEntryModal" doctype="CRM Organization" /> </template> <script setup> import ViewBreadcrumbs from '@/components/ViewBreadcrumbs.vue' import CustomActions from '@/components/CustomActions.vue' import OrganizationsIcon from '@/components/Icons/OrganizationsIcon.vue' import LayoutHeader from '@/components/LayoutHeader.vue' import OrganizationModal from '@/components/Modals/OrganizationModal.vue' import QuickEntryModal from '@/components/Modals/QuickEntryModal.vue' import OrganizationsListView from '@/components/ListViews/OrganizationsListView.vue' import ViewControls from '@/components/ViewControls.vue' import { dateFormat, dateTooltipFormat, timeAgo, website, formatNumberIntoCurrency, } from '@/utils' import { ref, computed } from 'vue' const organizationsListView = ref(null) const showOrganizationModal = ref(false) const showQuickEntryModal = ref(false) // organizations data is loaded in the ViewControls component const organizations = ref({}) const loadMore = ref(1) const triggerResize = ref(1) const updatedPageCount = ref(20) const viewControls = ref(null) const rows = computed(() => { if ( !organizations.value?.data?.data || !['list', 'group_by'].includes(organizations.value.data.view_type) ) return [] return organizations.value?.data.data.map((organization) => { let _rows = {} organizations.value?.data.rows.forEach((row) => { _rows[row] = organization[row] if (row === 'organization_name') { _rows[row] = { label: organization.organization_name, logo: organization.organization_logo, } } else if (row === 'website') { _rows[row] = website(organization.website) } else if (row === 'annual_revenue') { _rows[row] = formatNumberIntoCurrency( organization.annual_revenue, organization.currency, ) } else if (['modified', 'creation'].includes(row)) { _rows[row] = { label: dateFormat(organization[row], dateTooltipFormat), timeAgo: __(timeAgo(organization[row])), } } }) return _rows }) }) </script>
2302_79757062/crm
frontend/src/pages/Organizations.vue
Vue
agpl-3.0
4,338
<template> <LayoutHeader> <template #left-header> <ViewBreadcrumbs v-model="viewControls" routeName="Tasks" /> </template> <template #right-header> <CustomActions v-if="tasksListView?.customListActions" :actions="tasksListView.customListActions" /> <Button variant="solid" :label="__('Create')" @click="createTask"> <template #prefix><FeatherIcon name="plus" class="h-4" /></template> </Button> </template> </LayoutHeader> <ViewControls ref="viewControls" v-model="tasks" v-model:loadMore="loadMore" v-model:resizeColumn="triggerResize" v-model:updatedPageCount="updatedPageCount" doctype="CRM Task" :options="{ allowedViews: ['list', 'kanban'], }" /> <KanbanView v-if="$route.params.viewType == 'kanban' && rows.length" v-model="tasks" :options="{ onClick: (row) => showTask(row.name), onNewClick: (column) => createTask(column), }" @update="(data) => viewControls.updateKanbanSettings(data)" @loadMore="(columnName) => viewControls.loadMoreKanban(columnName)" > <template #title="{ titleField, itemName }"> <div class="flex items-center gap-2"> <div v-if="titleField === 'status'"> <TaskStatusIcon :status="getRow(itemName, titleField).label" /> </div> <div v-else-if="titleField === 'priority'"> <TaskPriorityIcon :priority="getRow(itemName, titleField).label" /> </div> <div v-else-if="titleField === 'assigned_to'"> <Avatar v-if="getRow(itemName, titleField).full_name" class="flex items-center" :image="getRow(itemName, titleField).user_image" :label="getRow(itemName, titleField).full_name" size="sm" /> </div> <div v-if="['modified', 'creation'].includes(titleField)" class="truncate text-base" > <Tooltip :text="getRow(itemName, titleField).label"> <div>{{ getRow(itemName, titleField).timeAgo }}</div> </Tooltip> </div> <div v-else-if="getRow(itemName, titleField).label" class="truncate text-base" > {{ getRow(itemName, titleField).label }} </div> <div class="text-gray-500" v-else>{{ __('No Title') }}</div> </div> </template> <template #fields="{ fieldName, itemName }"> <div v-if="getRow(itemName, fieldName).label" class="truncate flex items-center gap-2" > <div v-if="fieldName === 'status'"> <TaskStatusIcon class="size-3" :status="getRow(itemName, fieldName).label" /> </div> <div v-else-if="fieldName === 'priority'"> <TaskPriorityIcon :priority="getRow(itemName, fieldName).label" /> </div> <div v-else-if="fieldName === 'assigned_to'"> <Avatar v-if="getRow(itemName, fieldName).full_name" class="flex items-center" :image="getRow(itemName, fieldName).user_image" :label="getRow(itemName, fieldName).full_name" size="sm" /> </div> <div v-if="['modified', 'creation'].includes(fieldName)" class="truncate text-base" > <Tooltip :text="getRow(itemName, fieldName).label"> <div>{{ getRow(itemName, fieldName).timeAgo }}</div> </Tooltip> </div> <div v-else-if="fieldName == 'description'" class="truncate text-base max-h-44" > <TextEditor v-if="getRow(itemName, fieldName).label" :content="getRow(itemName, fieldName).label" :editable="false" editor-class="!prose-sm max-w-none focus:outline-none" class="flex-1 overflow-hidden" /> </div> <div v-else class="truncate text-base"> {{ getRow(itemName, fieldName).label }} </div> </div> </template> <template #actions="{ itemName }"> <div class="flex gap-2 items-center justify-between"> <div> <Button class="-ml-2" v-if="getRow(itemName, 'reference_docname').label" variant="ghost" size="sm" :label=" getRow(itemName, 'reference_doctype').label == 'CRM Deal' ? __('Deal') : __('Lead') " @click.stop=" redirect( getRow(itemName, 'reference_doctype').label, getRow(itemName, 'reference_docname').label, ) " > <template #suffix> <ArrowUpRightIcon class="h-4 w-4" /> </template> </Button> </div> <Dropdown class="flex items-center gap-2" :options="actions(itemName)" variant="ghost" @click.stop.prevent > <Button icon="more-horizontal" variant="ghost" /> </Dropdown> </div> </template> </KanbanView> <TasksListView ref="tasksListView" v-else-if="tasks.data && rows.length" v-model="tasks.data.page_length_count" v-model:list="tasks" :rows="rows" :columns="tasks.data.columns" :options="{ showTooltip: false, resizeColumn: true, rowCount: tasks.data.row_count, totalCount: tasks.data.total_count, }" @loadMore="() => loadMore++" @columnWidthUpdated="() => triggerResize++" @updatePageCount="(count) => (updatedPageCount = count)" @showTask="showTask" @applyFilter="(data) => viewControls.applyFilter(data)" @applyLikeFilter="(data) => viewControls.applyLikeFilter(data)" @likeDoc="(data) => viewControls.likeDoc(data)" /> <div v-else-if="tasks.data" class="flex h-full items-center justify-center"> <div class="flex flex-col items-center gap-3 text-xl font-medium text-gray-500" > <Email2Icon class="h-10 w-10" /> <span>{{ __('No {0} Found', [__('Tasks')]) }}</span> <Button :label="__('Create')" @click="showTaskModal = true"> <template #prefix><FeatherIcon name="plus" class="h-4" /></template> </Button> </div> </div> <TaskModal v-if="showTaskModal" v-model="showTaskModal" v-model:reloadTasks="tasks" :task="task" /> </template> <script setup> import ViewBreadcrumbs from '@/components/ViewBreadcrumbs.vue' import CustomActions from '@/components/CustomActions.vue' import ArrowUpRightIcon from '@/components/Icons/ArrowUpRightIcon.vue' import TaskStatusIcon from '@/components/Icons/TaskStatusIcon.vue' import TaskPriorityIcon from '@/components/Icons/TaskPriorityIcon.vue' import Email2Icon from '@/components/Icons/Email2Icon.vue' import LayoutHeader from '@/components/LayoutHeader.vue' import ViewControls from '@/components/ViewControls.vue' import TasksListView from '@/components/ListViews/TasksListView.vue' import KanbanView from '@/components/Kanban/KanbanView.vue' import TaskModal from '@/components/Modals/TaskModal.vue' import { usersStore } from '@/stores/users' import { dateFormat, dateTooltipFormat, timeAgo } from '@/utils' import { Tooltip, Avatar, TextEditor, Dropdown, call } from 'frappe-ui' import { computed, ref } from 'vue' import { useRouter } from 'vue-router' const { getUser } = usersStore() const router = useRouter() const tasksListView = ref(null) // tasks data is loaded in the ViewControls component const tasks = ref({}) const loadMore = ref(1) const triggerResize = ref(1) const updatedPageCount = ref(20) const viewControls = ref(null) function getRow(name, field) { function getValue(value) { if (value && typeof value === 'object') { return value } return { label: value } } return getValue(rows.value?.find((row) => row.name == name)[field]) } const rows = computed(() => { if (!tasks.value?.data?.data) return [] if (tasks.value.data.view_type === 'kanban') { return getKanbanRows(tasks.value.data.data) } return parseRows(tasks.value?.data.data) }) function getKanbanRows(data) { let _rows = [] data.forEach((column) => { column.data?.forEach((row) => { _rows.push(row) }) }) return parseRows(_rows) } function parseRows(rows) { return rows.map((task) => { let _rows = {} tasks.value?.data.rows.forEach((row) => { _rows[row] = task[row] if (['modified', 'creation'].includes(row)) { _rows[row] = { label: dateFormat(task[row], dateTooltipFormat), timeAgo: __(timeAgo(task[row])), } } else if (row == 'assigned_to') { _rows[row] = { label: task.assigned_to && getUser(task.assigned_to).full_name, ...(task.assigned_to && getUser(task.assigned_to)), } } }) return _rows }) } const showTaskModal = ref(false) const task = ref({ name: '', title: '', description: '', assigned_to: '', due_date: '', status: 'Backlog', priority: 'Low', reference_doctype: 'CRM Lead', reference_docname: '', }) function showTask(name) { let t = rows.value?.find((row) => row.name === name) task.value = { name: t.name, title: t.title, description: t.description, assigned_to: t.assigned_to?.email || '', due_date: t.due_date, status: t.status, priority: t.priority, reference_doctype: t.reference_doctype, reference_docname: t.reference_docname, } showTaskModal.value = true } function createTask(column) { task.value = { name: '', title: '', description: '', assigned_to: '', due_date: '', status: 'Backlog', priority: 'Low', reference_doctype: 'CRM Lead', reference_docname: '', } if (column.column?.name) { let column_field = tasks.value.params.column_field if (column_field) { task.value[column_field] = column.column.name } } showTaskModal.value = true } function actions(name) { return [ { label: __('Delete'), icon: 'trash-2', onClick: () => { deletetask(name) tasks.value.reload() }, }, ] } async function deletetask(name) { await call('frappe.client.delete', { doctype: 'CRM Task', name, }) } function redirect(doctype, docname) { if (!docname) return let name = doctype == 'CRM Deal' ? 'Deal' : 'Lead' let params = { leadId: docname } if (name == 'Deal') { params = { dealId: docname } } router.push({ name: name, params: params }) } </script>
2302_79757062/crm
frontend/src/pages/Tasks.vue
Vue
agpl-3.0
10,593
import { createRouter, createWebHistory } from 'vue-router' import { userResource } from '@/stores/user' import { sessionStore } from '@/stores/session' const routes = [ { path: '/', redirect: { name: 'Leads' }, name: 'Home', }, { path: '/notifications', name: 'Notifications', component: () => import('@/pages/MobileNotification.vue'), }, { alias: '/leads', path: '/leads/view/:viewType?', name: 'Leads', component: () => import('@/pages/Leads.vue'), meta: { scrollPos: { top: 0, left: 0 } }, }, { path: '/leads/:leadId', name: 'Lead', component: () => import(`@/pages/${handleMobileView('Lead')}.vue`), props: true, }, { alias: '/deals', path: '/deals/view/:viewType?', name: 'Deals', component: () => import('@/pages/Deals.vue'), meta: { scrollPos: { top: 0, left: 0 } }, }, { path: '/deals/:dealId', name: 'Deal', component: () => import(`@/pages/${handleMobileView('Deal')}.vue`), props: true, }, { alias: '/notes', path: '/notes/view/:viewType?', name: 'Notes', component: () => import('@/pages/Notes.vue'), }, { alias: '/tasks', path: '/tasks/view/:viewType?', name: 'Tasks', component: () => import('@/pages/Tasks.vue'), }, { alias: '/contacts', path: '/contacts/view/:viewType?', name: 'Contacts', component: () => import('@/pages/Contacts.vue'), meta: { scrollPos: { top: 0, left: 0 } }, }, { path: '/contacts/:contactId', name: 'Contact', component: () => import('@/pages/Contact.vue'), props: true, }, { alias: '/organizations', path: '/organizations/view/:viewType?', name: 'Organizations', component: () => import('@/pages/Organizations.vue'), meta: { scrollPos: { top: 0, left: 0 } }, }, { path: '/organizations/:organizationId', name: 'Organization', component: () => import('@/pages/Organization.vue'), props: true, }, { alias: '/call-logs', path: '/call-logs/view/:viewType?', name: 'Call Logs', component: () => import('@/pages/CallLogs.vue'), meta: { scrollPos: { top: 0, left: 0 } }, }, { alias: '/email-templates', path: '/email-templates/view/:viewType?', name: 'Email Templates', component: () => import('@/pages/EmailTemplates.vue'), meta: { scrollPos: { top: 0, left: 0 } }, }, { path: '/email-templates/:emailTemplateId', name: 'Email Template', component: () => import('@/pages/EmailTemplate.vue'), props: true, }, { path: '/:invalidpath', name: 'Invalid Page', component: () => import('@/pages/InvalidPage.vue'), }, ] const handleMobileView = (componentName) => { return window.innerWidth < 768 ? `Mobile${componentName}` : componentName } const scrollBehavior = (to, from, savedPosition) => { if (to.name === from.name) { to.meta?.scrollPos && (to.meta.scrollPos.top = 0) return { left: 0, top: 0 } } const scrollpos = to.meta?.scrollPos || { left: 0, top: 0 } if (scrollpos.top > 0) { setTimeout(() => { let el = document.querySelector('#list-rows') el.scrollTo({ top: scrollpos.top, left: scrollpos.left, behavior: 'smooth', }) }, 300) } } let router = createRouter({ history: createWebHistory('/crm'), routes, scrollBehavior, }) router.beforeEach(async (to, from, next) => { const { isLoggedIn } = sessionStore() isLoggedIn && (await userResource.promise) if (from.meta?.scrollPos) { from.meta.scrollPos.top = document.querySelector('#list-rows')?.scrollTop } if (to.name === 'Home' && isLoggedIn) { next({ name: 'Leads' }) } else if (!isLoggedIn) { window.location.href = "/login?redirect-to=/crm"; } else if (to.matched.length === 0) { next({ name: 'Invalid Page' }) } else { next() } }) export default router
2302_79757062/crm
frontend/src/router.js
JavaScript
agpl-3.0
3,901
import { io } from 'socket.io-client' import { socketio_port } from '../../../../sites/common_site_config.json' import { getCachedListResource } from 'frappe-ui/src/resources/listResource' import { getCachedResource } from 'frappe-ui/src/resources/resources' export function initSocket() { let host = window.location.hostname let siteName = window.site_name let port = window.location.port ? `:${socketio_port}` : '' let protocol = port ? 'http' : 'https' let url = `${protocol}://${host}${port}/${siteName}` let socket = io(url, { withCredentials: true, reconnectionAttempts: 5, }) socket.on('refetch_resource', (data) => { if (data.cache_key) { let resource = getCachedResource(data.cache_key) || getCachedListResource(data.cache_key) if (resource) { resource.reload() } } }) return socket }
2302_79757062/crm
frontend/src/socket.js
JavaScript
agpl-3.0
873
import { defineStore } from 'pinia' import { createResource } from 'frappe-ui' import { reactive } from 'vue' export const contactsStore = defineStore('crm-contacts', () => { let contactsByPhone = reactive({}) let contactsByName = reactive({}) let leadContactsByPhone = reactive({}) let allContacts = reactive([]) const contacts = createResource({ url: 'crm.api.session.get_contacts', cache: 'contacts', initialData: [], auto: true, transform(contacts) { for (let contact of contacts) { // remove special characters from phone number to make it easier to search // also remove spaces but keep + sign at the start contact.actual_mobile_no = contact.mobile_no contact.mobile_no = contact.mobile_no?.replace(/[^0-9+]/g, '') contactsByPhone[contact.mobile_no] = contact contactsByName[contact.name] = contact } allContacts = [...contacts] return contacts }, onError(error) { if (error && error.exc_type === 'AuthenticationError') { router.push('/login') } }, }) const leadContacts = createResource({ url: 'crm.api.session.get_lead_contacts', cache: 'lead_contacts', initialData: [], auto: true, transform(lead_contacts) { for (let lead_contact of lead_contacts) { // remove special characters from phone number to make it easier to search // also remove spaces but keep + sign at the start lead_contact.mobile_no = lead_contact.mobile_no?.replace(/[^0-9+]/g, '') lead_contact.full_name = lead_contact.lead_name leadContactsByPhone[lead_contact.mobile_no] = lead_contact } return lead_contacts }, onError(error) { if (error && error.exc_type === 'AuthenticationError') { router.push('/login') } }, }) function getContact(mobile_no) { mobile_no = mobile_no?.replace(/[^0-9+]/g, '') return contactsByPhone[mobile_no] } function getContactByName(name) { return contactsByName[name] } function getLeadContact(mobile_no) { mobile_no = mobile_no?.replace(/[^0-9+]/g, '') return leadContactsByPhone[mobile_no] } function getContacts() { return allContacts || contacts?.data || [] } return { contacts, getContacts, getContact, getContactByName, getLeadContact, } })
2302_79757062/crm
frontend/src/stores/contacts.js
JavaScript
agpl-3.0
2,373
import { defineStore } from 'pinia' import { getCurrentInstance, ref } from 'vue' export const globalStore = defineStore('crm-global', () => { const app = getCurrentInstance() const { $dialog, $socket } = app.appContext.config.globalProperties let twilioEnabled = ref(false) let callMethod = () => {} function setTwilioEnabled(value) { twilioEnabled.value = value } function setMakeCall(value) { callMethod = value } function makeCall(number) { callMethod(number) } return { $dialog, $socket, twilioEnabled, makeCall, setTwilioEnabled, setMakeCall, } })
2302_79757062/crm
frontend/src/stores/global.js
JavaScript
agpl-3.0
620
import { defineStore } from 'pinia' import { createResource } from 'frappe-ui' import { computed, ref } from 'vue' export const notificationsStore = defineStore('crm-notifications', () => { let visible = ref(false) const notifications = createResource({ url: 'crm.api.notifications.get_notifications', initialData: [], auto: true, }) const mark_as_read = createResource({ url: 'crm.api.notifications.mark_as_read', auto: false, onSuccess: () => { mark_as_read.params = {} notifications.reload() }, }) function toggle() { visible.value = !visible.value } const allNotifications = computed(() => notifications.data || []) const unreadNotificationsCount = computed( () => notifications.data?.filter((n) => !n.read).length || 0 ) function mark_doc_as_read(doc) { mark_as_read.params = { doc: doc } mark_as_read.reload() toggle() } return { notifications, visible, allNotifications, unreadNotificationsCount, mark_as_read, mark_doc_as_read, toggle, } })
2302_79757062/crm
frontend/src/stores/notifications.js
JavaScript
agpl-3.0
1,072
import { defineStore } from 'pinia' import { createResource } from 'frappe-ui' import { reactive } from 'vue' export const organizationsStore = defineStore('crm-organizations', () => { let organizationsByName = reactive({}) const organizations = createResource({ url: 'crm.api.session.get_organizations', cache: 'organizations', initialData: [], auto: true, transform(organizations) { for (let organization of organizations) { organizationsByName[organization.name] = organization } return organizations }, onError(error) { if (error && error.exc_type === 'AuthenticationError') { router.push('/login') } }, }) function getOrganization(name) { return organizationsByName[name] } return { organizations, getOrganization, } })
2302_79757062/crm
frontend/src/stores/organizations.js
JavaScript
agpl-3.0
833
import { defineStore } from 'pinia' import { createResource } from 'frappe-ui' import { userResource } from './user' import router from '@/router' import { ref, computed } from 'vue' export const sessionStore = defineStore('crm-session', () => { function sessionUser() { let cookies = new URLSearchParams(document.cookie.split('; ').join('&')) let _sessionUser = cookies.get('user_id') if (_sessionUser === 'Guest') { _sessionUser = null } return _sessionUser } let user = ref(sessionUser()) const isLoggedIn = computed(() => !!user.value) const login = createResource({ url: 'login', onError() { throw new Error('Invalid email or password') }, onSuccess() { userResource.reload() user.value = sessionUser() login.reset() router.replace({ path: '/' }) }, }) const logout = createResource({ url: 'logout', onSuccess() { userResource.reset() user.value = null router.replace({ name: 'Home' }) }, }) return { user, isLoggedIn, login, logout, } })
2302_79757062/crm
frontend/src/stores/session.js
JavaScript
agpl-3.0
1,091
import IndicatorIcon from '@/components/Icons/IndicatorIcon.vue' import { capture } from '@/telemetry' import { defineStore } from 'pinia' import { createListResource } from 'frappe-ui' import { reactive, h } from 'vue' export const statusesStore = defineStore('crm-statuses', () => { let leadStatusesByName = reactive({}) let dealStatusesByName = reactive({}) let communicationStatusesByName = reactive({}) const leadStatuses = createListResource({ doctype: 'CRM Lead Status', fields: ['name', 'color', 'position'], orderBy: 'position asc', cache: 'lead-statuses', initialData: [], auto: true, transform(statuses) { for (let status of statuses) { status.colorClass = colorClasses(status.color) status.iconColorClass = colorClasses(status.color, true) leadStatusesByName[status.name] = status } return statuses }, }) const dealStatuses = createListResource({ doctype: 'CRM Deal Status', fields: ['name', 'color', 'position'], orderBy: 'position asc', cache: 'deal-statuses', initialData: [], auto: true, transform(statuses) { for (let status of statuses) { status.colorClass = colorClasses(status.color) status.iconColorClass = colorClasses(status.color, true) dealStatusesByName[status.name] = status } return statuses }, }) const communicationStatuses = createListResource({ doctype: 'CRM Communication Status', fields: ['name'], cache: 'communication-statuses', initialData: [], auto: true, transform(statuses) { for (let status of statuses) { communicationStatusesByName[status.name] = status } return statuses }, }) function colorClasses(color, onlyIcon = false) { let textColor = `!text-${color}-600` if (color == 'black') { textColor = '!text-gray-900' } else if (['gray', 'green'].includes(color)) { textColor = `!text-${color}-700` } let bgColor = `!bg-${color}-100 hover:!bg-${color}-200 active:!bg-${color}-300` return [textColor, onlyIcon ? '' : bgColor] } function getLeadStatus(name) { if (!name) { name = leadStatuses.data[0].name } return leadStatusesByName[name] } function getDealStatus(name) { if (!name) { name = dealStatuses.data[0].name } return dealStatusesByName[name] } function getCommunicationStatus(name) { if (!name) { name = communicationStatuses.data[0].name } return communicationStatuses[name] } function statusOptions(doctype, action, statuses = []) { let statusesByName = doctype == 'deal' ? dealStatusesByName : leadStatusesByName if (statuses.length) { statusesByName = statuses.reduce((acc, status) => { acc[status] = statusesByName[status] return acc }, {}) } let options = [] for (const status in statusesByName) { options.push({ label: statusesByName[status].name, value: statusesByName[status].name, icon: () => h(IndicatorIcon, { class: statusesByName[status].iconColorClass, }), onClick: () => { capture('status_changed', { doctype, status }) action && action('status', statusesByName[status].name) }, }) } return options } return { leadStatuses, dealStatuses, communicationStatuses, getLeadStatus, getDealStatus, getCommunicationStatus, statusOptions, } })
2302_79757062/crm
frontend/src/stores/statuses.js
JavaScript
agpl-3.0
3,544
import router from '@/router' import { createResource } from 'frappe-ui' export const userResource = createResource({ url: 'frappe.auth.get_logged_user', cache: 'User', onError(error) { if (error && error.exc_type === 'AuthenticationError') { router.push({ name: 'Home' }) } }, })
2302_79757062/crm
frontend/src/stores/user.js
JavaScript
agpl-3.0
304
import { defineStore } from 'pinia' import { createResource } from 'frappe-ui' import { sessionStore } from './session' import { reactive } from 'vue' import { useRouter } from 'vue-router' export const usersStore = defineStore('crm-users', () => { const session = sessionStore() let usersByName = reactive({}) const router = useRouter() const users = createResource({ url: 'crm.api.session.get_users', cache: 'Users', initialData: [], auto: true, transform(users) { for (let user of users) { usersByName[user.name] = user if (user.name === 'Administrator') { usersByName[user.email] = user } } return users }, onError(error) { if (error && error.exc_type === 'AuthenticationError') { router.push('/login') } }, }) function getUser(email) { if (!email || email === 'sessionUser') { email = session.user } if (!usersByName[email]) { usersByName[email] = { name: email, email: email, full_name: email.split('@')[0], first_name: email.split('@')[0], last_name: '', user_image: null, role: null, } } return usersByName[email] } function isManager(email) { return getUser(email).is_manager } return { users, getUser, isManager, } })
2302_79757062/crm
frontend/src/stores/users.js
JavaScript
agpl-3.0
1,370
import { defineStore } from 'pinia' import { createResource } from 'frappe-ui' import { reactive, ref } from 'vue' export const viewsStore = defineStore('crm-views', (doctype) => { let viewsByName = reactive({}) let pinnedViews = ref([]) let publicViews = ref([]) let defaultView = ref({}) // Views const views = createResource({ url: 'crm.api.views.get_views', params: { doctype: doctype || '' }, cache: 'crm-views', initialData: [], auto: true, transform(views) { pinnedViews.value = [] publicViews.value = [] for (let view of views) { viewsByName[view.name] = view view.type = view.type || 'list' if (view.pinned) { pinnedViews.value?.push(view) } if (view.public) { publicViews.value?.push(view) } if (view.is_default && view.dt) { defaultView.value[view.dt + ' ' + view.type] = view } } return views }, }) function getView(view, type, doctype = null) { type = type || 'list' if (!view && doctype) { return defaultView.value[doctype + ' ' + type] || null } return viewsByName[view] } function getPinnedViews() { if (!pinnedViews.value?.length) return [] return pinnedViews.value } function getPublicViews() { if (!publicViews.value?.length) return [] return publicViews.value } async function reload() { await views.reload() } return { views, defaultView, getPinnedViews, getPublicViews, reload, getView, } })
2302_79757062/crm
frontend/src/stores/views.js
JavaScript
agpl-3.0
1,573
import '../../../frappe/frappe/public/js/lib/posthog.js' import { createResource } from 'frappe-ui' declare global { interface Window { posthog: any } } type PosthogSettings = { posthog_project_id: string posthog_host: string enable_telemetry: boolean telemetry_site_age: number } interface CaptureOptions { data: { user: string [key: string]: string | number | boolean | object } } let posthog: typeof window.posthog = window.posthog // Posthog Settings let posthogSettings = createResource({ url: 'crm.api.get_posthog_settings', cache: 'posthog_settings', onSuccess: (ps: PosthogSettings) => initPosthog(ps), }) let isTelemetryEnabled = () => { if (!posthogSettings.data) return false return ( posthogSettings.data.enable_telemetry && posthogSettings.data.posthog_project_id && posthogSettings.data.posthog_host ) } // Posthog Initialization function initPosthog(ps: PosthogSettings) { if (!isTelemetryEnabled()) return posthog.init(ps.posthog_project_id, { api_host: ps.posthog_host, person_profiles: 'identified_only', autocapture: false, capture_pageview: true, capture_pageleave: true, enable_heatmaps: false, disable_session_recording: false, loaded: (ph: typeof posthog) => { window.posthog = ph ph.identify(window.location.hostname) }, }) } // Posthog Functions function capture( event: string, options: CaptureOptions = { data: { user: '' } }, ) { if (!isTelemetryEnabled()) return window.posthog.capture(`crm_${event}`, options) } function startRecording() { if (!isTelemetryEnabled()) return if (window.posthog?.__loaded) { window.posthog.startSessionRecording() } } function stopRecording() { if (!isTelemetryEnabled()) return if (window.posthog?.__loaded && window.posthog.sessionRecordingStarted()) { window.posthog.stopSessionRecording() } } // Posthog Plugin function posthogPlugin(app: any) { app.config.globalProperties.posthog = posthog if (!window.posthog?.length) posthogSettings.fetch() } export { posthog, posthogSettings, posthogPlugin, capture, startRecording, stopRecording, }
2302_79757062/crm
frontend/src/telemetry.ts
TypeScript
agpl-3.0
2,166
import { createResource } from 'frappe-ui' export default function translationPlugin(app) { app.config.globalProperties.__ = translate window.__ = translate if (!window.translatedMessages) fetchTranslations() } function format(message, replace) { return message.replace(/{(\d+)}/g, function (match, number) { return typeof replace[number] != 'undefined' ? replace[number] : match }) } function translate(message, replace, context = null) { let translatedMessages = window.translatedMessages || {} let translatedMessage = '' if (context) { let key = `${message}:${context}` if (translatedMessages[key]) { translatedMessage = translatedMessages[key] } } if (!translatedMessage) { translatedMessage = translatedMessages[message] || message } const hasPlaceholders = /{\d+}/.test(message) if (!hasPlaceholders) { return translatedMessage } return format(translatedMessage, replace) } function fetchTranslations(lang) { createResource({ url: 'crm.api.get_translations', cache: 'translations', auto: true, transform: (data) => { window.translatedMessages = data }, }) }
2302_79757062/crm
frontend/src/translation.js
JavaScript
agpl-3.0
1,162
import { secondsToDuration, dateFormat, dateTooltipFormat, timeAgo, } from '@/utils' import { usersStore } from '@/stores/users' import { contactsStore } from '@/stores/contacts' const { getUser } = usersStore() const { getContact, getLeadContact } = contactsStore() export function getCallLogDetail(row, log) { let incoming = log.type === 'Incoming' if (row === 'caller') { return { label: incoming ? getContact(log.from)?.full_name || getLeadContact(log.from)?.full_name || 'Unknown' : getUser(log.caller).full_name, image: incoming ? getContact(log.from)?.image || getLeadContact(log.from)?.image : getUser(log.caller).user_image, } } else if (row === 'receiver') { return { label: incoming ? getUser(log.receiver).full_name : getContact(log.to)?.full_name || getLeadContact(log.to)?.full_name || 'Unknown', image: incoming ? getUser(log.receiver).user_image : getContact(log.to)?.image || getLeadContact(log.to)?.image, } } else if (row === 'duration') { return { label: secondsToDuration(log.duration), icon: 'clock', } } else if (row === 'type') { return { label: log.type, icon: incoming ? 'phone-incoming' : 'phone-outgoing', } } else if (row === 'status') { return { label: statusLabelMap[log.status], color: statusColorMap[log.status], } } else if (['modified', 'creation'].includes(row)) { return { label: dateFormat(log[row], dateTooltipFormat), timeAgo: __(timeAgo(log[row])), } } return log[row] } export const statusLabelMap = { Completed: 'Completed', Initiated: 'Initiated', Busy: 'Declined', Failed: 'Failed', Queued: 'Queued', Cancelled: 'Cancelled', Ringing: 'Ringing', 'No Answer': 'Missed Call', 'In Progress': 'In Progress', } export const statusColorMap = { Completed: 'green', Busy: 'orange', Failed: 'red', Initiated: 'gray', Queued: 'gray', Cancelled: 'gray', Ringing: 'gray', 'No Answer': 'red', 'In Progress': 'blue', }
2302_79757062/crm
frontend/src/utils/callLog.js
JavaScript
agpl-3.0
2,140
import { Dialog, ErrorMessage } from 'frappe-ui' import { reactive, ref } from 'vue' let dialogs = ref([]) export let Dialogs = { name: 'Dialogs', render() { return dialogs.value.map((dialog) => ( <Dialog options={dialog} modelValue={dialog.show} onUpdate:modelValue={(val) => (dialog.show = val)} > {{ 'body-content': () => { return [ dialog.message && ( <p class="text-p-base text-gray-700">{dialog.message}</p> ), dialog.html && ( <div v-html={dialog.html} /> ), <ErrorMessage class="mt-2" message={dialog.error} />, ] }, }} </Dialog> )) }, } export function createDialog(dialogOptions) { let dialog = reactive(dialogOptions) dialog.key = 'dialog-' + dialogs.value.length dialog.show = false setTimeout(() => { dialog.show = true }, 0) dialogs.value.push(dialog) }
2302_79757062/crm
frontend/src/utils/dialogs.jsx
JavaScript
agpl-3.0
1,005
import TaskStatusIcon from '@/components/Icons/TaskStatusIcon.vue' import TaskPriorityIcon from '@/components/Icons/TaskPriorityIcon.vue' import { useDateFormat, useTimeAgo } from '@vueuse/core' import { usersStore } from '@/stores/users' import { gemoji } from 'gemoji' import { toast } from 'frappe-ui' import { h } from 'vue' export function createToast(options) { toast({ position: 'bottom-right', ...options, }) } export function formatTime(seconds) { const days = Math.floor(seconds / (3600 * 24)) const hours = Math.floor((seconds % (3600 * 24)) / 3600) const minutes = Math.floor((seconds % 3600) / 60) const remainingSeconds = Math.floor(seconds % 60) let formattedTime = '' if (days > 0) { formattedTime += `${days}d ` } if (hours > 0 || days > 0) { formattedTime += `${hours}h ` } if (minutes > 0 || hours > 0 || days > 0) { formattedTime += `${minutes}m ` } formattedTime += `${remainingSeconds}s` return formattedTime.trim() } export function dateFormat(date, format) { const _format = format || 'DD-MM-YYYY HH:mm:ss' return useDateFormat(date, _format).value } export function timeAgo(date) { return useTimeAgo(date).value } export const dateTooltipFormat = 'ddd, MMM D, YYYY h:mm A' export function taskStatusOptions(action, data) { return ['Backlog', 'Todo', 'In Progress', 'Done', 'Canceled'].map( (status) => { return { icon: () => h(TaskStatusIcon, { status }), label: status, onClick: () => action && action(status, data), } }, ) } export function taskPriorityOptions(action, data) { return ['Low', 'Medium', 'High'].map((priority) => { return { label: priority, icon: () => h(TaskPriorityIcon, { priority }), onClick: () => action && action(priority, data), } }) } export function openWebsite(url) { if (!url.startsWith('http://') && !url.startsWith('https://')) { url = 'https://' + url } window.open(url, '_blank') } export function website(url) { return url && url.replace(/^(?:https?:\/\/)?(?:www\.)?/i, '') } export function htmlToText(html) { const div = document.createElement('div') div.innerHTML = html return div.textContent || div.innerText || '' } export function secondsToDuration(seconds) { const hours = Math.floor(seconds / 3600) const minutes = Math.floor((seconds % 3600) / 60) const _seconds = Math.floor((seconds % 3600) % 60) if (hours == 0 && minutes == 0) { return `${_seconds}s` } else if (hours == 0) { return `${minutes}m ${_seconds}s` } return `${hours}h ${minutes}m ${_seconds}s` } export function formatNumberIntoCurrency(value, currency = 'INR') { if (value) { return value.toLocaleString('en-IN', { maximumFractionDigits: 0, style: 'currency', currency: currency ? currency : 'INR', }) } return '' } export function startCase(str) { return str.charAt(0).toUpperCase() + str.slice(1) } export function validateEmail(email) { let regExp = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ return regExp.test(email) } export function setupAssignees(data) { let { getUser } = usersStore() let assignees = data._assign || [] data._assignedTo = assignees.map((user) => ({ name: user, image: getUser(user).user_image, label: getUser(user).full_name, })) } async function getFromScript(script, obj) { let scriptFn = new Function(script + '\nreturn setupForm')() let formScript = await scriptFn(obj) return formScript || {} } export async function setupCustomizations(data, obj) { if (!data._form_script) return [] let statuses = [] let actions = [] if (Array.isArray(data._form_script)) { for (let script of data._form_script) { let _script = await getFromScript(script, obj) actions = actions.concat(_script?.actions || []) statuses = statuses.concat(_script?.statuses || []) } } else { let _script = await getFromScript(data._form_script, obj) actions = _script?.actions || [] statuses = _script?.statuses || [] } data._customStatuses = statuses data._customActions = actions return { statuses, actions } } async function getListScript(script, obj) { let scriptFn = new Function(script + '\nreturn setupList')() let listScript = await scriptFn(obj) return listScript || {} } export async function setupListCustomizations(data, obj = {}) { if (!data.list_script) return [] let actions = [] let bulkActions = [] if (Array.isArray(data.list_script)) { for (let script of data.list_script) { let _script = await getListScript(script, obj) actions = actions.concat(_script?.actions || []) bulkActions = bulkActions.concat(_script?.bulk_actions || []) } } else { let _script = await getListScript(data.list_script, obj) actions = _script?.actions || [] bulkActions = _script?.bulk_actions || [] } data.listActions = actions data.bulkActions = bulkActions return { actions, bulkActions } } export function errorMessage(title, message) { createToast({ title: title || 'Error', text: message, icon: 'x', iconClasses: 'text-red-600', }) } export function copyToClipboard(text) { if (navigator.clipboard && window.isSecureContext) { navigator.clipboard.writeText(text).then(show_success_alert) } else { let input = document.createElement('textarea') document.body.appendChild(input) input.value = text input.select() document.execCommand('copy') show_success_alert() document.body.removeChild(input) } function show_success_alert() { createToast({ title: 'Copied to clipboard', text: text, icon: 'check', iconClasses: 'text-green-600', }) } } export function isEmoji(str) { const emojiList = gemoji.map((emoji) => emoji.emoji) return emojiList.includes(str) } export function isTouchScreenDevice() { return 'ontouchstart' in document.documentElement } export function convertArrayToString(array) { return array.map((item) => item).join(',') } export function _eval(code, context = {}) { let variable_names = Object.keys(context) let variables = Object.values(context) code = `let out = ${code}; return out` try { let expression_function = new Function(...variable_names, code) return expression_function(...variables) } catch (error) { console.log('Error evaluating the following expression:') console.error(code) throw error } } export function evaluate_depends_on_value(expression, doc) { if (!expression) return true if (!doc) return true let out = null if (typeof expression === 'boolean') { out = expression } else if (typeof expression === 'function') { out = expression(doc) } else if (expression.substr(0, 5) == 'eval:') { try { out = _eval(expression.substr(5), { doc }) } catch (e) { out = true } } else { let value = doc[expression] if (Array.isArray(value)) { out = !!value.length } else { out = !!value } } return out }
2302_79757062/crm
frontend/src/utils/index.js
JavaScript
agpl-3.0
7,182
import ListIcon from '@/components/Icons/ListIcon.vue' import GroupByIcon from '@/components/Icons/GroupByIcon.vue' import KanbanIcon from '@/components/Icons/KanbanIcon.vue' import { viewsStore } from '@/stores/views' import { markRaw } from 'vue' const { getView: getViewDetails } = viewsStore() function defaultView(type) { let types = { list: { label: __('List'), icon: markRaw(ListIcon), }, group_by: { label: __('Group By'), icon: markRaw(GroupByIcon), }, kanban: { label: __('Kanban'), icon: markRaw(KanbanIcon), }, } return types[type] } export function getView(view, type, doctype) { let viewType = type || 'list' let viewDetails = getViewDetails(view, viewType, doctype) if (viewDetails && !viewDetails.icon) { viewDetails.icon = defaultView(viewType).icon } return viewDetails || defaultView(viewType) }
2302_79757062/crm
frontend/src/utils/view.js
JavaScript
agpl-3.0
899
module.exports = { presets: [require('frappe-ui/src/utils/tailwind.config')], content: [ './index.html', './src/**/*.{vue,js,ts,jsx,tsx}', './node_modules/frappe-ui/src/components/**/*.{vue,js,ts,jsx,tsx}', '../node_modules/frappe-ui/src/components/**/*.{vue,js,ts,jsx,tsx}', ], safelist: [ { pattern: /!(text|bg)-/, variants: ['hover', 'active'] }, { pattern: /^grid-cols-/ }, ], theme: { extend: {}, }, plugins: [], }
2302_79757062/crm
frontend/tailwind.config.js
JavaScript
agpl-3.0
464
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import path from 'path' import frappeui from 'frappe-ui/vite' import { VitePWA } from 'vite-plugin-pwa' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ frappeui(), vue({ script: { propsDestructure: true, }, }), vueJsx(), VitePWA({ registerType: 'autoUpdate', devOptions: { enabled: true, }, manifest: { display: 'standalone', name: 'Frappe CRM', short_name: 'Frappe CRM', start_url: '/crm', description: 'Modern & 100% Open-source CRM tool to supercharge your sales operations', icons: [ { src: '/assets/crm/manifest/manifest-icon-192.maskable.png', sizes: '192x192', type: 'image/png', purpose: 'any', }, { src: '/assets/crm/manifest/manifest-icon-192.maskable.png', sizes: '192x192', type: 'image/png', purpose: 'maskable', }, { src: '/assets/crm/manifest/manifest-icon-512.maskable.png', sizes: '512x512', type: 'image/png', purpose: 'any', }, { src: '/assets/crm/manifest/manifest-icon-512.maskable.png', sizes: '512x512', type: 'image/png', purpose: 'maskable', }, ], }, }), { name: 'transform-index.html', transformIndexHtml(html, context) { if (!context.server) { return html.replace( /<\/body>/, ` <script> {% for key in boot %} window["{{ key }}"] = {{ boot[key] | tojson }}; {% endfor %} </script> </body> ` ) } return html }, }, ], resolve: { alias: { '@': path.resolve(__dirname, 'src'), }, }, build: { outDir: '../crm/public/frontend', emptyOutDir: true, commonjsOptions: { include: [/tailwind.config.js/, /node_modules/], }, sourcemap: true, }, optimizeDeps: { include: [ 'feather-icons', 'showdown', 'tailwind.config.js', 'engine.io-client', 'prosemirror-state', ], }, })
2302_79757062/crm
frontend/vite.config.js
JavaScript
agpl-3.0
2,432
#!bin/bash set -e if [[ -f "/workspaces/frappe_codespace/frappe-bench/apps/frappe" ]] then echo "Bench already exists, skipping init" exit 0 fi rm -rf /workspaces/frappe_codespace/.git source /home/frappe/.nvm/nvm.sh nvm alias default 18 nvm use 18 echo "nvm use 18" >> ~/.bashrc cd /workspace bench init \ --ignore-exist \ --skip-redis-config-generation \ frappe-bench cd frappe-bench # Use containers instead of localhost bench set-mariadb-host mariadb bench set-redis-cache-host redis-cache:6379 bench set-redis-queue-host redis-queue:6379 bench set-redis-socketio-host redis-socketio:6379 # Remove redis from Procfile sed -i '/redis/d' ./Procfile bench new-site dev.localhost \ --mariadb-root-password 123 \ --admin-password admin \ --no-mariadb-socket bench --site dev.localhost set-config developer_mode 1 bench --site dev.localhost clear-cache bench use dev.localhost bench get-app crm bench --site dev.localhost install-app crm
2302_79757062/crm
scripts/init.sh
Shell
agpl-3.0
955
import json import time import uuid import re import os import sys import requests import hashlib import hmac import base64 import argparse from datetime import datetime from concurrent.futures import ThreadPoolExecutor import logging from colorama import Fore, Style, init # 初始化 colorama init(autoreset=True) # 设置环境变量 os.environ['ALIBABA_ACCESS_KEY_ID'] = "YOUR_ACCESS_KEY_ID" # 替换为你的AccessKeyId os.environ['ALIBABA_ACCESS_KEY_SECRET'] = "YOUR_ACCESS_KEY_SECRET" # 替换为你的AccessKeySecret # 配置日志 logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler("translate.log"), logging.StreamHandler() ] ) logger = logging.getLogger(__name__) class AlibabaTranslator: def __init__(self, access_key_id, access_key_secret, target_language="zh", source_language="auto"): self.access_key_id = access_key_id self.access_key_secret = access_key_secret self.target_language = target_language self.source_language = source_language self.url = "http://mt.cn-hangzhou.aliyuncs.com/api/translate/web/general" self.max_workers = 20 # 并发线程数 self.request_interval = 0.1 # 请求间隔时间(秒) # 正则表达式,用于识别标题、列表和代码块等 self.md_title_pattern = re.compile(r'^#{1,6}\s+(.+)$') self.md_list_pattern = re.compile(r'^(\s*[-*+]\s+)(.+)$') self.md_ordered_list_pattern = re.compile(r'^(\s*\d+\.\s+)(.+)$') self.md_code_block_pattern = re.compile(r'^```[a-zA-Z]*$') self.md_inline_code_pattern = re.compile(r'`([^`]+)`') self.md_link_pattern = re.compile(r'$$([^$$]+)\]$([^)]+)$') # 不翻译的内容类型 self.skip_translate_types = ["code_block", "inline_code", "url", "empty"] def translate_text(self, text, retry_count=3): """翻译单个文本片段,支持重试""" if not text.strip(): return text # 返回空文本 for attempt in range(retry_count): try: # 准备请求体 body = { "FormatType": "text", "SourceLanguage": self.source_language, "TargetLanguage": self.target_language, "SourceText": text, "Scene": "general" } body_str = json.dumps(body, ensure_ascii=False) body_bytes = body_str.encode('utf-8') # 计算 Content-MD5 content_md5 = base64.b64encode(hashlib.md5(body_bytes).digest()).decode('utf-8') # 生成请求头 date = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT') nonce = str(uuid.uuid4()) # 准备签名字符串 string_to_sign = ( "POST\n" "application/json\n" f"{content_md5}\n" "application/json\n" f"{date}\n" f"x-acs-signature-method:HMAC-SHA1\n" f"x-acs-signature-nonce:{nonce}\n" f"x-acs-signature-version:1.0\n" "/api/translate/web/general" ) # 计算签名 signature = base64.b64encode( hmac.new( self.access_key_secret.encode('utf-8'), string_to_sign.encode('utf-8'), hashlib.sha1 ).digest() ).decode('utf-8') # 设置请求头 headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Content-MD5': content_md5, 'Date': date, 'Host': 'mt.cn-hangzhou.aliyuncs.com', 'x-acs-signature-nonce': nonce, 'x-acs-signature-method': 'HMAC-SHA1', 'x-acs-signature-version': '1.0', 'Authorization': f'acs {self.access_key_id}:{signature}' } # 发送请求 response = requests.post(self.url, data=body_bytes, headers=headers) # 解析响应 if response.status_code == 200: result = response.json() if result.get('Code') == '200': time.sleep(self.request_interval) # 避免请求过快 return result.get('Data', {}).get('Translated') else: logger.warning(f"翻译错误: {result.get('Message', '未知错误')} (尝试 {attempt+1}/{retry_count})") if attempt < retry_count - 1: time.sleep(1 * (attempt + 1)) # 指数级退避 continue return f"[翻译错误] {text}" else: logger.warning(f"请求错误: HTTP {response.status_code} (尝试 {attempt+1}/{retry_count})") if attempt < retry_count - 1: time.sleep(1 * (attempt + 1)) # 指数级退避 continue return f"[请求错误] {text}" except Exception as e: logger.error(f"处理文本时出错: {e} (尝试 {attempt+1}/{retry_count})") if attempt < retry_count - 1: time.sleep(1 * (attempt + 1)) # 指数级退避 continue return f"[处理错误] {text}" return f"[多次尝试后失败] {text}" def analyze_line(self, line): """分析行的类型和内容,以决定如何翻译""" line = line.rstrip('\n') # 空行 if not line.strip(): return {"type": "empty", "content": line, "prefix": "", "suffix": ""} # 检查是否为标题 title_match = self.md_title_pattern.match(line) if title_match: prefix = line[:line.find(title_match.group(1))] return {"type": "title", "content": title_match.group(1), "prefix": prefix, "suffix": ""} # 检查是否为无序列表 list_match = self.md_list_pattern.match(line) if list_match: return {"type": "list", "content": list_match.group(2), "prefix": list_match.group(1), "suffix": ""} # 检查是否为有序列表 ordered_list_match = self.md_ordered_list_pattern.match(line) if ordered_list_match: return {"type": "ordered_list", "content": ordered_list_match.group(2), "prefix": ordered_list_match.group(1), "suffix": ""} # 检查是否为代码块标记 if self.md_code_block_pattern.match(line): return {"type": "code_block_marker", "content": line, "prefix": "", "suffix": ""} # 处理行内代码和链接 processed_line = line inline_code_matches = self.md_inline_code_pattern.findall(line) link_matches = self.md_link_pattern.findall(line) if inline_code_matches or link_matches: # 保存需要特殊处理的部分 replacements = {} # 处理行内代码 for i, code in enumerate(inline_code_matches): placeholder = f"__CODE_{i}__" processed_line = processed_line.replace(f"`{code}`", placeholder) replacements[placeholder] = f"`{code}`" # 处理链接 for i, (text, url) in enumerate(link_matches): placeholder = f"__LINK_{i}__" processed_line = processed_line.replace(f"[{text}]({url})", placeholder) replacements[placeholder] = {"text": text, "url": url} return {"type": "mixed", "content": processed_line, "replacements": replacements, "prefix": "", "suffix": ""} # 普通文本 return {"type": "text", "content": line, "prefix": "", "suffix": ""} def process_mixed_content(self, analysis, translated_text): """处理包含代码和链接的混合内容""" result = translated_text for placeholder, replacement in analysis["replacements"].items(): if isinstance(replacement, dict): # 链接 # 仅翻译链接文本,保留URL translated_link_text = self.translate_text(replacement["text"]) result = result.replace(placeholder, f"[{translated_link_text}]({replacement['url']})") else: # 代码 result = result.replace(placeholder, replacement) return result def translate_file(self, input_file, output_file, batch_size=50): """翻译整个 Markdown 文件,添加批处理功能""" try: # 确保输入文件存在 if not os.path.exists(input_file): logger.error(f"输入文件不存在: {input_file}") return False # 确保输出目录存在 output_dir = os.path.dirname(output_file) if output_dir and not os.path.exists(output_dir): os.makedirs(output_dir) # 读取输入文件 with open(input_file, 'r', encoding='utf-8') as file: lines = file.readlines() # 分析每一行 analyses = [self.analyze_line(line) for line in lines] # 是否在代码块内部(不需要翻译) in_code_block = False # 处理每一行 translated_lines = [] tasks = [] logger.info(f"开始翻译文件: {input_file} -> {output_file} (共 {len(lines)} 行)") # 提前准备翻译任务 for i, analysis in enumerate(analyses): if analysis["type"] == "code_block_marker": in_code_block = not in_code_block tasks.append(None) # 占位符,不需要翻译 elif in_code_block or analysis["type"] in self.skip_translate_types: tasks.append(None) # 占位符,不需要翻译 else: tasks.append({"index": i, "content": analysis["content"]}) # 使用 ThreadPoolExecutor 进行并行翻译 # 分批处理,避免同时创建过多线程 translations = {} active_tasks = [task for task in tasks if task is not None] total_tasks = len(active_tasks) logger.info(f"需要翻译的行数: {total_tasks}") for batch_start in range(0, total_tasks, batch_size): batch_end = min(batch_start + batch_size, total_tasks) batch_tasks = active_tasks[batch_start:batch_end] logger.info(f"处理批次 {batch_start//batch_size + 1}, 行 {batch_start+1}-{batch_end} (共 {len(batch_tasks)} 行)") with ThreadPoolExecutor(max_workers=self.max_workers) as executor: futures = {} for task in batch_tasks: future = executor.submit(self.translate_text, task["content"]) futures[future] = task["index"] for future in futures: index = futures[future] try: translations[index] = future.result() except Exception as e: logger.error(f"翻译第 {index+1} 行时出错: {e}") translations[index] = f"[翻译失败] {analyses[index]['content']}" # 构建最终翻译结果 in_code_block = False for i, analysis in enumerate(analyses): if analysis["type"] == "code_block_marker": in_code_block = not in_code_block translated_lines.append(analysis["content"]) elif in_code_block or analysis["type"] in self.skip_translate_types: translated_lines.append(analyses[i]["content"]) else: if analysis["type"] == "mixed": # 处理混合内容(包含代码和链接) translated_content = self.process_mixed_content(analysis, translations.get(i, "[翻译丢失]")) else: translated_content = translations.get(i, "[翻译丢失]") # 重新构建行,保留前缀和后缀 translated_line = f"{analysis['prefix']}{translated_content}{analysis['suffix']}" translated_lines.append(translated_line) # 写入输出文件 with open(output_file, 'w', encoding='utf-8') as file: file.write('\n'.join(translated_lines)) logger.info(f"翻译完成! 共处理 {len(lines)} 行,结果已保存到 {output_file}") return True except Exception as e: logger.error(f"处理文件时出错: {e}") return False def validate_file(file_path): """验证文件路径是否有效""" if not os.path.exists(file_path): raise argparse.ArgumentTypeError(f"文件不存在: {file_path}") return file_path def get_default_output_filename(input_file): """根据输入文件生成默认输出文件名""" base_name, ext = os.path.splitext(input_file) return f"{base_name}_translated{ext}" def main(): # 打印工具名称和作者信息 print(Fore.CYAN + Style.BRIGHT + "\n" + "="*50) print(Fore.MAGENTA + Style.BRIGHT + "阿里云Markdown翻译 V1.0") print(Fore.YELLOW + Style.BRIGHT + "作者: Zero_Tu") print(Fore.CYAN + Style.BRIGHT + "="*50 + "\n") # 解析命令行参数 parser = argparse.ArgumentParser(description='阿里云机器翻译工具 - 支持Markdown格式翻译') parser.add_argument('-f', '--file', type=validate_file, required=True, help='要翻译的输入文件路径') parser.add_argument('-o', '--output', type=str, help='翻译结果输出文件路径 (默认为: <输入文件名>_translated.<扩展名>)') parser.add_argument('-s', '--source', type=str, default='auto', help='源语言代码 (默认: auto)') parser.add_argument('-t', '--target', type=str, default='zh', help='目标语言代码 (默认: zh)') parser.add_argument('--threads', type=int, default=20, help='并发线程数 (默认: 20)') parser.add_argument('--batch-size', type=int, default=50, help='批处理大小 (默认: 50)') parser.add_argument('--interval', type=float, default=0.1, help='请求间隔时间,秒 (默认: 0.1)') args = parser.parse_args() # 获取 API 密钥 (从环境变量获取) access_key_id = os.environ.get('ALIBABA_ACCESS_KEY_ID') access_key_secret = os.environ.get('ALIBABA_ACCESS_KEY_SECRET') if not access_key_id or not access_key_secret: logger.error("错误: 未提供阿里云 API 密钥。请在代码中设置正确的环境变量值。") return 1 # 生成输出文件名(如果未提供) output_file = args.output or get_default_output_filename(args.file) # 初始化翻译器 translator = AlibabaTranslator( access_key_id=access_key_id, access_key_secret=access_key_secret, source_language=args.source, target_language=args.target ) # 设置性能参数 translator.max_workers = args.threads translator.request_interval = args.interval # 执行翻译 logger.info(Fore.GREEN + "=== 阿里云翻译工具 ===") logger.info(f"输入文件: {args.file}") logger.info(f"输出文件: {output_file}") logger.info(f"语言: {args.source} -> {args.target}") logger.info(f"性能设置: 线程={args.threads}, 批大小={args.batch_size}, 间隔={args.interval}秒") start_time = time.time() success = translator.translate_file(args.file, output_file, args.batch_size) end_time = time.time() if success: logger.info(Fore.GREEN + f"总耗时: {end_time - start_time:.2f} 秒") return 0 else: logger.error("翻译过程中出现错误,请检查日志了解详情。") return 1 if __name__ == "__main__": sys.exit(main())
2302_80180283/aliyunTSfer
main.py
Python
unknown
17,523
FROM crawlabteam/crawlab-backend:latest AS backend-build FROM crawlabteam/crawlab-frontend:latest AS frontend-build FROM crawlabteam/crawlab-public-plugins:latest AS public-plugins-build # images FROM crawlabteam/crawlab-base:latest # add files COPY ./backend/conf /app/backend/conf COPY ./nginx /app/nginx COPY ./bin /app/bin # copy backend files RUN mkdir -p /opt/bin COPY --from=backend-build /go/bin/crawlab /opt/bin RUN cp /opt/bin/crawlab /usr/local/bin/crawlab-server # copy frontend files COPY --from=frontend-build /app/dist /app/dist # copy public-plugins files COPY --from=public-plugins-build /app/plugins /app/plugins # copy nginx config files COPY ./nginx/crawlab.conf /etc/nginx/conf.d # start backend CMD ["/bin/bash", "/app/bin/docker-init.sh"]
2302_79757062/crawlab
Dockerfile
Dockerfile
bsd-3-clause
771
FROM golang:1.18 AS build WORKDIR /go/src/app COPY . . ENV GO111MODULE on #ENV GOPROXY https://goproxy.io RUN go mod tidy \ && go install -v ./... FROM alpine:3.14 # copy files COPY --from=build /go/bin/crawlab /go/bin/crawlab
2302_79757062/crawlab
backend/Dockerfile
Dockerfile
bsd-3-clause
234
package main import ( "github.com/crawlab-team/crawlab-core/cmd" ) func main() { _ = cmd.Execute() }
2302_79757062/crawlab
backend/main.go
Go
bsd-3-clause
105
package apps import ( "context" "errors" "github.com/apex/log" "github.com/crawlab-team/crawlab/core/controllers" "github.com/crawlab-team/crawlab/core/interfaces" "github.com/crawlab-team/crawlab/core/middlewares" "github.com/crawlab-team/crawlab/core/routes" "github.com/gin-gonic/gin" "github.com/spf13/viper" "net" "net/http" "time" ) func init() { // set gin mode if viper.GetString("gin.mode") == "" { gin.SetMode(gin.ReleaseMode) } else { gin.SetMode(viper.GetString("gin.mode")) } } type Api struct { // dependencies interfaces.WithConfigPath // internals app *gin.Engine ln net.Listener srv *http.Server ready bool } func (app *Api) Init() { // initialize controllers _ = initModule("controllers", controllers.InitControllers) // initialize middlewares _ = app.initModuleWithApp("middlewares", middlewares.InitMiddlewares) // initialize routes _ = app.initModuleWithApp("routes", routes.InitRoutes) } func (app *Api) Start() { // address host := viper.GetString("server.host") port := viper.GetString("server.port") address := net.JoinHostPort(host, port) // http server app.srv = &http.Server{ Handler: app.app, Addr: address, } // listen var err error app.ln, err = net.Listen("tcp", address) if err != nil { panic(err) } app.ready = true // serve if err := http.Serve(app.ln, app.app); err != nil { if !errors.Is(err, http.ErrServerClosed) { log.Error("run server error:" + err.Error()) } else { log.Info("server graceful down") } } } func (app *Api) Wait() { DefaultWait() } func (app *Api) Stop() { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() if err := app.srv.Shutdown(ctx); err != nil { log.Error("run server error:" + err.Error()) } } func (app *Api) GetGinEngine() *gin.Engine { return app.app } func (app *Api) GetHttpServer() *http.Server { return app.srv } func (app *Api) Ready() (ok bool) { return app.ready } func (app *Api) initModuleWithApp(name string, fn func(app *gin.Engine) error) (err error) { return initModule(name, func() error { return fn(app.app) }) } func NewApi() *Api { api := &Api{ app: gin.New(), } api.Init() return api } var api *Api func GetApi() *Api { if api != nil { return api } api = NewApi() return api }
2302_79757062/crawlab
core/apps/api.go
Go
bsd-3-clause
2,324
package apps import ( "context" "errors" "github.com/apex/log" "github.com/crawlab-team/crawlab/core/controllers" "github.com/crawlab-team/crawlab/core/interfaces" "github.com/crawlab-team/crawlab/core/middlewares" "github.com/gin-gonic/gin" "github.com/spf13/viper" "net" "net/http" "time" ) func init() { // set gin mode if viper.GetString("gin.mode") == "" { gin.SetMode(gin.ReleaseMode) } else { gin.SetMode(viper.GetString("gin.mode")) } } type ApiV2 struct { // dependencies interfaces.WithConfigPath // internals app *gin.Engine ln net.Listener srv *http.Server ready bool } func (app *ApiV2) Init() { // initialize middlewares _ = app.initModuleWithApp("middlewares", middlewares.InitMiddlewares) // initialize routes _ = app.initModuleWithApp("routes", controllers.InitRoutes) } func (app *ApiV2) Start() { // address host := viper.GetString("server.host") port := viper.GetString("server.port") address := net.JoinHostPort(host, port) // http server app.srv = &http.Server{ Handler: app.app, Addr: address, } // listen var err error app.ln, err = net.Listen("tcp", address) if err != nil { panic(err) } app.ready = true // serve if err := http.Serve(app.ln, app.app); err != nil { if !errors.Is(err, http.ErrServerClosed) { log.Error("run server error:" + err.Error()) } else { log.Info("server graceful down") } } } func (app *ApiV2) Wait() { DefaultWait() } func (app *ApiV2) Stop() { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() if err := app.srv.Shutdown(ctx); err != nil { log.Error("run server error:" + err.Error()) } } func (app *ApiV2) GetGinEngine() *gin.Engine { return app.app } func (app *ApiV2) GetHttpServer() *http.Server { return app.srv } func (app *ApiV2) Ready() (ok bool) { return app.ready } func (app *ApiV2) initModuleWithApp(name string, fn func(app *gin.Engine) error) (err error) { return initModule(name, func() error { return fn(app.app) }) } func NewApiV2() *ApiV2 { api := &ApiV2{ app: gin.New(), } api.Init() return api } var apiV2 *ApiV2 func GetApiV2() *ApiV2 { if apiV2 != nil { return apiV2 } apiV2 = NewApiV2() return apiV2 }
2302_79757062/crawlab
core/apps/api_v2.go
Go
bsd-3-clause
2,236
package apps import ( "bufio" "fmt" "github.com/crawlab-team/crawlab/core/interfaces" "github.com/crawlab-team/crawlab/core/sys_exec" "github.com/crawlab-team/crawlab/core/utils" "github.com/crawlab-team/crawlab/trace" "github.com/imroc/req" "github.com/spf13/viper" "os" "os/exec" "strings" "time" ) type Docker struct { // parent parent ServerApp // dependencies interfaces.WithConfigPath // seaweedfs log fsLogFilePath string fsLogFile *os.File fsReady bool } func (app *Docker) Init() { var err error app.fsLogFile, err = os.OpenFile(app.fsLogFilePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, os.FileMode(0777)) if err != nil { trace.PrintError(err) } // replace paths if err := app.replacePaths(); err != nil { panic(err) } // start nginx go app.startNginx() // start seaweedfs go app.startSeaweedFs() } func (app *Docker) Start() { // import demo //if utils.IsDemo() && utils.InitializedDemo() { // go app.importDemo() //} } func (app *Docker) Wait() { DefaultWait() } func (app *Docker) Stop() { } func (app *Docker) GetParent() (parent ServerApp) { return app.parent } func (app *Docker) SetParent(parent ServerApp) { app.parent = parent } func (app *Docker) Ready() (ok bool) { return app.fsReady && app.parent.GetApi().Ready() } func (app *Docker) replacePaths() (err error) { // read indexHtmlPath := "/app/dist/index.html" indexHtmlBytes, err := os.ReadFile(indexHtmlPath) if err != nil { return trace.TraceError(err) } indexHtml := string(indexHtmlBytes) // replace paths baseUrl := viper.GetString("base.url") if baseUrl != "" { indexHtml = app._replacePath(indexHtml, "js", baseUrl) indexHtml = app._replacePath(indexHtml, "css", baseUrl) indexHtml = app._replacePath(indexHtml, "<link rel=\"stylesheet\" href=\"", baseUrl) indexHtml = app._replacePath(indexHtml, "<link rel=\"stylesheet\" href=\"", baseUrl) indexHtml = app._replacePath(indexHtml, "window.VUE_APP_API_BASE_URL = '", baseUrl) } // replace path of baidu tongji initBaiduTongji := viper.GetString("string") if initBaiduTongji != "" { indexHtml = strings.ReplaceAll(indexHtml, "window.VUE_APP_INIT_BAIDU_TONGJI = ''", fmt.Sprintf("window.VUE_APP_INIT_BAIDU_TONGJI = '%s'", initBaiduTongji)) } // replace path of umeng initUmeng := viper.GetString("string") if initUmeng != "" { indexHtml = strings.ReplaceAll(indexHtml, "window.VUE_APP_INIT_UMENG = ''", fmt.Sprintf("window.VUE_APP_INIT_UMENG = '%s'", initUmeng)) } // write if err := os.WriteFile(indexHtmlPath, []byte(indexHtml), os.FileMode(0766)); err != nil { return trace.TraceError(err) } return nil } func (app *Docker) _replacePath(text, path, baseUrl string) (res string) { text = strings.ReplaceAll(text, path, fmt.Sprintf("%s/%s", baseUrl, path)) return text } func (app *Docker) startNginx() { cmd := exec.Command("service", "nginx", "start") sys_exec.ConfigureCmdLogging(cmd, func(scanner *bufio.Scanner) { for scanner.Scan() { line := fmt.Sprintf("[nginx] %s\n", scanner.Text()) _, _ = os.Stdout.WriteString(line) } }) if err := cmd.Run(); err != nil { trace.PrintError(err) } } func (app *Docker) startSeaweedFs() { seaweedFsDataPath := "/data/seaweedfs" if !utils.Exists(seaweedFsDataPath) { _ = os.MkdirAll(seaweedFsDataPath, os.FileMode(0777)) } cmd := exec.Command("weed", "server", "-dir", "/data", "-master.dir", seaweedFsDataPath, "-volume.dir.idx", seaweedFsDataPath, "-ip", "localhost", "-volume.port", "9999", "-volume.minFreeSpace", "1GiB", "-filer", ) sys_exec.ConfigureCmdLogging(cmd, func(scanner *bufio.Scanner) { for scanner.Scan() { line := fmt.Sprintf("[seaweedfs] %s\n", scanner.Text()) _, _ = app.fsLogFile.WriteString(line) } }) go func() { if err := cmd.Run(); err != nil { trace.PrintError(err) } }() for { _, err := req.Get("http://localhost:8888") if err != nil { time.Sleep(1 * time.Second) continue } app.fsReady = true return } } func (app *Docker) importDemo() { for { if app.Ready() { break } time.Sleep(1 * time.Second) } _ = utils.ImportDemo() } func NewDocker(svr ServerApp) *Docker { dck := &Docker{ parent: svr, fsLogFilePath: "/var/log/weed.log", } dck.Init() return dck } var dck *Docker func GetDocker(svr ServerApp) *Docker { if dck != nil { return dck } dck = NewDocker(svr) return dck }
2302_79757062/crawlab
core/apps/docker.go
Go
bsd-3-clause
4,406
package apps import ( "github.com/crawlab-team/crawlab/core/interfaces" "github.com/gin-gonic/gin" "net/http" ) type App interface { Init() Start() Wait() Stop() } type ApiApp interface { App GetGinEngine() (engine *gin.Engine) GetHttpServer() (svr *http.Server) Ready() (ok bool) } type NodeApp interface { App interfaces.WithConfigPath } type ServerApp interface { NodeApp GetApi() (api ApiApp) GetNodeService() (masterSvc interfaces.NodeService) } type DockerApp interface { App GetParent() (parent NodeApp) SetParent(parent NodeApp) Ready() (ok bool) }
2302_79757062/crawlab
core/apps/interfaces.go
Go
bsd-3-clause
583
package apps import ( "fmt" "github.com/apex/log" "github.com/crawlab-team/crawlab/core/config" "github.com/crawlab-team/crawlab/core/controllers" "github.com/crawlab-team/crawlab/core/interfaces" "github.com/crawlab-team/crawlab/core/node/service" "github.com/crawlab-team/crawlab/core/utils" "github.com/spf13/viper" "net/http" _ "net/http/pprof" ) func init() { injectModules() } type Server struct { // settings grpcAddress interfaces.Address // dependencies interfaces.WithConfigPath nodeSvc interfaces.NodeService // modules api *Api dck *Docker // internals quit chan int } func (app *Server) SetGrpcAddress(address interfaces.Address) { app.grpcAddress = address } func (app *Server) GetApi() (api ApiApp) { return app.api } func (app *Server) GetNodeService() (svc interfaces.NodeService) { return app.nodeSvc } func (app *Server) Init() { // log node info app.logNodeInfo() if utils.IsMaster() { // initialize controllers if err := controllers.InitControllers(); err != nil { panic(err) } } // pprof app.initPprof() } func (app *Server) Start() { if utils.IsMaster() { // start docker app if utils.IsDocker() { go app.dck.Start() } // start api go app.api.Start() } // start node service go app.nodeSvc.Start() } func (app *Server) Wait() { <-app.quit } func (app *Server) Stop() { app.api.Stop() app.quit <- 1 } func (app *Server) logNodeInfo() { log.Infof("current node type: %s", utils.GetNodeType()) if utils.IsDocker() { log.Infof("running in docker container") } } func (app *Server) initPprof() { if viper.GetBool("pprof") { go func() { fmt.Println(http.ListenAndServe("0.0.0.0:6060", nil)) }() } } func NewServer() (app NodeApp) { // server svr := &Server{ WithConfigPath: config.NewConfigPathService(), quit: make(chan int, 1), } // service options var svcOpts []service.Option if svr.grpcAddress != nil { svcOpts = append(svcOpts, service.WithAddress(svr.grpcAddress)) } // master modules if utils.IsMaster() { // api svr.api = GetApi() // docker if utils.IsDocker() { svr.dck = GetDocker(svr) } } // node service var err error if utils.IsMaster() { svr.nodeSvc, err = service.NewMasterService(svcOpts...) } else { svr.nodeSvc, err = service.NewWorkerService(svcOpts...) } if err != nil { panic(err) } return svr } var server NodeApp func GetServer() NodeApp { if server != nil { return server } server = NewServer() return server }
2302_79757062/crawlab
core/apps/server.go
Go
bsd-3-clause
2,513
package apps import ( "fmt" "github.com/apex/log" "github.com/crawlab-team/crawlab/core/config" "github.com/crawlab-team/crawlab/core/interfaces" "github.com/crawlab-team/crawlab/core/node/service" "github.com/crawlab-team/crawlab/core/utils" "github.com/spf13/viper" "net/http" _ "net/http/pprof" ) type ServerV2 struct { // settings grpcAddress interfaces.Address // dependencies interfaces.WithConfigPath // modules nodeSvc interfaces.NodeService api *ApiV2 dck *Docker // internals quit chan int } func (app *ServerV2) Init() { // log node info app.logNodeInfo() // pprof app.initPprof() } func (app *ServerV2) Start() { if utils.IsMaster() { // start docker app if utils.IsDocker() { go app.dck.Start() } // start api go app.api.Start() } // start node service go app.nodeSvc.Start() } func (app *ServerV2) Wait() { <-app.quit } func (app *ServerV2) Stop() { app.api.Stop() app.quit <- 1 } func (app *ServerV2) GetApi() ApiApp { return app.api } func (app *ServerV2) GetNodeService() interfaces.NodeService { return app.nodeSvc } func (app *ServerV2) logNodeInfo() { log.Infof("current node type: %s", utils.GetNodeType()) if utils.IsDocker() { log.Infof("running in docker container") } } func (app *ServerV2) initPprof() { if viper.GetBool("pprof") { go func() { fmt.Println(http.ListenAndServe("0.0.0.0:6060", nil)) }() } } func NewServerV2() (app NodeApp) { // server svr := &ServerV2{ WithConfigPath: config.NewConfigPathService(), quit: make(chan int, 1), } // master modules if utils.IsMaster() { // api svr.api = GetApiV2() // docker if utils.IsDocker() { svr.dck = GetDocker(svr) } } // node service var err error if utils.IsMaster() { svr.nodeSvc, err = service.NewMasterServiceV2() } else { svr.nodeSvc, err = service.NewWorkerServiceV2() } if err != nil { panic(err) } return svr } var serverV2 NodeApp func GetServerV2() NodeApp { if serverV2 != nil { return serverV2 } serverV2 = NewServerV2() return serverV2 }
2302_79757062/crawlab
core/apps/server_v2.go
Go
bsd-3-clause
2,074
package apps import ( "fmt" "github.com/apex/log" "github.com/crawlab-team/crawlab/core/color" "github.com/crawlab-team/crawlab/core/config" "github.com/crawlab-team/crawlab/core/container" grpcclient "github.com/crawlab-team/crawlab/core/grpc/client" grpcserver "github.com/crawlab-team/crawlab/core/grpc/server" modelsclient "github.com/crawlab-team/crawlab/core/models/client" modelsservice "github.com/crawlab-team/crawlab/core/models/service" nodeconfig "github.com/crawlab-team/crawlab/core/node/config" "github.com/crawlab-team/crawlab/core/schedule" "github.com/crawlab-team/crawlab/core/spider/admin" "github.com/crawlab-team/crawlab/core/stats" "github.com/crawlab-team/crawlab/core/task/handler" "github.com/crawlab-team/crawlab/core/task/scheduler" taskstats "github.com/crawlab-team/crawlab/core/task/stats" "github.com/crawlab-team/crawlab/core/user" "github.com/crawlab-team/crawlab/core/utils" "github.com/crawlab-team/crawlab/trace" ) func Start(app App) { start(app) } func start(app App) { app.Init() go app.Start() app.Wait() app.Stop() } func DefaultWait() { utils.DefaultWait() } func initModule(name string, fn func() error) (err error) { if err := fn(); err != nil { log.Error(fmt.Sprintf("init %s error: %s", name, err.Error())) _ = trace.TraceError(err) panic(err) } log.Info(fmt.Sprintf("initialized %s successfully", name)) return nil } func initApp(name string, app App) { _ = initModule(name, func() error { app.Init() return nil }) } var injectors = []interface{}{ modelsservice.GetService, modelsclient.NewServiceDelegate, modelsclient.NewNodeServiceDelegate, modelsclient.NewSpiderServiceDelegate, modelsclient.NewTaskServiceDelegate, modelsclient.NewTaskStatServiceDelegate, modelsclient.NewEnvironmentServiceDelegate, grpcclient.NewClient, grpcclient.NewPool, grpcserver.GetServer, grpcserver.NewModelDelegateServer, grpcserver.NewModelBaseServiceServer, grpcserver.NewNodeServer, grpcserver.NewTaskServer, grpcserver.NewMessageServer, config.NewConfigPathService, user.GetUserService, schedule.GetScheduleService, admin.GetSpiderAdminService, stats.GetStatsService, nodeconfig.NewNodeConfigService, taskstats.GetTaskStatsService, color.NewService, scheduler.GetTaskSchedulerService, handler.GetTaskHandlerService, } func injectModules() { c := container.GetContainer() for _, injector := range injectors { if err := c.Provide(injector); err != nil { panic(err) } } }
2302_79757062/crawlab
core/apps/utils.go
Go
bsd-3-clause
2,487
package cmd import ( "github.com/spf13/cobra" ) var ( // Used for flags. cfgFile string rootCmd = &cobra.Command{ Use: "crawlab", Short: "CLI tool for Crawlab", Long: `The CLI tool is for controlling against Crawlab. Crawlab is a distributed web crawler and task admin platform aimed at making web crawling and task management easier. `, } ) // Execute executes the root command. func Execute() error { return rootCmd.Execute() } // GetRootCmd get rootCmd instance func GetRootCmd() *cobra.Command { return rootCmd } func init() { rootCmd.PersistentFlags().StringVar(&cfgFile, "c", "", "Use Custom Config File") }
2302_79757062/crawlab
core/cmd/root.go
Go
bsd-3-clause
636
package cmd import ( "github.com/crawlab-team/crawlab/core/apps" "github.com/spf13/cobra" ) func init() { rootCmd.AddCommand(serverCmd) } var serverCmd = &cobra.Command{ Use: "server", Aliases: []string{"s"}, Short: "Start Crawlab server", Long: `Start Crawlab node server that can serve as API, task scheduler, task runner, etc.`, Run: func(cmd *cobra.Command, args []string) { // app //svr := apps.GetServer(opts...) svr := apps.GetServerV2() // start apps.Start(svr) }, }
2302_79757062/crawlab
core/cmd/server.go
Go
bsd-3-clause
507
package color import ( "encoding/hex" "encoding/json" "github.com/crawlab-team/crawlab/core/data" "github.com/crawlab-team/crawlab/core/entity" "github.com/crawlab-team/crawlab/core/errors" "github.com/crawlab-team/crawlab/core/interfaces" "github.com/crawlab-team/crawlab/trace" "math/rand" "strconv" "strings" ) func NewService() (svc interfaces.ColorService, err error) { var cl []*entity.Color cm := map[string]*entity.Color{} if err := json.Unmarshal([]byte(data.ColorsDataText), &cl); err != nil { return nil, trace.TraceError(err) } for _, c := range cl { cm[c.Name] = c } return &Service{ cl: cl, cm: cm, }, nil } type Service struct { cl []*entity.Color cm map[string]*entity.Color } func (svc *Service) Inject() (err error) { return nil } func (svc *Service) GetByName(name string) (res interfaces.Color, err error) { res, ok := svc.cm[name] if !ok { return res, errors.ErrorModelNotFound } return res, err } func (svc *Service) GetRandom() (res interfaces.Color, err error) { if len(svc.cl) == 0 { hexStr, err := svc.getRandomColorHex() if err != nil { return res, err } return &entity.Color{Hex: hexStr}, nil } idx := rand.Intn(len(svc.cl)) return svc.cl[idx], nil } func (svc *Service) getRandomColorHex() (res string, err error) { n := 6 arr := make([]string, n) for i := 0; i < n; i++ { arr[i], err = svc.getRandomHexChar() if err != nil { return res, err } } return strings.Join(arr, ""), nil } func (svc *Service) getRandomHexChar() (res string, err error) { n := rand.Intn(16) b := []byte(strconv.Itoa(n)) h := make([]byte, 1) hex.Encode(h, b) return string(h), nil }
2302_79757062/crawlab
core/color/service.go
Go
bsd-3-clause
1,667