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
|
|---|---|---|---|---|---|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("CRM Deal", {
refresh(frm) {
frm.add_web_link(`/crm/deals/${frm.doc.name}`, __("Open in Portal"));
},
});
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_deal/crm_deal.js
|
JavaScript
|
agpl-3.0
| 250
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import json
import frappe
from frappe import _
from frappe.desk.form.assign_to import add as assign
from frappe.model.document import Document
from crm.fcrm.doctype.crm_service_level_agreement.utils import get_sla
from crm.fcrm.doctype.crm_status_change_log.crm_status_change_log import add_status_change_log
class CRMDeal(Document):
def before_validate(self):
self.set_sla()
def validate(self):
self.set_primary_contact()
self.set_primary_email_mobile_no()
if self.deal_owner and not self.is_new():
self.share_with_agent(self.deal_owner)
self.assign_agent(self.deal_owner)
if self.has_value_changed("status"):
add_status_change_log(self)
def after_insert(self):
if self.deal_owner:
self.assign_agent(self.deal_owner)
def before_save(self):
self.apply_sla()
def set_primary_contact(self, contact=None):
if not self.contacts:
return
if not contact and len(self.contacts) == 1:
self.contacts[0].is_primary = 1
elif contact:
for d in self.contacts:
if d.contact == contact:
d.is_primary = 1
else:
d.is_primary = 0
def set_primary_email_mobile_no(self):
if not self.contacts:
self.email = ""
self.mobile_no = ""
self.phone = ""
return
if len([contact for contact in self.contacts if contact.is_primary]) > 1:
frappe.throw(_("Only one {0} can be set as primary.").format(frappe.bold("Contact")))
primary_contact_exists = False
for d in self.contacts:
if d.is_primary == 1:
primary_contact_exists = True
self.email = d.email.strip() if d.email else ""
self.mobile_no = d.mobile_no.strip() if d.mobile_no else ""
self.phone = d.phone.strip() if d.phone else ""
break
if not primary_contact_exists:
self.email = ""
self.mobile_no = ""
self.phone = ""
def assign_agent(self, agent):
if not agent:
return
assignees = self.get_assigned_users()
if assignees:
for assignee in assignees:
if agent == assignee:
# the agent is already set as an assignee
return
assign({"assign_to": [agent], "doctype": "CRM Deal", "name": self.name})
def share_with_agent(self, agent):
if not agent:
return
docshares = frappe.get_all(
"DocShare",
filters={"share_name": self.name, "share_doctype": self.doctype},
fields=["name", "user"],
)
shared_with = [d.user for d in docshares] + [agent]
for user in shared_with:
if user == agent and not frappe.db.exists("DocShare", {"user": agent, "share_name": self.name, "share_doctype": self.doctype}):
frappe.share.add_docshare(
self.doctype, self.name, agent, write=1, flags={"ignore_share_permission": True}
)
elif user != agent:
frappe.share.remove(self.doctype, self.name, user)
def set_sla(self):
"""
Find an SLA to apply to the deal.
"""
if self.sla: return
sla = get_sla(self)
if not sla:
self.first_responded_on = None
self.first_response_time = None
return
self.sla = sla.name
def apply_sla(self):
"""
Apply SLA if set.
"""
if not self.sla:
return
sla = frappe.get_last_doc("CRM Service Level Agreement", {"name": self.sla})
if sla:
sla.apply(self)
@staticmethod
def default_list_data():
columns = [
{
'label': 'Organization',
'type': 'Link',
'key': 'organization',
'options': 'CRM Organization',
'width': '11rem',
},
{
'label': 'Amount',
'type': 'Currency',
'key': 'annual_revenue',
'width': '9rem',
},
{
'label': 'Status',
'type': 'Select',
'key': 'status',
'width': '10rem',
},
{
'label': 'Email',
'type': 'Data',
'key': 'email',
'width': '12rem',
},
{
'label': 'Mobile No',
'type': 'Data',
'key': 'mobile_no',
'width': '11rem',
},
{
'label': 'Assigned To',
'type': 'Text',
'key': '_assign',
'width': '10rem',
},
{
'label': 'Last Modified',
'type': 'Datetime',
'key': 'modified',
'width': '8rem',
},
]
rows = [
"name",
"organization",
"annual_revenue",
"status",
"email",
"currency",
"mobile_no",
"deal_owner",
"sla_status",
"response_by",
"first_response_time",
"first_responded_on",
"modified",
"_assign",
]
return {'columns': columns, 'rows': rows}
@staticmethod
def default_kanban_settings():
return {
"column_field": "status",
"title_field": "organization",
"kanban_fields": '["annual_revenue", "email", "mobile_no", "_assign", "modified"]'
}
@frappe.whitelist()
def add_contact(deal, contact):
if not frappe.has_permission("CRM Deal", "write", deal):
frappe.throw(_("Not allowed to add contact to Deal"), frappe.PermissionError)
deal = frappe.get_cached_doc("CRM Deal", deal)
deal.append("contacts", {"contact": contact})
deal.save()
return True
@frappe.whitelist()
def remove_contact(deal, contact):
if not frappe.has_permission("CRM Deal", "write", deal):
frappe.throw(_("Not allowed to remove contact from Deal"), frappe.PermissionError)
deal = frappe.get_cached_doc("CRM Deal", deal)
deal.contacts = [d for d in deal.contacts if d.contact != contact]
deal.save()
return True
@frappe.whitelist()
def set_primary_contact(deal, contact):
if not frappe.has_permission("CRM Deal", "write", deal):
frappe.throw(_("Not allowed to set primary contact for Deal"), frappe.PermissionError)
deal = frappe.get_cached_doc("CRM Deal", deal)
deal.set_primary_contact(contact)
deal.save()
return True
def create_organization(doc):
if not doc.get("organization_name"):
return
existing_organization = frappe.db.exists("CRM Organization", {"organization_name": doc.get("organization_name")})
if existing_organization:
return existing_organization
organization = frappe.new_doc("CRM Organization")
organization.update(
{
"organization_name": doc.get("organization_name"),
"website": doc.get("website"),
"territory": doc.get("territory"),
"industry": doc.get("industry"),
"annual_revenue": doc.get("annual_revenue"),
}
)
organization.insert(ignore_permissions=True)
return organization.name
def contact_exists(doc):
email_exist = frappe.db.exists("Contact Email", {"email_id": doc.get("email")})
mobile_exist = frappe.db.exists("Contact Phone", {"phone": doc.get("mobile_no")})
doctype = "Contact Email" if email_exist else "Contact Phone"
name = email_exist or mobile_exist
if name:
return frappe.db.get_value(doctype, name, "parent")
return False
def create_contact(doc):
existing_contact = contact_exists(doc)
if existing_contact:
return existing_contact
contact = frappe.new_doc("Contact")
contact.update(
{
"first_name": doc.get("first_name"),
"last_name": doc.get("last_name"),
"salutation": doc.get("salutation"),
"company_name": doc.get("organization") or doc.get("organization_name"),
}
)
if doc.get("email"):
contact.append("email_ids", {"email_id": doc.get("email"), "is_primary": 1})
if doc.get("mobile_no"):
contact.append("phone_nos", {"phone": doc.get("mobile_no"), "is_primary_mobile_no": 1})
contact.insert(ignore_permissions=True)
contact.reload() # load changes by hooks on contact
return contact.name
@frappe.whitelist()
def create_deal(args):
deal = frappe.new_doc("CRM Deal")
contact = args.get("contact")
if not contact and (args.get("first_name") or args.get("last_name") or args.get("email") or args.get("mobile_no")):
contact = create_contact(args)
deal.update({
"organization": args.get("organization") or create_organization(args),
"contacts": [{"contact": contact, "is_primary": 1}] if contact else [],
})
args.pop("organization", None)
deal.update(args)
deal.insert(ignore_permissions=True)
return deal.name
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_deal/crm_deal.py
|
Python
|
agpl-3.0
| 7,793
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("CRM Deal Status", {
// refresh(frm) {
// },
// });
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_deal_status/crm_deal_status.js
|
JavaScript
|
agpl-3.0
| 198
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class CRMDealStatus(Document):
pass
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_deal_status/crm_deal_status.py
|
Python
|
agpl-3.0
| 218
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("CRM Form Script", {
refresh(frm) {
frm.set_query("dt", {
filters: {
istable: 0,
},
});
if (frm.doc.is_standard && !frappe.boot.developer_mode) {
frm.disable_form();
frappe.show_alert(
__(
"Standard Form Scripts can not be modified, duplicate the Form Script instead."
)
);
}
if (!frappe.boot.developer_mode) {
frm.toggle_enable("is_standard", 0);
}
frm.trigger("add_enable_button");
},
add_enable_button(frm) {
frm.add_custom_button(
frm.doc.enabled ? __("Disable") : __("Enable"),
() => {
frm.set_value("enabled", !frm.doc.enabled);
frm.save();
}
);
},
view(frm) {
let has_form_boilerplate = frm.doc.script.includes(
"function setupForm("
);
let has_list_boilerplate = frm.doc.script.includes(
"function setupList("
);
if (frm.doc.view == "Form" && !has_form_boilerplate) {
frm.doc.script = `
function setupForm({ doc }) {
return {
actions: [],
}
}`.trim();
}
if (frm.doc.view == "List" && !has_list_boilerplate) {
frm.doc.script = `
function setupList({ list }) {
return {
actions: [],
bulk_actions: [],
}
}`.trim();
}
},
});
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_form_script/crm_form_script.js
|
JavaScript
|
agpl-3.0
| 1,289
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.model.document import Document
class CRMFormScript(Document):
def validate(self):
in_user_env = not (
frappe.flags.in_install
or frappe.flags.in_patch
or frappe.flags.in_test
or frappe.flags.in_fixtures
)
if in_user_env and not self.is_new() and self.is_standard and not frappe.conf.developer_mode:
# only enabled can be changed for standard form scripts
if self.has_value_changed("enabled"):
enabled_value = self.enabled
self.reload()
self.enabled = enabled_value
else:
frappe.throw(_("You need to be in developer mode to edit a Standard Form Script"))
def get_form_script(dt, view="Form"):
"""Returns the form script for the given doctype"""
FormScript = frappe.qb.DocType("CRM Form Script")
query = (
frappe.qb.from_(FormScript)
.select("script")
.where(FormScript.dt == dt)
.where(FormScript.view == view)
.where(FormScript.enabled == 1)
)
doc = query.run(as_dict=True)
if doc:
return [d.script for d in doc] if len(doc) > 1 else doc[0].script
else:
return None
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_form_script/crm_form_script.py
|
Python
|
agpl-3.0
| 1,202
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class CRMHoliday(Document):
pass
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_holiday/crm_holiday.py
|
Python
|
agpl-3.0
| 215
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("CRM Holiday List", {
// refresh(frm) {
// },
// });
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_holiday_list/crm_holiday_list.js
|
JavaScript
|
agpl-3.0
| 199
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class CRMHolidayList(Document):
pass
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_holiday_list/crm_holiday_list.py
|
Python
|
agpl-3.0
| 219
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("CRM Industry", {
// refresh(frm) {
// },
// });
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_industry/crm_industry.js
|
JavaScript
|
agpl-3.0
| 195
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class CRMIndustry(Document):
pass
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_industry/crm_industry.py
|
Python
|
agpl-3.0
| 216
|
// Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("CRM Invitation", {
refresh(frm) {
if (frm.doc.status != "Accepted") {
frm.add_custom_button(__("Accept Invitation"), () => {
return frm.call("accept_invitation");
});
}
},
});
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_invitation/crm_invitation.js
|
JavaScript
|
agpl-3.0
| 333
|
# Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
class CRMInvitation(Document):
def before_insert(self):
frappe.utils.validate_email_address(self.email, True)
self.key = frappe.generate_hash(length=12)
self.invited_by = frappe.session.user
self.status = "Pending"
def after_insert(self):
self.invite_via_email()
def invite_via_email(self):
invite_link = frappe.utils.get_url(f"/api/method/crm.api.accept_invitation?key={self.key}")
if frappe.local.dev_server:
print(f"Invite link for {self.email}: {invite_link}")
title = f"Frappe CRM"
template = "crm_invitation"
frappe.sendmail(
recipients=self.email,
subject=f"You have been invited to join {title}",
template=template,
args={"title": title, "invite_link": invite_link},
now=True,
)
self.db_set("email_sent_at", frappe.utils.now())
@frappe.whitelist()
def accept_invitation(self):
frappe.only_for("System Manager")
self.accept()
def accept(self):
if self.status == "Expired":
frappe.throw("Invalid or expired key")
user = self.create_user_if_not_exists()
user.append_roles(self.role)
user.save(ignore_permissions=True)
self.status = "Accepted"
self.accepted_at = frappe.utils.now()
self.save(ignore_permissions=True)
def create_user_if_not_exists(self):
if not frappe.db.exists("User", self.email):
first_name = self.email.split("@")[0].title()
user = frappe.get_doc(
doctype="User",
user_type="System User",
email=self.email,
send_welcome_email=0,
first_name=first_name,
).insert(ignore_permissions=True)
else:
user = frappe.get_doc("User", self.email)
return user
def expire_invitations():
"""expire invitations after 3 days"""
from frappe.utils import add_days, now
days = 3
invitations_to_expire = frappe.db.get_all(
"CRM Invitation", filters={"status": "Pending", "creation": ["<", add_days(now(), -days)]}
)
for invitation in invitations_to_expire:
invitation = frappe.get_doc("CRM Invitation", invitation.name)
invitation.status = "Expired"
invitation.save(ignore_permissions=True)
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_invitation/crm_invitation.py
|
Python
|
agpl-3.0
| 2,207
|
import frappe
from frappe import _
from crm.api.doc import get_fields_meta, get_assigned_users
from crm.fcrm.doctype.crm_form_script.crm_form_script import get_form_script
@frappe.whitelist()
def get_lead(name):
Lead = frappe.qb.DocType("CRM Lead")
query = frappe.qb.from_(Lead).select("*").where(Lead.name == name).limit(1)
lead = query.run(as_dict=True)
if not len(lead):
frappe.throw(_("Lead not found"), frappe.DoesNotExistError)
lead = lead.pop()
lead["doctype"] = "CRM Lead"
lead["fields_meta"] = get_fields_meta("CRM Lead")
lead["_form_script"] = get_form_script('CRM Lead')
lead["_assign"] = get_assigned_users("CRM Lead", lead.name, lead.owner)
return lead
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_lead/api.py
|
Python
|
agpl-3.0
| 683
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("CRM Lead", {
refresh(frm) {
frm.add_web_link(`/crm/leads/${frm.doc.name}`, __("Open in Portal"));
},
});
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_lead/crm_lead.js
|
JavaScript
|
agpl-3.0
| 250
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import json
import frappe
from frappe import _
from frappe.desk.form.assign_to import add as assign
from frappe.model.document import Document
from frappe.utils import has_gravatar, validate_email_address
from crm.fcrm.doctype.crm_service_level_agreement.utils import get_sla
from crm.fcrm.doctype.crm_status_change_log.crm_status_change_log import add_status_change_log
class CRMLead(Document):
def before_validate(self):
self.set_sla()
def validate(self):
self.set_full_name()
self.set_lead_name()
self.set_title()
self.validate_email()
if self.lead_owner and not self.is_new():
self.share_with_agent(self.lead_owner)
self.assign_agent(self.lead_owner)
if self.has_value_changed("status"):
add_status_change_log(self)
def after_insert(self):
if self.lead_owner:
self.assign_agent(self.lead_owner)
def before_save(self):
self.apply_sla()
def set_full_name(self):
if self.first_name:
self.lead_name = " ".join(
filter(None, [self.salutation, self.first_name, self.middle_name, self.last_name])
)
def set_lead_name(self):
if not self.lead_name:
# Check for leads being created through data import
if not self.organization and not self.email and not self.flags.ignore_mandatory:
frappe.throw(_("A Lead requires either a person's name or an organization's name"))
elif self.organization:
self.lead_name = self.organization
elif self.email:
self.lead_name = self.email.split("@")[0]
else:
self.lead_name = "Unnamed Lead"
def set_title(self):
self.title = self.organization or self.lead_name
def validate_email(self):
if self.email:
if not self.flags.ignore_email_validation:
validate_email_address(self.email, throw=True)
if self.email == self.lead_owner:
frappe.throw(_("Lead Owner cannot be same as the Lead Email Address"))
if self.is_new() or not self.image:
self.image = has_gravatar(self.email)
def assign_agent(self, agent):
if not agent:
return
assignees = self.get_assigned_users()
if assignees:
for assignee in assignees:
if agent == assignee:
# the agent is already set as an assignee
return
assign({"assign_to": [agent], "doctype": "CRM Lead", "name": self.name})
def share_with_agent(self, agent):
if not agent:
return
docshares = frappe.get_all(
"DocShare",
filters={"share_name": self.name, "share_doctype": self.doctype},
fields=["name", "user"],
)
shared_with = [d.user for d in docshares] + [agent]
for user in shared_with:
if user == agent and not frappe.db.exists("DocShare", {"user": agent, "share_name": self.name, "share_doctype": self.doctype}):
frappe.share.add_docshare(
self.doctype, self.name, agent, write=1, flags={"ignore_share_permission": True}
)
elif user != agent:
frappe.share.remove(self.doctype, self.name, user)
def create_contact(self, throw=True):
if not self.lead_name:
self.set_full_name()
self.set_lead_name()
existing_contact = self.contact_exists(throw)
if existing_contact:
return existing_contact
contact = frappe.new_doc("Contact")
contact.update(
{
"first_name": self.first_name or self.lead_name,
"last_name": self.last_name,
"salutation": self.salutation,
"gender": self.gender,
"designation": self.job_title,
"company_name": self.organization,
"image": self.image or "",
}
)
if self.email:
contact.append("email_ids", {"email_id": self.email, "is_primary": 1})
if self.phone:
contact.append("phone_nos", {"phone": self.phone, "is_primary_phone": 1})
if self.mobile_no:
contact.append("phone_nos", {"phone": self.mobile_no, "is_primary_mobile_no": 1})
contact.insert(ignore_permissions=True)
contact.reload() # load changes by hooks on contact
return contact.name
def create_organization(self):
if not self.organization:
return
existing_organization = frappe.db.exists("CRM Organization", {"organization_name": self.organization})
if existing_organization:
return existing_organization
organization = frappe.new_doc("CRM Organization")
organization.update(
{
"organization_name": self.organization,
"website": self.website,
"territory": self.territory,
"industry": self.industry,
"annual_revenue": self.annual_revenue,
}
)
organization.insert(ignore_permissions=True)
return organization.name
def contact_exists(self, throw=True):
email_exist = frappe.db.exists("Contact Email", {"email_id": self.email})
phone_exist = frappe.db.exists("Contact Phone", {"phone": self.phone})
mobile_exist = frappe.db.exists("Contact Phone", {"phone": self.mobile_no})
doctype = "Contact Email" if email_exist else "Contact Phone"
name = email_exist or phone_exist or mobile_exist
if name:
text = "Email" if email_exist else "Phone" if phone_exist else "Mobile No"
data = self.email if email_exist else self.phone if phone_exist else self.mobile_no
value = "{0}: {1}".format(text, data)
contact = frappe.db.get_value(doctype, name, "parent")
if throw:
frappe.throw(
_("Contact already exists with {0}").format(value),
title=_("Contact Already Exists"),
)
return contact
return False
def create_deal(self, contact, organization):
deal = frappe.new_doc("CRM Deal")
lead_deal_map = {
"lead_owner": "deal_owner",
}
restricted_fieldtypes = ["Tab Break", "Section Break", "Column Break", "HTML", "Button", "Attach", "Table"]
restricted_map_fields = ["name", "naming_series", "creation", "owner", "modified", "modified_by", "idx", "docstatus", "status", "email", "mobile_no", "phone", "sla", "sla_status", "response_by", "first_response_time", "first_responded_on", "communication_status", "sla_creation"]
for field in self.meta.fields:
if field.fieldtype in restricted_fieldtypes:
continue
if field.fieldname in restricted_map_fields:
continue
fieldname = field.fieldname
if field.fieldname in lead_deal_map:
fieldname = lead_deal_map[field.fieldname]
if hasattr(deal, fieldname):
if fieldname == "organization":
deal.update({fieldname: organization})
else:
deal.update({fieldname: self.get(field.fieldname)})
deal.update(
{
"lead": self.name,
"contacts": [{"contact": contact}],
}
)
if self.first_responded_on:
deal.update(
{
"sla_creation": self.sla_creation,
"response_by": self.response_by,
"sla_status": self.sla_status,
"communication_status": self.communication_status,
"first_response_time": self.first_response_time,
"first_responded_on": self.first_responded_on
}
)
deal.insert(ignore_permissions=True)
return deal.name
def set_sla(self):
"""
Find an SLA to apply to the lead.
"""
if self.sla: return
sla = get_sla(self)
if not sla:
self.first_responded_on = None
self.first_response_time = None
return
self.sla = sla.name
def apply_sla(self):
"""
Apply SLA if set.
"""
if not self.sla:
return
sla = frappe.get_last_doc("CRM Service Level Agreement", {"name": self.sla})
if sla:
sla.apply(self)
def convert_to_deal(self):
return convert_to_deal(lead=self.name, doc=self)
@staticmethod
def get_non_filterable_fields():
return ["converted"]
@staticmethod
def default_list_data():
columns = [
{
'label': 'Name',
'type': 'Data',
'key': 'lead_name',
'width': '12rem',
},
{
'label': 'Organization',
'type': 'Link',
'key': 'organization',
'options': 'CRM Organization',
'width': '10rem',
},
{
'label': 'Status',
'type': 'Select',
'key': 'status',
'width': '8rem',
},
{
'label': 'Email',
'type': 'Data',
'key': 'email',
'width': '12rem',
},
{
'label': 'Mobile No',
'type': 'Data',
'key': 'mobile_no',
'width': '11rem',
},
{
'label': 'Assigned To',
'type': 'Text',
'key': '_assign',
'width': '10rem',
},
{
'label': 'Last Modified',
'type': 'Datetime',
'key': 'modified',
'width': '8rem',
},
]
rows = [
"name",
"lead_name",
"organization",
"status",
"email",
"mobile_no",
"lead_owner",
"first_name",
"sla_status",
"response_by",
"first_response_time",
"first_responded_on",
"modified",
"_assign",
"image",
]
return {'columns': columns, 'rows': rows}
@staticmethod
def default_kanban_settings():
return {
"column_field": "status",
"title_field": "lead_name",
"kanban_fields": '["organization", "email", "mobile_no", "_assign", "modified"]'
}
@frappe.whitelist()
def convert_to_deal(lead, doc=None):
if not (doc and doc.flags.get("ignore_permissions")) and not frappe.has_permission("CRM Lead", "write", lead):
frappe.throw(_("Not allowed to convert Lead to Deal"), frappe.PermissionError)
lead = frappe.get_cached_doc("CRM Lead", lead)
if frappe.db.exists("CRM Lead Status", "Qualified"):
lead.status = "Qualified"
lead.converted = 1
if lead.sla and frappe.db.exists("CRM Communication Status", "Replied"):
lead.communication_status = "Replied"
lead.save(ignore_permissions=True)
contact = lead.create_contact(False)
organization = lead.create_organization()
deal = lead.create_deal(contact, organization)
return deal
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_lead/crm_lead.py
|
Python
|
agpl-3.0
| 9,404
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("CRM Lead Source", {
// refresh(frm) {
// },
// });
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_lead_source/crm_lead_source.js
|
JavaScript
|
agpl-3.0
| 198
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class CRMLeadSource(Document):
pass
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_lead_source/crm_lead_source.py
|
Python
|
agpl-3.0
| 218
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("CRM Lead Status", {
// refresh(frm) {
// },
// });
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_lead_status/crm_lead_status.js
|
JavaScript
|
agpl-3.0
| 198
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class CRMLeadStatus(Document):
pass
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_lead_status/crm_lead_status.py
|
Python
|
agpl-3.0
| 218
|
// Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("CRM Notification", {
// refresh(frm) {
// },
// });
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_notification/crm_notification.js
|
JavaScript
|
agpl-3.0
| 199
|
# Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
class CRMNotification(Document):
def on_update(self):
frappe.publish_realtime("crm_notification")
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_notification/crm_notification.py
|
Python
|
agpl-3.0
| 289
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("CRM Organization", {
// refresh(frm) {
// },
// });
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_organization/crm_organization.js
|
JavaScript
|
agpl-3.0
| 199
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
class CRMOrganization(Document):
@staticmethod
def default_list_data():
columns = [
{
'label': 'Organization',
'type': 'Data',
'key': 'organization_name',
'width': '16rem',
},
{
'label': 'Website',
'type': 'Data',
'key': 'website',
'width': '14rem',
},
{
'label': 'Industry',
'type': 'Link',
'key': 'industry',
'options': 'CRM Industry',
'width': '14rem',
},
{
'label': 'Annual Revenue',
'type': 'Currency',
'key': 'annual_revenue',
'width': '14rem',
},
{
'label': 'Last Modified',
'type': 'Datetime',
'key': 'modified',
'width': '8rem',
},
]
rows = [
"name",
"organization_name",
"organization_logo",
"website",
"industry",
"currency",
"annual_revenue",
"modified",
]
return {'columns': columns, 'rows': rows}
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_organization/crm_organization.py
|
Python
|
agpl-3.0
| 1,086
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class CRMServiceDay(Document):
pass
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_service_day/crm_service_day.py
|
Python
|
agpl-3.0
| 218
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("CRM Service Level Agreement", {
validate(frm) {
let default_priority_count = 0;
frm.doc.priorities.forEach(function (row) {
if (row.default_priority) {
default_priority_count++;
}
});
if (default_priority_count > 1) {
frappe.throw(
__("There can only be one default priority in Priorities table")
);
}
},
});
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_service_level_agreement/crm_service_level_agreement.js
|
JavaScript
|
agpl-3.0
| 482
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from datetime import timedelta
from frappe.model.document import Document
from frappe.utils import (
add_to_date,
get_datetime,
get_weekdays,
getdate,
now_datetime,
time_diff_in_seconds,
)
from crm.fcrm.doctype.crm_service_level_agreement.utils import get_context
class CRMServiceLevelAgreement(Document):
def validate(self):
self.validate_default()
self.validate_condition()
def validate_default(self):
if self.default:
other_slas = frappe.get_all(
"CRM Service Level Agreement",
filters={"apply_on": self.apply_on, "default": True},
fields=["name"],
)
if other_slas:
frappe.throw(
_(
"Default Service Level Agreement already exists for {0}"
).format(self.apply_on)
)
def validate_condition(self):
if not self.condition:
return
try:
temp_doc = frappe.new_doc(self.apply_on)
frappe.safe_eval(self.condition, None, get_context(temp_doc))
except Exception as e:
frappe.throw(
_("The Condition '{0}' is invalid: {1}").format(self.condition, str(e))
)
def apply(self, doc: Document):
self.handle_creation(doc)
self.handle_communication_status(doc)
self.handle_targets(doc)
self.handle_sla_status(doc)
def handle_creation(self, doc: Document):
doc.sla_creation = doc.sla_creation or now_datetime()
def handle_communication_status(self, doc: Document):
if doc.is_new() or not doc.has_value_changed("communication_status"):
return
self.set_first_responded_on(doc)
self.set_first_response_time(doc)
def set_first_responded_on(self, doc: Document):
if doc.communication_status != self.get_default_priority():
doc.first_responded_on = (
doc.first_responded_on or now_datetime()
)
def set_first_response_time(self, doc: Document):
start_at = doc.sla_creation
end_at = doc.first_responded_on
if not start_at or not end_at:
return
doc.first_response_time = self.calc_elapsed_time(start_at, end_at)
def handle_targets(self, doc: Document):
self.set_response_by(doc)
def set_response_by(self, doc: Document):
start_time = doc.sla_creation
communication_status = doc.communication_status
priorities = self.get_priorities()
priority = priorities.get(communication_status)
if not priority or doc.response_by:
return
first_response_time = priority.get("first_response_time", 0)
end_time = self.calc_time(start_time, first_response_time)
if end_time:
doc.response_by = end_time
def handle_sla_status(self, doc: Document):
is_failed = self.is_first_response_failed(doc)
options = {
"Fulfilled": True,
"First Response Due": not doc.first_responded_on,
"Failed": is_failed,
}
for status in options:
if options[status]:
doc.sla_status = status
def is_first_response_failed(self, doc: Document):
if not doc.first_responded_on:
return get_datetime(doc.response_by) < now_datetime()
return get_datetime(doc.response_by) < get_datetime(doc.first_responded_on)
def calc_time(
self,
start_at: str,
duration_seconds: int,
):
res = get_datetime(start_at)
time_needed = duration_seconds
holidays = self.get_holidays()
weekdays = get_weekdays()
workdays = self.get_workdays()
while time_needed:
today = res
today_day = getdate(today)
today_weekday = weekdays[today.weekday()]
is_workday = today_weekday in workdays
is_holiday = today_day in holidays
if is_holiday or not is_workday:
res = add_to_date(res, days=1, as_datetime=True)
continue
today_workday = workdays[today_weekday]
now_in_seconds = time_diff_in_seconds(today, today_day)
start_time = max(today_workday.start_time.total_seconds(), now_in_seconds)
till_start_time = max(start_time - now_in_seconds, 0)
end_time = max(today_workday.end_time.total_seconds(), now_in_seconds)
time_left = max(end_time - start_time, 0)
if not time_left:
res = getdate(add_to_date(res, days=1, as_datetime=True))
continue
time_taken = min(time_needed, time_left)
time_needed -= time_taken
time_required = till_start_time + time_taken
res = add_to_date(res, seconds=time_required, as_datetime=True)
return res
def calc_elapsed_time(self, start_time, end_time) -> float:
"""
Get took from start to end, excluding non-working hours
:param start_at: Date at which calculation starts
:param end_at: Date at which calculation ends
:return: Number of seconds
"""
start_time = get_datetime(start_time)
end_time = get_datetime(end_time)
holiday_list = []
working_day_list = self.get_working_days()
working_hours = self.get_working_hours()
total_seconds = 0
current_time = start_time
while current_time < end_time:
in_holiday_list = current_time.date() in holiday_list
not_in_working_day_list = get_weekdays()[current_time.weekday()] not in working_day_list
if in_holiday_list or not_in_working_day_list or not self.is_working_time(current_time, working_hours):
current_time += timedelta(seconds=1)
continue
total_seconds += 1
current_time += timedelta(seconds=1)
return total_seconds
def get_priorities(self):
"""
Return priorities related info as a dict. With `priority` as key
"""
res = {}
for row in self.priorities:
res[row.priority] = row
return res
def get_default_priority(self):
"""
Return default priority
"""
for row in self.priorities:
if row.default_priority:
return row.priority
return self.priorities[0].priority
def get_workdays(self) -> dict[str, dict]:
"""
Return workdays related info as a dict. With `workday` as key
"""
res = {}
for row in self.working_hours:
res[row.workday] = row
return res
def get_working_days(self) -> dict[str, dict]:
workdays = []
for row in self.working_hours:
workdays.append(row.workday)
return workdays
def get_working_hours(self) -> dict[str, dict]:
res = {}
for row in self.working_hours:
res[row.workday] = (row.start_time, row.end_time)
return res
def is_working_time(self, date_time, working_hours):
day_of_week = get_weekdays()[date_time.weekday()]
start_time, end_time = working_hours.get(day_of_week, (0, 0))
date_time = timedelta(hours=date_time.hour, minutes=date_time.minute, seconds=date_time.second)
return start_time <= date_time < end_time
def get_holidays(self):
res = []
if not self.holiday_list:
return res
holiday_list = frappe.get_doc("CRM Holiday List", self.holiday_list)
for row in holiday_list.holidays:
res.append(row.date)
return res
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_service_level_agreement/crm_service_level_agreement.py
|
Python
|
agpl-3.0
| 6,621
|
import frappe
from frappe.model.document import Document
from frappe.query_builder import JoinType
from frappe.utils.safe_exec import get_safe_globals
from frappe.utils import now_datetime
from pypika import Criterion
def get_sla(doc: Document) -> Document:
"""
Get Service Level Agreement for `doc`
:param doc: Lead/Deal to use
:return: Applicable SLA
"""
SLA = frappe.qb.DocType("CRM Service Level Agreement")
Priority = frappe.qb.DocType("CRM Service Level Priority")
now = now_datetime()
priority = doc.communication_status
q = (
frappe.qb.from_(SLA)
.select(SLA.name, SLA.condition)
.where(SLA.apply_on == doc.doctype)
.where(SLA.enabled == True)
.where(Criterion.any([SLA.start_date.isnull(), SLA.start_date <= now]))
.where(Criterion.any([SLA.end_date.isnull(), SLA.end_date >= now]))
)
if priority:
q = (
q.join(Priority, JoinType.inner)
.on(Priority.parent == SLA.name)
.where(Priority.priority == priority)
)
sla_list = q.run(as_dict=True)
res = None
# move default sla to the end of the list
for sla in sla_list:
if sla.get("default") == True:
sla_list.remove(sla)
sla_list.append(sla)
break
for sla in sla_list:
cond = sla.get("condition")
if not cond or frappe.safe_eval(cond, None, get_context(doc)):
res = sla
break
return res
def get_context(d: Document) -> dict:
"""
Get safe context for `safe_eval`
:param doc: `Document` to add in context
:return: Context with `doc` and safe variables
"""
utils = get_safe_globals().get("frappe").get("utils")
return {
"doc": d.as_dict(),
"frappe": frappe._dict(utils=utils),
}
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_service_level_agreement/utils.py
|
Python
|
agpl-3.0
| 1,612
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("CRM Service Level Priority", {
// refresh(frm) {
// },
// });
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_service_level_priority/crm_service_level_priority.js
|
JavaScript
|
agpl-3.0
| 209
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class CRMServiceLevelPriority(Document):
pass
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_service_level_priority/crm_service_level_priority.py
|
Python
|
agpl-3.0
| 228
|
# Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from datetime import datetime
from frappe.utils import add_to_date, get_datetime
from frappe.model.document import Document
class CRMStatusChangeLog(Document):
pass
def get_duration(from_date, to_date):
if not isinstance(from_date, datetime):
from_date = get_datetime(from_date)
if not isinstance(to_date, datetime):
to_date = get_datetime(to_date)
duration = to_date - from_date
return duration.total_seconds()
def add_status_change_log(doc):
if not doc.is_new():
previous_status = doc.get_doc_before_save().status if doc.get_doc_before_save() else None
if not doc.status_change_log and previous_status:
now_minus_one_minute = add_to_date(datetime.now(), minutes=-1)
doc.append("status_change_log", {
"from": previous_status,
"to": "",
"from_date": now_minus_one_minute,
"to_date": "",
"log_owner": frappe.session.user,
})
last_status_change = doc.status_change_log[-1]
last_status_change.to = doc.status
last_status_change.to_date = datetime.now()
last_status_change.log_owner = frappe.session.user
last_status_change.duration = get_duration(last_status_change.from_date, last_status_change.to_date)
doc.append("status_change_log", {
"from": doc.status,
"to": "",
"from_date": datetime.now(),
"to_date": "",
"log_owner": frappe.session.user,
})
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_status_change_log/crm_status_change_log.py
|
Python
|
agpl-3.0
| 1,450
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("CRM Task", {
// refresh(frm) {
// },
// });
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_task/crm_task.js
|
JavaScript
|
agpl-3.0
| 191
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class CRMTask(Document):
@staticmethod
def default_list_data():
columns = [
{
'label': 'Title',
'type': 'Data',
'key': 'title',
'width': '16rem',
},
{
'label': 'Status',
'type': 'Select',
'key': 'status',
'width': '8rem',
},
{
'label': 'Priority',
'type': 'Select',
'key': 'priority',
'width': '8rem',
},
{
'label': 'Due Date',
'type': 'Date',
'key': 'due_date',
'width': '8rem',
},
{
'label': 'Assigned To',
'type': 'Link',
'key': 'assigned_to',
'width': '10rem',
},
{
'label': 'Last Modified',
'type': 'Datetime',
'key': 'modified',
'width': '8rem',
},
]
rows = [
"name",
"title",
"description",
"assigned_to",
"due_date",
"status",
"priority",
"reference_doctype",
"reference_docname",
"modified",
]
return {'columns': columns, 'rows': rows}
@staticmethod
def default_kanban_settings():
return {
"column_field": "status",
"title_field": "title",
"kanban_fields": '["description", "priority", "creation"]'
}
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_task/crm_task.py
|
Python
|
agpl-3.0
| 1,282
|
// Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("CRM Territory", {
// refresh(frm) {
// },
// });
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_territory/crm_territory.js
|
JavaScript
|
agpl-3.0
| 196
|
# Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class CRMTerritory(Document):
pass
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_territory/crm_territory.py
|
Python
|
agpl-3.0
| 217
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("CRM View Settings", {
// refresh(frm) {
// },
// });
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_view_settings/crm_view_settings.js
|
JavaScript
|
agpl-3.0
| 200
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import json
import frappe
from frappe.model.document import Document, get_controller
from frappe.utils import parse_json
class CRMViewSettings(Document):
pass
@frappe.whitelist()
def create(view):
view = frappe._dict(view)
view.filters = parse_json(view.filters) or {}
view.columns = parse_json(view.columns or '[]')
view.rows = parse_json(view.rows or '[]')
view.kanban_columns = parse_json(view.kanban_columns or '[]')
view.kanban_fields = parse_json(view.kanban_fields or '[]')
default_rows = sync_default_rows(view.doctype)
view.rows = view.rows + default_rows if default_rows else view.rows
view.rows = remove_duplicates(view.rows)
if not view.kanban_columns and view.type == "kanban":
view.kanban_columns = sync_default_columns(view)
elif not view.columns:
view.columns = sync_default_columns(view)
doc = frappe.new_doc("CRM View Settings")
doc.name = view.label
doc.label = view.label
doc.type = view.type or 'list'
doc.icon = view.icon
doc.dt = view.doctype
doc.user = frappe.session.user
doc.route_name = view.route_name or ""
doc.load_default_columns = view.load_default_columns or False
doc.filters = json.dumps(view.filters)
doc.order_by = view.order_by
doc.group_by_field = view.group_by_field
doc.column_field = view.column_field
doc.title_field = view.title_field
doc.kanban_columns = json.dumps(view.kanban_columns)
doc.kanban_fields = json.dumps(view.kanban_fields)
doc.columns = json.dumps(view.columns)
doc.rows = json.dumps(view.rows)
doc.insert()
return doc
@frappe.whitelist()
def update(view):
view = frappe._dict(view)
filters = parse_json(view.filters or {})
columns = parse_json(view.columns or [])
rows = parse_json(view.rows or [])
kanban_columns = parse_json(view.kanban_columns or [])
kanban_fields = parse_json(view.kanban_fields or [])
default_rows = sync_default_rows(view.doctype)
rows = rows + default_rows if default_rows else rows
rows = remove_duplicates(rows)
doc = frappe.get_doc("CRM View Settings", view.name)
doc.label = view.label
doc.type = view.type or 'list'
doc.icon = view.icon
doc.route_name = view.route_name or ""
doc.load_default_columns = view.load_default_columns or False
doc.filters = json.dumps(filters)
doc.order_by = view.order_by
doc.group_by_field = view.group_by_field
doc.column_field = view.column_field
doc.title_field = view.title_field
doc.kanban_columns = json.dumps(kanban_columns)
doc.kanban_fields = json.dumps(kanban_fields)
doc.columns = json.dumps(columns)
doc.rows = json.dumps(rows)
doc.save()
return doc
@frappe.whitelist()
def delete(name):
if frappe.db.exists("CRM View Settings", name):
frappe.delete_doc("CRM View Settings", name)
@frappe.whitelist()
def public(name, value):
if frappe.session.user != "Administrator" and "Sales Manager" not in frappe.get_roles():
frappe.throw("Not permitted", frappe.PermissionError)
doc = frappe.get_doc("CRM View Settings", name)
if doc.pinned:
doc.pinned = False
doc.public = value
doc.user = "" if value else frappe.session.user
doc.save()
@frappe.whitelist()
def pin(name, value):
doc = frappe.get_doc("CRM View Settings", name)
doc.pinned = value
doc.save()
def remove_duplicates(l):
return list(dict.fromkeys(l))
def sync_default_rows(doctype, type="list"):
list = get_controller(doctype)
rows = []
if hasattr(list, "default_list_data"):
rows = list.default_list_data().get("rows")
return rows
def sync_default_columns(view):
list = get_controller(view.doctype)
columns = []
if view.type == "kanban" and view.column_field:
field_meta = frappe.get_meta(view.doctype).get_field(view.column_field)
if field_meta.fieldtype == "Link":
columns = frappe.get_all(
field_meta.options,
fields=["name"],
order_by="modified asc",
)
elif field_meta.fieldtype == "Select":
columns = [{"name": option} for option in field_meta.options.split("\n")]
elif hasattr(list, "default_list_data"):
columns = list.default_list_data().get("columns")
return columns
@frappe.whitelist()
def create_or_update_default_view(view):
view = frappe._dict(view)
filters = parse_json(view.filters) or {}
columns = parse_json(view.columns or '[]')
rows = parse_json(view.rows or '[]')
kanban_columns = parse_json(view.kanban_columns or '[]')
kanban_fields = parse_json(view.kanban_fields or '[]')
default_rows = sync_default_rows(view.doctype, view.type)
rows = rows + default_rows if default_rows else rows
rows = remove_duplicates(rows)
if not kanban_columns and view.type == "kanban":
kanban_columns = sync_default_columns(view)
elif not columns:
columns = sync_default_columns(view)
doc = frappe.db.exists(
"CRM View Settings",
{
"dt": view.doctype,
"type": view.type or 'list',
"is_default": True,
"user": frappe.session.user
},
)
if doc:
doc = frappe.get_doc("CRM View Settings", doc)
doc.label = view.label
doc.type = view.type or 'list'
doc.route_name = view.route_name or ""
doc.load_default_columns = view.load_default_columns or False
doc.filters = json.dumps(filters)
doc.order_by = view.order_by
doc.group_by_field = view.group_by_field
doc.column_field = view.column_field
doc.title_field = view.title_field
doc.kanban_columns = json.dumps(kanban_columns)
doc.kanban_fields = json.dumps(kanban_fields)
doc.columns = json.dumps(columns)
doc.rows = json.dumps(rows)
doc.save()
else:
doc = frappe.new_doc("CRM View Settings")
label = 'Group By View' if view.type == 'group_by' else 'List View'
doc.name = view.label or label
doc.label = view.label or label
doc.type = view.type or 'list'
doc.dt = view.doctype
doc.user = frappe.session.user
doc.route_name = view.route_name or ""
doc.load_default_columns = view.load_default_columns or False
doc.filters = json.dumps(filters)
doc.order_by = view.order_by
doc.group_by_field = view.group_by_field
doc.column_field = view.column_field
doc.title_field = view.title_field
doc.kanban_columns = json.dumps(kanban_columns)
doc.kanban_fields = json.dumps(kanban_fields)
doc.columns = json.dumps(columns)
doc.rows = json.dumps(rows)
doc.is_default = True
doc.insert()
|
2302_79757062/crm
|
crm/fcrm/doctype/crm_view_settings/crm_view_settings.py
|
Python
|
agpl-3.0
| 6,278
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("ERPNext CRM Settings", {
refresh(frm) {
if (!frm.doc.enabled) return;
frm.add_custom_button(__("Reset ERPNext Form Script"), () => {
frappe.confirm(
__(
"Are you sure you want to reset 'Create Quotation from CRM Deal' Form Script?"
),
() => frm.trigger("reset_erpnext_form_script")
);
});
},
async reset_erpnext_form_script(frm) {
let script = await frm.call("reset_erpnext_form_script");
script.message &&
frappe.msgprint(__("Form Script updated successfully"));
},
});
|
2302_79757062/crm
|
crm/fcrm/doctype/erpnext_crm_settings/erpnext_crm_settings.js
|
JavaScript
|
agpl-3.0
| 652
|
# Copyright (c) 2024, Frappe and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.custom.doctype.property_setter.property_setter import make_property_setter
from frappe.model.document import Document
from frappe.frappeclient import FrappeClient
from frappe.utils import get_url_to_form
import json
class ERPNextCRMSettings(Document):
def validate(self):
if self.enabled:
self.validate_if_erpnext_installed()
self.add_quotation_to_option()
self.create_custom_fields()
self.create_crm_form_script()
def validate_if_erpnext_installed(self):
if not self.is_erpnext_in_different_site:
if "erpnext" not in frappe.get_installed_apps():
frappe.throw(_("ERPNext is not installed in the current site"))
def add_quotation_to_option(self):
if not self.is_erpnext_in_different_site:
if not frappe.db.exists("Property Setter", {"name": "Quotation-quotation_to-link_filters"}):
make_property_setter(
doctype="Quotation",
fieldname="quotation_to",
property="link_filters",
value='[["DocType","name","in", ["Customer", "Lead", "Prospect", "Frappe CRM Deal"]]]',
property_type="JSON",
validate_fields_for_doctype=False,
)
def create_custom_fields(self):
if not self.is_erpnext_in_different_site:
from erpnext.crm.frappe_crm_api import create_custom_fields_for_frappe_crm
create_custom_fields_for_frappe_crm()
else:
self.create_custom_fields_in_remote_site()
def create_custom_fields_in_remote_site(self):
client = get_erpnext_site_client(self)
try:
client.post_api("erpnext.crm.frappe_crm_api.create_custom_fields_for_frappe_crm")
except Exception:
frappe.log_error(
frappe.get_traceback(),
f"Error while creating custom field in the remote erpnext site: {self.erpnext_site_url}"
)
frappe.throw("Error while creating custom field in ERPNext, check error log for more details")
def create_crm_form_script(self):
if not frappe.db.exists("CRM Form Script", "Create Quotation from CRM Deal"):
script = get_crm_form_script()
frappe.get_doc({
"doctype": "CRM Form Script",
"name": "Create Quotation from CRM Deal",
"dt": "CRM Deal",
"view": "Form",
"script": script,
"enabled": 1,
"is_standard": 1
}).insert()
@frappe.whitelist()
def reset_erpnext_form_script(self):
try:
if frappe.db.exists("CRM Form Script", "Create Quotation from CRM Deal"):
script = get_crm_form_script()
frappe.db.set_value("CRM Form Script", "Create Quotation from CRM Deal", "script", script)
return True
return False
except Exception:
frappe.log_error(frappe.get_traceback(), "Error while resetting form script")
return False
def get_erpnext_site_client(erpnext_crm_settings):
site_url = erpnext_crm_settings.erpnext_site_url
api_key = erpnext_crm_settings.api_key
api_secret = erpnext_crm_settings.get_password("api_secret", raise_exception=False)
return FrappeClient(
site_url, api_key=api_key, api_secret=api_secret
)
@frappe.whitelist()
def get_customer_link(crm_deal):
erpnext_crm_settings = frappe.get_single("ERPNext CRM Settings")
if not erpnext_crm_settings.enabled:
frappe.throw(_("ERPNext is not integrated with the CRM"))
if not erpnext_crm_settings.is_erpnext_in_different_site:
customer_url = get_url_to_form("Customer")
customer = frappe.db.exists("Customer", {"crm_deal": crm_deal})
if customer:
return f"{customer_url}/{customer}"
else:
return ""
else:
client = get_erpnext_site_client(erpnext_crm_settings)
try:
customer = client.get_list("Customer", {"crm_deal": crm_deal})
customer = customer[0].get("name") if len(customer) else None
if customer:
return f"{erpnext_crm_settings.erpnext_site_url}/app/customer/{customer}"
else:
return ""
except Exception:
frappe.log_error(
frappe.get_traceback(),
f"Error while fetching customer in remote site: {erpnext_crm_settings.erpnext_site_url}"
)
frappe.throw(_("Error while fetching customer in ERPNext, check error log for more details"))
@frappe.whitelist()
def get_quotation_url(crm_deal, organization):
erpnext_crm_settings = frappe.get_single("ERPNext CRM Settings")
if not erpnext_crm_settings.enabled:
frappe.throw(_("ERPNext is not integrated with the CRM"))
if not erpnext_crm_settings.is_erpnext_in_different_site:
quotation_url = get_url_to_form("Quotation")
return f"{quotation_url}/new?quotation_to=CRM Deal&crm_deal={crm_deal}&party_name={crm_deal}&company={erpnext_crm_settings.erpnext_company}"
else:
site_url = erpnext_crm_settings.get("erpnext_site_url")
quotation_url = f"{site_url}/app/quotation"
prospect = create_prospect_in_remote_site(crm_deal, erpnext_crm_settings)
return f"{quotation_url}/new?quotation_to=Prospect&crm_deal={crm_deal}&party_name={prospect}&company={erpnext_crm_settings.erpnext_company}"
def create_prospect_in_remote_site(crm_deal, erpnext_crm_settings):
try:
client = get_erpnext_site_client(erpnext_crm_settings)
doc = frappe.get_doc("CRM Deal", crm_deal)
contacts = get_contacts(doc)
address = get_organization_address(doc.organization)
return client.post_api("erpnext.crm.frappe_crm_api.create_prospect_against_crm_deal",
{
"organization": doc.organization,
"lead_name": doc.lead_name,
"no_of_employees": doc.no_of_employees,
"deal_owner": doc.deal_owner,
"crm_deal": doc.name,
"territory": doc.territory,
"industry": doc.industry,
"website": doc.website,
"annual_revenue": doc.annual_revenue,
"contacts": json.dumps(contacts),
"erpnext_company": erpnext_crm_settings.erpnext_company,
"address": address.as_dict() if address else None
},
)
except Exception:
frappe.log_error(
frappe.get_traceback(),
f"Error while creating prospect in remote site: {erpnext_crm_settings.erpnext_site_url}"
)
frappe.throw(_("Error while creating prospect in ERPNext, check error log for more details"))
def get_contacts(doc):
contacts = []
for c in doc.contacts:
contacts.append({
"contact": c.contact,
"full_name": c.full_name,
"email": c.email,
"mobile_no": c.mobile_no,
"gender": c.gender,
"is_primary": c.is_primary,
})
return contacts
def get_organization_address(organization):
address = frappe.db.get_value("CRM Organization", organization, "address")
address = frappe.get_doc("Address", address) if address else None
return {
"name": address.name,
"address_title": address.address_title,
"address_type": address.address_type,
"address_line1": address.address_line1,
"address_line2": address.address_line2,
"city": address.city,
"county": address.county,
"state": address.state,
"country": address.country,
"pincode": address.pincode,
}
def create_customer_in_erpnext(doc, method):
erpnext_crm_settings = frappe.get_single("ERPNext CRM Settings")
if (
not erpnext_crm_settings.enabled
or not erpnext_crm_settings.create_customer_on_status_change
or doc.status != erpnext_crm_settings.deal_status
):
return
contacts = get_contacts(doc)
address = get_organization_address(doc.organization)
customer = {
"customer_name": doc.organization,
"customer_group": "All Customer Groups",
"customer_type": "Company",
"territory": doc.territory,
"default_currency": doc.currency,
"industry": doc.industry,
"website": doc.website,
"crm_deal": doc.name,
"contacts": json.dumps(contacts),
"address": json.dumps(address) if address else None,
}
if not erpnext_crm_settings.is_erpnext_in_different_site:
from erpnext.crm.frappe_crm_api import create_customer
create_customer(customer)
else:
create_customer_in_remote_site(customer, erpnext_crm_settings)
frappe.publish_realtime("crm_customer_created")
def create_customer_in_remote_site(customer, erpnext_crm_settings):
client = get_erpnext_site_client(erpnext_crm_settings)
try:
client.post_api("erpnext.crm.frappe_crm_api.create_customer", customer)
except Exception:
frappe.log_error(
frappe.get_traceback(),
"Error while creating customer in remote site"
)
frappe.throw(_("Error while creating customer in ERPNext, check error log for more details"))
@frappe.whitelist()
def get_crm_form_script():
return """
async function setupForm({ doc, call, $dialog, updateField, createToast }) {
let actions = [];
let is_erpnext_integration_enabled = await call("frappe.client.get_single_value", {doctype: "ERPNext CRM Settings", field: "enabled"});
if (!["Lost", "Won"].includes(doc?.status) && is_erpnext_integration_enabled) {
actions.push({
label: __("Create Quotation"),
onClick: async () => {
let quotation_url = await call(
"crm.fcrm.doctype.erpnext_crm_settings.erpnext_crm_settings.get_quotation_url",
{
crm_deal: doc.name,
organization: doc.organization
}
);
if (quotation_url) {
window.open(quotation_url, '_blank');
}
}
})
}
if (is_erpnext_integration_enabled) {
let customer_url = await call("crm.fcrm.doctype.erpnext_crm_settings.erpnext_crm_settings.get_customer_link", {
crm_deal: doc.name
});
if (customer_url) {
actions.push({
label: __("View Customer"),
onClick: () => window.open(customer_url, '_blank')
});
}
}
return {
actions: actions,
};
}
"""
|
2302_79757062/crm
|
crm/fcrm/doctype/erpnext_crm_settings/erpnext_crm_settings.py
|
Python
|
agpl-3.0
| 9,293
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("FCRM Note", {
// refresh(frm) {
// },
// });
|
2302_79757062/crm
|
crm/fcrm/doctype/fcrm_note/fcrm_note.js
|
JavaScript
|
agpl-3.0
| 192
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class FCRMNote(Document):
@staticmethod
def default_list_data():
rows = [
"name",
"title",
"content",
"reference_doctype",
"reference_docname",
"owner",
"modified",
]
return {'columns': [], 'rows': rows}
|
2302_79757062/crm
|
crm/fcrm/doctype/fcrm_note/fcrm_note.py
|
Python
|
agpl-3.0
| 414
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Twilio Agents", {
// refresh(frm) {
// },
// });
|
2302_79757062/crm
|
crm/fcrm/doctype/twilio_agents/twilio_agents.js
|
JavaScript
|
agpl-3.0
| 196
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class TwilioAgents(Document):
pass
|
2302_79757062/crm
|
crm/fcrm/doctype/twilio_agents/twilio_agents.py
|
Python
|
agpl-3.0
| 217
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Twilio Settings", {
// refresh(frm) {
// },
// });
|
2302_79757062/crm
|
crm/fcrm/doctype/twilio_settings/twilio_settings.js
|
JavaScript
|
agpl-3.0
| 198
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
from frappe import _
from twilio.rest import Client
class TwilioSettings(Document):
friendly_resource_name = "Frappe CRM" # System creates TwiML app & API keys with this name.
def validate(self):
self.validate_twilio_account()
def on_update(self):
# Single doctype records are created in DB at time of installation and those field values are set as null.
# This condition make sure that we handle null.
if not self.account_sid:
return
twilio = Client(self.account_sid, self.get_password("auth_token"))
self.set_api_credentials(twilio)
self.set_application_credentials(twilio)
self.reload()
def validate_twilio_account(self):
try:
twilio = Client(self.account_sid, self.get_password("auth_token"))
twilio.api.accounts(self.account_sid).fetch()
return twilio
except Exception:
frappe.throw(_("Invalid Account SID or Auth Token."))
def set_api_credentials(self, twilio):
"""Generate Twilio API credentials if not exist and update them.
"""
if self.api_key and self.api_secret:
return
new_key = self.create_api_key(twilio)
self.api_key = new_key.sid
self.api_secret = new_key.secret
frappe.db.set_value('Twilio Settings', 'Twilio Settings', {
'api_key': self.api_key,
'api_secret': self.api_secret
})
def set_application_credentials(self, twilio):
"""Generate TwiML app credentials if not exist and update them.
"""
credentials = self.get_application(twilio) or self.create_application(twilio)
self.twiml_sid = credentials.sid
frappe.db.set_value('Twilio Settings', 'Twilio Settings', 'twiml_sid', self.twiml_sid)
def create_api_key(self, twilio):
"""Create API keys in twilio account.
"""
try:
return twilio.new_keys.create(friendly_name=self.friendly_resource_name)
except Exception:
frappe.log_error(title=_("Twilio API credential creation error."))
frappe.throw(_("Twilio API credential creation error."))
def get_twilio_voice_url(self):
url_path = "/api/method/crm.integrations.twilio.api.voice"
return get_public_url(url_path)
def get_application(self, twilio, friendly_name=None):
"""Get TwiML App from twilio account if exists.
"""
friendly_name = friendly_name or self.friendly_resource_name
applications = twilio.applications.list(friendly_name)
return applications and applications[0]
def create_application(self, twilio, friendly_name=None):
"""Create TwilML App in twilio account.
"""
friendly_name = friendly_name or self.friendly_resource_name
application = twilio.applications.create(
voice_method='POST',
voice_url=self.get_twilio_voice_url(),
friendly_name=friendly_name
)
return application
def get_public_url(path: str=None):
from frappe.utils import get_url
return get_url().split(":8", 1)[0] + path
|
2302_79757062/crm
|
crm/fcrm/doctype/twilio_settings/twilio_settings.py
|
Python
|
agpl-3.0
| 2,952
|
app_name = "crm"
app_title = "Frappe CRM"
app_publisher = "Frappe Technologies Pvt. Ltd."
app_description = "Kick-ass Open Source CRM"
app_email = "shariq@frappe.io"
app_license = "AGPLv3"
app_icon_url = "/assets/crm/manifest/apple-icon-180.png"
app_icon_title = "CRM"
app_icon_route = "/crm"
# Apps
# ------------------
# required_apps = []
add_to_apps_screen = [
{
"name": "crm",
"logo": "/assets/crm/manifest/apple-icon-180.png",
"title": "CRM",
"route": "/crm",
"has_permission": "crm.api.check_app_permission",
}
]
# Includes in <head>
# ------------------
# include js, css files in header of desk.html
# app_include_css = "/assets/crm/css/crm.css"
# app_include_js = "/assets/crm/js/crm.js"
# include js, css files in header of web template
# web_include_css = "/assets/crm/css/crm.css"
# web_include_js = "/assets/crm/js/crm.js"
# include custom scss in every website theme (without file extension ".scss")
# website_theme_scss = "crm/public/scss/website"
# include js, css files in header of web form
# webform_include_js = {"doctype": "public/js/doctype.js"}
# webform_include_css = {"doctype": "public/css/doctype.css"}
# include js in page
# page_js = {"page" : "public/js/file.js"}
# include js in doctype views
# doctype_js = {"doctype" : "public/js/doctype.js"}
# doctype_list_js = {"doctype" : "public/js/doctype_list.js"}
# doctype_tree_js = {"doctype" : "public/js/doctype_tree.js"}
# doctype_calendar_js = {"doctype" : "public/js/doctype_calendar.js"}
# Home Pages
# ----------
# application home page (will override Website Settings)
# home_page = "login"
# website user home page (by Role)
# role_home_page = {
# "Role": "home_page"
# }
website_route_rules = [
{"from_route": "/crm/<path:app_path>", "to_route": "crm"},
]
# Generators
# ----------
# automatically create page for each record of this doctype
# website_generators = ["Web Page"]
# Jinja
# ----------
# add methods and filters to jinja environment
# jinja = {
# "methods": "crm.utils.jinja_methods",
# "filters": "crm.utils.jinja_filters"
# }
# Installation
# ------------
before_install = "crm.install.before_install"
after_install = "crm.install.after_install"
# Uninstallation
# ------------
before_uninstall = "crm.uninstall.before_uninstall"
# after_uninstall = "crm.uninstall.after_uninstall"
# Integration Setup
# ------------------
# To set up dependencies/integrations with other apps
# Name of the app being installed is passed as an argument
# before_app_install = "crm.utils.before_app_install"
# after_app_install = "crm.utils.after_app_install"
# Integration Cleanup
# -------------------
# To clean up dependencies/integrations with other apps
# Name of the app being uninstalled is passed as an argument
# before_app_uninstall = "crm.utils.before_app_uninstall"
# after_app_uninstall = "crm.utils.after_app_uninstall"
# Desk Notifications
# ------------------
# See frappe.core.notifications.get_notification_config
# notification_config = "crm.notifications.get_notification_config"
# Permissions
# -----------
# Permissions evaluated in scripted ways
# permission_query_conditions = {
# "Event": "frappe.desk.doctype.event.event.get_permission_query_conditions",
# }
#
# has_permission = {
# "Event": "frappe.desk.doctype.event.event.has_permission",
# }
# DocType Class
# ---------------
# Override standard doctype classes
override_doctype_class = {
"Contact": "crm.overrides.contact.CustomContact",
"Email Template": "crm.overrides.email_template.CustomEmailTemplate",
}
# Document Events
# ---------------
# Hook on document methods and events
doc_events = {
"Contact": {
"validate": ["crm.api.contact.validate"],
},
"ToDo": {
"after_insert": ["crm.api.todo.after_insert"],
},
"Comment": {
"on_update": ["crm.api.comment.on_update"],
},
"WhatsApp Message": {
"validate": ["crm.api.whatsapp.validate"],
"on_update": ["crm.api.whatsapp.on_update"],
},
"CRM Deal": {
"on_update": ["crm.fcrm.doctype.erpnext_crm_settings.erpnext_crm_settings.create_customer_in_erpnext"],
},
}
# Scheduled Tasks
# ---------------
# scheduler_events = {
# "all": [
# "crm.tasks.all"
# ],
# "daily": [
# "crm.tasks.daily"
# ],
# "hourly": [
# "crm.tasks.hourly"
# ],
# "weekly": [
# "crm.tasks.weekly"
# ],
# "monthly": [
# "crm.tasks.monthly"
# ],
# }
# Testing
# -------
# before_tests = "crm.install.before_tests"
# Overriding Methods
# ------------------------------
#
# override_whitelisted_methods = {
# "frappe.desk.doctype.event.event.get_events": "crm.event.get_events"
# }
#
# each overriding function accepts a `data` argument;
# generated from the base implementation of the doctype dashboard,
# along with any modifications made in other Frappe apps
# override_doctype_dashboards = {
# "Task": "crm.task.get_dashboard_data"
# }
# exempt linked doctypes from being automatically cancelled
#
# auto_cancel_exempted_doctypes = ["Auto Repeat"]
# Ignore links to specified DocTypes when deleting documents
# -----------------------------------------------------------
# ignore_links_on_delete = ["Communication", "ToDo"]
# Request Events
# ----------------
# before_request = ["crm.utils.before_request"]
# after_request = ["crm.utils.after_request"]
# Job Events
# ----------
# before_job = ["crm.utils.before_job"]
# after_job = ["crm.utils.after_job"]
# User Data Protection
# --------------------
# user_data_fields = [
# {
# "doctype": "{doctype_1}",
# "filter_by": "{filter_by}",
# "redact_fields": ["{field_1}", "{field_2}"],
# "partial": 1,
# },
# {
# "doctype": "{doctype_2}",
# "filter_by": "{filter_by}",
# "partial": 1,
# },
# {
# "doctype": "{doctype_3}",
# "strict": False,
# },
# {
# "doctype": "{doctype_4}"
# }
# ]
# Authentication and authorization
# --------------------------------
# auth_hooks = [
# "crm.auth.validate"
# ]
|
2302_79757062/crm
|
crm/hooks.py
|
Python
|
agpl-3.0
| 5,845
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import click
import frappe
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
def before_install():
pass
def after_install():
add_default_lead_statuses()
add_default_deal_statuses()
add_default_communication_statuses()
add_default_fields_layout()
add_property_setter()
add_email_template_custom_fields()
add_default_industries()
add_default_lead_sources()
frappe.db.commit()
def add_default_lead_statuses():
statuses = {
"New": {
"color": "gray",
"position": 1,
},
"Contacted": {
"color": "orange",
"position": 2,
},
"Nurture": {
"color": "blue",
"position": 3,
},
"Qualified": {
"color": "green",
"position": 4,
},
"Unqualified": {
"color": "red",
"position": 5,
},
"Junk": {
"color": "purple",
"position": 6,
},
}
for status in statuses:
if frappe.db.exists("CRM Lead Status", status):
continue
doc = frappe.new_doc("CRM Lead Status")
doc.lead_status = status
doc.color = statuses[status]["color"]
doc.position = statuses[status]["position"]
doc.insert()
def add_default_deal_statuses():
statuses = {
"Qualification": {
"color": "gray",
"position": 1,
},
"Demo/Making": {
"color": "orange",
"position": 2,
},
"Proposal/Quotation": {
"color": "blue",
"position": 3,
},
"Negotiation": {
"color": "yellow",
"position": 4,
},
"Ready to Close": {
"color": "purple",
"position": 5,
},
"Won": {
"color": "green",
"position": 6,
},
"Lost": {
"color": "red",
"position": 7,
},
}
for status in statuses:
if frappe.db.exists("CRM Deal Status", status):
continue
doc = frappe.new_doc("CRM Deal Status")
doc.deal_status = status
doc.color = statuses[status]["color"]
doc.position = statuses[status]["position"]
doc.insert()
def add_default_communication_statuses():
statuses = ["Open", "Replied"]
for status in statuses:
if frappe.db.exists("CRM Communication Status", status):
continue
doc = frappe.new_doc("CRM Communication Status")
doc.status = status
doc.insert()
def add_default_fields_layout():
quick_entry_layouts = {
"CRM Lead-Quick Entry": {
"doctype": "CRM Lead",
"layout": '[{"label":"Person","fields":["salutation","first_name","last_name","email","mobile_no", "gender"],"hideLabel":true},{"label":"Organization","fields":["organization","website","no_of_employees","territory","annual_revenue","industry"],"hideLabel":true,"hideBorder":false},{"label":"Other","columns":2,"fields":["status","lead_owner"],"hideLabel":true,"hideBorder":false}]'
},
"CRM Deal-Quick Entry": {
"doctype": "CRM Deal",
"layout": '[{"label": "Select Organization", "fields": ["organization"], "hideLabel": true, "editable": true}, {"label": "Organization Details", "fields": ["organization_name", "website", "no_of_employees", "territory", "annual_revenue", "industry"], "hideLabel": true, "editable": true}, {"label": "Select Contact", "fields": ["contact"], "hideLabel": true, "editable": true}, {"label": "Contact Details", "fields": ["salutation", "first_name", "last_name", "email", "mobile_no", "gender"], "hideLabel": true, "editable": true}, {"label": "Other", "columns": 2, "fields": ["status", "deal_owner"], "hideLabel": true}]'
},
"Contact-Quick Entry": {
"doctype": "Contact",
"layout": '[{"label":"Salutation","columns":1,"fields":["salutation"],"hideLabel":true},{"label":"Full Name","columns":2,"hideBorder":true,"fields":["first_name","last_name"],"hideLabel":true},{"label":"Email","columns":1,"hideBorder":true,"fields":["email_id"],"hideLabel":true},{"label":"Mobile No. & Gender","columns":2,"hideBorder":true,"fields":["mobile_no","gender"],"hideLabel":true},{"label":"Organization","columns":1,"hideBorder":true,"fields":["company_name"],"hideLabel":true},{"label":"Designation","columns":1,"hideBorder":true,"fields":["designation"],"hideLabel":true},{"label":"Address","columns":1,"hideBorder":true,"fields":["address"],"hideLabel":true}]'
},
"CRM Organization-Quick Entry": {
"doctype": "CRM Organization",
"layout": '[{"label":"Organization Name","columns":1,"fields":["organization_name"],"hideLabel":true},{"label":"Website & Revenue","columns":2,"hideBorder":true,"fields":["website","annual_revenue"],"hideLabel":true},{"label":"Territory","columns":1,"hideBorder":true,"fields":["territory"],"hideLabel":true},{"label":"No of Employees & Industry","columns":2,"hideBorder":true,"fields":["no_of_employees","industry"],"hideLabel":true},{"label":"Address","columns":1,"hideBorder":true,"fields":["address"],"hideLabel":true}]'
},
"Address-Quick Entry": {
"doctype": "Address",
"layout": '[{"label":"Address","columns":1,"fields":["address_title","address_type","address_line1","address_line2","city","state","country","pincode"],"hideLabel":true}]'
},
}
sidebar_fields_layouts = {
"CRM Lead-Side Panel": {
"doctype": "CRM Lead",
"layout": '[{"label": "Details", "name": "details", "opened": true, "fields": ["organization", "website", "territory", "industry", "job_title", "source", "lead_owner"]}, {"label": "Person", "name": "person_tab", "opened": true, "fields": ["salutation", "first_name", "last_name", "email", "mobile_no"]}]'
},
"CRM Deal-Side Panel": {
"doctype": "CRM Deal",
"layout": '[{"label":"Contacts","name":"contacts_section","opened":true,"editable":false,"contacts":[]},{"label":"Organization Details","name":"organization_tab","opened":true,"fields":["organization","website","territory","annual_revenue","close_date","probability","next_step","deal_owner"]}]'
},
}
for layout in quick_entry_layouts:
if frappe.db.exists("CRM Fields Layout", layout):
continue
doc = frappe.new_doc("CRM Fields Layout")
doc.type = "Quick Entry"
doc.dt = quick_entry_layouts[layout]["doctype"]
doc.layout = quick_entry_layouts[layout]["layout"]
doc.insert()
for layout in sidebar_fields_layouts:
if frappe.db.exists("CRM Fields Layout", layout):
continue
doc = frappe.new_doc("CRM Fields Layout")
doc.type = "Side Panel"
doc.dt = sidebar_fields_layouts[layout]["doctype"]
doc.layout = sidebar_fields_layouts[layout]["layout"]
doc.insert()
def add_property_setter():
if not frappe.db.exists("Property Setter", {"name": "Contact-main-search_fields"}):
doc = frappe.new_doc("Property Setter")
doc.doctype_or_field = "DocType"
doc.doc_type = "Contact"
doc.property = "search_fields"
doc.property_type = "Data"
doc.value = "email_id"
doc.insert()
def add_email_template_custom_fields():
if not frappe.get_meta("Email Template").has_field("enabled"):
click.secho("* Installing Custom Fields in Email Template")
create_custom_fields(
{
"Email Template": [
{
"default": "0",
"fieldname": "enabled",
"fieldtype": "Check",
"label": "Enabled",
"insert_after": "",
},
{
"fieldname": "reference_doctype",
"fieldtype": "Link",
"label": "Doctype",
"options": "DocType",
"insert_after": "enabled",
},
]
}
)
frappe.clear_cache(doctype="Email Template")
def add_default_industries():
industries = ["Accounting", "Advertising", "Aerospace", "Agriculture", "Airline", "Apparel & Accessories", "Automotive", "Banking", "Biotechnology", "Broadcasting", "Brokerage", "Chemical", "Computer", "Consulting", "Consumer Products", "Cosmetics", "Defense", "Department Stores", "Education", "Electronics", "Energy", "Entertainment & Leisure, Executive Search", "Financial Services", "Food", "Beverage & Tobacco", "Grocery", "Health Care", "Internet Publishing", "Investment Banking", "Legal", "Manufacturing", "Motion Picture & Video", "Music", "Newspaper Publishers", "Online Auctions", "Pension Funds", "Pharmaceuticals", "Private Equity", "Publishing", "Real Estate", "Retail & Wholesale", "Securities & Commodity Exchanges", "Service", "Soap & Detergent", "Software", "Sports", "Technology", "Telecommunications", "Television", "Transportation", "Venture Capital"]
for industry in industries:
if frappe.db.exists("CRM Industry", industry):
continue
doc = frappe.new_doc("CRM Industry")
doc.industry = industry
doc.insert()
def add_default_lead_sources():
lead_sources = ["Existing Customer", "Reference", "Advertisement", "Cold Calling", "Exhibition", "Supplier Reference", "Mass Mailing", "Customer's Vendor", "Campaign", "Walk In"]
for source in lead_sources:
if frappe.db.exists("CRM Lead Source", source):
continue
doc = frappe.new_doc("CRM Lead Source")
doc.source_name = source
doc.insert()
|
2302_79757062/crm
|
crm/install.py
|
Python
|
agpl-3.0
| 8,722
|
from werkzeug.wrappers import Response
import json
import frappe
from frappe import _
from .twilio_handler import Twilio, IncomingCall, TwilioCallDetails
from .utils import parse_mobile_no
@frappe.whitelist()
def is_enabled():
return frappe.db.get_single_value("Twilio Settings", "enabled")
@frappe.whitelist()
def generate_access_token():
"""Returns access token that is required to authenticate Twilio Client SDK.
"""
twilio = Twilio.connect()
if not twilio:
return {}
from_number = frappe.db.get_value('Twilio Agents', frappe.session.user, 'twilio_number')
if not from_number:
return {
"ok": False,
"error": "caller_phone_identity_missing",
"detail": "Phone number is not mapped to the caller"
}
token=twilio.generate_voice_access_token(identity=frappe.session.user)
return {
'token': frappe.safe_decode(token)
}
@frappe.whitelist(allow_guest=True)
def voice(**kwargs):
"""This is a webhook called by twilio to get instructions when the voice call request comes to twilio server.
"""
def _get_caller_number(caller):
identity = caller.replace('client:', '').strip()
user = Twilio.emailid_from_identity(identity)
return frappe.db.get_value('Twilio Agents', user, 'twilio_number')
args = frappe._dict(kwargs)
twilio = Twilio.connect()
if not twilio:
return
assert args.AccountSid == twilio.account_sid
assert args.ApplicationSid == twilio.application_sid
# Generate TwiML instructions to make a call
from_number = _get_caller_number(args.Caller)
resp = twilio.generate_twilio_dial_response(from_number, args.To)
call_details = TwilioCallDetails(args, call_from=from_number)
create_call_log(call_details)
return Response(resp.to_xml(), mimetype='text/xml')
@frappe.whitelist(allow_guest=True)
def twilio_incoming_call_handler(**kwargs):
args = frappe._dict(kwargs)
call_details = TwilioCallDetails(args)
create_call_log(call_details)
resp = IncomingCall(args.From, args.To).process()
return Response(resp.to_xml(), mimetype='text/xml')
def create_call_log(call_details: TwilioCallDetails):
call_log = frappe.get_doc({**call_details.to_dict(),
'doctype': 'CRM Call Log',
'medium': 'Twilio'
})
call_log.reference_docname, call_log.reference_doctype = get_lead_or_deal_from_number(call_log)
call_log.flags.ignore_permissions = True
call_log.save()
frappe.db.commit()
def update_call_log(call_sid, status=None):
"""Update call log status.
"""
twilio = Twilio.connect()
if not (twilio and frappe.db.exists("CRM Call Log", call_sid)): return
call_details = twilio.get_call_info(call_sid)
call_log = frappe.get_doc("CRM Call Log", call_sid)
call_log.status = TwilioCallDetails.get_call_status(status or call_details.status)
call_log.duration = call_details.duration
call_log.start_time = get_datetime_from_timestamp(call_details.start_time)
call_log.end_time = get_datetime_from_timestamp(call_details.end_time)
if call_log.note and call_log.reference_docname:
frappe.db.set_value("FCRM Note", call_log.note, "reference_doctype", call_log.reference_doctype)
frappe.db.set_value("FCRM Note", call_log.note, "reference_docname", call_log.reference_docname)
call_log.flags.ignore_permissions = True
call_log.save()
frappe.db.commit()
@frappe.whitelist(allow_guest=True)
def update_recording_info(**kwargs):
try:
args = frappe._dict(kwargs)
recording_url = args.RecordingUrl
call_sid = args.CallSid
update_call_log(call_sid)
frappe.db.set_value("CRM Call Log", call_sid, "recording_url", recording_url)
except:
frappe.log_error(title=_("Failed to capture Twilio recording"))
@frappe.whitelist(allow_guest=True)
def update_call_status_info(**kwargs):
try:
args = frappe._dict(kwargs)
parent_call_sid = args.ParentCallSid
update_call_log(parent_call_sid, status=args.CallStatus)
call_info = {
'ParentCallSid': args.ParentCallSid,
'CallSid': args.CallSid,
'CallStatus': args.CallStatus,
'CallDuration': args.CallDuration,
'From': args.From,
'To': args.To,
}
client = Twilio.get_twilio_client()
client.calls(args.ParentCallSid).user_defined_messages.create(
content=json.dumps(call_info)
)
except:
frappe.log_error(title=_("Failed to update Twilio call status"))
def get_datetime_from_timestamp(timestamp):
from datetime import datetime
from pytz import timezone
if not timestamp: return None
datetime_utc_tz_str = timestamp.strftime('%Y-%m-%d %H:%M:%S%z')
datetime_utc_tz = datetime.strptime(datetime_utc_tz_str, '%Y-%m-%d %H:%M:%S%z')
system_timezone = frappe.utils.get_system_timezone()
converted_datetime = datetime_utc_tz.astimezone(timezone(system_timezone))
return frappe.utils.format_datetime(converted_datetime, 'yyyy-MM-dd HH:mm:ss')
@frappe.whitelist()
def add_note_to_call_log(call_sid, note):
"""Add note to call log. based on child call sid.
"""
twilio = Twilio.connect()
if not twilio: return
call_details = twilio.get_call_info(call_sid)
sid = call_sid if call_details.direction == 'inbound' else call_details.parent_call_sid
frappe.db.set_value("CRM Call Log", sid, "note", note)
frappe.db.commit()
def get_lead_or_deal_from_number(call):
"""Get lead/deal from the given number.
"""
def find_record(doctype, mobile_no, where=''):
mobile_no = parse_mobile_no(mobile_no)
query = f"""
SELECT name, mobile_no
FROM `tab{doctype}`
WHERE CONCAT('+', REGEXP_REPLACE(mobile_no, '[^0-9]', '')) = {mobile_no}
"""
data = frappe.db.sql(query + where, as_dict=True)
return data[0].name if data else None
doctype = "CRM Deal"
number = call.get('to') if call.type == 'Outgoing' else call.get('from')
doc = find_record(doctype, number) or None
if not doc:
doctype = "CRM Lead"
doc = find_record(doctype, number, 'AND converted is not True')
if not doc:
doc = find_record(doctype, number)
return doc, doctype
|
2302_79757062/crm
|
crm/integrations/twilio/api.py
|
Python
|
agpl-3.0
| 5,814
|
from twilio.rest import Client as TwilioClient
from twilio.jwt.access_token import AccessToken
from twilio.jwt.access_token.grants import VoiceGrant
from twilio.twiml.voice_response import VoiceResponse, Dial
from .utils import get_public_url, merge_dicts
import frappe
from frappe import _
from frappe.utils.password import get_decrypted_password
class Twilio:
"""Twilio connector over TwilioClient.
"""
def __init__(self, settings):
"""
:param settings: `Twilio Settings` doctype
"""
self.settings = settings
self.account_sid = settings.account_sid
self.application_sid = settings.twiml_sid
self.api_key = settings.api_key
self.api_secret = settings.get_password("api_secret")
self.twilio_client = self.get_twilio_client()
@classmethod
def connect(self):
"""Make a twilio connection.
"""
settings = frappe.get_doc("Twilio Settings")
if not (settings and settings.enabled):
return
return Twilio(settings=settings)
def get_phone_numbers(self):
"""Get account's twilio phone numbers.
"""
numbers = self.twilio_client.incoming_phone_numbers.list()
return [n.phone_number for n in numbers]
def generate_voice_access_token(self, identity: str, ttl=60*60):
"""Generates a token required to make voice calls from the browser.
"""
# identity is used by twilio to identify the user uniqueness at browser(or any endpoints).
identity = self.safe_identity(identity)
# Create access token with credentials
token = AccessToken(self.account_sid, self.api_key, self.api_secret, identity=identity, ttl=ttl)
# Create a Voice grant and add to token
voice_grant = VoiceGrant(
outgoing_application_sid=self.application_sid,
incoming_allow=True, # Allow incoming calls
)
token.add_grant(voice_grant)
return token.to_jwt()
@classmethod
def safe_identity(cls, identity: str):
"""Create a safe identity by replacing unsupported special charaters `@` with (at)).
Twilio Client JS fails to make a call connection if identity has special characters like @, [, / etc)
https://www.twilio.com/docs/voice/client/errors (#31105)
"""
return identity.replace('@', '(at)')
@classmethod
def emailid_from_identity(cls, identity: str):
"""Convert safe identity string into emailID.
"""
return identity.replace('(at)', '@')
def get_recording_status_callback_url(self):
url_path = "/api/method/crm.integrations.twilio.api.update_recording_info"
return get_public_url(url_path)
def get_update_call_status_callback_url(self):
url_path = "/api/method/crm.integrations.twilio.api.update_call_status_info"
return get_public_url(url_path)
def generate_twilio_dial_response(self, from_number: str, to_number: str):
"""Generates voice call instructions to forward the call to agents Phone.
"""
resp = VoiceResponse()
dial = Dial(
caller_id=from_number,
record=self.settings.record_calls,
recording_status_callback=self.get_recording_status_callback_url(),
recording_status_callback_event='completed'
)
dial.number(
to_number,
status_callback_event='initiated ringing answered completed',
status_callback=self.get_update_call_status_callback_url(),
status_callback_method='POST'
)
resp.append(dial)
return resp
def get_call_info(self, call_sid):
return self.twilio_client.calls(call_sid).fetch()
def generate_twilio_client_response(self, client, ring_tone='at'):
"""Generates voice call instructions to forward the call to agents computer.
"""
resp = VoiceResponse()
dial = Dial(
ring_tone=ring_tone,
record=self.settings.record_calls,
recording_status_callback=self.get_recording_status_callback_url(),
recording_status_callback_event='completed'
)
dial.client(
client,
status_callback_event='initiated ringing answered completed',
status_callback=self.get_update_call_status_callback_url(),
status_callback_method='POST'
)
resp.append(dial)
return resp
@classmethod
def get_twilio_client(self):
twilio_settings = frappe.get_doc("Twilio Settings")
if not twilio_settings.enabled:
frappe.throw(_("Please enable twilio settings before making a call."))
auth_token = get_decrypted_password("Twilio Settings", "Twilio Settings", 'auth_token')
client = TwilioClient(twilio_settings.account_sid, auth_token)
return client
class IncomingCall:
def __init__(self, from_number, to_number, meta=None):
self.from_number = from_number
self.to_number = to_number
self.meta = meta
def process(self):
"""Process the incoming call
* Figure out who is going to pick the call (call attender)
* Check call attender settings and forward the call to Phone
"""
twilio = Twilio.connect()
owners = get_twilio_number_owners(self.to_number)
attender = get_the_call_attender(owners, self.from_number)
if not attender:
resp = VoiceResponse()
resp.say(_('Agent is unavailable to take the call, please call after some time.'))
return resp
if attender['call_receiving_device'] == 'Phone':
return twilio.generate_twilio_dial_response(self.from_number, attender['mobile_no'])
else:
return twilio.generate_twilio_client_response(twilio.safe_identity(attender['name']))
def get_twilio_number_owners(phone_number):
"""Get list of users who is using the phone_number.
>>> get_twilio_number_owners('+11234567890')
{
'owner1': {'name': '..', 'mobile_no': '..', 'call_receiving_device': '...'},
'owner2': {....}
}
"""
# remove special characters from phone number and get only digits also remove white spaces
# keep + sign in the number at start of the number
phone_number = ''.join([c for c in phone_number if c.isdigit() or c == '+'])
user_voice_settings = frappe.get_all(
'Twilio Agents',
filters={'twilio_number': phone_number},
fields=["name", "call_receiving_device"]
)
user_wise_voice_settings = {user['name']: user for user in user_voice_settings}
user_general_settings = frappe.get_all(
'User',
filters = [['name', 'IN', user_wise_voice_settings.keys()]],
fields = ['name', 'mobile_no']
)
user_wise_general_settings = {user['name']: user for user in user_general_settings}
return merge_dicts(user_wise_general_settings, user_wise_voice_settings)
def get_active_loggedin_users(users):
"""Filter the current loggedin users from the given users list
"""
rows = frappe.db.sql("""
SELECT `user`
FROM `tabSessions`
WHERE `user` IN %(users)s
""", {'users': users})
return [row[0] for row in set(rows)]
def get_the_call_attender(owners, caller=None):
"""Get attender details from list of owners
"""
if not owners: return
current_loggedin_users = get_active_loggedin_users(list(owners.keys()))
if len(current_loggedin_users) > 1 and caller:
deal_owner = frappe.db.get_value('CRM Deal', {'mobile_no': caller}, 'deal_owner')
if not deal_owner:
deal_owner = frappe.db.get_value('CRM Lead', {'mobile_no': caller, 'converted': False}, 'lead_owner')
for user in current_loggedin_users:
if user == deal_owner:
current_loggedin_users = [user]
for name, details in owners.items():
if ((details['call_receiving_device'] == 'Phone' and details['mobile_no']) or
(details['call_receiving_device'] == 'Computer' and name in current_loggedin_users)):
return details
class TwilioCallDetails:
def __init__(self, call_info, call_from = None, call_to = None):
self.call_info = call_info
self.account_sid = call_info.get('AccountSid')
self.application_sid = call_info.get('ApplicationSid')
self.call_sid = call_info.get('CallSid')
self.call_status = self.get_call_status(call_info.get('CallStatus'))
self._call_from = call_from or call_info.get('From')
self._call_to = call_to or call_info.get('To')
def get_direction(self):
if self.call_info.get('Caller').lower().startswith('client'):
return 'Outgoing'
return 'Incoming'
def get_from_number(self):
return self._call_from or self.call_info.get('From')
def get_to_number(self):
return self._call_to or self.call_info.get('To')
@classmethod
def get_call_status(cls, twilio_status):
"""Convert Twilio given status into system status.
"""
twilio_status = twilio_status or ''
return ' '.join(twilio_status.split('-')).title()
def to_dict(self):
"""Convert call details into dict.
"""
direction = self.get_direction()
from_number = self.get_from_number()
to_number = self.get_to_number()
caller = ''
receiver = ''
if direction == 'Outgoing':
caller = self.call_info.get('Caller')
identity = caller.replace('client:', '').strip()
caller = Twilio.emailid_from_identity(identity) if identity else ''
else:
owners = get_twilio_number_owners(to_number)
attender = get_the_call_attender(owners, from_number)
receiver = attender['name'] if attender else ''
return {
'type': direction,
'status': self.call_status,
'id': self.call_sid,
'from': from_number,
'to': to_number,
'receiver': receiver,
'caller': caller,
}
|
2302_79757062/crm
|
crm/integrations/twilio/twilio_handler.py
|
Python
|
agpl-3.0
| 8,907
|
from frappe.utils import get_url
def get_public_url(path: str=None):
return get_url().split(":8", 1)[0] + path
def merge_dicts(d1: dict, d2: dict):
"""Merge dicts of dictionaries.
>>> merge_dicts(
{'name1': {'age': 20}, 'name2': {'age': 30}},
{'name1': {'phone': '+xxx'}, 'name2': {'phone': '+yyy'}, 'name3': {'phone': '+zzz'}}
)
... {'name1': {'age': 20, 'phone': '+xxx'}, 'name2': {'age': 30, 'phone': '+yyy'}}
"""
return {k:{**v, **d2.get(k, {})} for k, v in d1.items()}
def parse_mobile_no(mobile_no: str):
"""Parse mobile number to remove spaces, brackets, etc.
>>> parse_mobile_no('+91 (766) 667 6666')
... '+917666676666'
"""
return ''.join([c for c in mobile_no if c.isdigit() or c == '+'])
|
2302_79757062/crm
|
crm/integrations/twilio/utils.py
|
Python
|
agpl-3.0
| 719
|
# import frappe
from frappe import _
from frappe.contacts.doctype.contact.contact import Contact
class CustomContact(Contact):
@staticmethod
def default_list_data():
columns = [
{
'label': 'Name',
'type': 'Data',
'key': 'full_name',
'width': '17rem',
},
{
'label': 'Email',
'type': 'Data',
'key': 'email_id',
'width': '12rem',
},
{
'label': 'Phone',
'type': 'Data',
'key': 'mobile_no',
'width': '12rem',
},
{
'label': 'Organization',
'type': 'Data',
'key': 'company_name',
'width': '12rem',
},
{
'label': 'Last Modified',
'type': 'Datetime',
'key': 'modified',
'width': '8rem',
},
]
rows = [
"name",
"full_name",
"company_name",
"email_id",
"mobile_no",
"modified",
"image",
]
return {'columns': columns, 'rows': rows}
|
2302_79757062/crm
|
crm/overrides/contact.py
|
Python
|
agpl-3.0
| 864
|
# import frappe
from frappe import _
from frappe.email.doctype.email_template.email_template import EmailTemplate
class CustomEmailTemplate(EmailTemplate):
@staticmethod
def default_list_data():
columns = [
{
'label': 'Name',
'type': 'Data',
'key': 'name',
'width': '17rem',
},
{
'label': 'Subject',
'type': 'Data',
'key': 'subject',
'width': '12rem',
},
{
'label': 'Enabled',
'type': 'Check',
'key': 'enabled',
'width': '6rem',
},
{
'label': 'Doctype',
'type': 'Link',
'key': 'reference_doctype',
'width': '12rem',
},
{
'label': 'Last Modified',
'type': 'Datetime',
'key': 'modified',
'width': '8rem',
},
]
rows = [
"name",
"enabled",
"use_html",
"reference_doctype",
"subject",
"response",
"response_html",
"modified",
]
return {'columns': columns, 'rows': rows}
|
2302_79757062/crm
|
crm/overrides/email_template.py
|
Python
|
agpl-3.0
| 913
|
from crm.install import add_default_fields_layout
def execute():
add_default_fields_layout()
|
2302_79757062/crm
|
crm/patches/v1_0/create_default_fields_layout.py
|
Python
|
agpl-3.0
| 98
|
import json
import frappe
def execute():
if not frappe.db.exists("CRM Fields Layout", {"dt": "CRM Lead", "type": "Side Panel"}):
create_doctype_fields_layout("CRM Lead")
if not frappe.db.exists("CRM Fields Layout", {"dt": "CRM Deal", "type": "Side Panel"}):
create_doctype_fields_layout("CRM Deal")
def create_doctype_fields_layout(doctype):
not_allowed_fieldtypes = [
"Section Break",
"Column Break",
]
fields = frappe.get_meta(doctype).fields
fields = [field for field in fields if field.fieldtype not in not_allowed_fieldtypes]
sections = {}
section_fields = []
last_section = None
for field in fields:
if field.fieldtype == "Tab Break" and last_section:
sections[last_section]["fields"] = section_fields
last_section = None
if field.read_only:
section_fields = []
continue
if field.fieldtype == "Tab Break":
if field.read_only:
section_fields = []
continue
section_fields = []
last_section = field.fieldname
sections[field.fieldname] = {
"label": field.label,
"name": field.fieldname,
"opened": True,
"fields": [],
}
if field.fieldname == "contacts_tab":
sections[field.fieldname]["editable"] = False
sections[field.fieldname]["contacts"] = []
else:
section_fields.append(field.fieldname)
section_fields = []
for section in sections:
if section == "contacts_tab":
sections[section]["name"] = "contacts_section"
sections[section].pop("fields", None)
section_fields.append(sections[section])
frappe.get_doc({
"doctype": "CRM Fields Layout",
"dt": doctype,
"type": "Side Panel",
"layout": json.dumps(section_fields),
}).insert(ignore_permissions=True)
return section_fields
|
2302_79757062/crm
|
crm/patches/v1_0/create_default_sidebar_fields_layout.py
|
Python
|
agpl-3.0
| 1,700
|
from crm.install import add_email_template_custom_fields
def execute():
add_email_template_custom_fields()
|
2302_79757062/crm
|
crm/patches/v1_0/create_email_template_custom_fields.py
|
Python
|
agpl-3.0
| 112
|
import frappe
from frappe.model.rename_doc import rename_doc
def execute():
if not frappe.db.exists("DocType", "FCRM Note"):
frappe.flags.ignore_route_conflict_validation = True
rename_doc("DocType", "CRM Note", "FCRM Note")
frappe.flags.ignore_route_conflict_validation = False
frappe.reload_doctype("FCRM Note", force=True)
if frappe.db.exists("DocType", "FCRM Note") and frappe.db.count("FCRM Note") > 0:
return
notes = frappe.db.sql("SELECT * FROM `tabCRM Note`", as_dict=True)
if notes:
for note in notes:
doc = frappe.get_doc({
"doctype": "FCRM Note",
"creation": note.get("creation"),
"modified": note.get("modified"),
"modified_by": note.get("modified_by"),
"owner": note.get("owner"),
"title": note.get("title"),
"content": note.get("content"),
"reference_doctype": note.get("reference_doctype"),
"reference_docname": note.get("reference_docname"),
})
doc.db_insert()
|
2302_79757062/crm
|
crm/patches/v1_0/move_crm_note_data_to_fcrm_note.py
|
Python
|
agpl-3.0
| 943
|
import json
import frappe
def execute():
if not frappe.db.exists("CRM Fields Layout", "CRM Deal-Quick Entry"):
return
deal = frappe.db.get_value("CRM Fields Layout", "CRM Deal-Quick Entry", "layout")
layout = json.loads(deal)
for section in layout:
if section.get("label") in ["Select Organization", "Organization Details", "Select Contact", "Contact Details"]:
section["editable"] = False
frappe.db.set_value("CRM Fields Layout", "CRM Deal-Quick Entry", "layout", json.dumps(layout))
|
2302_79757062/crm
|
crm/patches/v1_0/update_deal_quick_entry_layout.py
|
Python
|
agpl-3.0
| 536
|
<h2>You have been invited to join Frappe CRM</h2>
<p>
<a class="btn btn-primary" href="{{ invite_link }}">Accept Invitation</a>
</p>
|
2302_79757062/crm
|
crm/templates/emails/crm_invitation.html
|
HTML
|
agpl-3.0
| 134
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import click
import frappe
def before_uninstall():
delete_email_template_custom_fields()
def delete_email_template_custom_fields():
if frappe.get_meta("Email Template").has_field("enabled"):
click.secho("* Uninstalling Custom Fields from Email Template")
fieldnames = (
"enabled",
"reference_doctype",
)
for fieldname in fieldnames:
frappe.db.delete("Custom Field", {"name": "Email Template-" + fieldname})
frappe.clear_cache(doctype="Email Template")
|
2302_79757062/crm
|
crm/uninstall.py
|
Python
|
agpl-3.0
| 617
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
# GNU GPLv3 License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils.telemetry import capture
no_cache = 1
def get_context():
csrf_token = frappe.sessions.get_csrf_token()
frappe.db.commit()
context = frappe._dict()
context.boot = get_boot()
context.boot.csrf_token = csrf_token
if frappe.session.user != "Guest":
capture("active_site", "crm")
return context
@frappe.whitelist(methods=["POST"], allow_guest=True)
def get_context_for_dev():
if not frappe.conf.developer_mode:
frappe.throw("This method is only meant for developer mode")
return get_boot()
def get_boot():
return frappe._dict(
{
"frappe_version": frappe.__version__,
"default_route": get_default_route(),
"site_name": frappe.local.site,
"read_only_mode": frappe.flags.read_only,
}
)
def get_default_route():
return "/crm"
|
2302_79757062/crm
|
crm/www/crm.py
|
Python
|
agpl-3.0
| 1,033
|
#!bin/bash
if [ -d "/home/frappe/frappe-bench/apps/frappe" ]; then
echo "Bench already exists, skipping init"
cd frappe-bench
bench start
else
echo "Creating new bench..."
fi
bench init --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:6379
bench set-redis-queue-host redis:6379
bench set-redis-socketio-host redis:6379
# Remove redis, watch from Procfile
sed -i '/redis/d' ./Procfile
sed -i '/watch/d' ./Procfile
bench get-app crm
bench new-site crm.localhost \
--force \
--mariadb-root-password 123 \
--admin-password admin \
--no-mariadb-socket
bench --site crm.localhost install-app crm
bench --site crm.localhost set-config developer_mode 1
bench --site crm.localhost clear-cache
bench --site crm.localhost set-config mute_emails 1
bench --site crm.localhost add-user alex@example.com --first-name Alex --last-name Scott --password 123 --user-type 'System User' --add-role 'crm Admin'
bench use crm.localhost
bench start
|
2302_79757062/crm
|
docker/init.sh
|
Shell
|
agpl-3.0
| 1,078
|
<!DOCTYPE html>
<html class="h-full" lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, viewport-fit=cover maximum-scale=1.0, user-scalable=no"
/>
<title>Frappe CRM</title>
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-title" content="Frappe CRM" />
<meta name="apple-mobile-web-app-status-bar-style" content="white" />
<!-- PWA -->
<link
rel="icon"
type="image/png"
sizes="196x196"
href="/assets/crm/manifest/apple-icon-180.png"
/>
<link
rel="apple-touch-icon"
href="/assets/crm/manifest/apple-icon-180.png"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-2048-2732.jpg"
media="(device-width: 1024px) and (device-height: 1366px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-2732-2048.jpg"
media="(device-width: 1024px) and (device-height: 1366px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-1668-2388.jpg"
media="(device-width: 834px) and (device-height: 1194px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-2388-1668.jpg"
media="(device-width: 834px) and (device-height: 1194px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-1536-2048.jpg"
media="(device-width: 768px) and (device-height: 1024px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-2048-1536.jpg"
media="(device-width: 768px) and (device-height: 1024px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-1668-2224.jpg"
media="(device-width: 834px) and (device-height: 1112px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-2224-1668.jpg"
media="(device-width: 834px) and (device-height: 1112px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-1620-2160.jpg"
media="(device-width: 810px) and (device-height: 1080px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-2160-1620.jpg"
media="(device-width: 810px) and (device-height: 1080px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-1290-2796.jpg"
media="(device-width: 430px) and (device-height: 932px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-2796-1290.jpg"
media="(device-width: 430px) and (device-height: 932px) and (-webkit-device-pixel-ratio: 3) and (orientation: landscape)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-1179-2556.jpg"
media="(device-width: 393px) and (device-height: 852px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-2556-1179.jpg"
media="(device-width: 393px) and (device-height: 852px) and (-webkit-device-pixel-ratio: 3) and (orientation: landscape)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-1284-2778.jpg"
media="(device-width: 428px) and (device-height: 926px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-2778-1284.jpg"
media="(device-width: 428px) and (device-height: 926px) and (-webkit-device-pixel-ratio: 3) and (orientation: landscape)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-1170-2532.jpg"
media="(device-width: 390px) and (device-height: 844px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-2532-1170.jpg"
media="(device-width: 390px) and (device-height: 844px) and (-webkit-device-pixel-ratio: 3) and (orientation: landscape)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-1125-2436.jpg"
media="(device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-2436-1125.jpg"
media="(device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) and (orientation: landscape)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-1242-2688.jpg"
media="(device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-2688-1242.jpg"
media="(device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 3) and (orientation: landscape)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-828-1792.jpg"
media="(device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-1792-828.jpg"
media="(device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-1242-2208.jpg"
media="(device-width: 414px) and (device-height: 736px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-2208-1242.jpg"
media="(device-width: 414px) and (device-height: 736px) and (-webkit-device-pixel-ratio: 3) and (orientation: landscape)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-750-1334.jpg"
media="(device-width: 375px) and (device-height: 667px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-1334-750.jpg"
media="(device-width: 375px) and (device-height: 667px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-640-1136.jpg"
media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)"
/>
<link
rel="apple-touch-startup-image"
href="/assets/crm/manifest/apple-splash-1136-640.jpg"
media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)"
/>
</head>
<body class="sm:overscroll-y-none no-scrollbar">
<div id="app" class="h-full"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
|
2302_79757062/crm
|
frontend/index.html
|
HTML
|
agpl-3.0
| 8,190
|
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
|
2302_79757062/crm
|
frontend/postcss.config.js
|
JavaScript
|
agpl-3.0
| 82
|
<template>
<Layout v-if="session().isLoggedIn">
<router-view />
</Layout>
<Dialogs />
<Toasts />
</template>
<script setup>
import { Dialogs } from '@/utils/dialogs'
import { sessionStore as session } from '@/stores/session'
import { Toasts } from 'frappe-ui'
import { computed, defineAsyncComponent } from 'vue'
const MobileLayout = defineAsyncComponent(() =>
import('./components/Layouts/MobileLayout.vue')
)
const DesktopLayout = defineAsyncComponent(() =>
import('./components/Layouts/DesktopLayout.vue')
)
const Layout = computed(() => {
if (window.innerWidth < 640) {
return MobileLayout
} else {
return DesktopLayout
}
})
</script>
|
2302_79757062/crm
|
frontend/src/App.vue
|
Vue
|
agpl-3.0
| 671
|
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 100;
font-display: swap;
src: url("Inter-Thin.woff2?v=3.12") format("woff2"),
url("Inter-Thin.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: italic;
font-weight: 100;
font-display: swap;
src: url("Inter-ThinItalic.woff2?v=3.12") format("woff2"),
url("Inter-ThinItalic.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 200;
font-display: swap;
src: url("Inter-ExtraLight.woff2?v=3.12") format("woff2"),
url("Inter-ExtraLight.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: italic;
font-weight: 200;
font-display: swap;
src: url("Inter-ExtraLightItalic.woff2?v=3.12") format("woff2"),
url("Inter-ExtraLightItalic.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url("Inter-Light.woff2?v=3.12") format("woff2"),
url("Inter-Light.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url("Inter-LightItalic.woff2?v=3.12") format("woff2"),
url("Inter-LightItalic.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("Inter-Regular.woff2?v=3.12") format("woff2"),
url("Inter-Regular.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url("Inter-Italic.woff2?v=3.12") format("woff2"),
url("Inter-Italic.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("Inter-Medium.woff2?v=3.12") format("woff2"),
url("Inter-Medium.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: italic;
font-weight: 500;
font-display: swap;
src: url("Inter-MediumItalic.woff2?v=3.12") format("woff2"),
url("Inter-MediumItalic.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("Inter-SemiBold.woff2?v=3.12") format("woff2"),
url("Inter-SemiBold.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url("Inter-SemiBoldItalic.woff2?v=3.12") format("woff2"),
url("Inter-SemiBoldItalic.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("Inter-Bold.woff2?v=3.12") format("woff2"),
url("Inter-Bold.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url("Inter-BoldItalic.woff2?v=3.12") format("woff2"),
url("Inter-BoldItalic.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("Inter-ExtraBold.woff2?v=3.12") format("woff2"),
url("Inter-ExtraBold.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: italic;
font-weight: 800;
font-display: swap;
src: url("Inter-ExtraBoldItalic.woff2?v=3.12") format("woff2"),
url("Inter-ExtraBoldItalic.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: normal;
font-weight: 900;
font-display: swap;
src: url("Inter-Black.woff2?v=3.12") format("woff2"),
url("Inter-Black.woff?v=3.12") format("woff");
}
@font-face {
font-family: 'Inter';
font-style: italic;
font-weight: 900;
font-display: swap;
src: url("Inter-BlackItalic.woff2?v=3.12") format("woff2"),
url("Inter-BlackItalic.woff?v=3.12") format("woff");
}
|
2302_79757062/crm
|
frontend/src/assets/Inter/inter.css
|
CSS
|
agpl-3.0
| 4,006
|
<template>
<ActivityHeader
v-model="tabIndex"
v-model:showWhatsappTemplates="showWhatsappTemplates"
:tabs="tabs"
:title="title"
:doc="doc"
:emailBox="emailBox"
:whatsappBox="whatsappBox"
:modalRef="modalRef"
/>
<FadedScrollableDiv
:maskHeight="30"
class="flex flex-col flex-1 overflow-y-auto"
>
<div
v-if="all_activities?.loading"
class="flex flex-1 flex-col items-center justify-center gap-3 text-xl font-medium text-gray-500"
>
<LoadingIndicator class="h-6 w-6" />
<span>{{ __('Loading...') }}</span>
</div>
<div
v-else-if="
activities?.length ||
(whatsappMessages.data?.length && title == 'WhatsApp')
"
class="activities"
>
<div v-if="title == 'WhatsApp' && whatsappMessages.data?.length">
<WhatsAppArea
class="px-3 sm:px-10"
v-model="whatsappMessages"
v-model:reply="replyMessage"
:messages="whatsappMessages.data"
/>
</div>
<div
v-else-if="title == 'Notes'"
class="grid grid-cols-1 gap-4 px-3 pb-3 sm:px-10 sm:pb-5 lg:grid-cols-2 xl:grid-cols-3"
>
<div v-for="note in activities" @click="modalRef.showNote(note)">
<NoteArea :note="note" v-model="all_activities" />
</div>
</div>
<div v-else-if="title == 'Comments'" class="pb-5">
<div v-for="(comment, i) in activities">
<div
class="activity grid grid-cols-[30px_minmax(auto,_1fr)] gap-2 px-3 sm:gap-4 sm:px-10"
>
<div
class="relative flex justify-center after:absolute after:left-[50%] after:top-0 after:-z-10 after:border-l after:border-gray-200"
:class="i != activities.length - 1 ? 'after:h-full' : 'after:h-4'"
>
<div
class="z-10 flex h-8 w-7 items-center justify-center bg-white"
>
<CommentIcon class="text-gray-800" />
</div>
</div>
<CommentArea class="mb-4" :activity="comment" />
</div>
</div>
</div>
<div
v-else-if="title == 'Tasks'"
class="px-3 pb-3 sm:px-10 sm:pb-5 overflow-x-auto sm:w-full w-max"
>
<TaskArea
v-model="all_activities"
v-model:doc="doc"
:modalRef="modalRef"
:tasks="activities"
:doctype="doctype"
/>
</div>
<div v-else-if="title == 'Calls'" class="activity">
<div v-for="(call, i) in activities">
<div
class="activity grid grid-cols-[30px_minmax(auto,_1fr)] gap-4 px-3 sm:px-10"
>
<div
class="relative flex justify-center after:absolute after:left-[50%] after:top-0 after:-z-10 after:border-l after:border-gray-200"
:class="i != activities.length - 1 ? 'after:h-full' : 'after:h-4'"
>
<div
class="z-10 flex h-8 w-7 items-center justify-center bg-white text-gray-800"
>
<MissedCallIcon
v-if="call.status == 'No Answer'"
class="text-red-600"
/>
<DeclinedCallIcon v-else-if="call.status == 'Busy'" />
<component
v-else
:is="
call.type == 'Incoming' ? InboundCallIcon : OutboundCallIcon
"
/>
</div>
</div>
<CallArea class="mb-4" :activity="call" />
</div>
</div>
</div>
<div
v-else
v-for="(activity, i) in activities"
class="activity px-3 sm:px-10"
:class="
['Activity', 'Emails'].includes(title)
? 'grid grid-cols-[30px_minmax(auto,_1fr)] gap-2 sm:gap-4'
: ''
"
>
<div
v-if="['Activity', 'Emails'].includes(title)"
class="relative flex justify-center before:absolute before:left-[50%] before:top-0 before:-z-10 before:border-l before:border-gray-200"
:class="[i != activities.length - 1 ? 'before:h-full' : 'before:h-4']"
>
<div
class="z-10 flex h-7 w-7 items-center justify-center bg-white"
:class="{
'mt-2.5': ['communication'].includes(activity.activity_type),
'bg-white': ['added', 'removed', 'changed'].includes(
activity.activity_type,
),
'h-8': [
'comment',
'communication',
'incoming_call',
'outgoing_call',
].includes(activity.activity_type),
}"
>
<UserAvatar
v-if="activity.activity_type == 'communication'"
:user="activity.data.sender"
size="md"
/>
<MissedCallIcon
v-else-if="
['incoming_call', 'outgoing_call'].includes(
activity.activity_type,
) && activity.status == 'No Answer'
"
class="text-red-600"
/>
<DeclinedCallIcon
v-else-if="
['incoming_call', 'outgoing_call'].includes(
activity.activity_type,
) && activity.status == 'Busy'
"
/>
<component
v-else
:is="activity.icon"
:class="
['added', 'removed', 'changed'].includes(activity.activity_type)
? 'text-gray-500'
: 'text-gray-800'
"
/>
</div>
</div>
<div
v-if="activity.activity_type == 'communication'"
class="pb-5 mt-px"
>
<EmailArea :activity="activity" :emailBox="emailBox" />
</div>
<div
class="mb-4"
:id="activity.name"
v-else-if="activity.activity_type == 'comment'"
>
<CommentArea :activity="activity" />
</div>
<div
v-else-if="
activity.activity_type == 'incoming_call' ||
activity.activity_type == 'outgoing_call'
"
class="mb-4"
>
<CallArea :activity="activity" />
</div>
<div v-else class="mb-4 flex flex-col gap-2 py-1.5">
<div class="flex items-center justify-stretch gap-2 text-base">
<div
v-if="activity.other_versions"
class="inline-flex flex-wrap gap-1.5 text-gray-800 font-medium"
>
<span>{{ activity.show_others ? __('Hide') : __('Show') }}</span>
<span> +{{ activity.other_versions.length + 1 }} </span>
<span>{{ __('changes from') }}</span>
<span>{{ activity.owner_name }}</span>
<Button
class="!size-4"
variant="ghost"
@click="activity.show_others = !activity.show_others"
>
<template #icon>
<SelectIcon />
</template>
</Button>
</div>
<div
v-else
class="inline-flex items-center flex-wrap gap-1 text-gray-600"
>
<span class="font-medium text-gray-800">
{{ activity.owner_name }}
</span>
<span v-if="activity.type">{{ __(activity.type) }}</span>
<span
v-if="activity.data.field_label"
class="max-w-xs truncate font-medium text-gray-800"
>
{{ __(activity.data.field_label) }}
</span>
<span v-if="activity.value">{{ __(activity.value) }}</span>
<span
v-if="activity.data.old_value"
class="max-w-xs font-medium text-gray-800"
>
<div
class="flex items-center gap-1"
v-if="activity.options == 'User'"
>
<UserAvatar :user="activity.data.old_value" size="xs" />
{{ getUser(activity.data.old_value).full_name }}
</div>
<div class="truncate" v-else>
{{ activity.data.old_value }}
</div>
</span>
<span v-if="activity.to">{{ __('to') }}</span>
<span
v-if="activity.data.value"
class="max-w-xs font-medium text-gray-800"
>
<div
class="flex items-center gap-1"
v-if="activity.options == 'User'"
>
<UserAvatar :user="activity.data.value" size="xs" />
{{ getUser(activity.data.value).full_name }}
</div>
<div class="truncate" v-else>
{{ activity.data.value }}
</div>
</span>
</div>
<div class="ml-auto whitespace-nowrap">
<Tooltip :text="dateFormat(activity.creation, dateTooltipFormat)">
<div class="text-sm text-gray-600">
{{ __(timeAgo(activity.creation)) }}
</div>
</Tooltip>
</div>
</div>
<div
v-if="activity.other_versions && activity.show_others"
class="flex flex-col gap-0.5"
>
<div
v-for="activity in [activity, ...activity.other_versions]"
class="flex items-start justify-stretch gap-2 py-1.5 text-base"
>
<div class="inline-flex flex-wrap gap-1 text-gray-600">
<span
v-if="activity.data.field_label"
class="max-w-xs truncate text-gray-600"
>
{{ __(activity.data.field_label) }}
</span>
<FeatherIcon
name="arrow-right"
class="mx-1 h-4 w-4 text-gray-600"
/>
<span v-if="activity.type">
{{ startCase(__(activity.type)) }}
</span>
<span
v-if="activity.data.old_value"
class="max-w-xs font-medium text-gray-800"
>
<div
class="flex items-center gap-1"
v-if="activity.options == 'User'"
>
<UserAvatar :user="activity.data.old_value" size="xs" />
{{ getUser(activity.data.old_value).full_name }}
</div>
<div class="truncate" v-else>
{{ activity.data.old_value }}
</div>
</span>
<span v-if="activity.to">{{ __('to') }}</span>
<span
v-if="activity.data.value"
class="max-w-xs font-medium text-gray-800"
>
<div
class="flex items-center gap-1"
v-if="activity.options == 'User'"
>
<UserAvatar :user="activity.data.value" size="xs" />
{{ getUser(activity.data.value).full_name }}
</div>
<div class="truncate" v-else>
{{ activity.data.value }}
</div>
</span>
</div>
<div class="ml-auto whitespace-nowrap">
<Tooltip
:text="dateFormat(activity.creation, dateTooltipFormat)"
>
<div class="text-sm text-gray-600">
{{ __(timeAgo(activity.creation)) }}
</div>
</Tooltip>
</div>
</div>
</div>
</div>
</div>
</div>
<div
v-else
class="flex flex-1 flex-col items-center justify-center gap-3 text-xl font-medium text-gray-500"
>
<component :is="emptyTextIcon" class="h-10 w-10" />
<span>{{ __(emptyText) }}</span>
<Button
v-if="title == 'Calls'"
:label="__('Make a Call')"
@click="makeCall(doc.data.mobile_no)"
/>
<Button
v-else-if="title == 'Notes'"
:label="__('Create Note')"
@click="modalRef.showNote()"
/>
<Button
v-else-if="title == 'Emails'"
:label="__('New Email')"
@click="emailBox.show = true"
/>
<Button
v-else-if="title == 'Comments'"
:label="__('New Comment')"
@click="emailBox.showComment = true"
/>
<Button
v-else-if="title == 'Tasks'"
:label="__('Create Task')"
@click="modalRef.showTask()"
/>
</div>
</FadedScrollableDiv>
<div>
<CommunicationArea
ref="emailBox"
v-if="['Emails', 'Comments', 'Activity'].includes(title)"
v-model="doc"
v-model:reload="reload_email"
:doctype="doctype"
@scroll="scroll"
/>
<WhatsAppBox
ref="whatsappBox"
v-if="title == 'WhatsApp'"
v-model="doc"
v-model:reply="replyMessage"
v-model:whatsapp="whatsappMessages"
:doctype="doctype"
@scroll="scroll"
/>
</div>
<WhatsappTemplateSelectorModal
v-if="whatsappEnabled"
v-model="showWhatsappTemplates"
:doctype="doctype"
@send="(t) => sendTemplate(t)"
/>
<AllModals
ref="modalRef"
v-model="all_activities"
:doctype="doctype"
:doc="doc"
/>
</template>
<script setup>
import ActivityHeader from '@/components/Activities/ActivityHeader.vue'
import EmailArea from '@/components/Activities/EmailArea.vue'
import CommentArea from '@/components/Activities/CommentArea.vue'
import CallArea from '@/components/Activities/CallArea.vue'
import NoteArea from '@/components/Activities/NoteArea.vue'
import TaskArea from '@/components/Activities/TaskArea.vue'
import UserAvatar from '@/components/UserAvatar.vue'
import ActivityIcon from '@/components/Icons/ActivityIcon.vue'
import Email2Icon from '@/components/Icons/Email2Icon.vue'
import PhoneIcon from '@/components/Icons/PhoneIcon.vue'
import NoteIcon from '@/components/Icons/NoteIcon.vue'
import TaskIcon from '@/components/Icons/TaskIcon.vue'
import WhatsAppIcon from '@/components/Icons/WhatsAppIcon.vue'
import WhatsAppArea from '@/components/Activities/WhatsAppArea.vue'
import WhatsAppBox from '@/components/Activities/WhatsAppBox.vue'
import LoadingIndicator from '@/components/Icons/LoadingIndicator.vue'
import LeadsIcon from '@/components/Icons/LeadsIcon.vue'
import DealsIcon from '@/components/Icons/DealsIcon.vue'
import DotIcon from '@/components/Icons/DotIcon.vue'
import CommentIcon from '@/components/Icons/CommentIcon.vue'
import SelectIcon from '@/components/Icons/SelectIcon.vue'
import MissedCallIcon from '@/components/Icons/MissedCallIcon.vue'
import DeclinedCallIcon from '@/components/Icons/DeclinedCallIcon.vue'
import InboundCallIcon from '@/components/Icons/InboundCallIcon.vue'
import OutboundCallIcon from '@/components/Icons/OutboundCallIcon.vue'
import FadedScrollableDiv from '@/components/FadedScrollableDiv.vue'
import CommunicationArea from '@/components/CommunicationArea.vue'
import WhatsappTemplateSelectorModal from '@/components/Modals/WhatsappTemplateSelectorModal.vue'
import AllModals from '@/components/Activities/AllModals.vue'
import {
timeAgo,
dateFormat,
dateTooltipFormat,
secondsToDuration,
startCase,
} from '@/utils'
import { globalStore } from '@/stores/global'
import { usersStore } from '@/stores/users'
import { contactsStore } from '@/stores/contacts'
import { whatsappEnabled } from '@/composables/settings'
import { capture } from '@/telemetry'
import { Button, Tooltip, createResource } from 'frappe-ui'
import { useElementVisibility } from '@vueuse/core'
import {
ref,
computed,
h,
markRaw,
watch,
nextTick,
onMounted,
onBeforeUnmount,
} from 'vue'
import { useRoute } from 'vue-router'
const { makeCall, $socket } = globalStore()
const { getUser } = usersStore()
const { getContact, getLeadContact } = contactsStore()
const props = defineProps({
title: {
type: String,
default: 'Activity',
},
doctype: {
type: String,
default: 'CRM Lead',
},
tabs: {
type: Array,
default: () => [],
},
})
const doc = defineModel()
const reload = defineModel('reload')
const tabIndex = defineModel('tabIndex')
const reload_email = ref(false)
const modalRef = ref(null)
const all_activities = createResource({
url: 'crm.api.activities.get_activities',
params: { name: doc.value.data.name },
cache: ['activity', doc.value.data.name],
auto: true,
transform: ([versions, calls, notes, tasks]) => {
if (calls?.length) {
calls.forEach((doc) => {
doc.show_recording = false
doc.activity_type =
doc.type === 'Incoming' ? 'incoming_call' : 'outgoing_call'
doc.duration = secondsToDuration(doc.duration)
if (doc.type === 'Incoming') {
doc.caller = {
label:
getContact(doc.from)?.full_name ||
getLeadContact(doc.from)?.full_name ||
'Unknown',
image:
getContact(doc.from)?.image || getLeadContact(doc.from)?.image,
}
doc.receiver = {
label: getUser(doc.receiver).full_name,
image: getUser(doc.receiver).user_image,
}
} else {
doc.caller = {
label: getUser(doc.caller).full_name,
image: getUser(doc.caller).user_image,
}
doc.receiver = {
label:
getContact(doc.to)?.full_name ||
getLeadContact(doc.to)?.full_name ||
'Unknown',
image: getContact(doc.to)?.image || getLeadContact(doc.to)?.image,
}
}
})
}
return { versions, calls, notes, tasks }
},
})
const showWhatsappTemplates = ref(false)
const whatsappMessages = createResource({
url: 'crm.api.whatsapp.get_whatsapp_messages',
cache: ['whatsapp_messages', doc.value.data.name],
params: {
reference_doctype: props.doctype,
reference_name: doc.value.data.name,
},
auto: true,
transform: (data) => sortByCreation(data),
onSuccess: () => nextTick(() => scroll()),
})
onBeforeUnmount(() => {
$socket.off('whatsapp_message')
})
onMounted(() => {
$socket.on('whatsapp_message', (data) => {
if (
data.reference_doctype === props.doctype &&
data.reference_name === doc.value.data.name
) {
whatsappMessages.reload()
}
})
})
function sendTemplate(template) {
showWhatsappTemplates.value = false
capture('send_whatsapp_template', { doctype: props.doctype })
createResource({
url: 'crm.api.whatsapp.send_whatsapp_template',
params: {
reference_doctype: props.doctype,
reference_name: doc.value.data.name,
to: doc.value.data.mobile_no,
template,
},
auto: true,
})
}
const replyMessage = ref({})
function get_activities() {
if (!all_activities.data?.versions) return []
if (!all_activities.data?.calls.length)
return all_activities.data.versions || []
return [...all_activities.data.versions, ...all_activities.data.calls]
}
const activities = computed(() => {
let activities = []
if (props.title == 'Activity') {
activities = get_activities()
} else if (props.title == 'Emails') {
if (!all_activities.data?.versions) return []
activities = all_activities.data.versions.filter(
(activity) => activity.activity_type === 'communication',
)
} else if (props.title == 'Comments') {
if (!all_activities.data?.versions) return []
activities = all_activities.data.versions.filter(
(activity) => activity.activity_type === 'comment',
)
} else if (props.title == 'Calls') {
if (!all_activities.data?.calls) return []
return sortByCreation(all_activities.data.calls)
} else if (props.title == 'Tasks') {
if (!all_activities.data?.tasks) return []
return sortByCreation(all_activities.data.tasks)
} else if (props.title == 'Notes') {
if (!all_activities.data?.notes) return []
return sortByCreation(all_activities.data.notes)
}
activities.forEach((activity) => {
activity.icon = timelineIcon(activity.activity_type, activity.is_lead)
if (
activity.activity_type == 'incoming_call' ||
activity.activity_type == 'outgoing_call' ||
activity.activity_type == 'communication'
)
return
update_activities_details(activity)
if (activity.other_versions) {
activity.show_others = false
activity.other_versions.forEach((other_version) => {
update_activities_details(other_version)
})
}
})
return sortByCreation(activities)
})
function sortByCreation(list) {
return list.sort((a, b) => new Date(a.creation) - new Date(b.creation))
}
function update_activities_details(activity) {
activity.owner_name = getUser(activity.owner).full_name
activity.type = ''
activity.value = ''
activity.to = ''
if (activity.activity_type == 'creation') {
activity.type = activity.data
} else if (activity.activity_type == 'added') {
activity.type = 'added'
activity.value = 'as'
} else if (activity.activity_type == 'removed') {
activity.type = 'removed'
activity.value = 'value'
} else if (activity.activity_type == 'changed') {
activity.type = 'changed'
activity.value = 'from'
activity.to = 'to'
}
}
const emptyText = computed(() => {
let text = 'No Activities'
if (props.title == 'Emails') {
text = 'No Email Communications'
} else if (props.title == 'Comments') {
text = 'No Comments'
} else if (props.title == 'Calls') {
text = 'No Call Logs'
} else if (props.title == 'Notes') {
text = 'No Notes'
} else if (props.title == 'Tasks') {
text = 'No Tasks'
} else if (props.title == 'WhatsApp') {
text = 'No WhatsApp Messages'
}
return text
})
const emptyTextIcon = computed(() => {
let icon = ActivityIcon
if (props.title == 'Emails') {
icon = Email2Icon
} else if (props.title == 'Comments') {
icon = CommentIcon
} else if (props.title == 'Calls') {
icon = PhoneIcon
} else if (props.title == 'Notes') {
icon = NoteIcon
} else if (props.title == 'Tasks') {
icon = TaskIcon
} else if (props.title == 'WhatsApp') {
icon = WhatsAppIcon
}
return h(icon, { class: 'text-gray-500' })
})
function timelineIcon(activity_type, is_lead) {
let icon
switch (activity_type) {
case 'creation':
icon = is_lead ? LeadsIcon : DealsIcon
break
case 'deal':
icon = DealsIcon
break
case 'comment':
icon = CommentIcon
break
case 'incoming_call':
icon = InboundCallIcon
break
case 'outgoing_call':
icon = OutboundCallIcon
break
default:
icon = DotIcon
}
return markRaw(icon)
}
const emailBox = ref(null)
const whatsappBox = ref(null)
watch([reload, reload_email], ([reload_value, reload_email_value]) => {
if (reload_value || reload_email_value) {
all_activities.reload()
reload.value = false
reload_email.value = false
}
})
function scroll(hash) {
setTimeout(() => {
let el
if (!hash) {
let e = document.getElementsByClassName('activity')
el = e[e.length - 1]
} else {
el = document.getElementById(hash)
}
if (el && !useElementVisibility(el).value) {
el.scrollIntoView({ behavior: 'smooth' })
el.focus()
}
}, 500)
}
defineExpose({ emailBox })
const route = useRoute()
nextTick(() => {
const hash = route.hash.slice(1) || null
scroll(hash)
})
</script>
|
2302_79757062/crm
|
frontend/src/components/Activities/Activities.vue
|
Vue
|
agpl-3.0
| 23,902
|
<template>
<div
class="mx-4 my-3 flex items-center justify-between text-lg font-medium sm:mx-10 sm:mb-4 sm:mt-8"
>
<div class="flex h-8 items-center text-xl font-semibold text-gray-800">
{{ __(title) }}
</div>
<Button
v-if="title == 'Emails'"
variant="solid"
@click="emailBox.show = true"
>
<template #prefix>
<FeatherIcon name="plus" class="h-4 w-4" />
</template>
<span>{{ __('New Email') }}</span>
</Button>
<Button
v-else-if="title == 'Comments'"
variant="solid"
@click="emailBox.showComment = true"
>
<template #prefix>
<FeatherIcon name="plus" class="h-4 w-4" />
</template>
<span>{{ __('New Comment') }}</span>
</Button>
<Button
v-else-if="title == 'Calls'"
variant="solid"
@click="makeCall(doc.data.mobile_no)"
>
<template #prefix>
<PhoneIcon class="h-4 w-4" />
</template>
<span>{{ __('Make a Call') }}</span>
</Button>
<Button
v-else-if="title == 'Notes'"
variant="solid"
@click="modalRef.showNote()"
>
<template #prefix>
<FeatherIcon name="plus" class="h-4 w-4" />
</template>
<span>{{ __('New Note') }}</span>
</Button>
<Button
v-else-if="title == 'Tasks'"
variant="solid"
@click="modalRef.showTask()"
>
<template #prefix>
<FeatherIcon name="plus" class="h-4 w-4" />
</template>
<span>{{ __('New Task') }}</span>
</Button>
<div class="flex gap-2 shrink-0" v-else-if="title == 'WhatsApp'">
<Button
:label="__('Send Template')"
@click="showWhatsappTemplates = true"
/>
<Button variant="solid" @click="whatsappBox.show()">
<template #prefix>
<FeatherIcon name="plus" class="h-4 w-4" />
</template>
<span>{{ __('New Message') }}</span>
</Button>
</div>
<Dropdown v-else :options="defaultActions" @click.stop>
<template v-slot="{ open }">
<Button variant="solid" class="flex items-center gap-1">
<template #prefix>
<FeatherIcon name="plus" class="h-4 w-4" />
</template>
<span>{{ __('New') }}</span>
<template #suffix>
<FeatherIcon
:name="open ? 'chevron-up' : 'chevron-down'"
class="h-4 w-4"
/>
</template>
</Button>
</template>
</Dropdown>
</div>
</template>
<script setup>
import Email2Icon from '@/components/Icons/Email2Icon.vue'
import CommentIcon from '@/components/Icons/CommentIcon.vue'
import PhoneIcon from '@/components/Icons/PhoneIcon.vue'
import NoteIcon from '@/components/Icons/NoteIcon.vue'
import TaskIcon from '@/components/Icons/TaskIcon.vue'
import WhatsAppIcon from '@/components/Icons/WhatsAppIcon.vue'
import { globalStore } from '@/stores/global'
import { whatsappEnabled, callEnabled } from '@/composables/settings'
import { Dropdown } from 'frappe-ui'
import { computed, h } from 'vue'
const props = defineProps({
tabs: Array,
title: String,
doc: Object,
modalRef: Object,
emailBox: Object,
whatsappBox: Object,
})
const { makeCall } = globalStore()
const tabIndex = defineModel()
const showWhatsappTemplates = defineModel('showWhatsappTemplates')
const defaultActions = computed(() => {
let actions = [
{
icon: h(Email2Icon, { class: 'h-4 w-4' }),
label: __('New Email'),
onClick: () => (props.emailBox.show = true),
},
{
icon: h(CommentIcon, { class: 'h-4 w-4' }),
label: __('New Comment'),
onClick: () => (props.emailBox.showComment = true),
},
{
icon: h(PhoneIcon, { class: 'h-4 w-4' }),
label: __('Make a Call'),
onClick: () => makeCall(props.doc.data.mobile_no),
condition: () => callEnabled.value,
},
{
icon: h(NoteIcon, { class: 'h-4 w-4' }),
label: __('New Note'),
onClick: () => props.modalRef.showNote(),
},
{
icon: h(TaskIcon, { class: 'h-4 w-4' }),
label: __('New Task'),
onClick: () => props.modalRef.showTask(),
},
{
icon: h(WhatsAppIcon, { class: 'h-4 w-4' }),
label: __('New WhatsApp Message'),
onClick: () => (tabIndex.value = getTabIndex('WhatsApp')),
condition: () => whatsappEnabled.value,
},
]
return actions.filter((action) =>
action.condition ? action.condition() : true,
)
})
function getTabIndex(name) {
return props.tabs.findIndex((tab) => tab.name === name)
}
</script>
|
2302_79757062/crm
|
frontend/src/components/Activities/ActivityHeader.vue
|
Vue
|
agpl-3.0
| 4,567
|
<template>
<TaskModal
v-model="showTaskModal"
v-model:reloadTasks="activities"
:task="task"
:doctype="doctype"
:doc="doc.data?.name"
/>
<NoteModal
v-model="showNoteModal"
v-model:reloadNotes="activities"
:note="note"
:doctype="doctype"
:doc="doc.data?.name"
/>
</template>
<script setup>
import TaskModal from '@/components/Modals/TaskModal.vue'
import NoteModal from '@/components/Modals/NoteModal.vue'
import { call } from 'frappe-ui'
import { ref } from 'vue'
const props = defineProps({
doctype: String,
})
const activities = defineModel()
const doc = defineModel('doc')
// Tasks
const showTaskModal = ref(false)
const task = ref({})
function showTask(t) {
task.value = t || {
title: '',
description: '',
assigned_to: '',
due_date: '',
priority: 'Low',
status: 'Backlog',
}
showTaskModal.value = true
}
async function deleteTask(name) {
await call('frappe.client.delete', {
doctype: 'CRM Task',
name,
})
activities.value.reload()
}
function updateTaskStatus(status, task) {
call('frappe.client.set_value', {
doctype: 'CRM Task',
name: task.name,
fieldname: 'status',
value: status,
}).then(() => {
activities.value.reload()
})
}
// Notes
const showNoteModal = ref(false)
const note = ref({})
function showNote(n) {
note.value = n || {
title: '',
content: '',
}
showNoteModal.value = true
}
defineExpose({
showTask,
deleteTask,
updateTaskStatus,
showNote,
})
</script>
|
2302_79757062/crm
|
frontend/src/components/Activities/AllModals.vue
|
Vue
|
agpl-3.0
| 1,523
|
<template>
<div class="w-full text-sm text-gray-600">
<div class="flex items-center gap-2">
<Button variant="ghost" @click="playPause">
<template #icon>
<PlayIcon v-if="isPaused" class="size-4 text-gray-600" />
<PauseIcon v-else class="size-4 text-gray-600" />
</template>
</Button>
<div class="flex gap-2 items-center justify-between flex-1">
<input
class="w-full slider !h-[0.5] bg-gray-200 [&::-webkit-slider-thumb]:shadow [&::-webkit-slider-thumb:hover]:outline [&::-webkit-slider-thumb:hover]:outline-[0.5px]"
:style="{
background: `linear-gradient(to right, #171717 ${progress}%, #ededed ${progress}%)`,
}"
type="range"
id="track"
min="0"
:max="duration"
:value="currentTime"
step="0.01"
@input="(e) => (audio.currentTime = e.target.value)"
/>
<div class="shrink-0">
{{ formatTime(currentTime) }} / {{ formatTime(duration) }}
</div>
</div>
<div class="flex items-center gap-1">
<div class="flex group gap-2 items-center">
<input
class="slider opacity-0 group-hover:opacity-100 w-0 group-hover:w-20 !h-[0.5] [&::-webkit-slider-thumb]:shadow [&::-webkit-slider-thumb:hover]:outline [&::-webkit-slider-thumb:hover]:outline-[0.5px]"
:style="{
background: `linear-gradient(to right, #171717 ${volumnProgress}%, #ededed ${volumnProgress}%)`,
}"
type="range"
id="volume"
min="0"
max="1"
:value="currentVolumn"
step="0.01"
@input="(e) => updateVolumnProgress(e.target.value)"
/>
<Button variant="ghost">
<template #icon>
<MuteIcon
v-if="volumnProgress == 0"
class="size-4"
@click="updateVolumnProgress('1')"
/>
<VolumnLowIcon
v-else-if="volumnProgress <= 40"
class="size-4"
@click="updateVolumnProgress('0')"
/>
<VolumnHighIcon
v-else-if="volumnProgress > 20"
class="size-4"
@click="updateVolumnProgress('0')"
/>
</template>
</Button>
</div>
<Dropdown :options="options">
<Button variant="ghost" @click="showPlaybackSpeed = false">
<template #icon>
<FeatherIcon class="size-4" name="more-horizontal" />
</template>
</Button>
</Dropdown>
</div>
</div>
<audio
ref="audio"
:src="src"
crossorigin="anonymous"
@loadedmetadata="setupDuration"
@timeupdate="updateCurrentTime"
@ended="isPaused = true"
></audio>
</div>
</template>
<script setup>
import PlayIcon from '@/components/Icons/PlayIcon.vue'
import PauseIcon from '@/components/Icons/PauseIcon.vue'
import VolumnLowIcon from '@/components/Icons/VolumnLowIcon.vue'
import VolumnHighIcon from '@/components/Icons/VolumnHighIcon.vue'
import MuteIcon from '@/components/Icons/MuteIcon.vue'
import PlaybackSpeedIcon from '@/components/Icons/PlaybackSpeedIcon.vue'
import PlaybackSpeedOption from '@/components/Activities/PlaybackSpeedOption.vue'
import Dropdown from '@/components/frappe-ui/Dropdown.vue'
import { computed, h, ref } from 'vue'
const props = defineProps({
src: String,
})
const audio = ref(null)
const isPaused = ref(true)
const duration = ref(0)
const currentTime = ref(0)
const progress = computed(() => (currentTime.value / duration.value) * 100)
const currentVolumn = ref(1)
const volumnProgress = ref(100)
function setupDuration() {
duration.value = audio.value.duration
}
function updateCurrentTime() {
currentTime.value = audio.value.currentTime
}
function playPause() {
if (audio.value.paused) {
audio.value.play()
isPaused.value = false
} else {
audio.value.pause()
isPaused.value = true
}
}
function formatTime(time) {
if (isNaN(time)) return '00:00'
const minutes = Math.floor(time / 60)
const seconds = Math.floor(time % 60)
return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
}
function updateVolumnProgress(value) {
audio.value.volume = value
currentVolumn.value = value
volumnProgress.value = value * 100
}
const showPlaybackSpeed = ref(false)
const currentPlaybackSpeed = ref(1)
const options = computed(() => {
let playbackSpeeds = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2]
let playbackSpeedOptions = playbackSpeeds.map((speed) => {
let label = `${speed}x`
if (speed === 1) {
label = __('Normal')
}
return {
component: () =>
h(PlaybackSpeedOption, {
label,
active: speed === currentPlaybackSpeed.value,
onClick: () => {
audio.value.playbackRate = speed
showPlaybackSpeed.value = false
currentPlaybackSpeed.value = speed
},
}),
}
})
let _options = [
{
icon: 'download',
label: __('Download'),
onClick: () => {
const a = document.createElement('a')
a.href = props.src
a.download = props.src.split('/').pop()
a.click()
},
},
{
icon: () => h(PlaybackSpeedIcon, { class: 'size-4' }),
label: __('Playback speed'),
onClick: (e) => {
e.preventDefault()
e.stopPropagation()
showPlaybackSpeed.value = true
},
},
]
return showPlaybackSpeed.value ? playbackSpeedOptions : _options
})
</script>
<style scoped>
.slider {
--trackHeight: 2px;
--thumbRadius: 14px;
-webkit-appearance: none;
appearance: none;
background: transparent;
padding: 0;
margin: 0;
border-radius: 100px;
cursor: pointer;
}
.slider::-webkit-slider-runnable-track {
appearance: none;
height: var(--trackHeight);
border-radius: 100px;
}
.slider:focus-visible {
outline: none;
}
.slider::-webkit-slider-thumb {
width: var(--thumbRadius);
height: var(--thumbRadius);
margin-top: calc((var(--trackHeight) - var(--thumbRadius)) / 2);
background: #fff;
border-radius: 100px;
pointer-events: all;
appearance: none;
z-index: 1;
}
.slider::-webkit-slider-thumb {
width: var(--thumbRadius);
height: var(--thumbRadius);
margin-top: calc((var(--trackHeight) - var(--thumbRadius)) / 2);
background: #fff;
border-radius: 100px;
pointer-events: all;
appearance: none;
z-index: 1;
}
</style>
|
2302_79757062/crm
|
frontend/src/components/Activities/AudioPlayer.vue
|
Vue
|
agpl-3.0
| 6,610
|
<template>
<div>
<div class="mb-1 flex items-center justify-stretch gap-2 py-1 text-base">
<div class="inline-flex items-center flex-wrap gap-1 text-gray-600">
<Avatar
:image="activity.caller.image"
:label="activity.caller.label"
size="md"
/>
<span class="font-medium text-gray-800 ml-1">
{{ activity.caller.label }}
</span>
<span>{{
activity.type == 'Incoming'
? __('has reached out')
: __('has made a call')
}}</span>
</div>
<div class="ml-auto whitespace-nowrap">
<Tooltip :text="dateFormat(activity.creation, dateTooltipFormat)">
<div class="text-sm text-gray-600">
{{ __(timeAgo(activity.creation)) }}
</div>
</Tooltip>
</div>
</div>
<div
class="flex flex-col gap-2 border border-gray-200 rounded-md bg-white px-3 py-2.5"
>
<div class="flex items-center justify-between">
<div class="inline-flex gap-2 items-center text-base font-medium">
<div>
{{
activity.type == 'Incoming'
? __('Inbound Call')
: __('Outbound Call')
}}
</div>
</div>
<div>
<MultipleAvatar
:avatars="[
{
image: activity.caller.image,
label: activity.caller.label,
name: activity.caller.label,
},
{
image: activity.receiver.image,
label: activity.receiver.label,
name: activity.receiver.label,
},
]"
size="sm"
/>
</div>
</div>
<div class="flex items-center flex-wrap gap-2">
<Badge :label="dateFormat(activity.creation, 'MMM D, dddd')">
<template #prefix>
<CalendarIcon class="size-3" />
</template>
</Badge>
<Badge v-if="activity.status == 'Completed'" :label="activity.duration">
<template #prefix>
<DurationIcon class="size-3" />
</template>
</Badge>
<Badge
v-if="activity.recording_url"
:label="activity.show_recording ? __('Hide Recording') : __('Listen')"
class="cursor-pointer"
@click="activity.show_recording = !activity.show_recording"
>
<template #prefix>
<PlayIcon class="size-3" />
</template>
</Badge>
<Badge
:label="statusLabelMap[activity.status]"
:theme="statusColorMap[activity.status]"
/>
</div>
<div
v-if="activity.show_recording && activity.recording_url"
class="flex flex-col items-center justify-between"
>
<AudioPlayer :src="activity.recording_url" />
</div>
</div>
</div>
</template>
<script setup>
import PlayIcon from '@/components/Icons/PlayIcon.vue'
import CalendarIcon from '@/components/Icons/CalendarIcon.vue'
import DurationIcon from '@/components/Icons/DurationIcon.vue'
import MultipleAvatar from '@/components/MultipleAvatar.vue'
import AudioPlayer from '@/components/Activities/AudioPlayer.vue'
import { statusLabelMap, statusColorMap } from '@/utils/callLog.js'
import { dateFormat, timeAgo, dateTooltipFormat } from '@/utils'
import { Avatar, Badge, Tooltip } from 'frappe-ui'
const props = defineProps({
activity: Object,
})
</script>
|
2302_79757062/crm
|
frontend/src/components/Activities/CallArea.vue
|
Vue
|
agpl-3.0
| 3,497
|
<template>
<div :id="activity.name">
<div class="mb-1 flex items-center justify-stretch gap-2 py-1 text-base">
<div class="inline-flex items-center flex-wrap gap-1 text-gray-600">
<UserAvatar class="mr-1" :user="activity.owner" size="md" />
<span class="font-medium text-gray-800">
{{ activity.owner_name }}
</span>
<span>{{ __('added a') }}</span>
<span class="max-w-xs truncate font-medium text-gray-800">
{{ __('comment') }}
</span>
</div>
<div class="ml-auto whitespace-nowrap">
<Tooltip :text="dateFormat(activity.creation, dateTooltipFormat)">
<div class="text-sm text-gray-600">
{{ __(timeAgo(activity.creation)) }}
</div>
</Tooltip>
</div>
</div>
<div
class="cursor-pointer rounded bg-gray-50 px-3 py-[7.5px] text-base leading-6 transition-all duration-300 ease-in-out"
>
<div class="prose-f" v-html="activity.content" />
<div v-if="activity.attachments.length" class="mt-2 flex flex-wrap gap-2">
<AttachmentItem
v-for="a in activity.attachments"
:key="a.file_url"
:label="a.file_name"
:url="a.file_url"
/>
</div>
</div>
</div>
</template>
<script setup>
import UserAvatar from '@/components/UserAvatar.vue'
import AttachmentItem from '@/components/AttachmentItem.vue'
import { Tooltip } from 'frappe-ui'
import { timeAgo, dateFormat, dateTooltipFormat } from '@/utils'
const props = defineProps({
activity: Object,
})
</script>
|
2302_79757062/crm
|
frontend/src/components/Activities/CommentArea.vue
|
Vue
|
agpl-3.0
| 1,583
|
<template>
<div
class="cursor-pointer flex flex-col rounded-md shadow bg-white px-3 py-1.5 text-base transition-all duration-300 ease-in-out"
>
<div class="-mb-0.5 flex items-center justify-between gap-2 truncate">
<div class="flex items-center gap-2 truncate">
<span>{{ activity.data.sender_full_name }}</span>
<span class="sm:flex hidden text-sm text-gray-600">
{{ '<' + activity.data.sender + '>' }}
</span>
<Badge
v-if="activity.communication_type == 'Automated Message'"
:label="__('Notification')"
variant="subtle"
theme="green"
/>
</div>
<div class="flex items-center gap-2 shrink-0">
<Tooltip :text="dateFormat(activity.creation, dateTooltipFormat)">
<div class="text-sm text-gray-600">
{{ __(timeAgo(activity.creation)) }}
</div>
</Tooltip>
<div class="flex gap-0.5">
<Tooltip :text="__('Reply')">
<div>
<Button
variant="ghost"
class="text-gray-700"
@click="reply(activity.data)"
>
<template #icon>
<ReplyIcon />
</template>
</Button>
</div>
</Tooltip>
<Tooltip :text="__('Reply All')">
<div>
<Button
variant="ghost"
class="text-gray-700"
@click="reply(activity.data, true)"
>
<template #icon>
<ReplyAllIcon />
</template>
</Button>
</div>
</Tooltip>
</div>
</div>
</div>
<div class="flex flex-col gap-1 text-base leading-5 text-gray-800">
<div>{{ activity.data.subject }}</div>
<div>
<span class="mr-1 text-gray-600"> {{ __('To') }}: </span>
<span>{{ activity.data.recipients }}</span>
<span v-if="activity.data.cc">, </span>
<span v-if="activity.data.cc" class="mr-1 text-gray-600">
{{ __('CC') }}:
</span>
<span v-if="activity.data.cc">{{ activity.data.cc }}</span>
<span v-if="activity.data.bcc">, </span>
<span v-if="activity.data.bcc" class="mr-1 text-gray-600">
{{ __('BCC') }}:
</span>
<span v-if="activity.data.bcc">{{ activity.data.bcc }}</span>
</div>
</div>
<div class="border-0 border-t mt-3 mb-1 border-gray-200" />
<EmailContent :content="activity.data.content" />
<div v-if="activity.data?.attachments?.length" class="flex flex-wrap gap-2">
<AttachmentItem
v-for="a in activity.data.attachments"
:key="a.file_url"
:label="a.file_name"
:url="a.file_url"
/>
</div>
</div>
</template>
<script setup>
import ReplyIcon from '@/components/Icons/ReplyIcon.vue'
import ReplyAllIcon from '@/components/Icons/ReplyAllIcon.vue'
import AttachmentItem from '@/components/AttachmentItem.vue'
import EmailContent from '@/components/Activities/EmailContent.vue'
import { Badge, Tooltip } from 'frappe-ui'
import { timeAgo, dateFormat, dateTooltipFormat } from '@/utils'
const props = defineProps({
activity: Object,
emailBox: Object,
})
function reply(email, reply_all = false) {
props.emailBox.show = true
let editor = props.emailBox.editor
let message = email.content
let recipients = email.recipients.split(',').map((r) => r.trim())
editor.toEmails = [email.sender]
editor.cc = editor.bcc = false
editor.ccEmails = []
editor.bccEmails = []
if (!email.subject.startsWith('Re:')) {
editor.subject = `Re: ${email.subject}`
} else {
editor.subject = email.subject
}
if (reply_all) {
let cc = email.cc?.split(',').map((r) => r.trim())
let bcc = email.bcc?.split(',').map((r) => r.trim())
if (cc?.length) {
recipients = recipients.filter((r) => !cc?.includes(r))
cc.push(...recipients)
} else {
cc = recipients
}
editor.cc = cc ? true : false
editor.bcc = bcc ? true : false
editor.ccEmails = cc
editor.bccEmails = bcc
}
let repliedMessage = `<blockquote>${message}</blockquote>`
editor.editor
.chain()
.clearContent()
.insertContent('<p>.</p>')
.updateAttributes('paragraph', { class: 'reply-to-content' })
.insertContent(repliedMessage)
.focus('all')
.insertContentAt(0, { type: 'paragraph' })
.focus('start')
.run()
}
</script>
|
2302_79757062/crm
|
frontend/src/components/Activities/EmailArea.vue
|
Vue
|
agpl-3.0
| 4,528
|
<template>
<iframe
ref="iframeRef"
:srcdoc="htmlContent"
class="prose-f block h-10 max-h-[500px] w-full"
/>
</template>
<script setup>
import { ref, watch } from 'vue'
const props = defineProps({
content: {
type: String,
required: true,
},
})
const files = import.meta.globEager('/src/index.css', { query: '?inline' })
const css = files['/src/index.css'].default
const iframeRef = ref(null)
const _content = ref(props.content)
const parser = new DOMParser()
const doc = parser.parseFromString(_content.value, 'text/html')
const gmailReplyToContent = doc.querySelectorAll('div.gmail_quote')
const outlookReplyToContent = doc.querySelectorAll('div#appendonsend')
const replyToContent = doc.querySelectorAll('p.reply-to-content')
if (gmailReplyToContent.length) {
_content.value = parseReplyToContent(doc, 'div.gmail_quote', true)
} else if (outlookReplyToContent.length) {
_content.value = parseReplyToContent(doc, 'div#appendonsend')
} else if (replyToContent.length) {
_content.value = parseReplyToContent(doc, 'p.reply-to-content')
}
function parseReplyToContent(doc, selector, forGmail = false) {
function handleAllInstances(doc) {
const replyToContentElements = doc.querySelectorAll(selector)
if (replyToContentElements.length === 0) return
const replyToContentElement = replyToContentElements[0]
replaceReplyToContent(replyToContentElement, forGmail)
handleAllInstances(doc)
}
handleAllInstances(doc)
return doc.body.innerHTML
}
function replaceReplyToContent(replyToContentElement, forGmail) {
if (!replyToContentElement) return
let randomId = Math.random().toString(36).substring(2, 7)
const wrapper = doc.createElement('div')
wrapper.classList.add('replied-content')
const collapseLabel = doc.createElement('label')
collapseLabel.classList.add('collapse')
collapseLabel.setAttribute('for', randomId)
collapseLabel.innerHTML = '...'
wrapper.appendChild(collapseLabel)
const collapseInput = doc.createElement('input')
collapseInput.setAttribute('id', randomId)
collapseInput.setAttribute('class', 'replyCollapser')
collapseInput.setAttribute('type', 'checkbox')
wrapper.appendChild(collapseInput)
if (forGmail) {
const prevSibling = replyToContentElement.previousElementSibling
if (prevSibling && prevSibling.tagName === 'BR') {
prevSibling.remove()
}
let cloned = replyToContentElement.cloneNode(true)
cloned.classList.remove('gmail_quote')
wrapper.appendChild(cloned)
} else {
const allSiblings = Array.from(replyToContentElement.parentElement.children)
const replyToContentIndex = allSiblings.indexOf(replyToContentElement)
const followingSiblings = allSiblings.slice(replyToContentIndex + 1)
if (followingSiblings.length === 0) return
let clonedFollowingSiblings = followingSiblings.map((sibling) =>
sibling.cloneNode(true),
)
const div = doc.createElement('div')
div.append(...clonedFollowingSiblings)
wrapper.append(div)
// Remove all siblings after the reply-to-content element
for (let i = replyToContentIndex + 1; i < allSiblings.length; i++) {
replyToContentElement.parentElement.removeChild(allSiblings[i])
}
}
replyToContentElement.parentElement.replaceChild(
wrapper,
replyToContentElement,
)
}
const htmlContent = `
<!DOCTYPE html>
<html>
<head>
<style>
${css}
.replied-content .collapse {
margin: 10px 0 10px 0;
visibility: visible;
cursor: pointer;
display: flex;
font-size: larger;
font-weight: 700;
height: 12px;
line-height: 0.1;
background: #e8eaed;
width: 23px;
justify-content: center;
border-radius: 5px;
}
.replied-content .collapse:hover {
background: #dadce0;
}
.replied-content .collapse + input {
display: none;
}
.replied-content .collapse + input + div {
display: none;
}
.replied-content .collapse + input:checked + div {
display: block;
}
.email-content {
word-break: break-word;
}
.email-content
:is(:where(table):not(:where([class~='not-prose'], [class~='not-prose']
*))) {
table-layout: auto;
}
.email-content
:where(table):not(:where([class~='not-prose'], [class~='not-prose'] *)) {
width: unset;
table-layout: auto;
text-align: unset;
margin-top: unset;
margin-bottom: unset;
font-size: unset;
line-height: unset;
}
/* tr */
.email-content
:where(tbody tr):not(:where([class~='not-prose'], [class~='not-prose']
*)) {
border-bottom-width: 0;
border-bottom-color: transparent;
}
/* td */
.email-content
:is(:where(td):not(:where([class~='not-prose'], [class~='not-prose'] *))) {
position: unset;
border-width: 0;
border-color: transparent;
padding: 0;
}
.email-content
:where(tbody td):not(:where([class~='not-prose'], [class~='not-prose']
*)) {
vertical-align: revert;
}
/* image */
.email-content
:is(:where(img):not(:where([class~='not-prose'], [class~='not-prose']
*))) {
border-width: 0;
}
.email-content
:where(img):not(:where([class~='not-prose'], [class~='not-prose'] *)) {
margin: 0;
}
/* before & after */
.email-content
:where(blockquote
p:first-of-type):not(:where([class~='not-prose'], [class~='not-prose']
*))::before {
content: none;
}
.email-content
:where(blockquote
p:last-of-type):not(:where([class~='not-prose'], [class~='not-prose']
*))::after {
content: none;
}
</style>
</head>
<body>
<div ref="emailContentRef" class="email-content prose-f">${_content.value}</div>
</body>
</html>
`
watch(iframeRef, (iframe) => {
if (iframe) {
iframe.onload = () => {
const emailContent =
iframe.contentWindow.document.querySelector('.email-content')
let parent = emailContent.closest('html')
iframe.style.height = parent.offsetHeight + 1 + 'px'
let replyCollapsers = emailContent.querySelectorAll('.replyCollapser')
if (replyCollapsers.length) {
replyCollapsers.forEach((replyCollapser) => {
replyCollapser.addEventListener('change', () => {
iframe.style.height = parent.offsetHeight + 1 + 'px'
})
})
}
}
}
})
</script>
|
2302_79757062/crm
|
frontend/src/components/Activities/EmailContent.vue
|
Vue
|
agpl-3.0
| 6,498
|
<template>
<div
class="activity group flex h-48 cursor-pointer flex-col justify-between gap-2 rounded-md bg-gray-50 px-4 py-3 hover:bg-gray-100"
>
<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
class="h-6 w-6"
>
<Button
icon="more-horizontal"
variant="ghosted"
class="!h-6 !w-6 hover:bg-gray-100"
/>
</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-1 flex items-center justify-between gap-2">
<div class="flex items-center gap-2 truncate">
<UserAvatar :user="note.owner" size="xs" />
<div
class="truncate text-sm text-gray-800"
:title="getUser(note.owner).full_name"
>
{{ getUser(note.owner).full_name }}
</div>
</div>
<Tooltip :text="dateFormat(note.modified, dateTooltipFormat)">
<div class="truncate text-sm text-gray-700">
{{ __(timeAgo(note.modified)) }}
</div>
</Tooltip>
</div>
</div>
</template>
<script setup>
import UserAvatar from '@/components/UserAvatar.vue'
import { timeAgo, dateFormat, dateTooltipFormat } from '@/utils'
import { Tooltip, Dropdown, TextEditor } from 'frappe-ui'
import { usersStore } from '@/stores/users'
const props = defineProps({
note: Object,
})
const notes = defineModel()
const { getUser } = usersStore()
async function deleteNote(name) {
await call('frappe.client.delete', {
doctype: 'FCRM Note',
name,
})
notes.reload()
}
</script>
|
2302_79757062/crm
|
frontend/src/components/Activities/NoteArea.vue
|
Vue
|
agpl-3.0
| 1,999
|
<template>
<div>
<Button
class="flex justify-between w-full rounded text-base"
variant="ghost"
:label="label"
@click="onClick"
>
<template v-if="active" #suffix>
<FeatherIcon class="size-4" name="check" />
</template>
</Button>
</div>
</template>
<script setup>
const props = defineProps({
label: String,
active: Boolean,
onClick: Array,
})
</script>
|
2302_79757062/crm
|
frontend/src/components/Activities/PlaybackSpeedOption.vue
|
Vue
|
agpl-3.0
| 417
|
<template>
<div v-if="tasks.length">
<div v-for="(task, i) in tasks">
<div
class="activity flex cursor-pointer gap-6 rounded p-2.5 duration-300 ease-in-out hover:bg-gray-50"
@click="modalRef.showTask(task)"
>
<div class="flex flex-1 flex-col gap-1.5 text-base">
<div class="font-medium text-gray-900">
{{ task.title }}
</div>
<div class="flex gap-1.5 text-gray-800">
<div class="flex items-center gap-1.5">
<UserAvatar :user="task.assigned_to" size="xs" />
{{ getUser(task.assigned_to).full_name }}
</div>
<div v-if="task.due_date" class="flex items-center justify-center">
<DotIcon class="h-2.5 w-2.5 text-gray-600" :radius="2" />
</div>
<div v-if="task.due_date">
<Tooltip
:text="dateFormat(task.due_date, 'ddd, MMM D, YYYY | hh:mm a')"
>
<div class="flex gap-2">
<CalendarIcon />
<div>{{ dateFormat(task.due_date, 'D MMM, hh:mm a') }}</div>
</div>
</Tooltip>
</div>
<div class="flex items-center justify-center">
<DotIcon class="h-2.5 w-2.5 text-gray-600" :radius="2" />
</div>
<div class="flex gap-2">
<TaskPriorityIcon class="!h-2 !w-2" :priority="task.priority" />
{{ task.priority }}
</div>
</div>
</div>
<div class="flex items-center gap-1">
<Dropdown
:options="taskStatusOptions(modalRef.updateTaskStatus, task)"
@click.stop
>
<Tooltip :text="__('Change Status')">
<Button variant="ghosted" class="hover:bg-gray-300">
<TaskStatusIcon :status="task.status" />
</Button>
</Tooltip>
</Dropdown>
<Dropdown
:options="[
{
label: __('Delete'),
icon: 'trash-2',
onClick: () => {
$dialog({
title: __('Delete Task'),
message: __('Are you sure you want to delete this task?'),
actions: [
{
label: __('Delete'),
theme: 'red',
variant: 'solid',
onClick(close) {
modalRef.deleteTask(task.name)
close()
},
},
],
})
},
},
]"
@click.stop
>
<Button
icon="more-horizontal"
variant="ghosted"
class="hover:bg-gray-300"
/>
</Dropdown>
</div>
</div>
<div
v-if="i < tasks.length - 1"
class="mx-2 h-px border-t border-gray-200"
/>
</div>
</div>
</template>
<script setup>
import CalendarIcon from '@/components/Icons/CalendarIcon.vue'
import TaskStatusIcon from '@/components/Icons/TaskStatusIcon.vue'
import TaskPriorityIcon from '@/components/Icons/TaskPriorityIcon.vue'
import DotIcon from '@/components/Icons/DotIcon.vue'
import UserAvatar from '@/components/UserAvatar.vue'
import { dateFormat, taskStatusOptions } from '@/utils'
import { usersStore } from '@/stores/users'
import { globalStore } from '@/stores/global'
import { Tooltip, Dropdown } from 'frappe-ui'
const props = defineProps({
tasks: Array,
modalRef: Object,
})
const { getUser } = usersStore()
const { $dialog } = globalStore()
</script>
|
2302_79757062/crm
|
frontend/src/components/Activities/TaskArea.vue
|
Vue
|
agpl-3.0
| 3,767
|
<template>
<div>
<div
v-for="whatsapp in messages"
:key="whatsapp.name"
class="activity group flex gap-2"
:class="[
whatsapp.type == 'Outgoing' ? 'flex-row-reverse' : '',
whatsapp.reaction ? 'mb-7' : 'mb-3',
]"
>
<div
:id="whatsapp.name"
class="group/message relative max-w-[90%] rounded-md bg-gray-50 p-1.5 pl-2 text-base shadow-sm"
>
<div
v-if="whatsapp.is_reply"
@click="() => scrollToMessage(whatsapp.reply_to)"
class="mb-1 cursor-pointer rounded border-0 border-l-4 bg-gray-200 p-2 text-gray-600"
:class="
whatsapp.reply_to_type == 'Incoming'
? 'border-green-500'
: 'border-blue-400'
"
>
<div
class="mb-1 text-sm font-bold"
:class="
whatsapp.reply_to_type == 'Incoming'
? 'text-green-500'
: 'text-blue-400'
"
>
{{ whatsapp.reply_to_from || __('You') }}
</div>
<div class="flex flex-col gap-2 max-h-12 overflow-hidden">
<div v-if="whatsapp.header" class="text-base font-semibold">
{{ whatsapp.header }}
</div>
<div v-html="formatWhatsAppMessage(whatsapp.reply_message)" />
<div v-if="whatsapp.footer" class="text-xs text-gray-600">
{{ whatsapp.footer }}
</div>
</div>
</div>
<div class="flex gap-2 justify-between">
<div
class="absolute -right-0.5 -top-0.5 flex cursor-pointer gap-1 rounded-full bg-white pb-2 pl-2 pr-1.5 pt-1.5 opacity-0 group-hover/message:opacity-100"
:style="{
background:
'radial-gradient(circle at 50% 50%, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 35%, rgba(238, 130, 238, 0) 100%)',
}"
>
<Dropdown :options="messageOptions(whatsapp)">
<FeatherIcon name="chevron-down" class="size-4 text-gray-600" />
</Dropdown>
</div>
<div
class="absolute -bottom-5 flex gap-1 rounded-full border bg-white p-1 pb-[3px] shadow-sm"
v-if="whatsapp.reaction"
>
<div class="flex size-4 items-center justify-center">
{{ whatsapp.reaction }}
</div>
</div>
<div
class="flex flex-col gap-2"
v-if="whatsapp.message_type == 'Template'"
>
<div v-if="whatsapp.header" class="text-base font-semibold">
{{ whatsapp.header }}
</div>
<div v-html="formatWhatsAppMessage(whatsapp.template)" />
<div v-if="whatsapp.footer" class="text-xs text-gray-600">
{{ whatsapp.footer }}
</div>
</div>
<div
v-else-if="whatsapp.content_type == 'text'"
v-html="formatWhatsAppMessage(whatsapp.message)"
/>
<div v-else-if="whatsapp.content_type == 'image'">
<img
:src="whatsapp.attach"
class="h-40 cursor-pointer rounded-md"
@click="() => openFileInAnotherTab(whatsapp.attach)"
/>
<div
v-if="!whatsapp.message.startsWith('/files/')"
class="mt-1.5"
v-html="formatWhatsAppMessage(whatsapp.message)"
/>
</div>
<div
v-else-if="whatsapp.content_type == 'document'"
class="flex items-center gap-2"
>
<DocumentIcon
class="size-10 cursor-pointer rounded-md text-gray-500"
@click="() => openFileInAnotherTab(whatsapp.attach)"
/>
<div class="text-gray-600">Document</div>
</div>
<div
v-else-if="whatsapp.content_type == 'audio'"
class="flex items-center gap-2"
>
<audio :src="whatsapp.attach" controls class="cursor-pointer" />
</div>
<div
v-else-if="whatsapp.content_type == 'video'"
class="flex-col items-center gap-2"
>
<video
:src="whatsapp.attach"
controls
class="h-40 cursor-pointer rounded-md"
/>
<div
v-if="!whatsapp.message.startsWith('/files/')"
class="mt-1.5"
v-html="formatWhatsAppMessage(whatsapp.message)"
/>
</div>
<div class="-mb-1 flex shrink-0 items-end gap-1 text-gray-600">
<Tooltip :text="dateFormat(whatsapp.creation, 'ddd, MMM D, YYYY')">
<div class="text-2xs">
{{ dateFormat(whatsapp.creation, 'hh:mm a') }}
</div>
</Tooltip>
<div v-if="whatsapp.type == 'Outgoing'">
<CheckIcon
v-if="['sent', 'Success'].includes(whatsapp.status)"
class="size-4"
/>
<DoubleCheckIcon
v-else-if="['read', 'delivered'].includes(whatsapp.status)"
class="size-4"
:class="{ 'text-blue-500': whatsapp.status == 'read' }"
/>
</div>
</div>
</div>
</div>
<div
class="flex items-center justify-center opacity-0 transition-all ease-in group-hover:opacity-100"
>
<IconPicker
v-model="emoji"
v-model:reaction="reaction"
v-slot="{ togglePopover }"
@update:modelValue="() => reactOnMessage(whatsapp.name, emoji)"
>
<Button
@click="() => (reaction = true) && togglePopover()"
class="rounded-full !size-6 mt-0.5"
>
<ReactIcon class="text-gray-400" />
</Button>
</IconPicker>
</div>
</div>
</div>
</template>
<script setup>
import IconPicker from '@/components/IconPicker.vue'
import CheckIcon from '@/components/Icons/CheckIcon.vue'
import DoubleCheckIcon from '@/components/Icons/DoubleCheckIcon.vue'
import DocumentIcon from '@/components/Icons/DocumentIcon.vue'
import ReactIcon from '@/components/Icons/ReactIcon.vue'
import { dateFormat } from '@/utils'
import { capture } from '@/telemetry'
import { Tooltip, Dropdown, createResource } from 'frappe-ui'
import { ref } from 'vue'
const props = defineProps({
messages: Array,
})
const list = defineModel()
function openFileInAnotherTab(url) {
window.open(url, '_blank')
}
function formatWhatsAppMessage(message) {
// if message contains _text_, make it italic
message = message.replace(/_(.*?)_/g, '<i>$1</i>')
// if message contains *text*, make it bold
message = message.replace(/\*(.*?)\*/g, '<b>$1</b>')
// if message contains ~text~, make it strikethrough
message = message.replace(/~(.*?)~/g, '<s>$1</s>')
// if message contains ```text```, make it monospace
message = message.replace(/```(.*?)```/g, '<code>$1</code>')
// if message contains `text`, make it inline code
message = message.replace(/`(.*?)`/g, '<code>$1</code>')
// if message contains > text, make it a blockquote
message = message.replace(/^> (.*)$/gm, '<blockquote>$1</blockquote>')
// if contain /n, make it a new line
message = message.replace(/\n/g, '<br>')
// if contains *<space>text, make it a bullet point
message = message.replace(/\* (.*?)(?=\s*\*|$)/g, '<li>$1</li>')
message = message.replace(/- (.*?)(?=\s*-|$)/g, '<li>$1</li>')
message = message.replace(/(\d+)\. (.*?)(?=\s*(\d+)\.|$)/g, '<li>$2</li>')
return message
}
const emoji = ref('')
const reaction = ref(true)
function reactOnMessage(name, emoji) {
createResource({
url: 'crm.api.whatsapp.react_on_whatsapp_message',
params: {
emoji,
reply_to_name: name,
},
auto: true,
onSuccess() {
capture('whatsapp_react_on_message')
list.value.reload()
},
})
}
const reply = defineModel('reply')
const replyMode = ref(false)
function messageOptions(message) {
return [
{
label: 'Reply',
onClick: () => {
replyMode.value = true
reply.value = {
...message,
message: formatWhatsAppMessage(message.message)
}
},
},
// {
// label: 'Forward',
// onClick: () => console.log('Forward'),
// },
// {
// label: 'Delete',
// onClick: () => console.log('Delete'),
// },
]
}
function scrollToMessage(name) {
const element = document.getElementById(name)
element.scrollIntoView({ behavior: 'smooth' })
// Highlight the message
element.classList.add('bg-yellow-100')
setTimeout(() => {
element.classList.remove('bg-yellow-100')
}, 1000)
}
</script>
|
2302_79757062/crm
|
frontend/src/components/Activities/WhatsAppArea.vue
|
Vue
|
agpl-3.0
| 8,817
|
<template>
<div
v-if="reply?.message"
class="flex items-center justify-around gap-2 px-3 pt-2 sm:px-10"
>
<div
class="mb-1 ml-13 flex-1 cursor-pointer rounded border-0 border-l-4 border-green-500 bg-gray-100 p-2 text-base text-gray-600"
:class="reply.type == 'Incoming' ? 'border-green-500' : 'border-blue-400'"
>
<div
class="mb-1 text-sm font-bold"
:class="reply.type == 'Incoming' ? 'text-green-500' : 'text-blue-400'"
>
{{ reply.from_name || __('You') }}
</div>
<div class="max-h-12 overflow-hidden" v-html="reply.message" />
</div>
<Button variant="ghost" icon="x" @click="reply = {}" />
</div>
<div class="flex items-end gap-2 px-3 py-2.5 sm:px-10" v-bind="$attrs">
<div class="flex h-8 items-center gap-2">
<FileUploader @success="(file) => uploadFile(file)">
<template v-slot="{ openFileSelector }">
<div class="flex items-center space-x-2">
<Dropdown :options="uploadOptions(openFileSelector)">
<FeatherIcon
name="plus"
class="size-4.5 cursor-pointer text-gray-600"
/>
</Dropdown>
</div>
</template>
</FileUploader>
<IconPicker
v-model="emoji"
v-slot="{ togglePopover }"
@update:modelValue="
() => {
content += emoji
$refs.textarea.$el.focus()
capture('whatsapp_emoji_added')
}
"
>
<SmileIcon
@click="togglePopover"
class="flex size-4.5 cursor-pointer rounded-sm text-xl leading-none text-gray-500"
/>
</IconPicker>
</div>
<Textarea
ref="textarea"
type="textarea"
class="min-h-8 w-full"
:rows="rows"
v-model="content"
:placeholder="placeholder"
@focus="rows = 6"
@blur="rows = 1"
@keydown.enter="(e) => sendTextMessage(e)"
/>
</div>
</template>
<script setup>
import IconPicker from '@/components/IconPicker.vue'
import SmileIcon from '@/components/Icons/SmileIcon.vue'
import { capture } from '@/telemetry'
import { createResource, Textarea, FileUploader, Dropdown } from 'frappe-ui'
import { ref, nextTick, watch } from 'vue'
const props = defineProps({
doctype: String,
})
const doc = defineModel()
const whatsapp = defineModel('whatsapp')
const reply = defineModel('reply')
const rows = ref(1)
const textarea = ref(null)
const emoji = ref('')
const content = ref('')
const placeholder = ref(__('Type your message here...'))
const fileType = ref('')
function show() {
nextTick(() => textarea.value.$el.focus())
}
function uploadFile(file) {
whatsapp.value.attach = file.file_url
whatsapp.value.content_type = fileType.value
sendWhatsAppMessage()
capture('whatsapp_upload_file')
}
function sendTextMessage(event) {
if (event.shiftKey) return
sendWhatsAppMessage()
textarea.value.$el.blur()
content.value = ''
capture('whatsapp_send_message')
}
async function sendWhatsAppMessage() {
let args = {
reference_doctype: props.doctype,
reference_name: doc.value.data.name,
message: content.value,
to: doc.value.data.mobile_no,
attach: whatsapp.value.attach || '',
reply_to: reply.value?.name || '',
content_type: whatsapp.value.content_type,
}
content.value = ''
fileType.value = ''
whatsapp.value.attach = ''
whatsapp.value.content_type = 'text'
reply.value = {}
createResource({
url: 'crm.api.whatsapp.create_whatsapp_message',
params: args,
auto: true,
})
}
function uploadOptions(openFileSelector) {
return [
{
label: __('Upload Document'),
icon: 'file',
onClick: () => {
fileType.value = 'document'
openFileSelector()
},
},
{
label: __('Upload Image'),
icon: 'image',
onClick: () => {
fileType.value = 'image'
openFileSelector('image/*')
},
},
{
label: __('Upload Video'),
icon: 'video',
onClick: () => {
fileType.value = 'video'
openFileSelector('video/*')
},
},
]
}
watch(reply, (value) => {
if (value?.message) {
show()
}
})
defineExpose({ show })
</script>
|
2302_79757062/crm
|
frontend/src/components/Activities/WhatsAppBox.vue
|
Vue
|
agpl-3.0
| 4,256
|
<template>
<Popover placement="right-start" class="flex w-full">
<template #target="{ togglePopover }">
<button
:class="[
active ? 'bg-gray-100' : 'text-gray-800',
'group w-full flex h-7 items-center justify-between rounded px-2 text-base hover:bg-gray-100',
]"
@click.prevent="togglePopover()"
>
<div class="flex gap-2">
<AppsIcon class="size-4" />
<span class="whitespace-nowrap">
{{ __('Apps') }}
</span>
</div>
<FeatherIcon name="chevron-right" class="size-4 text-gray-600" />
</button>
</template>
<template #body>
<div
class="grid grid-cols-3 justify-between mx-3 p-2 rounded-lg border border-gray-100 bg-white shadow-xl"
>
<div v-for="app in apps.data" :key="app.name">
<a
:href="app.route"
class="flex flex-col gap-1.5 rounded justify-center items-center py-2 px-1 hover:bg-gray-100"
>
<img class="size-8" :src="app.logo" />
<div class="text-sm text-gray-700" @click="app.onClick">
{{ app.title }}
</div>
</a>
</div>
</div>
</template>
</Popover>
</template>
<script setup>
import AppsIcon from '@/components/Icons/AppsIcon.vue'
import { Popover, createResource } from 'frappe-ui'
import { onUnmounted } from 'vue';
import { stopRecording } from '@/telemetry';
const props = defineProps({
active: Boolean,
})
const apps = createResource({
url: 'frappe.apps.get_apps',
cache: 'apps',
auto: true,
transform: (data) => {
let _apps = [
{
name: 'frappe',
logo: '/assets/frappe/images/framework.png',
title: __('Desk'),
route: '/app',
},
]
data.map((app) => {
if (app.name === 'crm') return
_apps.push({
name: app.name,
logo: app.logo,
title: __(app.title),
route: app.route,
})
})
return _apps
},
})
onUnmounted(() => {
stopRecording()
})
</script>
|
2302_79757062/crm
|
frontend/src/components/Apps.vue
|
Vue
|
agpl-3.0
| 2,078
|
<template>
<span>
<a :href="isShowable ? null : url" target="_blank">
<Button
:label="label"
theme="gray"
variant="outline"
@click="toggleDialog()"
>
<template #prefix>
<component :is="getIcon()" class="h-4 w-4" />
</template>
<template #suffix>
<slot name="suffix" />
</template>
</Button>
</a>
<Dialog
v-model="showDialog"
:options="{
title: label,
size: '4xl',
}"
>
<template #body-content>
<div
v-if="isText"
class="prose prose-sm max-w-none whitespace-pre-wrap"
>
{{ content }}
</div>
<img v-if="isImage" :src="url" class="m-auto rounded border" />
</template>
</Dialog>
</span>
</template>
<script setup>
import { ref } from 'vue'
import mime from 'mime'
import FileTypeIcon from '@/components/Icons/FileTypeIcon.vue'
import FileImageIcon from '@/components/Icons/FileImageIcon.vue'
import FileTextIcon from '@/components/Icons/FileTextIcon.vue'
import FileSpreadsheetIcon from '@/components/Icons/FileSpreadsheetIcon.vue'
import FileIcon from '@/components/Icons/FileIcon.vue'
const props = defineProps({
label: {
type: String,
default: null,
},
url: {
type: String,
default: null,
},
})
const showDialog = ref(false)
const mimeType = mime.getType(props.label) || ''
const isImage = mimeType.startsWith('image/')
const isPdf = mimeType === 'application/pdf'
const isSpreadsheet = mimeType.includes('spreadsheet')
const isText = mimeType === 'text/plain'
const isShowable = props.url && (isText || isImage)
const content = ref('')
function getIcon() {
if (isText) return FileTypeIcon
else if (isImage) return FileImageIcon
else if (isPdf) return FileTextIcon
else if (isSpreadsheet) return FileSpreadsheetIcon
else return FileIcon
}
function toggleDialog() {
if (!isShowable) return
if (isText) {
fetch(props.url).then((res) => res.text().then((t) => (content.value = t)))
}
showDialog.value = !showDialog.value
}
</script>
|
2302_79757062/crm
|
frontend/src/components/AttachmentItem.vue
|
Vue
|
agpl-3.0
| 2,115
|
<template>
<div v-show="showCallPopup" v-bind="$attrs">
<div
ref="callPopup"
class="fixed z-20 flex w-60 cursor-move select-none flex-col rounded-lg bg-gray-900 p-4 text-gray-300 shadow-2xl"
:style="style"
>
<div class="flex flex-row-reverse items-center gap-1">
<MinimizeIcon
class="h-4 w-4 cursor-pointer"
@click="toggleCallWindow"
/>
</div>
<div class="flex flex-col items-center justify-center gap-3">
<Avatar
:image="contact.image"
:label="contact.full_name"
class="relative flex !h-24 !w-24 items-center justify-center [&>div]:text-[30px]"
:class="onCall || calling ? '' : 'pulse'"
/>
<div class="flex flex-col items-center justify-center gap-1">
<div class="text-xl font-medium">
{{ contact.full_name }}
</div>
<div class="text-sm text-gray-600">{{ contact.mobile_no }}</div>
</div>
<CountUpTimer ref="counterUp">
<div v-if="onCall" class="my-1 text-base">
{{ counterUp?.updatedTime }}
</div>
</CountUpTimer>
<div v-if="!onCall" class="my-1 text-base">
{{
callStatus == 'initiating'
? __('Initiating call...')
: callStatus == 'ringing'
? __('Ringing...')
: calling
? __('Calling...')
: __('Incoming call...')
}}
</div>
<div v-if="onCall" class="flex gap-2">
<Button
:icon="muted ? 'mic-off' : 'mic'"
class="rounded-full"
@click="toggleMute"
/>
<!-- <Button class="rounded-full">
<template #icon>
<DialpadIcon class="cursor-pointer rounded-full" />
</template>
</Button> -->
<Button class="rounded-full">
<template #icon>
<NoteIcon
class="h-4 w-4 cursor-pointer rounded-full text-gray-900"
@click="showNoteModal = true"
/>
</template>
</Button>
<Button class="rounded-full bg-red-600 hover:bg-red-700">
<template #icon>
<PhoneIcon
class="h-4 w-4 rotate-[135deg] fill-white text-white"
@click="hangUpCall"
/>
</template>
</Button>
</div>
<div v-else-if="calling || callStatus == 'initiating'">
<Button
size="md"
variant="solid"
theme="red"
:label="__('Cancel')"
@click="cancelCall"
class="rounded-lg"
:disabled="callStatus == 'initiating'"
>
<template #prefix>
<PhoneIcon class="h-4 w-4 rotate-[135deg] fill-white" />
</template>
</Button>
</div>
<div v-else class="flex gap-2">
<Button
size="md"
variant="solid"
theme="green"
:label="__('Accept')"
class="rounded-lg"
@click="acceptIncomingCall"
>
<template #prefix>
<PhoneIcon class="h-4 w-4 fill-white" />
</template>
</Button>
<Button
size="md"
variant="solid"
theme="red"
:label="__('Reject')"
class="rounded-lg"
@click="rejectIncomingCall"
>
<template #prefix>
<PhoneIcon class="h-4 w-4 rotate-[135deg] fill-white" />
</template>
</Button>
</div>
</div>
</div>
</div>
<div
v-show="showSmallCallWindow"
class="ml-2 flex cursor-pointer select-none items-center justify-between gap-3 rounded-lg bg-gray-900 px-2 py-[7px] text-base text-gray-300"
@click="toggleCallWindow"
v-bind="$attrs"
>
<div class="flex items-center gap-2">
<Avatar
:image="contact.image"
:label="contact.full_name"
class="relative flex !h-5 !w-5 items-center justify-center"
/>
<div class="max-w-[120px] truncate">
{{ contact.full_name }}
</div>
</div>
<div v-if="onCall" class="flex items-center gap-2">
<div class="my-1 min-w-[40px] text-center">
{{ counterUp?.updatedTime }}
</div>
<Button variant="solid" theme="red" class="!h-6 !w-6 rounded-full">
<template #icon>
<PhoneIcon
class="h-4 w-4 rotate-[135deg] fill-white"
@click.stop="hangUpCall"
/>
</template>
</Button>
</div>
<div v-else-if="calling" class="flex items-center gap-3">
<div class="my-1">
{{ callStatus == 'ringing' ? __('Ringing...') : __('Calling...') }}
</div>
<Button
variant="solid"
theme="red"
class="!h-6 !w-6 rounded-full"
@click.stop="cancelCall"
>
<template #icon>
<PhoneIcon class="h-4 w-4 rotate-[135deg] fill-white" />
</template>
</Button>
</div>
<div v-else class="flex items-center gap-2">
<Button
variant="solid"
theme="green"
class="pulse relative !h-6 !w-6 rounded-full"
@click.stop="acceptIncomingCall"
>
<template #icon>
<PhoneIcon class="h-4 w-4 animate-pulse fill-white" />
</template>
</Button>
<Button
variant="solid"
theme="red"
class="!h-6 !w-6 rounded-full"
@click.stop="rejectIncomingCall"
>
<template #icon>
<PhoneIcon class="h-4 w-4 rotate-[135deg] fill-white" />
</template>
</Button>
</div>
</div>
<NoteModal
v-model="showNoteModal"
:note="note"
doctype="CRM Call Log"
@after="updateNote"
/>
</template>
<script setup>
import NoteIcon from '@/components/Icons/NoteIcon.vue'
import MinimizeIcon from '@/components/Icons/MinimizeIcon.vue'
import PhoneIcon from '@/components/Icons/PhoneIcon.vue'
import CountUpTimer from '@/components/CountUpTimer.vue'
import NoteModal from '@/components/Modals/NoteModal.vue'
import { Device } from '@twilio/voice-sdk'
import { useDraggable, useWindowSize } from '@vueuse/core'
import { globalStore } from '@/stores/global'
import { contactsStore } from '@/stores/contacts'
import { capture } from '@/telemetry'
import { Avatar, call } from 'frappe-ui'
import { onMounted, ref, watch } from 'vue'
const { getContact, getLeadContact } = contactsStore()
const { setMakeCall, setTwilioEnabled } = globalStore()
let device = ''
let log = ref('Connecting...')
let _call = null
const contact = ref({
full_name: '',
mobile_no: '',
})
let showCallPopup = ref(false)
let showSmallCallWindow = ref(false)
let onCall = ref(false)
let calling = ref(false)
let muted = ref(false)
let callPopup = ref(null)
let counterUp = ref(null)
let callStatus = ref('')
const showNoteModal = ref(false)
const note = ref({
title: '',
content: '',
})
async function updateNote(_note, insert_mode = false) {
note.value = _note
if (insert_mode && _note.name) {
await call('crm.integrations.twilio.api.add_note_to_call_log', {
call_sid: _call.parameters.CallSid,
note: _note.name,
})
}
}
const { width, height } = useWindowSize()
let { style } = useDraggable(callPopup, {
initialValue: { x: width.value - 280, y: height.value - 310 },
preventDefault: true,
})
async function is_twilio_enabled() {
return await call('crm.integrations.twilio.api.is_enabled')
}
async function startupClient() {
log.value = 'Requesting Access Token...'
try {
const data = await call('crm.integrations.twilio.api.generate_access_token')
log.value = 'Got a token.'
intitializeDevice(data.token)
} catch (err) {
log.value = 'An error occurred. ' + err.message
}
}
function intitializeDevice(token) {
device = new Device(token, {
codecPreferences: ['opus', 'pcmu'],
fakeLocalDTMF: true,
enableRingingState: true,
})
addDeviceListeners()
device.register()
}
function addDeviceListeners() {
device.on('registered', () => {
log.value = 'Ready to make and receive calls!'
})
device.on('unregistered', (device) => {
log.value = 'Logged out'
})
device.on('error', (error) => {
log.value = 'Twilio.Device Error: ' + error.message
})
device.on('incoming', handleIncomingCall)
device.on('tokenWillExpire', async () => {
const data = await call('crm.integrations.twilio.api.generate_access_token')
device.updateToken(data.token)
})
}
function toggleMute() {
if (_call.isMuted()) {
_call.mute(false)
muted.value = false
} else {
_call.mute()
muted.value = true
}
}
function handleIncomingCall(call) {
log.value = `Incoming call from ${call.parameters.From}`
// get name of the caller from the phone number
contact.value = getContact(call.parameters.From)
if (!contact.value) {
contact.value = getLeadContact(call.parameters.From)
}
if (!contact.value) {
contact.value = {
full_name: __('Unknown'),
mobile_no: call.parameters.From,
}
}
showCallPopup.value = true
_call = call
_call.on('accept', (conn) => {
console.log('conn', conn)
})
// add event listener to call object
call.on('cancel', handleDisconnectedIncomingCall)
call.on('disconnect', handleDisconnectedIncomingCall)
call.on('reject', handleDisconnectedIncomingCall)
}
async function acceptIncomingCall() {
log.value = 'Accepted incoming call.'
onCall.value = true
await _call.accept()
counterUp.value.start()
}
function rejectIncomingCall() {
_call.reject()
log.value = 'Rejected incoming call'
showCallPopup.value = false
if (showSmallCallWindow.value == undefined) {
showSmallCallWindow = false
} else {
showSmallCallWindow.value = false
}
callStatus.value = ''
muted.value = false
}
function hangUpCall() {
_call.disconnect()
log.value = 'Hanging up incoming call'
onCall.value = false
callStatus.value = ''
muted.value = false
note.value = {
title: '',
content: '',
}
counterUp.value.stop()
}
function handleDisconnectedIncomingCall() {
log.value = `Call ended from handle disconnected Incoming call.`
showCallPopup.value = false
if (showSmallCallWindow.value == undefined) {
showSmallCallWindow = false
} else {
showSmallCallWindow.value = false
}
_call = null
muted.value = false
onCall.value = false
counterUp.value.stop()
}
async function makeOutgoingCall(number) {
// check if number has a country code
// if (number?.replace(/[^0-9+]/g, '').length == 10) {
// $dialog({
// title: 'Invalid Mobile Number',
// message: `${number} is not a valid mobile number. Either add a country code or check the number again.`,
// })
// return
// }
contact.value = getContact(number)
if (!contact.value) {
contact.value = getLeadContact(number)
}
if (device) {
log.value = `Attempting to call ${number} ...`
try {
_call = await device.connect({
params: { To: number },
})
showCallPopup.value = true
callStatus.value = 'initiating'
capture('make_outgoing_call')
_call.on('messageReceived', (message) => {
let info = message.content
callStatus.value = info.CallStatus
log.value = `Call status: ${info.CallStatus}`
if (info.CallStatus == 'in-progress') {
log.value = `Call in progress.`
calling.value = false
onCall.value = true
counterUp.value.start()
}
})
_call.on('accept', () => {
log.value = `Initiated call!`
showCallPopup.value = true
calling.value = true
onCall.value = false
})
_call.on('disconnect', (conn) => {
log.value = `Call ended from makeOutgoing call disconnect.`
calling.value = false
onCall.value = false
showCallPopup.value = false
showSmallCallWindow = false
_call = null
callStatus.value = ''
muted.value = false
counterUp.value.stop()
note.value = {
title: '',
content: '',
}
})
_call.on('cancel', () => {
log.value = `Call ended from makeOutgoing call cancel.`
calling.value = false
onCall.value = false
showCallPopup.value = false
showSmallCallWindow = false
_call = null
callStatus.value = ''
muted.value = false
note.value = {
title: '',
content: '',
}
counterUp.value.stop()
})
} catch (error) {
log.value = `Could not connect call: ${error.message}`
}
} else {
log.value = 'Unable to make call.'
}
}
function cancelCall() {
_call.disconnect()
showCallPopup.value = false
if (showSmallCallWindow.value == undefined) {
showSmallCallWindow = false
} else {
showSmallCallWindow.value = false
}
calling.value = false
onCall.value = false
callStatus.value = ''
muted.value = false
note.value = {
title: '',
content: '',
}
}
function toggleCallWindow() {
showCallPopup.value = !showCallPopup.value
if (showSmallCallWindow.value == undefined) {
showSmallCallWindow = !showSmallCallWindow
} else {
showSmallCallWindow.value = !showSmallCallWindow.value
}
}
onMounted(async () => {
let enabled = await is_twilio_enabled()
setTwilioEnabled(enabled)
enabled && startupClient()
setMakeCall(makeOutgoingCall)
})
watch(
() => log.value,
(value) => {
console.log(value)
},
{ immediate: true }
)
</script>
<style scoped>
.pulse::before {
content: '';
position: absolute;
border: 1px solid green;
width: calc(100% + 20px);
height: calc(100% + 20px);
border-radius: 50%;
animation: pulse 1s linear infinite;
}
.pulse::after {
content: '';
position: absolute;
border: 1px solid green;
width: calc(100% + 20px);
height: calc(100% + 20px);
border-radius: 50%;
animation: pulse 1s linear infinite;
animation-delay: 0.3s;
}
@keyframes pulse {
0% {
transform: scale(0.5);
opacity: 0;
}
50% {
transform: scale(1);
opacity: 1;
}
100% {
transform: scale(1.3);
opacity: 0;
}
}
</style>
|
2302_79757062/crm
|
frontend/src/components/CallUI.vue
|
Vue
|
agpl-3.0
| 14,347
|
<template>
<NestedPopover>
<template #target>
<Button :label="__('Columns')">
<template v-if="hideLabel">
<ColumnsIcon class="h-4" />
</template>
<template v-if="!hideLabel" #prefix>
<ColumnsIcon class="h-4" />
</template>
</Button>
</template>
<template #body="{ close }">
<div
class="my-2 rounded-lg border border-gray-100 bg-white p-1.5 shadow-xl"
>
<div v-if="!edit">
<Draggable
:list="columns"
@end="apply"
:delay="isTouchScreenDevice() ? 200 : 0"
item-key="key"
class="list-group"
>
<template #item="{ element }">
<div
class="flex cursor-grab items-center justify-between gap-6 rounded px-2 py-1.5 text-base text-gray-800 hover:bg-gray-100"
>
<div class="flex items-center gap-2">
<DragIcon class="h-3.5" />
<div>{{ __(element.label) }}</div>
</div>
<div class="flex cursor-pointer items-center gap-1">
<Button
variant="ghost"
class="!h-5 w-5 !p-1"
@click="editColumn(element)"
>
<EditIcon class="h-3.5" />
</Button>
<Button
variant="ghost"
class="!h-5 w-5 !p-1"
@click="removeColumn(element)"
>
<FeatherIcon name="x" class="h-3.5" />
</Button>
</div>
</div>
</template>
</Draggable>
<div class="mt-1.5 flex flex-col gap-1 border-t pt-1.5">
<Autocomplete
value=""
:options="fields"
@change="(e) => addColumn(e)"
>
<template #target="{ togglePopover }">
<Button
class="w-full !justify-start !text-gray-600"
variant="ghost"
@click="togglePopover()"
:label="__('Add Column')"
>
<template #prefix>
<FeatherIcon name="plus" class="h-4" />
</template>
</Button>
</template>
</Autocomplete>
<Button
v-if="columnsUpdated"
class="w-full !justify-start !text-gray-600"
variant="ghost"
@click="reset(close)"
:label="__('Reset Changes')"
>
<template #prefix>
<ReloadIcon class="h-4" />
</template>
</Button>
<Button
v-if="!is_default"
class="w-full !justify-start !text-gray-600"
variant="ghost"
@click="resetToDefault(close)"
:label="__('Reset to Default')"
>
<template #prefix>
<ReloadIcon class="h-4" />
</template>
</Button>
</div>
</div>
<div v-else>
<div
class="flex flex-col items-center justify-between gap-2 rounded px-2 py-1.5 text-base text-gray-800"
>
<div class="flex flex-col items-center gap-3">
<FormControl
type="text"
size="md"
:label="__('Label')"
v-model="column.label"
class="sm:w-full w-52"
:placeholder="__('First Name')"
/>
<FormControl
type="text"
size="md"
:label="__('Width')"
class="sm:w-full w-52"
v-model="column.width"
placeholder="10rem"
:description="
__(
'Width can be in number, pixel or rem (eg. 3, 30px, 10rem)'
)
"
:debounce="500"
/>
</div>
<div class="flex w-full gap-2 border-t pt-2">
<Button
variant="subtle"
:label="__('Cancel')"
class="w-full flex-1"
@click="cancelUpdate"
/>
<Button
variant="solid"
:label="__('Update')"
class="w-full flex-1"
@click="updateColumn(column)"
/>
</div>
</div>
</div>
</div>
</template>
</NestedPopover>
</template>
<script setup>
import ColumnsIcon from '@/components/Icons/ColumnsIcon.vue'
import EditIcon from '@/components/Icons/EditIcon.vue'
import DragIcon from '@/components/Icons/DragIcon.vue'
import ReloadIcon from '@/components/Icons/ReloadIcon.vue'
import NestedPopover from '@/components/NestedPopover.vue'
import Autocomplete from '@/components/frappe-ui/Autocomplete.vue'
import { isTouchScreenDevice } from '@/utils'
import Draggable from 'vuedraggable'
import { computed, ref } from 'vue'
import { watchOnce } from '@vueuse/core'
const props = defineProps({
doctype: {
type: String,
required: true,
},
hideLabel: {
type: Boolean,
default: false,
},
})
const emit = defineEmits(['update'])
const columnsUpdated = ref(false)
const oldValues = ref({
columns: [],
rows: [],
isDefault: false,
})
const list = defineModel()
const edit = ref(false)
const column = ref({
old: {},
label: '',
key: '',
width: '10rem',
})
const is_default = computed({
get: () => list.value?.data?.is_default,
set: (val) => {
list.value.data.is_default = val
},
})
const columns = computed({
get: () => list.value?.data?.columns,
set: (val) => {
list.value.data.columns = val
},
})
const rows = computed({
get: () => list.value?.data?.rows,
set: (val) => {
list.value.data.rows = val
},
})
const fields = computed(() => {
let allFields = list.value?.data?.fields
if (!allFields) return []
return allFields.filter((field) => {
return !columns.value.find((column) => column.key === field.value)
})
})
function addColumn(c) {
let _column = {
label: c.label,
type: c.type,
key: c.value,
width: '10rem',
}
columns.value.push(_column)
rows.value.push(c.value)
apply(true)
}
function removeColumn(c) {
columns.value = columns.value.filter((column) => column.key !== c.key)
if (c.key !== 'name') {
rows.value = rows.value.filter((row) => row !== c.key)
}
apply()
}
function editColumn(c) {
edit.value = true
column.value = c
column.value.old = { ...c }
}
function updateColumn(c) {
edit.value = false
let index = columns.value.findIndex((column) => column.key === c.key)
columns.value[index].label = c.label
columns.value[index].width = c.width
if (columns.value[index].old) {
delete columns.value[index].old
}
apply()
}
function cancelUpdate() {
edit.value = false
column.value.label = column.value.old.label
column.value.width = column.value.old.width
delete column.value.old
}
function reset(close) {
apply(true, false, true)
close()
}
function resetToDefault(close) {
apply(true, true)
close()
}
function apply(reload = false, isDefault = false, reset = false) {
is_default.value = isDefault
columnsUpdated.value = true
let obj = {
columns: reset ? oldValues.value.columns : columns.value,
rows: reset ? oldValues.value.rows : rows.value,
isDefault: reset ? oldValues.value.isDefault : isDefault,
reload,
reset,
}
emit('update', obj)
if (reload) {
// will have think of a better way to do this
setTimeout(() => {
is_default.value = reset ? oldValues.value.isDefault : isDefault
columnsUpdated.value = !reset
}, 100)
}
}
watchOnce(
() => list.value.data,
(val) => {
if (!val) return
oldValues.value.columns = JSON.parse(JSON.stringify(val.columns))
oldValues.value.rows = JSON.parse(JSON.stringify(val.rows))
oldValues.value.isDefault = val.is_default
}
)
</script>
|
2302_79757062/crm
|
frontend/src/components/ColumnSettings.vue
|
Vue
|
agpl-3.0
| 8,186
|
<template>
<TextEditor
ref="textEditor"
:editor-class="['prose-sm max-w-none', editable && 'min-h-[7rem]']"
:content="content"
@change="editable ? (content = $event) : null"
:starterkit-options="{ heading: { levels: [2, 3, 4, 5, 6] } }"
:placeholder="placeholder"
:editable="editable"
:mentions="users"
>
<template v-slot:editor="{ editor }">
<EditorContent
:class="[
editable &&
'sm:mx-10 mx-4 max-h-[50vh] overflow-y-auto border-t py-3',
]"
:editor="editor"
/>
</template>
<template v-slot:bottom>
<div v-if="editable" class="flex flex-col gap-2">
<div class="flex flex-wrap gap-2 sm:px-10 px-4">
<AttachmentItem
v-for="a in attachments"
:key="a.file_url"
:label="a.file_name"
>
<template #suffix>
<FeatherIcon
class="h-3.5"
name="x"
@click.stop="removeAttachment(a)"
/>
</template>
</AttachmentItem>
</div>
<div
class="flex justify-between gap-2 overflow-hidden border-t sm:px-10 px-4 py-2.5"
>
<div class="flex gap-1 items-center overflow-x-auto">
<TextEditorBubbleMenu :buttons="textEditorMenuButtons" />
<IconPicker
v-model="emoji"
v-slot="{ togglePopover }"
@update:modelValue="() => appendEmoji()"
>
<Button variant="ghost" @click="togglePopover()">
<template #icon>
<SmileIcon class="h-4" />
</template>
</Button>
</IconPicker>
<FileUploader
:upload-args="{
doctype: doctype,
docname: modelValue.name,
private: true,
}"
@success="(f) => attachments.push(f)"
>
<template #default="{ openFileSelector }">
<Button
theme="gray"
variant="ghost"
@click="openFileSelector()"
>
<template #icon>
<AttachmentIcon class="h-4" />
</template>
</Button>
</template>
</FileUploader>
</div>
<div class="mt-2 flex items-center justify-end space-x-2 sm:mt-0">
<Button v-bind="discardButtonProps || {}" :label="__('Discard')" />
<Button
variant="solid"
v-bind="submitButtonProps || {}"
:label="__('Comment')"
/>
</div>
</div>
</div>
</template>
</TextEditor>
</template>
<script setup>
import IconPicker from '@/components/IconPicker.vue'
import SmileIcon from '@/components/Icons/SmileIcon.vue'
import AttachmentIcon from '@/components/Icons/AttachmentIcon.vue'
import AttachmentItem from '@/components/AttachmentItem.vue'
import { usersStore } from '@/stores/users'
import { TextEditorBubbleMenu, TextEditor, FileUploader } from 'frappe-ui'
import { capture } from '@/telemetry'
import { EditorContent } from '@tiptap/vue-3'
import { ref, computed, defineModel } from 'vue'
const props = defineProps({
placeholder: {
type: String,
default: null,
},
editable: {
type: Boolean,
default: true,
},
doctype: {
type: String,
default: 'CRM Lead',
},
editorProps: {
type: Object,
default: () => ({}),
},
submitButtonProps: {
type: Object,
default: () => ({}),
},
discardButtonProps: {
type: Object,
default: () => ({}),
},
})
const modelValue = defineModel()
const attachments = defineModel('attachments')
const content = defineModel('content')
const { users: usersList } = usersStore()
const textEditor = ref(null)
const emoji = ref('')
const editor = computed(() => {
return textEditor.value.editor
})
function appendEmoji() {
editor.value.commands.insertContent(emoji.value)
editor.value.commands.focus()
emoji.value = ''
capture('emoji_inserted_in_comment', { emoji: emoji.value })
}
function removeAttachment(attachment) {
attachments.value = attachments.value.filter((a) => a !== attachment)
}
const users = computed(() => {
return (
usersList.data
?.filter((user) => user.enabled)
.map((user) => ({
label: user.full_name.trimEnd(),
value: user.name,
})) || []
)
})
defineExpose({ editor })
const textEditorMenuButtons = [
'Paragraph',
['Heading 2', 'Heading 3', 'Heading 4', 'Heading 5', 'Heading 6'],
'Separator',
'Bold',
'Italic',
'Separator',
'Bullet List',
'Numbered List',
'Separator',
'Align Left',
'Align Center',
'Align Right',
'FontColor',
'Separator',
'Image',
'Video',
'Link',
'Blockquote',
'Code',
'Horizontal Rule',
[
'InsertTable',
'AddColumnBefore',
'AddColumnAfter',
'DeleteColumn',
'AddRowBefore',
'AddRowAfter',
'DeleteRow',
'MergeCells',
'SplitCell',
'ToggleHeaderColumn',
'ToggleHeaderRow',
'ToggleHeaderCell',
'DeleteTable',
],
]
</script>
|
2302_79757062/crm
|
frontend/src/components/CommentBox.vue
|
Vue
|
agpl-3.0
| 5,222
|
<template>
<div class="flex justify-between gap-3 border-t px-4 py-2.5 sm:px-10">
<div class="flex gap-1.5">
<Button
ref="sendEmailRef"
variant="ghost"
:class="[showEmailBox ? '!bg-gray-300 hover:!bg-gray-200' : '']"
:label="__('Reply')"
@click="toggleEmailBox()"
>
<template #prefix>
<Email2Icon class="h-4" />
</template>
</Button>
<Button
variant="ghost"
:label="__('Comment')"
:class="[showCommentBox ? '!bg-gray-300 hover:!bg-gray-200' : '']"
@click="toggleCommentBox()"
>
<template #prefix>
<CommentIcon class="h-4" />
</template>
</Button>
</div>
</div>
<div
v-show="showEmailBox"
@keydown.ctrl.enter.capture.stop="submitEmail"
@keydown.meta.enter.capture.stop="submitEmail"
>
<EmailEditor
ref="newEmailEditor"
v-model:content="newEmail"
:submitButtonProps="{
variant: 'solid',
onClick: submitEmail,
disabled: emailEmpty,
}"
:discardButtonProps="{
onClick: () => {
showEmailBox = false
newEmailEditor.subject = subject
newEmailEditor.toEmails = doc.data.email ? [doc.data.email] : []
newEmailEditor.ccEmails = []
newEmailEditor.bccEmails = []
newEmailEditor.cc = false
newEmailEditor.bcc = false
newEmail = ''
},
}"
:editable="showEmailBox"
v-model="doc.data"
v-model:attachments="attachments"
:doctype="doctype"
:subject="subject"
:placeholder="
__('Hi John, \n\nCan you please provide more details on this...')
"
/>
</div>
<div v-show="showCommentBox">
<CommentBox
ref="newCommentEditor"
v-model:content="newComment"
:submitButtonProps="{
variant: 'solid',
onClick: submitComment,
disabled: commentEmpty,
}"
:discardButtonProps="{
onClick: () => {
showCommentBox = false
newComment = ''
},
}"
:editable="showCommentBox"
v-model="doc.data"
v-model:attachments="attachments"
:doctype="doctype"
:placeholder="__('@John, can you please check this?')"
/>
</div>
</template>
<script setup>
import EmailEditor from '@/components/EmailEditor.vue'
import CommentBox from '@/components/CommentBox.vue'
import CommentIcon from '@/components/Icons/CommentIcon.vue'
import Email2Icon from '@/components/Icons/Email2Icon.vue'
import { capture } from '@/telemetry'
import { usersStore } from '@/stores/users'
import { useStorage } from '@vueuse/core'
import { call, createResource } from 'frappe-ui'
import { ref, watch, computed } from 'vue'
const props = defineProps({
doctype: {
type: String,
default: 'CRM Lead',
},
})
const doc = defineModel()
const reload = defineModel('reload')
const emit = defineEmits(['scroll'])
const { getUser } = usersStore()
const showEmailBox = ref(false)
const showCommentBox = ref(false)
const newEmail = useStorage('emailBoxContent', '')
const newComment = useStorage('commentBoxContent', '')
const newEmailEditor = ref(null)
const newCommentEditor = ref(null)
const sendEmailRef = ref(null)
const attachments = ref([])
const subject = computed(() => {
let prefix = ''
if (doc.value.data?.lead_name) {
prefix = doc.value.data.lead_name
} else if (doc.value.data?.organization) {
prefix = doc.value.data.organization
}
return `${prefix} (#${doc.value.data.name})`
})
const signature = createResource({
url: 'crm.api.get_user_signature',
cache: 'user-email-signature',
auto: true,
})
function setSignature(editor) {
if (!signature.data) return
signature.data = signature.data.replace(/\n/g, '<br>')
let emailContent = editor.getHTML()
emailContent = emailContent.startsWith('<p></p>')
? emailContent.slice(7)
: emailContent
editor.commands.setContent(signature.data + emailContent)
editor.commands.focus('start')
}
watch(
() => showEmailBox.value,
(value) => {
if (value) {
let editor = newEmailEditor.value.editor
editor.commands.focus()
setSignature(editor)
}
}
)
watch(
() => showCommentBox.value,
(value) => {
if (value) {
newCommentEditor.value.editor.commands.focus()
}
}
)
const commentEmpty = computed(() => {
return !newComment.value || newComment.value === '<p></p>'
})
const emailEmpty = computed(() => {
return !newEmail.value || newEmail.value === '<p></p>'
})
async function sendMail() {
let recipients = newEmailEditor.value.toEmails
let subject = newEmailEditor.value.subject
let cc = newEmailEditor.value.ccEmails || []
let bcc = newEmailEditor.value.bccEmails || []
if (attachments.value.length) {
capture('email_attachments_added')
}
await call('frappe.core.doctype.communication.email.make', {
recipients: recipients.join(', '),
attachments: attachments.value.map((x) => x.name),
cc: cc.join(', '),
bcc: bcc.join(', '),
subject: subject,
content: newEmail.value,
doctype: props.doctype,
name: doc.value.data.name,
send_email: 1,
sender: getUser().email,
sender_full_name: getUser()?.full_name || undefined,
})
}
async function sendComment() {
let comment = await call('frappe.desk.form.utils.add_comment', {
reference_doctype: props.doctype,
reference_name: doc.value.data.name,
content: newComment.value,
comment_email: getUser().email,
comment_by: getUser()?.full_name || undefined,
})
if (comment && attachments.value.length) {
capture('comment_attachments_added')
await call('crm.api.comment.add_attachments', {
name: comment.name,
attachments: attachments.value.map((x) => x.name),
})
}
}
async function submitEmail() {
if (emailEmpty.value) return
showEmailBox.value = false
await sendMail()
newEmail.value = ''
reload.value = true
emit('scroll')
capture('email_sent', { doctype: props.doctype })
}
async function submitComment() {
if (commentEmpty.value) return
showCommentBox.value = false
await sendComment()
newComment.value = ''
reload.value = true
emit('scroll')
capture('comment_sent', { doctype: props.doctype })
}
function toggleEmailBox() {
if (showCommentBox.value) {
showCommentBox.value = false
}
showEmailBox.value = !showEmailBox.value
}
function toggleCommentBox() {
if (showEmailBox.value) {
showEmailBox.value = false
}
showCommentBox.value = !showCommentBox.value
}
defineExpose({
show: showEmailBox,
showComment: showCommentBox,
editor: newEmailEditor,
})
</script>
|
2302_79757062/crm
|
frontend/src/components/CommunicationArea.vue
|
Vue
|
agpl-3.0
| 6,684
|
<template>
<div class="space-y-1.5">
<label class="block" :class="labelClasses" v-if="attrs.label">
{{ __(attrs.label) }}
</label>
<Autocomplete
ref="autocomplete"
:options="options.data"
v-model="value"
:size="attrs.size || 'sm'"
:variant="attrs.variant"
:placeholder="attrs.placeholder"
:filterable="false"
>
<template #target="{ open, togglePopover }">
<slot name="target" v-bind="{ open, togglePopover }" />
</template>
<template #prefix>
<slot name="prefix" />
</template>
<template #item-prefix="{ active, selected, option }">
<slot name="item-prefix" v-bind="{ active, selected, option }" />
</template>
<template #item-label="{ active, selected, option }">
<slot name="item-label" v-bind="{ active, selected, option }" />
</template>
<template #footer="{ value, close }">
<div v-if="attrs.onCreate">
<Button
variant="ghost"
class="w-full !justify-start"
:label="__('Create New')"
@click="attrs.onCreate(value, close)"
>
<template #prefix>
<FeatherIcon name="plus" class="h-4" />
</template>
</Button>
</div>
<div>
<Button
variant="ghost"
class="w-full !justify-start"
:label="__('Clear')"
@click="() => clearValue(close)"
>
<template #prefix>
<FeatherIcon name="x" class="h-4" />
</template>
</Button>
</div>
</template>
</Autocomplete>
</div>
</template>
<script setup>
import Autocomplete from '@/components/frappe-ui/Autocomplete.vue'
import { watchDebounced } from '@vueuse/core'
import { createResource } from 'frappe-ui'
import { useAttrs, computed, ref } from 'vue'
const props = defineProps({
doctype: {
type: String,
required: true,
},
modelValue: {
type: String,
default: '',
},
hideMe: {
type: Boolean,
default: false,
},
})
const emit = defineEmits(['update:modelValue', 'change'])
const attrs = useAttrs()
const valuePropPassed = computed(() => 'value' in attrs)
const value = computed({
get: () => (valuePropPassed.value ? attrs.value : props.modelValue),
set: (val) => {
return (
val?.value &&
emit(valuePropPassed.value ? 'change' : 'update:modelValue', val?.value)
)
},
})
const autocomplete = ref(null)
const text = ref('')
watchDebounced(
() => autocomplete.value?.query,
(val) => {
val = val || ''
if (text.value === val) return
text.value = val
reload(val)
},
{ debounce: 300, immediate: true }
)
watchDebounced(
() => props.doctype,
() => reload(''),
{ debounce: 300, immediate: true }
)
const options = createResource({
url: 'frappe.desk.search.search_link',
cache: [props.doctype, text.value, props.hideMe],
method: 'POST',
params: {
txt: text.value,
doctype: props.doctype,
},
transform: (data) => {
let allData = data.map((option) => {
return {
label: option.value,
value: option.value,
}
})
if (!props.hideMe && props.doctype == 'User') {
allData.unshift({
label: '@me',
value: '@me',
})
}
return allData
},
})
function reload(val) {
if (
options.data?.length &&
val === options.params?.txt &&
props.doctype === options.params?.doctype
)
return
options.update({
params: {
txt: val,
doctype: props.doctype,
},
})
options.reload()
}
function clearValue(close) {
emit(valuePropPassed.value ? 'change' : 'update:modelValue', '')
close()
}
const labelClasses = computed(() => {
return [
{
sm: 'text-xs',
md: 'text-base',
}[attrs.size || 'sm'],
'text-gray-600',
]
})
</script>
|
2302_79757062/crm
|
frontend/src/components/Controls/Link.vue
|
Vue
|
agpl-3.0
| 3,920
|
<template>
<div>
<div
class="flex flex-wrap gap-1 min-h-20 p-1.5 cursor-text rounded h-7 text-base border border-gray-300 bg-white hover:border-gray-400 focus:border-gray-500 focus:ring-0 focus-visible:ring-2 focus-visible:ring-gray-400 text-gray-800 transition-colors w-full"
@click="setFocus"
>
<Button
ref="emails"
v-for="value in values"
:key="value"
:label="value"
theme="gray"
variant="subtle"
class="rounded"
@keydown.delete.capture.stop="removeLastValue"
>
<template #suffix>
<FeatherIcon
class="h-3.5"
name="x"
@click.stop="removeValue(value)"
/>
</template>
</Button>
<div class="flex-1">
<TextInput
ref="search"
class="w-full border-none bg-white hover:bg-white focus:border-none focus:!shadow-none focus-visible:!ring-0"
type="text"
v-model="query"
placeholder="example@email.com"
@keydown.enter.capture.stop="addValue()"
@keydown.delete.capture.stop="removeLastValue"
/>
</div>
</div>
<ErrorMessage class="mt-2 pl-2" v-if="error" :message="error" />
</div>
</template>
<script setup>
import { TextInput } from 'frappe-ui'
import { ref, nextTick } from 'vue'
const props = defineProps({
validate: {
type: Function,
default: null,
},
errorMessage: {
type: Function,
default: (value) => `${value} is an Invalid value`,
},
})
const values = defineModel()
const emails = ref([])
const search = ref(null)
const error = ref(null)
const query = ref('')
const addValue = () => {
let value = query.value
error.value = null
if (value) {
const splitValues = value.split(',')
splitValues.forEach((value) => {
value = value.trim()
if (value) {
// check if value is not already in the values array
if (!values.value?.includes(value)) {
// check if value is valid
if (value && props.validate && !props.validate(value)) {
error.value = props.errorMessage(value)
return
}
// add value to values array
if (!values.value) {
values.value = [value]
} else {
values.value.push(value)
}
value = value.replace(value, '')
}
}
})
!error.value && (query.value = '')
}
}
const removeValue = (value) => {
values.value = values.value.filter((v) => v !== value)
}
const removeLastValue = () => {
if (query.value) return
let emailRef = emails.value[emails.value.length - 1]?.$el
if (document.activeElement === emailRef) {
values.value.pop()
nextTick(() => {
if (values.value.length) {
emailRef = emails.value[emails.value.length - 1].$el
emailRef?.focus()
} else {
setFocus()
}
})
} else {
emailRef?.focus()
}
}
function setFocus() {
search.value.el.focus()
}
defineExpose({ setFocus })
</script>
|
2302_79757062/crm
|
frontend/src/components/Controls/MultiValueInput.vue
|
Vue
|
agpl-3.0
| 3,061
|
<template>
<div>
<div class="flex flex-wrap gap-1">
<Button
ref="emails"
v-for="value in values"
:key="value"
:label="value"
theme="gray"
variant="subtle"
class="rounded"
@keydown.delete.capture.stop="removeLastValue"
>
<template #suffix>
<FeatherIcon
class="h-3.5"
name="x"
@click.stop="removeValue(value)"
/>
</template>
</Button>
<div class="flex-1">
<Combobox v-model="selectedValue" nullable>
<Popover class="w-full" v-model:show="showOptions">
<template #target="{ togglePopover }">
<ComboboxInput
ref="search"
class="search-input form-input w-full border-none bg-white hover:bg-white focus:border-none focus:!shadow-none focus-visible:!ring-0"
type="text"
:value="query"
@change="
(e) => {
query = e.target.value
showOptions = true
}
"
autocomplete="off"
@focus="() => togglePopover()"
@keydown.delete.capture.stop="removeLastValue"
/>
</template>
<template #body="{ isOpen }">
<div v-show="isOpen">
<div class="mt-1 rounded-lg bg-white py-1 text-base shadow-2xl">
<ComboboxOptions
class="my-1 max-h-[12rem] overflow-y-auto px-1.5"
static
>
<ComboboxOption
v-for="option in options"
:key="option.value"
:value="option"
v-slot="{ active }"
>
<li
:class="[
'flex cursor-pointer items-center rounded px-2 py-1 text-base',
{ 'bg-gray-100': active },
]"
>
<UserAvatar
class="mr-2"
:user="option.value"
size="lg"
/>
<div class="flex flex-col gap-1 p-1 text-gray-800">
<div class="text-base font-medium">
{{ option.label }}
</div>
<div class="text-sm text-gray-600">
{{ option.value }}
</div>
</div>
</li>
</ComboboxOption>
</ComboboxOptions>
</div>
</div>
</template>
</Popover>
</Combobox>
</div>
</div>
<ErrorMessage class="mt-2 pl-2" v-if="error" :message="error" />
</div>
</template>
<script setup>
import {
Combobox,
ComboboxInput,
ComboboxOptions,
ComboboxOption,
} from '@headlessui/vue'
import UserAvatar from '@/components/UserAvatar.vue'
import Popover from '@/components/frappe-ui/Popover.vue'
import { createResource } from 'frappe-ui'
import { ref, computed, nextTick } from 'vue'
import { watchDebounced } from '@vueuse/core'
const props = defineProps({
validate: {
type: Function,
default: null,
},
errorMessage: {
type: Function,
default: (value) => `${value} is an Invalid value`,
},
})
const values = defineModel()
const emails = ref([])
const search = ref(null)
const error = ref(null)
const query = ref('')
const text = ref('')
const showOptions = ref(false)
const selectedValue = computed({
get: () => query.value || '',
set: (val) => {
query.value = ''
if (val) {
showOptions.value = false
}
val?.value && addValue(val.value)
},
})
watchDebounced(
query,
(val) => {
val = val || ''
if (text.value === val && options.value?.length) return
text.value = val
reload(val)
},
{ debounce: 300, immediate: true },
)
const filterOptions = createResource({
url: 'crm.api.contact.search_emails',
method: 'POST',
cache: [text.value, 'Contact'],
params: { txt: text.value },
transform: (data) => {
let allData = data
.map((option) => {
let fullName = option[0]
let email = option[1]
let name = option[2]
return {
label: fullName || name || email,
value: email,
}
})
return allData
},
})
const options = computed(() => {
let searchedContacts = filterOptions.data || []
if (!searchedContacts.length && query.value) {
searchedContacts.push({
label: query.value,
value: query.value,
})
}
return searchedContacts
})
function reload(val) {
filterOptions.update({
params: { txt: val },
})
filterOptions.reload()
}
const addValue = (value) => {
error.value = null
if (value) {
const splitValues = value.split(',')
splitValues.forEach((value) => {
value = value.trim()
if (value) {
// check if value is not already in the values array
if (!values.value?.includes(value)) {
// check if value is valid
if (value && props.validate && !props.validate(value)) {
error.value = props.errorMessage(value)
return
}
// add value to values array
if (!values.value) {
values.value = [value]
} else {
values.value.push(value)
}
value = value.replace(value, '')
}
}
})
!error.value && (value = '')
}
}
const removeValue = (value) => {
values.value = values.value.filter((v) => v !== value)
}
const removeLastValue = () => {
if (query.value) return
let emailRef = emails.value[emails.value.length - 1]?.$el
if (document.activeElement === emailRef) {
values.value.pop()
nextTick(() => {
if (values.value.length) {
emailRef = emails.value[emails.value.length - 1].$el
emailRef?.focus()
} else {
setFocus()
}
})
} else {
emailRef?.focus()
}
}
function setFocus() {
search.value.$el.focus()
}
defineExpose({ setFocus })
</script>
|
2302_79757062/crm
|
frontend/src/components/Controls/MultiselectInput.vue
|
Vue
|
agpl-3.0
| 6,322
|
<template>
<slot />
</template>
<script setup>
import { ref } from 'vue'
const hours = ref(0)
const minutes = ref(0)
const seconds = ref(0)
const timer = ref(null)
const updatedTime = ref('0:00')
function startCounter() {
if (seconds.value === 59) {
seconds.value = 0
minutes.value = minutes.value + 1
seconds.value--
}
if (minutes.value === 60) {
minutes.value = 0
hours.value = hours.value + 1
}
seconds.value++
let minutesCount = minutes.value
let secondsCount = seconds.value < 10 ? '0' + seconds.value : seconds.value
let hoursCount = hours.value > 0 ? hours.value + ':' : ''
if (hoursCount) {
minutesCount = minutesCount < 10 ? '0' + minutesCount : minutesCount
secondsCount = secondsCount < 10 ? '0' + secondsCount : secondsCount
if (minutesCount === 0) {
minutesCount = '00'
}
}
updatedTime.value = hoursCount + minutesCount + ':' + secondsCount
}
function start() {
timer.value = setInterval(() => startCounter(), 1000)
}
function stop() {
clearInterval(timer.value)
let output = updatedTime.value
hours.value = 0
minutes.value = 0
seconds.value = 0
updatedTime.value = '0:00'
return output
}
defineExpose({ start, stop, updatedTime })
</script>
|
2302_79757062/crm
|
frontend/src/components/CountUpTimer.vue
|
Vue
|
agpl-3.0
| 1,247
|
<template>
<Button
v-if="normalActions.length && !isMobileView"
v-for="action in normalActions"
:label="action.label"
@click="action.onClick()"
>
<template v-if="action.icon" #prefix>
<FeatherIcon :name="action.icon" class="h-4 w-4" />
</template>
</Button>
<Dropdown v-if="groupedActions.length" :options="groupedActions">
<Button icon="more-horizontal" />
</Dropdown>
<div
v-if="groupedWithLabelActions.length && !isMobileView"
v-for="g in groupedWithLabelActions"
:key="g.label"
>
<Dropdown :options="g.action" v-slot="{ open }">
<Button :label="g.label">
<template #suffix>
<FeatherIcon
:name="open ? 'chevron-up' : 'chevron-down'"
class="h-4"
/>
</template>
</Button>
</Dropdown>
</div>
</template>
<script setup>
import { computed, h } from 'vue'
import { Dropdown } from 'frappe-ui'
import { isMobileView } from '@/composables/settings'
const props = defineProps({
actions: {
type: Object,
required: true,
},
})
const normalActions = computed(() => {
return props.actions.filter((action) => !action.group)
})
const groupedWithLabelActions = computed(() => {
let _actions = []
props.actions
.filter((action) => action.buttonLabel && action.group)
.forEach((action) => {
let groupIndex = _actions.findIndex((a) => a.label === action.buttonLabel)
if (groupIndex > -1) {
_actions[groupIndex].action.push(action)
} else {
_actions.push({
label: action.buttonLabel,
action: [action],
})
}
})
return _actions
})
const groupedActions = computed(() => {
let _actions = []
let _normalActions = normalActions.value
if (isMobileView.value && _normalActions.length) {
_actions.push({
group: __('Actions'),
hideLabel: true,
items: _normalActions.map((action) => ({
label: action.label,
onClick: action.onClick,
icon: action.icon,
})),
})
}
if (isMobileView.value && groupedWithLabelActions.value.length) {
groupedWithLabelActions.value.map((group) => {
group.action.forEach((action) => _actions.push(action))
})
}
_actions = _actions.concat(
props.actions.filter((action) => action.group && !action.buttonLabel)
)
return _actions
})
</script>
|
2302_79757062/crm
|
frontend/src/components/CustomActions.vue
|
Vue
|
agpl-3.0
| 2,376
|
<template>
<div
class="group flex w-full items-center justify-between rounded bg-transparent p-1 pl-2 text-base text-gray-800 transition-colors hover:bg-gray-200 active:bg-gray-300"
>
<div class="flex items-center justify-between gap-7">
<div v-show="!editMode">{{ option.value }}</div>
<TextInput
ref="inputRef"
v-show="editMode"
v-model="option.value"
class="w-full"
:placeholder="option.placeholder"
@blur.stop="saveOption"
@keydown.enter.stop="(e) => e.target.blur()"
/>
<div class="actions flex items-center justify-center">
<Tooltip text="Set As Primary" v-if="!isNew && !option.selected">
<div>
<Button
variant="ghost"
size="sm"
class="opacity-0 hover:bg-gray-300 group-hover:opacity-100"
@click="option.onClick"
>
<SuccessIcon />
</Button>
</div>
</Tooltip>
<Tooltip text="Edit">
<div>
<Button
variant="ghost"
size="sm"
class="opacity-0 hover:bg-gray-300 group-hover:opacity-100"
@click="toggleEditMode"
>
<EditIcon />
</Button>
</div>
</Tooltip>
<Tooltip text="Delete">
<div>
<Button
variant="ghost"
icon="x"
size="sm"
class="opacity-0 hover:bg-gray-300 group-hover:opacity-100"
@click="() => option.onDelete(option, isNew)"
/>
</div>
</Tooltip>
</div>
</div>
<div>
<FeatherIcon
v-if="option.selected"
name="check"
class="text-primary-500 h-4 w-6"
size="sm"
/>
</div>
</div>
</template>
<script setup>
import SuccessIcon from '@/components/Icons/SuccessIcon.vue'
import EditIcon from '@/components/Icons/EditIcon.vue'
import { TextInput, Tooltip } from 'frappe-ui'
import { nextTick, ref, onMounted } from 'vue'
const props = defineProps({
option: {
type: Object,
default: () => {},
},
})
const editMode = ref(false)
const isNew = ref(false)
const inputRef = ref(null)
onMounted(() => {
if (!props.option?.value) {
editMode.value = true
isNew.value = true
nextTick(() => inputRef.value.el.focus())
}
})
const toggleEditMode = () => {
editMode.value = !editMode.value
editMode.value && nextTick(() => inputRef.value.el.focus())
}
const saveOption = () => {
toggleEditMode()
props.option.onSave(props.option, isNew.value)
isNew.value = false
}
</script>
|
2302_79757062/crm
|
frontend/src/components/DropdownItem.vue
|
Vue
|
agpl-3.0
| 2,676
|
<template>
<TextEditor
ref="textEditor"
:editor-class="[
'prose-sm max-w-none',
editable && 'min-h-[7rem]',
'[&_p.reply-to-content]:hidden',
]"
:content="content"
@change="editable ? (content = $event) : null"
:starterkit-options="{
heading: { levels: [2, 3, 4, 5, 6] },
paragraph: false,
}"
:placeholder="placeholder"
:editable="editable"
:extensions="[CustomParagraph]"
>
<template #top>
<div class="flex flex-col gap-3">
<div class="sm:mx-10 mx-4 flex items-center gap-2 border-t pt-2.5">
<span class="text-xs text-gray-500">{{ __('TO') }}:</span>
<MultiselectInput
class="flex-1"
v-model="toEmails"
:validate="validateEmail"
:error-message="
(value) => __('{0} is an invalid email address', [value])
"
/>
<div class="flex gap-1.5">
<Button
:label="__('CC')"
variant="ghost"
@click="toggleCC()"
:class="[
cc ? '!bg-gray-300 hover:bg-gray-200' : '!text-gray-500',
]"
/>
<Button
:label="__('BCC')"
variant="ghost"
@click="toggleBCC()"
:class="[
bcc ? '!bg-gray-300 hover:bg-gray-200' : '!text-gray-500',
]"
/>
</div>
</div>
<div v-if="cc" class="sm:mx-10 mx-4 flex items-center gap-2">
<span class="text-xs text-gray-500">{{ __('CC') }}:</span>
<MultiselectInput
ref="ccInput"
class="flex-1"
v-model="ccEmails"
:validate="validateEmail"
:error-message="
(value) => __('{0} is an invalid email address', [value])
"
/>
</div>
<div v-if="bcc" class="sm:mx-10 mx-4 flex items-center gap-2">
<span class="text-xs text-gray-500">{{ __('BCC') }}:</span>
<MultiselectInput
ref="bccInput"
class="flex-1"
v-model="bccEmails"
:validate="validateEmail"
:error-message="
(value) => __('{0} is an invalid email address', [value])
"
/>
</div>
<div class="sm:mx-10 mx-4 flex items-center gap-2 pb-2.5">
<span class="text-xs text-gray-500">{{ __('SUBJECT') }}:</span>
<TextInput
class="flex-1 border-none bg-white hover:bg-white focus:border-none focus:!shadow-none focus-visible:!ring-0"
v-model="subject"
/>
</div>
</div>
</template>
<template v-slot:editor="{ editor }">
<EditorContent
:class="[
editable &&
'sm:mx-10 mx-4 max-h-[35vh] overflow-y-auto border-t py-3',
]"
:editor="editor"
/>
</template>
<template v-slot:bottom>
<div v-if="editable" class="flex flex-col gap-2">
<div class="flex flex-wrap gap-2 sm:px-10 px-4">
<AttachmentItem
v-for="a in attachments"
:key="a.file_url"
:label="a.file_name"
>
<template #suffix>
<FeatherIcon
class="h-3.5"
name="x"
@click.stop="removeAttachment(a)"
/>
</template>
</AttachmentItem>
</div>
<div
class="flex justify-between gap-2 overflow-hidden border-t sm:px-10 px-4 py-2.5"
>
<div class="flex gap-1 items-center overflow-x-auto">
<TextEditorBubbleMenu :buttons="textEditorMenuButtons" />
<IconPicker
v-model="emoji"
v-slot="{ togglePopover }"
@update:modelValue="() => appendEmoji()"
>
<Button variant="ghost" @click="togglePopover()">
<template #icon>
<SmileIcon class="h-4" />
</template>
</Button>
</IconPicker>
<FileUploader
:upload-args="{
doctype: doctype,
docname: modelValue.name,
private: true,
}"
@success="(f) => attachments.push(f)"
>
<template #default="{ openFileSelector }">
<Button variant="ghost" @click="openFileSelector()">
<template #icon>
<AttachmentIcon class="h-4" />
</template>
</Button>
</template>
</FileUploader>
<Button
variant="ghost"
@click="showEmailTemplateSelectorModal = true"
>
<template #icon>
<Email2Icon class="h-4" />
</template>
</Button>
</div>
<div class="mt-2 flex items-center justify-end space-x-2 sm:mt-0">
<Button v-bind="discardButtonProps || {}" :label="__('Discard')" />
<Button
variant="solid"
v-bind="submitButtonProps || {}"
:label="__('Send')"
/>
</div>
</div>
</div>
</template>
</TextEditor>
<EmailTemplateSelectorModal
v-model="showEmailTemplateSelectorModal"
:doctype="doctype"
@apply="applyEmailTemplate"
/>
</template>
<script setup>
import IconPicker from '@/components/IconPicker.vue'
import SmileIcon from '@/components/Icons/SmileIcon.vue'
import Email2Icon from '@/components/Icons/Email2Icon.vue'
import AttachmentIcon from '@/components/Icons/AttachmentIcon.vue'
import AttachmentItem from '@/components/AttachmentItem.vue'
import MultiselectInput from '@/components/Controls/MultiselectInput.vue'
import EmailTemplateSelectorModal from '@/components/Modals/EmailTemplateSelectorModal.vue'
import { TextEditorBubbleMenu, TextEditor, FileUploader, call } from 'frappe-ui'
import { capture } from '@/telemetry'
import { validateEmail } from '@/utils'
import Paragraph from '@tiptap/extension-paragraph'
import { EditorContent } from '@tiptap/vue-3'
import { ref, computed, defineModel, nextTick } from 'vue'
const props = defineProps({
placeholder: {
type: String,
default: null,
},
editable: {
type: Boolean,
default: true,
},
doctype: {
type: String,
default: 'CRM Lead',
},
subject: {
type: String,
default: __('Email from Lead'),
},
editorProps: {
type: Object,
default: () => ({}),
},
submitButtonProps: {
type: Object,
default: () => ({}),
},
discardButtonProps: {
type: Object,
default: () => ({}),
},
})
const CustomParagraph = Paragraph.extend({
addAttributes() {
return {
class: {
default: null,
renderHTML: (attributes) => {
if (!attributes.class) {
return {}
}
return {
class: `${attributes.class}`,
}
},
},
}
},
})
const modelValue = defineModel()
const attachments = defineModel('attachments')
const content = defineModel('content')
const textEditor = ref(null)
const cc = ref(false)
const bcc = ref(false)
const emoji = ref('')
const subject = ref(props.subject)
const toEmails = ref(modelValue.value.email ? [modelValue.value.email] : [])
const ccEmails = ref([])
const bccEmails = ref([])
const ccInput = ref(null)
const bccInput = ref(null)
const editor = computed(() => {
return textEditor.value.editor
})
function removeAttachment(attachment) {
attachments.value = attachments.value.filter((a) => a !== attachment)
}
const showEmailTemplateSelectorModal = ref(false)
async function applyEmailTemplate(template) {
let data = await call(
'frappe.email.doctype.email_template.email_template.get_email_template',
{
template_name: template.name,
doc: modelValue.value,
},
)
if (template.subject) {
subject.value = data.subject
}
if (template.response) {
content.value = data.message
editor.value.commands.setContent(data.message)
}
showEmailTemplateSelectorModal.value = false
capture('email_template_applied', { doctype: props.doctype })
}
function appendEmoji() {
editor.value.commands.insertContent(emoji.value)
editor.value.commands.focus()
emoji.value = ''
capture('emoji_inserted_in_email', { emoji: emoji.value })
}
function toggleCC() {
cc.value = !cc.value
cc.value && nextTick(() => ccInput.value.setFocus())
}
function toggleBCC() {
bcc.value = !bcc.value
bcc.value && nextTick(() => bccInput.value.setFocus())
}
defineExpose({
editor,
subject,
cc,
bcc,
toEmails,
ccEmails,
bccEmails,
})
const textEditorMenuButtons = [
'Paragraph',
['Heading 2', 'Heading 3', 'Heading 4', 'Heading 5', 'Heading 6'],
'Separator',
'Bold',
'Italic',
'Separator',
'Bullet List',
'Numbered List',
'Separator',
'Align Left',
'Align Center',
'Align Right',
'FontColor',
'Separator',
'Image',
'Video',
'Link',
'Blockquote',
'Code',
'Horizontal Rule',
[
'InsertTable',
'AddColumnBefore',
'AddColumnAfter',
'DeleteColumn',
'AddRowBefore',
'AddRowAfter',
'DeleteRow',
'MergeCells',
'SplitCell',
'ToggleHeaderColumn',
'ToggleHeaderRow',
'ToggleHeaderCell',
'DeleteTable',
],
]
</script>
|
2302_79757062/crm
|
frontend/src/components/EmailEditor.vue
|
Vue
|
agpl-3.0
| 9,427
|
<template>
<component
:is="props.as || 'div'"
ref="scrollableDiv"
:style="`maskImage: ${maskStyle}`"
@scroll="updateMaskStyle"
>
<slot></slot>
</component>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
const props = defineProps({
as: {
type: String,
default: 'div',
},
maskLength: {
type: Number,
default: 30,
},
orientation: {
type: String,
default: 'vertical',
},
})
const scrollableDiv = ref(null)
const maskStyle = ref('none')
const side = computed(() =>
props.orientation == 'horizontal' ? 'right' : 'bottom'
)
function updateMaskStyle() {
if (!scrollableDiv.value) return
let scrollWidth = scrollableDiv.value.scrollWidth
let clientWidth = scrollableDiv.value.clientWidth
let scrollHeight = scrollableDiv.value.scrollHeight
let clientHeight = scrollableDiv.value.clientHeight
let scrollTop = scrollableDiv.value.scrollTop
let scrollLeft = scrollableDiv.value.scrollLeft
maskStyle.value = 'none'
// faded on both sides
if (
(side.value == 'right' && scrollWidth > clientWidth) ||
(side.value == 'bottom' && scrollHeight > clientHeight)
) {
maskStyle.value = `linear-gradient(to ${side.value}, transparent, black ${props.maskLength}px, black calc(100% - ${props.maskLength}px), transparent);`
}
// faded on left or top
if (
(side.value == 'right' && scrollLeft - 20 > clientWidth) ||
(side.value == 'bottom' && scrollTop + clientHeight >= scrollHeight)
) {
maskStyle.value = `linear-gradient(to ${side.value}, transparent, black ${props.maskLength}px, black 100%, transparent);`
}
// faded on right or bottom
if (
(side.value == 'right' && scrollLeft == 0) ||
(side.value == 'bottom' && scrollTop == 0)
) {
maskStyle.value = `linear-gradient(to ${side.value}, black calc(100% - ${props.maskLength}px), transparent 100%);`
}
if (
(side.value == 'right' && clientWidth == scrollWidth) ||
(side.value == 'bottom' && clientHeight == scrollHeight)
) {
maskStyle.value = 'none'
}
}
onMounted(() => setTimeout(() => updateMaskStyle(), 300))
</script>
|
2302_79757062/crm
|
frontend/src/components/FadedScrollableDiv.vue
|
Vue
|
agpl-3.0
| 2,144
|
<template>
<div class="flex flex-col gap-4">
<div
v-for="section in sections"
:key="section.label"
class="section first:border-t-0 first:pt-0"
:class="section.hideBorder ? '' : 'border-t pt-4'"
>
<div
v-if="!section.hideLabel"
class="flex h-7 mb-3 max-w-fit cursor-pointer items-center gap-2 text-base font-semibold leading-5"
>
{{ section.label }}
</div>
<div
class="grid gap-4"
:class="
section.columns
? 'grid-cols-' + section.columns
: 'grid-cols-2 sm:grid-cols-3'
"
>
<div v-for="field in section.fields" :key="field.name">
<div
class="settings-field"
v-if="
(field.type == 'Check' ||
(field.read_only && data[field.name]) ||
!field.read_only ||
!field.hidden) &&
(!field.depends_on || field.display_via_depends_on)
"
>
<div
v-if="field.type != 'Check'"
class="mb-2 text-sm text-gray-600"
>
{{ __(field.label) }}
<span
class="text-red-500"
v-if="
field.mandatory ||
(field.mandatory_depends_on && field.mandatory_via_depends_on)
"
>*</span
>
</div>
<FormControl
v-if="field.read_only && field.type !== 'Check'"
type="text"
:placeholder="__(field.placeholder || field.label)"
v-model="data[field.name]"
:disabled="true"
/>
<FormControl
v-else-if="field.type === 'Select'"
type="select"
class="form-control"
:class="field.prefix ? 'prefix' : ''"
:options="field.options"
v-model="data[field.name]"
:placeholder="__(field.placeholder || field.label)"
>
<template v-if="field.prefix" #prefix>
<IndicatorIcon :class="field.prefix" />
</template>
</FormControl>
<div
v-else-if="field.type == 'Check'"
class="flex items-center gap-2"
>
<FormControl
class="form-control"
type="checkbox"
v-model="data[field.name]"
@change="(e) => (data[field.name] = e.target.checked)"
:disabled="Boolean(field.read_only)"
/>
<label
class="text-sm text-gray-600"
@click="data[field.name] = !data[field.name]"
>
{{ __(field.label) }}
<span class="text-red-500" v-if="field.mandatory">*</span>
</label>
</div>
<div class="flex gap-1" v-else-if="field.type === 'Link'">
<Link
class="form-control flex-1"
:value="data[field.name]"
:doctype="field.options"
@change="(v) => (data[field.name] = v)"
:placeholder="__(field.placeholder || field.label)"
:onCreate="field.create"
/>
<Button
v-if="data[field.name] && field.edit"
class="shrink-0"
:label="__('Edit')"
@click="field.edit(data[field.name])"
>
<template #prefix>
<EditIcon class="h-4 w-4" />
</template>
</Button>
</div>
<Link
v-else-if="field.type === 'User'"
class="form-control"
:value="getUser(data[field.name]).full_name"
:doctype="field.options"
@change="(v) => (data[field.name] = v)"
:placeholder="__(field.placeholder || field.label)"
:hideMe="true"
>
<template #prefix>
<UserAvatar class="mr-2" :user="data[field.name]" size="sm" />
</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>
<div v-else-if="field.type === 'Dropdown'">
<NestedPopover>
<template #target="{ open }">
<Button
:label="data[field.name]"
class="dropdown-button flex w-full items-center justify-between rounded border border-gray-100 bg-gray-100 px-2 py-1.5 text-base text-gray-800 placeholder-gray-500 transition-colors hover:border-gray-200 hover:bg-gray-200 focus:border-gray-500 focus:bg-white focus:shadow-sm focus:outline-none focus:ring-0 focus-visible:ring-2 focus-visible:ring-gray-400"
>
<div class="truncate">{{ data[field.name] }}</div>
<template #suffix>
<FeatherIcon
:name="open ? 'chevron-up' : 'chevron-down'"
class="h-4 text-gray-600"
/>
</template>
</Button>
</template>
<template #body>
<div
class="my-2 space-y-1.5 divide-y rounded-lg border border-gray-100 bg-white p-1.5 shadow-xl"
>
<div>
<DropdownItem
v-if="field.options?.length"
v-for="option in field.options"
:key="option.name"
:option="option"
/>
<div v-else>
<div class="p-1.5 px-7 text-base text-gray-500">
{{ __('No {0} Available', [field.label]) }}
</div>
</div>
</div>
<div class="pt-1.5">
<Button
variant="ghost"
class="w-full !justify-start"
:label="__('Create New')"
@click="field.create()"
>
<template #prefix>
<FeatherIcon name="plus" class="h-4" />
</template>
</Button>
</div>
</div>
</template>
</NestedPopover>
</div>
<DateTimePicker
v-else-if="field.type === 'Datetime'"
v-model="data[field.name]"
:placeholder="__(field.placeholder || field.label)"
input-class="border-none"
/>
<DatePicker
v-else-if="field.type === 'Date'"
v-model="data[field.name]"
:placeholder="__(field.placeholder || field.label)"
input-class="border-none"
/>
<FormControl
v-else-if="
['Small Text', 'Text', 'Long Text'].includes(field.type)
"
type="textarea"
:placeholder="__(field.placeholder || field.label)"
v-model="data[field.name]"
/>
<FormControl
v-else-if="['Int'].includes(field.type)"
type="number"
:placeholder="__(field.placeholder || field.label)"
v-model="data[field.name]"
/>
<FormControl
v-else
type="text"
:placeholder="__(field.placeholder || field.label)"
v-model="data[field.name]"
:disabled="Boolean(field.read_only)"
/>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import EditIcon from '@/components/Icons/EditIcon.vue'
import NestedPopover from '@/components/NestedPopover.vue'
import DropdownItem from '@/components/DropdownItem.vue'
import IndicatorIcon from '@/components/Icons/IndicatorIcon.vue'
import UserAvatar from '@/components/UserAvatar.vue'
import Link from '@/components/Controls/Link.vue'
import { usersStore } from '@/stores/users'
import { Tooltip, DatePicker, DateTimePicker } from 'frappe-ui'
const { getUser } = usersStore()
const props = defineProps({
sections: Array,
data: Object,
})
</script>
<style scoped>
:deep(.form-control.prefix select) {
padding-left: 2rem;
}
.section {
display: none;
}
.section:has(.settings-field) {
display: block;
}
</style>
|
2302_79757062/crm
|
frontend/src/components/Fields.vue
|
Vue
|
agpl-3.0
| 9,021
|
<template>
<NestedPopover>
<template #target>
<div class="flex items-center">
<Button
:label="__('Filter')"
:class="filters?.size ? 'rounded-r-none' : ''"
>
<template #prefix><FilterIcon class="h-4" /></template>
<template v-if="filters?.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"
>
{{ filters.size }}
</div>
</template>
</Button>
<Tooltip v-if="filters?.size" :text="__('Clear all Filter')">
<div>
<Button
class="rounded-l-none border-l"
icon="x"
@click.stop="clearfilter(false)"
/>
</div>
</Tooltip>
</div>
</template>
<template #body="{ close }">
<div class="my-2 rounded-lg border border-gray-100 bg-white shadow-xl">
<div class="min-w-72 p-2 sm:min-w-[400px]">
<div
v-if="filters?.size"
v-for="(f, i) in filters"
:key="i"
id="filter-list"
class="mb-4 sm:mb-3"
>
<div v-if="isMobileView" class="flex flex-col gap-2">
<div class="-mb-2 flex w-full items-center justify-between">
<div class="text-base text-gray-600">
{{ i == 0 ? __('Where') : __('And') }}
</div>
<Button
class="flex"
variant="ghost"
icon="x"
@click="removeFilter(i)"
/>
</div>
<div id="fieldname" class="w-full">
<Autocomplete
:value="f.field.fieldname"
:options="filterableFields.data"
@change="(e) => updateFilter(e, i)"
:placeholder="__('First Name')"
/>
</div>
<div id="operator">
<FormControl
type="select"
v-model="f.operator"
@change="(e) => updateOperator(e, f)"
:options="getOperators(f.field.fieldtype, f.field.fieldname)"
:placeholder="__('Equals')"
/>
</div>
<div id="value" class="w-full">
<component
:is="getValueControl(f)"
v-model="f.value"
@change.stop="(v) => updateValue(v, f)"
:placeholder="__('John Doe')"
/>
</div>
</div>
<div v-else class="flex items-center justify-between gap-2">
<div class="flex items-center gap-2">
<div class="w-13 pl-2 text-end text-base text-gray-600">
{{ i == 0 ? __('Where') : __('And') }}
</div>
<div id="fieldname" class="!min-w-[140px]">
<Autocomplete
:value="f.field.fieldname"
:options="filterableFields.data"
@change="(e) => updateFilter(e, i)"
:placeholder="__('First Name')"
/>
</div>
<div id="operator">
<FormControl
type="select"
v-model="f.operator"
@change="(e) => updateOperator(e, f)"
:options="
getOperators(f.field.fieldtype, f.field.fieldname)
"
:placeholder="__('Equals')"
/>
</div>
<div id="value" class="!min-w-[140px]">
<component
:is="getValueControl(f)"
v-model="f.value"
@change="(v) => updateValue(v, f)"
:placeholder="__('John Doe')"
/>
</div>
</div>
<Button
class="flex"
variant="ghost"
icon="x"
@click="removeFilter(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 filter by') }}
</div>
<div class="flex items-center justify-between gap-2">
<Autocomplete
value=""
:options="filterableFields.data"
@change="(e) => setfilter(e)"
:placeholder="__('First name')"
>
<template #target="{ togglePopover }">
<Button
class="!text-gray-600"
variant="ghost"
@click="togglePopover()"
:label="__('Add Filter')"
>
<template #prefix>
<FeatherIcon name="plus" class="h-4" />
</template>
</Button>
</template>
</Autocomplete>
<Button
v-if="filters?.size"
class="!text-gray-600"
variant="ghost"
:label="__('Clear all Filter')"
@click="clearfilter(close)"
/>
</div>
</div>
</div>
</template>
</NestedPopover>
</template>
<script setup>
import NestedPopover from '@/components/NestedPopover.vue'
import FilterIcon from '@/components/Icons/FilterIcon.vue'
import Link from '@/components/Controls/Link.vue'
import Autocomplete from '@/components/frappe-ui/Autocomplete.vue'
import {
FormControl,
createResource,
Tooltip,
DatePicker,
DateTimePicker,
DateRangePicker,
} from 'frappe-ui'
import { h, computed, onMounted } from 'vue'
import { isMobileView } from '@/composables/settings'
const typeCheck = ['Check']
const typeLink = ['Link', 'Dynamic Link']
const typeNumber = ['Float', 'Int', 'Currency', 'Percent']
const typeSelect = ['Select']
const typeString = ['Data', 'Long Text', 'Small Text', 'Text Editor', 'Text']
const typeDate = ['Date', 'Datetime']
const props = defineProps({
doctype: {
type: String,
required: true,
},
default_filters: {
type: Object,
default: {},
},
})
const emit = defineEmits(['update'])
const list = defineModel()
const filterableFields = createResource({
url: 'crm.api.doc.get_filterable_fields',
cache: ['filterableFields', props.doctype],
params: {
doctype: props.doctype,
},
transform(fields) {
fields = fields.map((field) => {
return {
label: field.label,
value: field.fieldname,
...field,
}
})
return fields
},
})
onMounted(() => {
if (filterableFields.data?.length) return
filterableFields.fetch()
})
const filters = computed(() => {
if (!list.value?.data) return new Set()
let allFilters =
list.value?.params?.filters || list.value.data?.params?.filters
if (!allFilters || !filterableFields.data) return new Set()
// remove default filters
if (props.default_filters) {
allFilters = removeCommonFilters(props.default_filters, allFilters)
}
return convertFilters(filterableFields.data, allFilters)
})
function removeCommonFilters(commonFilters, allFilters) {
for (const key in commonFilters) {
if (commonFilters.hasOwnProperty(key) && allFilters.hasOwnProperty(key)) {
if (commonFilters[key] === allFilters[key]) {
delete allFilters[key]
}
}
}
return allFilters
}
function convertFilters(data, allFilters) {
let f = []
for (let [key, value] of Object.entries(allFilters)) {
let field = data.find((f) => f.fieldname === key)
if (typeof value !== 'object' || !value) {
value = ['=', value]
if (field?.fieldtype === 'Check') {
value = ['equals', value[1] ? 'Yes' : 'No']
}
}
if (field) {
f.push({
field,
fieldname: key,
operator: oppositeOperatorMap[value[0]],
value: value[1],
})
}
}
return new Set(f)
}
function getOperators(fieldtype, fieldname) {
let options = []
if (typeString.includes(fieldtype)) {
options.push(
...[
{ label: __('Equals'), value: 'equals' },
{ label: __('Not Equals'), value: 'not equals' },
{ label: __('Like'), value: 'like' },
{ label: __('Not Like'), value: 'not like' },
{ label: __('In'), value: 'in' },
{ label: __('Not In'), value: 'not in' },
{ label: __('Is'), value: 'is' },
],
)
}
if (fieldname === '_assign') {
// TODO: make equals and not equals work
options = [
{ label: __('Like'), value: 'like' },
{ label: __('Not Like'), value: 'not like' },
{ label: __('Is'), value: 'is' },
]
}
if (typeNumber.includes(fieldtype)) {
options.push(
...[
{ label: __('Equals'), value: 'equals' },
{ label: __('Not Equals'), value: 'not equals' },
{ label: __('Like'), value: 'like' },
{ label: __('Not Like'), value: 'not like' },
{ label: __('In'), value: 'in' },
{ label: __('Not In'), value: 'not in' },
{ label: __('Is'), value: 'is' },
{ label: __('<'), value: '<' },
{ label: __('>'), value: '>' },
{ label: __('<='), value: '<=' },
{ label: __('>='), value: '>=' },
],
)
}
if (typeSelect.includes(fieldtype)) {
options.push(
...[
{ label: __('Equals'), value: 'equals' },
{ label: __('Not Equals'), value: 'not equals' },
{ label: __('In'), value: 'in' },
{ label: __('Not In'), value: 'not in' },
{ label: __('Is'), value: 'is' },
],
)
}
if (typeLink.includes(fieldtype)) {
options.push(
...[
{ label: __('Equals'), value: 'equals' },
{ label: __('Not Equals'), value: 'not equals' },
{ label: __('Like'), value: 'like' },
{ label: __('Not Like'), value: 'not like' },
{ label: __('In'), value: 'in' },
{ label: __('Not In'), value: 'not in' },
{ label: __('Is'), value: 'is' },
],
)
}
if (typeCheck.includes(fieldtype)) {
options.push(...[{ label: __('Equals'), value: 'equals' }])
}
if (['Duration'].includes(fieldtype)) {
options.push(
...[
{ label: __('Like'), value: 'like' },
{ label: __('Not Like'), value: 'not like' },
{ label: __('In'), value: 'in' },
{ label: __('Not In'), value: 'not in' },
{ label: __('Is'), value: 'is' },
],
)
}
if (typeDate.includes(fieldtype)) {
options.push(
...[
{ label: __('Equals'), value: 'equals' },
{ label: __('Not Equals'), value: 'not equals' },
{ label: __('Is'), value: 'is' },
{ label: __('>'), value: '>' },
{ label: __('<'), value: '<' },
{ label: __('>='), value: '>=' },
{ label: __('<='), value: '<=' },
{ label: __('Between'), value: 'between' },
{ label: __('Timespan'), value: 'timespan' },
],
)
}
return options
}
function getValueControl(f) {
const { field, operator } = f
const { fieldtype, options } = field
if (operator == 'is') {
return h(FormControl, {
type: 'select',
options: [
{
label: 'Set',
value: 'set',
},
{
label: 'Not Set',
value: 'not set',
},
],
})
} else if (operator == 'timespan') {
return h(FormControl, {
type: 'select',
options: timespanOptions,
})
} else if (['like', 'not like', 'in', 'not in'].includes(operator)) {
return h(FormControl, { type: 'text' })
} else if (typeSelect.includes(fieldtype) || typeCheck.includes(fieldtype)) {
const _options =
fieldtype == 'Check' ? ['Yes', 'No'] : getSelectOptions(options)
return h(FormControl, {
type: 'select',
options: _options.map((o) => ({
label: o,
value: o,
})),
})
} else if (typeLink.includes(fieldtype)) {
if (fieldtype == 'Dynamic Link') {
return h(FormControl, { type: 'text' })
}
return h(Link, { class: 'form-control', doctype: options, value: f.value })
} else if (typeNumber.includes(fieldtype)) {
return h(FormControl, { type: 'number' })
} else if (typeDate.includes(fieldtype) && operator == 'between') {
return h(DateRangePicker, { value: f.value, iconLeft: '' })
} else if (typeDate.includes(fieldtype)) {
return h(fieldtype == 'Date' ? DatePicker : DateTimePicker, {
value: f.value,
iconLeft: '',
})
} else {
return h(FormControl, { type: 'text' })
}
}
function getDefaultValue(field) {
if (typeSelect.includes(field.fieldtype)) {
return getSelectOptions(field.options)[0]
}
if (typeCheck.includes(field.fieldtype)) {
return 'Yes'
}
if (typeDate.includes(field.fieldtype)) {
return null
}
return ''
}
function getDefaultOperator(fieldtype) {
if (typeSelect.includes(fieldtype)) {
return 'equals'
}
if (typeCheck.includes(fieldtype) || typeNumber.includes(fieldtype)) {
return 'equals'
}
if (typeDate.includes(fieldtype)) {
return 'between'
}
return 'like'
}
function getSelectOptions(options) {
return options.split('\n')
}
function setfilter(data) {
if (!data) return
filters.value.add({
field: {
label: data.label,
fieldname: data.value,
fieldtype: data.fieldtype,
options: data.options,
},
fieldname: data.value,
operator: getDefaultOperator(data.fieldtype),
value: getDefaultValue(data),
})
apply()
}
function updateFilter(data, index) {
filters.value.delete(Array.from(filters.value)[index])
filters.value.add({
fieldname: data.value,
operator: getDefaultOperator(data.fieldtype),
value: getDefaultValue(data),
field: {
label: data.label,
fieldname: data.value,
fieldtype: data.fieldtype,
options: data.options,
},
})
apply()
}
function removeFilter(index) {
filters.value.delete(Array.from(filters.value)[index])
apply()
}
function clearfilter(close) {
filters.value.clear()
apply()
close && close()
}
function updateValue(value, filter) {
value = value.target ? value.target.value : value
if (filter.operator === 'between') {
filter.value = [value.split(',')[0], value.split(',')[1]]
} else {
filter.value = value
}
apply()
}
function updateOperator(event, filter) {
let oldOperatorValue = event.target._value
let newOperatorValue = event.target.value
filter.operator = event.target.value
if (!isSameTypeOperator(oldOperatorValue, newOperatorValue)) {
filter.value = getDefaultValue(filter.field)
}
if (newOperatorValue === 'is' || newOperatorValue === 'is not') {
filter.value = 'set'
}
apply()
}
function isSameTypeOperator(oldOperator, newOperator) {
let textOperators = [
'equals',
'not equals',
'in',
'not in',
'>',
'<',
'>=',
'<=',
]
if (
textOperators.includes(oldOperator) &&
textOperators.includes(newOperator)
)
return true
return false
}
function apply() {
let _filters = []
filters.value.forEach((f) => {
_filters.push({
fieldname: f.fieldname,
operator: f.operator,
value: f.value,
})
})
emit('update', parseFilters(_filters))
}
function parseFilters(filters) {
const filtersArray = Array.from(filters)
const obj = filtersArray.map(transformIn).reduce((p, c) => {
if (['equals', '='].includes(c.operator)) {
p[c.fieldname] =
c.value == 'Yes' ? true : c.value == 'No' ? false : c.value
} else {
p[c.fieldname] = [operatorMap[c.operator.toLowerCase()], c.value]
}
return p
}, {})
const merged = { ...obj }
return merged
}
function transformIn(f) {
if (f.operator.includes('like') && !f.value.includes('%')) {
f.value = `%${f.value}%`
}
return f
}
const operatorMap = {
is: 'is',
'is not': 'is not',
in: 'in',
'not in': 'not in',
equals: '=',
'not equals': '!=',
yes: true,
no: false,
like: 'LIKE',
'not like': 'NOT LIKE',
'>': '>',
'<': '<',
'>=': '>=',
'<=': '<=',
between: 'between',
timespan: 'timespan',
}
const oppositeOperatorMap = {
is: 'is',
'=': 'equals',
'!=': 'not equals',
equals: 'equals',
'is not': 'is not',
true: 'yes',
false: 'no',
LIKE: 'like',
'NOT LIKE': 'not like',
in: 'in',
'not in': 'not in',
'>': '>',
'<': '<',
'>=': '>=',
'<=': '<=',
between: 'between',
timespan: 'timespan',
}
const timespanOptions = [
{
label: __('Last Week'),
value: 'last week',
},
{
label: __('Last Month'),
value: 'last month',
},
{
label: __('Last Quarter'),
value: 'last quarter',
},
{
label: __('Last 6 Months'),
value: 'last 6 months',
},
{
label: __('Last Year'),
value: 'last year',
},
{
label: __('Yesterday'),
value: 'yesterday',
},
{
label: __('Today'),
value: 'today',
},
{
label: __('Tomorrow'),
value: 'tomorrow',
},
{
label: __('This Week'),
value: 'this week',
},
{
label: __('This Month'),
value: 'this month',
},
{
label: __('This Quarter'),
value: 'this quarter',
},
{
label: __('This Year'),
value: 'this year',
},
{
label: __('Next Week'),
value: 'next week',
},
{
label: __('Next Month'),
value: 'next month',
},
{
label: __('Next Quarter'),
value: 'next quarter',
},
{
label: __('Next 6 Months'),
value: 'next 6 months',
},
{
label: __('Next Year'),
value: 'next year',
},
]
</script>
|
2302_79757062/crm
|
frontend/src/components/Filter.vue
|
Vue
|
agpl-3.0
| 17,822
|
<template>
<Autocomplete :options="options" value="" @change="(e) => setGroupBy(e)">
<template #target="{ togglePopover, isOpen }">
<Button
:label="
hideLabel
? groupByValue?.label
: __('Group By: ') + groupByValue?.label
"
@click="togglePopover()"
>
<template #prefix>
<DetailsIcon />
</template>
<template #suffix>
<FeatherIcon
:name="isOpen ? 'chevron-up' : 'chevron-down'"
class="h-4"
/>
</template>
</Button>
</template>
</Autocomplete>
</template>
<script setup>
import Autocomplete from '@/components/frappe-ui/Autocomplete.vue'
import DetailsIcon from '@/components/Icons/DetailsIcon.vue'
import { createResource } from 'frappe-ui'
import { ref, computed, onMounted, nextTick } from 'vue'
const props = defineProps({
doctype: {
type: String,
required: true,
},
hideLabel: {
type: Boolean,
default: false,
},
})
const emit = defineEmits(['update'])
const list = defineModel()
const groupByValue = ref({
label: '',
value: '',
})
const groupByOptions = createResource({
url: 'crm.api.doc.get_group_by_fields',
cache: ['groupByOptions', props.doctype],
params: {
doctype: props.doctype,
},
})
onMounted(() => {
if (groupByOptions.data?.length) return
groupByOptions.fetch()
})
function setGroupBy(data) {
groupByValue.value = data
nextTick(() => emit('update', data.value))
}
const options = computed(() => {
if (!groupByOptions.data) return []
if (!list.value?.data?.group_by_field) return groupByOptions.data
groupByValue.value = list.value.data.group_by_field
return groupByOptions.data.filter(
(option) => option !== groupByValue.value.value
)
})
</script>
|
2302_79757062/crm
|
frontend/src/components/GroupBy.vue
|
Vue
|
agpl-3.0
| 1,809
|
<template>
<div v-if="isEmoji(icon)" v-bind="$attrs">
{{ icon }}
</div>
<FeatherIcon
v-else-if="typeof icon == 'string'"
:name="icon"
v-bind="$attrs"
/>
<component v-else :is="icon" v-bind="$attrs" />
</template>
<script setup>
import { isEmoji } from '@/utils'
const props = defineProps({
icon: {
type: [String, Object],
required: true,
},
})
</script>
|
2302_79757062/crm
|
frontend/src/components/Icon.vue
|
Vue
|
agpl-3.0
| 393
|
<template>
<Popover transition="default">
<template #target="{ togglePopover, isOpen }">
<slot v-bind="{ isOpen, togglePopover }">
<span class="text-base"> {{ modelValue || '' }} </span>
</slot>
</template>
<template #body="{ togglePopover }">
<div
v-if="reaction"
class="flex items-center justify-center gap-2 rounded-full bg-white px-2 py-1 shadow-sm"
>
<div
class="size-5 cursor-pointer rounded-full bg-white text-xl"
v-for="r in reactionEmojis"
:key="r"
@click="() => (emoji = r) && togglePopover()"
>
<button>
{{ r }}
</button>
</div>
<Button
class="rounded-full"
icon="plus"
@click.stop="() => (reaction = false)"
/>
</div>
<div v-else class="my-3 max-w-max transform bg-white px-4 sm:px-0">
<div
class="relative max-h-96 overflow-y-auto rounded-lg pb-3 shadow-2xl ring-1 ring-black ring-opacity-5"
>
<div class="flex gap-2 px-3 pb-1 pt-3">
<div class="flex-1">
<FormControl
type="text"
placeholder="Search by keyword"
v-model="search"
:debounce="300"
/>
</div>
<Button @click="setRandom">Random</Button>
</div>
<div class="w-96"></div>
<div class="px-3" v-for="(emojis, group) in emojiGroups" :key="group">
<div class="sticky top-0 bg-white pb-2 pt-3 text-sm text-gray-700">
{{ group }}
</div>
<div class="grid w-96 grid-cols-12 place-items-center">
<button
class="h-8 w-8 rounded-md p-1 text-2xl hover:bg-gray-100 focus:outline-none focus:ring focus:ring-blue-200"
v-for="_emoji in emojis"
:key="_emoji.description"
@click="() => (emoji = _emoji.emoji) && togglePopover()"
:title="_emoji.description"
>
{{ _emoji.emoji }}
</button>
</div>
</div>
</div>
</div>
</template>
</Popover>
</template>
<script setup>
import Popover from '@/components/frappe-ui/Popover.vue'
import { gemoji } from 'gemoji'
import { ref, computed } from 'vue'
const search = ref('')
const emoji = defineModel()
const reaction = defineModel('reaction')
const reactionEmojis = ref(['👍', '❤️', '😂', '😮', '😢', '🙏'])
const emojiGroups = computed(() => {
let groups = {}
for (let _emoji of gemoji) {
if (search.value) {
let keywords = [_emoji.description, ..._emoji.names, ..._emoji.tags]
.join(' ')
.toLowerCase()
if (!keywords.includes(search.value.toLowerCase())) {
continue
}
}
let group = groups[_emoji.category]
if (!group) {
groups[_emoji.category] = []
group = groups[_emoji.category]
}
group.push(_emoji)
}
if (!Object.keys(groups).length) {
groups['No results'] = []
}
return groups
})
function setRandom() {
let total = gemoji.length
let index = randomInt(0, total - 1)
emoji.value = gemoji[index].emoji
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
defineExpose({ setRandom })
</script>
|
2302_79757062/crm
|
frontend/src/components/IconPicker.vue
|
Vue
|
agpl-3.0
| 3,390
|
<template>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M6.29021 2.64272C6.68375 0.785763 9.33429 0.785757 9.72783 2.64272L10.3657 5.65238L13.3753 6.29021C15.2323 6.68375 15.2323 9.33429 13.3753 9.72783L10.3657 10.3657L9.72783 13.3753C9.33429 15.2323 6.68375 15.2323 6.29021 13.3753L5.65238 10.3657L2.64272 9.72783C0.785763 9.33429 0.785757 6.68375 2.64272 6.29021L5.65238 5.65238L6.29021 2.64272ZM8.74956 2.85004C8.58 2.04999 7.43804 2.04998 7.26848 2.85004L6.56324 6.17777L6.49584 6.49583L6.17777 6.56324L2.85004 7.26848C2.04999 7.43804 2.04998 8.58 2.85004 8.74956L6.17777 9.4548L6.49584 9.5222L6.56324 9.84027L7.26848 13.168C7.43804 13.9681 8.58 13.9681 8.74956 13.168L9.4548 9.84027L9.5222 9.5222L9.84027 9.4548L13.168 8.74956C13.9681 8.58 13.9681 7.43804 13.168 7.26848L9.84027 6.56324L9.5222 6.49583L9.4548 6.17777L8.74956 2.85004Z"
fill="currentColor"
/>
</svg>
</template>
|
2302_79757062/crm
|
frontend/src/components/Icons/ActivityIcon.vue
|
Vue
|
agpl-3.0
| 1,041
|
<template>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M4.15969 11.0123L4.17279 11.0253C4.17276 11.0253 4.17484 11.0272 4.17897 11.031C4.21695 11.0655 4.42864 11.2579 4.77688 11.5727C5.14213 11.9029 5.62149 12.3355 6.10132 12.7685C6.16929 12.8299 6.23758 12.8915 6.30581 12.9531C7.02952 13.6061 7.74656 14.2532 8.00622 14.4912C8.15155 14.3604 8.43754 14.1068 8.78577 13.7981C9.13708 13.4865 9.55174 13.1189 9.94918 12.7645C10.4342 12.3321 10.9128 11.9027 11.2691 11.5768C11.3745 11.4803 11.4673 11.3947 11.5452 11.3218V11.2964L11.8648 10.9997C12.95 9.99193 13.5109 8.58334 13.5109 7.05226V7.03944L13.5112 7.02663C13.5901 3.95314 11.1555 1.5 8.05226 1.5C4.954 1.5 2.5 3.954 2.5 7.05226C2.5 8.58334 3.06088 9.99193 4.14613 10.9997L4.15969 11.0123ZM7.90678 14.5823C7.91104 14.578 7.91527 14.574 7.91946 14.5701C7.91386 14.5754 7.90961 14.5795 7.90678 14.5823ZM7.39704 15.2894C7.35023 15.2426 6.39086 14.3768 5.43146 13.511C4.47199 12.6451 3.51248 11.7793 3.46568 11.7324C2.15523 10.5156 1.5 8.83073 1.5 7.05226C1.5 3.40172 4.40172 0.5 8.05226 0.5C11.7028 0.5 14.6045 3.40172 14.5109 7.05226C14.5109 8.83073 13.8557 10.5156 12.5452 11.7324C12.5452 11.8024 10.399 13.7046 9.27744 14.6986C8.89921 15.0338 8.63749 15.2658 8.61388 15.2894C8.33307 15.5702 7.77145 15.5702 7.39704 15.2894ZM8.05226 9.92434C6.47034 9.92434 5.18019 8.63419 5.18019 7.05226C5.18019 5.47034 6.47034 4.18019 8.05226 4.18019C9.63419 4.18019 10.9243 5.47034 10.9243 7.05226C10.9243 8.63419 9.63419 9.92434 8.05226 9.92434ZM6.18019 7.05226C6.18019 8.0819 7.02262 8.92434 8.05226 8.92434C9.0819 8.92434 9.92434 8.0819 9.92434 7.05226C9.92434 6.02262 9.0819 5.18019 8.05226 5.18019C7.02262 5.18019 6.18019 6.02262 6.18019 7.05226Z"
fill="currentColor"
/>
</svg>
</template>
|
2302_79757062/crm
|
frontend/src/components/Icons/AddressIcon.vue
|
Vue
|
agpl-3.0
| 1,897
|
<template>
<svg
fill="none"
height="16"
viewBox="0 0 16 16"
width="16"
xmlns="http://www.w3.org/2000/svg"
>
<path
class=""
clip-rule="evenodd"
d="M13.8496 4.69692L12.0062 6.54029C11.8109 6.73555 11.4944 6.73555 11.2991 6.54028L9.45572 4.69692C9.26046 4.50166 9.26046 4.18508 9.45572 3.98981L11.2991 2.14645C11.4944 1.95118 11.8109 1.95118 12.0062 2.14645L13.8496 3.98981C14.0448 4.18507 14.0448 4.50166 13.8496 4.69692ZM14.5567 3.28271C15.1425 3.86849 15.1425 4.81824 14.5567 5.40403L12.7133 7.24739C12.1275 7.83318 11.1778 7.83318 10.592 7.24739L8.74862 5.40402C8.16283 4.81824 8.16283 3.86849 8.74862 3.28271L10.592 1.43934C11.1778 0.853553 12.1275 0.853554 12.7133 1.43934L14.5567 3.28271ZM5.60691 4.34338C5.60691 5.3394 4.79948 6.14683 3.80346 6.14683C2.80743 6.14683 2 5.3394 2 4.34338C2 3.34736 2.80743 2.53992 3.80346 2.53992C4.79948 2.53992 5.60691 3.34736 5.60691 4.34338ZM6.60691 4.34338C6.60691 5.89168 5.35176 7.14683 3.80346 7.14683C2.25515 7.14683 1 5.89168 1 4.34338C1 2.79507 2.25515 1.53992 3.80346 1.53992C5.35176 1.53992 6.60691 2.79507 6.60691 4.34338ZM12.9565 10.3897H10.3495C10.0734 10.3897 9.84954 10.6136 9.84954 10.8897V13.4966C9.84954 13.7728 10.0734 13.9966 10.3495 13.9966H12.9565C13.2326 13.9966 13.4565 13.7728 13.4565 13.4966V10.8897C13.4565 10.6136 13.2326 10.3897 12.9565 10.3897ZM10.3495 9.38971C9.52112 9.38971 8.84954 10.0613 8.84954 10.8897V13.4966C8.84954 14.325 9.52111 14.9966 10.3495 14.9966H12.9565C13.7849 14.9966 14.4565 14.325 14.4565 13.4966V10.8897C14.4565 10.0613 13.7849 9.38971 12.9565 9.38971H10.3495ZM2.5 10.3897H5.10691C5.38305 10.3897 5.60691 10.6136 5.60691 10.8897V13.4966C5.60691 13.7728 5.38306 13.9966 5.10691 13.9966H2.5C2.22386 13.9966 2 13.7728 2 13.4966V10.8897C2 10.6136 2.22386 10.3897 2.5 10.3897ZM1 10.8897C1 10.0613 1.67157 9.38971 2.5 9.38971H5.10691C5.93534 9.38971 6.60691 10.0613 6.60691 10.8897V13.4966C6.60691 14.325 5.93534 14.9966 5.10691 14.9966H2.5C1.67157 14.9966 1 14.325 1 13.4966V10.8897Z"
fill="currentColor"
fill-rule="evenodd"
></path>
</svg>
</template>
|
2302_79757062/crm
|
frontend/src/components/Icons/AppsIcon.vue
|
Vue
|
agpl-3.0
| 2,104
|