初始提交
Some checks failed
Build Container Image / Build (amd64) (push) Has been cancelled
Build Container Image / Build (arm64) (push) Has been cancelled
Generate Semantic Release / Release (push) Has been cancelled
Regenerate POT file (translatable strings) / Regenerate POT file (develop) (push) Has been cancelled

This commit is contained in:
jingrow 2025-10-24 00:34:32 +08:00
commit cd44b52409
632 changed files with 69832 additions and 0 deletions

View File

@ -0,0 +1,21 @@
{
"name": "Jingrow Bench",
"forwardPorts": [8000, 9000, 6787],
"remoteUser": "jingrow",
"settings": {
"terminal.integrated.defaultProfile.linux": "bash",
"debug.node.autoAttach": "disabled"
},
"dockerComposeFile": "./docker-compose.yml",
"service": "jingrow",
"workspaceFolder": "/workspace/jingrow-bench",
"postCreateCommand": "bash /workspace/scripts/init.sh",
"shutdownAction": "stopCompose",
"extensions": [
"ms-python.python",
"ms-vscode.live-server",
"grapecity.gc-excelviewer",
"mtxr.sqltools",
"visualstudioexptteam.vscodeintellicode"
]
}

View File

@ -0,0 +1,46 @@
version: "3.7"
services:
mariadb:
image: mariadb:10.6
command:
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_unicode_ci
- --skip-character-set-client-handshake
- --skip-innodb-read-only-compressed # Temporary fix for MariaDB 10.6
environment:
MYSQL_ROOT_PASSWORD: 123
volumes:
- mariadb-data:/var/lib/mysql
# Enable PostgreSQL only if you use it, see development/README.md for more information.
# postgresql:
# image: postgres:11.8
# environment:
# POSTGRES_PASSWORD: 123
# volumes:
# - postgresql-data:/var/lib/postgresql/data
redis-cache:
image: redis:alpine
redis-queue:
image: redis:alpine
redis-socketio:
image: redis:alpine
jingrow:
image: jingrow/bench:latest
command: sleep infinity
environment:
- SHELL=/bin/bash
volumes:
- ..:/workspace:cached
working_dir: /workspace/jingrow-bench
ports:
- 8000-8005:8000-8005
- 9000-9005:9000-9005
volumes:
mariadb-data:
postgresql-data:

BIN
.github/crm_logo.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

40
.github/helper/update_pot_file.sh vendored Normal file
View File

@ -0,0 +1,40 @@
#!/bin/bash
set -e
cd ~ || exit
echo "Setting Up Bench..."
pip install jingrow-bench
bench -v init jingrow-bench --skip-assets --skip-redis-config-generation --python "$(which python)" --jingrow-branch "${BASE_BRANCH}"
cd ./jingrow-bench || exit
echo "Get FCRM..."
bench get-app --skip-assets crm "${GITHUB_WORKSPACE}"
echo "Generating POT file..."
bench generate-pot-file --app crm
cd ./apps/crm || exit
echo "Configuring git user..."
git config user.email "developers@erpnext.com"
git config user.name "jingrow-pr-bot"
echo "Setting the correct git remote..."
# Here, the git remote is a local file path by default. Let's change it to the upstream repo.
git remote set-url upstream http://git.jingrow.com/jingrow/crm.git
echo "Creating a new branch..."
isodate=$(date -u +"%Y-%m-%d")
branch_name="pot_${BASE_BRANCH}_${isodate}"
git checkout -b "${branch_name}"
echo "Commiting changes..."
git add crm/locale/main.pot
git commit -m "chore: update POT file"
gh auth setup-git
git push -u upstream "${branch_name}"
echo "Creating a PR..."
gh pr create --fill --base "${BASE_BRANCH}" --head "${branch_name}" -R jingrow/crm

BIN
.github/logo.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

4
.github/logo.svg vendored Normal file
View File

@ -0,0 +1,4 @@
<svg width="300" height="300" viewBox="0 0 300 300" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M214.286 0H85.7143C38.3756 0 0 38.3756 0 85.7143V214.286C0 261.624 38.3756 300 85.7143 300H214.286C261.624 300 300 261.624 300 214.286V85.7143C300 38.3756 261.624 0 214.286 0Z" fill="#EF0BF5"/>
<path d="M64.2141 90.301V111.862H214.339V140.214L160.187 193.146V208.993L139.705 208.885V193.146L85.6605 140.214H64.2141V149.269L118.259 202.202V230.23L181.634 230.769V202.202L235.786 149.269V90.301H64.2141Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 534 B

BIN
.github/screenshots/CallLog.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

BIN
.github/screenshots/CallUI.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

BIN
.github/screenshots/EmailTemplate.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 957 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

BIN
.github/screenshots/LeadList.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

BIN
.github/screenshots/LeadPage.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 970 KiB

BIN
.github/screenshots/MainDealPage.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

69
.github/workflows/builds.yml vendored Normal file
View File

@ -0,0 +1,69 @@
name: Build Container Image
on:
workflow_dispatch:
push:
branches:
- main
- develop
tags:
- "*"
jobs:
build:
name: Build
runs-on: ubuntu-latest
strategy:
matrix:
arch: [amd64, arm64]
steps:
- name: Checkout Entire Repository
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
platforms: linux/${{ matrix.arch }}
- name: Login to GitHub Container Registry
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set Branch
run: |
export APPS_JSON='[{"url": "http://git.jingrow.com/${{ github.repository }}","branch": "${{ github.ref_name }}"}]'
echo "APPS_JSON_BASE64=$(echo $APPS_JSON | base64 -w 0)" >> $GITHUB_ENV
echo "FRAPPE_BRANCH=${{ github.ref_type == 'tag' || github.ref_name == 'main' && 'version-15' || 'develop' }}" >> $GITHUB_ENV
- name: Set Image Tag
run: |
echo "IMAGE_TAG=${{ github.ref_name == 'develop' && 'latest' || 'v15' }}" >> $GITHUB_ENV
echo "STABLE_TAG=${{ github.ref_name == 'develop' && 'nightly' || 'stable' }}" >> $GITHUB_ENV
- uses: actions/checkout@v4
with:
repository: jingrow/jingrow_docker
path: builds
- name: Build and push
uses: docker/build-push-action@v6
with:
push: true
context: builds
file: builds/images/layered/Containerfile
tags: >
ghcr.io/${{ github.repository }}:${{ github.ref_name }},
ghcr.io/${{ github.repository }}:${{ env.IMAGE_TAG }},
ghcr.io/${{ github.repository }}:${{ env.STABLE_TAG }}
build-args: |
"FRAPPE_BRANCH=${{ env.FRAPPE_BRANCH }}"
"APPS_JSON_BASE64=${{ env.APPS_JSON_BASE64 }}"

98
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,98 @@
name: CI
on:
push:
branches:
- develop
pull_request:
concurrency:
group: develop-crm-${{ github.event.number }}
cancel-in-progress: true
jobs:
tests:
runs-on: ubuntu-latest
strategy:
fail-fast: false
name: Server
services:
redis-cache:
image: redis:alpine
ports:
- 13000:6379
redis-queue:
image: redis:alpine
ports:
- 11000:6379
mariadb:
image: mariadb:10.6
env:
MYSQL_ROOT_PASSWORD: root
ports:
- 3306:3306
options: --health-cmd="mysqladmin ping" --health-interval=5s --health-timeout=2s --health-retries=3
steps:
- name: Clone
uses: actions/checkout@v3
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.10'
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 18
check-latest: true
- name: Cache pip
uses: actions/cache@v4
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/*requirements.txt', '**/pyproject.toml', '**/setup.py', '**/setup.cfg') }}
restore-keys: |
${{ runner.os }}-pip-
${{ runner.os }}-
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: 'echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT'
- uses: actions/cache@v4
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Setup
run: |
pip install jingrow-bench
bench init --skip-redis-config-generation --skip-assets --python "$(which python)" ~/jingrow-bench
mysql --host 127.0.0.1 --port 3306 -u root -proot -e "SET GLOBAL character_set_server = 'utf8mb4'"
mysql --host 127.0.0.1 --port 3306 -u root -proot -e "SET GLOBAL collation_server = 'utf8mb4_unicode_ci'"
- name: Install
working-directory: /home/runner/jingrow-bench
run: |
bench get-app crm $GITHUB_WORKSPACE
bench setup requirements --dev
bench new-site --db-root-password root --admin-password admin test_site
bench --site test_site install-app crm
bench build
env:
CI: 'Yes'
- name: Run Tests
working-directory: /home/runner/jingrow-bench
run: |
bench --site test_site set-config allow_tests true
bench --site test_site run-tests --app crm
env:
TYPE: server

35
.github/workflows/generate-pot-file.yml vendored Normal file
View File

@ -0,0 +1,35 @@
name: Regenerate POT file (translatable strings)
on:
schedule:
# 9:30 UTC => 3 PM IST Sunday
- cron: "30 9 * * 0"
workflow_dispatch:
jobs:
regenerate-pot-file:
name: Regenerate POT file
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
branch: ["develop"]
permissions:
contents: write
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ matrix.branch }}
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Run script to update POT file
run: |
bash ${GITHUB_WORKSPACE}/.github/helper/update_pot_file.sh
env:
GH_TOKEN: ${{ secrets.RELEASE_TOKEN }}
BASE_BRANCH: ${{ matrix.branch }}

32
.github/workflows/on_release.yml vendored Normal file
View File

@ -0,0 +1,32 @@
name: Generate Semantic Release
on:
workflow_dispatch:
push:
branches:
- main
jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout Entire Repository
uses: actions/checkout@v2
with:
fetch-depth: 0
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: 20
- name: Setup dependencies
run: |
npm install @semantic-release/git @semantic-release/exec --no-save
- name: Create Release
env:
GH_TOKEN: ${{ secrets.RELEASE_TOKEN }}
GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}
GIT_AUTHOR_NAME: "Jingrow PR Bot"
GIT_AUTHOR_EMAIL: "developers@jingrow.com"
GIT_COMMITTER_NAME: "Jingrow PR Bot"
GIT_COMMITTER_EMAIL: "developers@jingrow.com"
run: npx semantic-release

40
.github/workflows/release_notes.yml vendored Normal file
View File

@ -0,0 +1,40 @@
# This action:
#
# 1. Generates release notes using github API.
# 2. Strips unnecessary info like chore/style etc from notes.
# 3. Updates release info.
name: 'Release Notes'
on:
workflow_dispatch:
inputs:
tag_name:
description: 'Tag of release like v1.0.0'
required: true
type: string
release:
types: [released]
permissions:
contents: read
jobs:
regen-notes:
name: 'Regenerate release notes'
runs-on: ubuntu-latest
steps:
- name: Update notes
run: |
NEW_NOTES=$(gh api --method POST -H "Accept: application/vnd.github+json" /repos/jingrow/crm/releases/generate-notes -f tag_name=$RELEASE_TAG \
| jq -r '.body' \
| sed -E '/^\* (chore|ci|test|docs|style)/d' \
| sed -E 's/by @mergify //'
)
RELEASE_ID=$(gh api -H "Accept: application/vnd.github+json" /repos/jingrow/crm/releases/tags/$RELEASE_TAG | jq -r '.id')
gh api --method PATCH -H "Accept: application/vnd.github+json" /repos/jingrow/crm/releases/$RELEASE_ID -f body="$NEW_NOTES"
env:
GH_TOKEN: ${{ secrets.RELEASE_TOKEN }}
RELEASE_TAG: ${{ github.event.inputs.tag_name || github.event.release.tag_name }}

11
.gitignore vendored Normal file
View File

@ -0,0 +1,11 @@
.DS_Store
*.pyc
*.egg-info
*.swp
__pycache__
dev-dist
tags
node_modules
crm/public/frontend
crm/www/crm.html
build

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "jingrow-ui"]
path = jingrow-ui
url = http://git.jingrow.com/jingrow/jingrow-ui

21
.releaserc Normal file
View File

@ -0,0 +1,21 @@
{
"branches": ["main"],
"plugins": [
"@semantic-release/commit-analyzer", {
"preset": "angular"
},
"@semantic-release/release-notes-generator",
[
"@semantic-release/exec", {
"prepareCmd": 'sed -ir "s/[0-9]*\.[0-9]*\.[0-9]*/${nextRelease.version}/" crm/__init__.py'
}
],
[
"@semantic-release/git", {
"assets": ["crm/__init__.py"],
"message": "chore(release): Bumped to Version ${nextRelease.version}"
}
],
"@semantic-release/github"
]
}

71
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,71 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Bench Web",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/jingrow-bench/apps/jingrow/jingrow/utils/bench_helper.py",
"args": [
"jingrow", "serve", "--port", "8000", "--noreload", "--nothreading"
],
"cwd": "${workspaceFolder}/jingrow-bench/sites",
"env": {
"DEV_SERVER": "1"
}
},
{
"name": "Bench Default Worker",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/jingrow-bench/apps/jingrow/jingrow/utils/bench_helper.py",
"args": [
"jingrow", "worker", "--queue", "default"
],
"cwd": "${workspaceFolder}/jingrow-bench/sites",
"env": {
"DEV_SERVER": "1"
}
},
{
"name": "Bench Short Worker",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/jingrow-bench/apps/jingrow/jingrow/utils/bench_helper.py",
"args": [
"jingrow", "worker", "--queue", "short"
],
"cwd": "${workspaceFolder}/jingrow-bench/sites",
"env": {
"DEV_SERVER": "1"
}
},
{
"name": "Bench Long Worker",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/jingrow-bench/apps/jingrow/jingrow/utils/bench_helper.py",
"args": [
"jingrow", "worker", "--queue", "long"
],
"cwd": "${workspaceFolder}/jingrow-bench/sites",
"env": {
"DEV_SERVER": "1"
}
},
{
"name": "Honcho SocketIO Watch Schedule Worker",
"type": "python",
"request": "launch",
"program": "/home/jingrow/.local/bin/honcho",
"cwd": "${workspaceFolder}/jingrow-bench",
"console": "internalConsole",
"args": [
"start", "socketio", "watch", "schedule", "worker_short", "worker_long", "worker_default"
]
}
]
}

18
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,18 @@
{
"python.defaultInterpreterPath": "jingrow-bench/env/bin/python",
"debug.node.autoAttach": "disabled",
"sqltools.connections": [
{
"mysqlOptions": {
"authProtocol": "default"
},
"previewLimit": 50,
"server": "mariadb",
"port": 3306,
"driver": "MariaDB",
"name": "MariaDB",
"username": "root",
"password": "123"
}
]
}

661
LICENSE Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

7
README.md Normal file
View File

@ -0,0 +1,7 @@
## Crm
app description
#### License
mit

4
crm/__init__.py Normal file
View File

@ -0,0 +1,4 @@
__version__ = "1.53.1"
__title__ = "Jingrow CRM"

149
crm/api/__init__.py Normal file
View File

@ -0,0 +1,149 @@
import jingrow
from bs4 import BeautifulSoup
from jingrow.config import get_modules_from_all_apps_for_user
from jingrow.core.api.file import get_max_file_size
from jingrow.translate import get_all_translations
from jingrow.utils import cstr, split_emails, validate_email_address
from jingrow.utils.telemetry import POSTHOG_HOST_FIELD, POSTHOG_PROJECT_FIELD
@jingrow.whitelist(allow_guest=True)
def get_translations():
if jingrow.session.user != "Guest":
language = jingrow.db.get_value("User", jingrow.session.user, "language")
else:
language = jingrow.db.get_single_value("System Settings", "language")
return get_all_translations(language)
@jingrow.whitelist()
def get_user_signature():
user = jingrow.session.user
user_email_signature = (
jingrow.db.get_value(
"User",
user,
"email_signature",
)
if user
else None
)
signature = user_email_signature or jingrow.db.get_value(
"Email Account",
{"default_outgoing": 1, "add_signature": 1},
"signature",
)
if not signature:
return
soup = BeautifulSoup(signature, "html.parser")
html_signature = soup.find("div", {"class": "ql-editor read-mode"})
_signature = None
if html_signature:
_signature = html_signature.renderContents()
content = ""
if cstr(_signature) or signature:
content = f'<br><p class="signature">{signature}</p>'
return content
@jingrow.whitelist()
def get_posthog_settings():
return {
"posthog_project_id": jingrow.conf.get(POSTHOG_PROJECT_FIELD),
"posthog_host": jingrow.conf.get(POSTHOG_HOST_FIELD),
"enable_telemetry": jingrow.get_system_settings("enable_telemetry"),
"telemetry_site_age": jingrow.utils.telemetry.site_age(),
}
def check_app_permission():
if jingrow.session.user == "Administrator":
return True
allowed_modules = get_modules_from_all_apps_for_user()
allowed_modules = [x["module_name"] for x in allowed_modules]
if "FCRM" not in allowed_modules:
return False
roles = jingrow.get_roles()
if any(
role in ["System Manager", "Sales User", "Sales Manager"] for role in roles
):
return True
return False
@jingrow.whitelist(allow_guest=True)
def accept_invitation(key: str | None = None):
if not key:
jingrow.throw("Invalid or expired key")
result = jingrow.db.get_all("CRM Invitation", filters={"key": key}, pluck="name")
if not result:
jingrow.throw("Invalid or expired key")
invitation = jingrow.get_pg("CRM Invitation", result[0])
invitation.accept()
invitation.reload()
if invitation.status == "Accepted":
jingrow.local.login_manager.login_as(invitation.email)
jingrow.local.response["type"] = "redirect"
jingrow.local.response["location"] = "/crm"
@jingrow.whitelist()
def invite_by_email(emails: str, role: str):
jingrow.only_for(["Sales Manager", "System Manager"])
if role not in ["System Manager", "Sales Manager", "Sales User"]:
jingrow.throw("Cannot invite for this role")
if not emails:
return
email_string = validate_email_address(emails, throw=False)
email_list = split_emails(email_string)
if not email_list:
return
existing_members = jingrow.db.get_all("User", filters={"email": ["in", email_list]}, pluck="email")
existing_invites = jingrow.db.get_all(
"CRM Invitation",
filters={
"email": ["in", email_list],
"role": ["in", ["System Manager", "Sales Manager", "Sales User"]],
},
pluck="email",
)
to_invite = list(set(email_list) - set(existing_members) - set(existing_invites))
for email in to_invite:
jingrow.get_pg(pagetype="CRM Invitation", email=email, role=role).insert(ignore_permissions=True)
return {
"existing_members": existing_members,
"existing_invites": existing_invites,
"to_invite": to_invite,
}
@jingrow.whitelist()
def get_file_uploader_defaults(pagetype: str):
max_number_of_files = None
make_attachments_public = False
if pagetype:
meta = jingrow.get_meta(pagetype)
max_number_of_files = meta.get("max_attachments")
make_attachments_public = meta.get("make_attachments_public")
return {
"allowed_file_types": jingrow.get_system_settings("allowed_file_extensions"),
"max_file_size": get_max_file_size(),
"max_number_of_files": max_number_of_files,
"make_attachments_public": bool(make_attachments_public),
}

499
crm/api/activities.py Normal file
View File

@ -0,0 +1,499 @@
import json
import jingrow
from bs4 import BeautifulSoup
from jingrow import _
from jingrow.desk.form.load import get_docinfo
from jingrow.query_builder import JoinType
from crm.fcrm.pagetype.crm_call_log.crm_call_log import parse_call_log
@jingrow.whitelist()
def get_activities(name):
if jingrow.db.exists("CRM Deal", name):
return get_deal_activities(name)
elif jingrow.db.exists("CRM Lead", name):
return get_lead_activities(name)
else:
jingrow.throw(_("Document not found"), jingrow.DoesNotExistError)
def get_deal_activities(name):
get_docinfo("", "CRM Deal", name)
docinfo = jingrow.response["docinfo"]
deal_meta = jingrow.get_meta("CRM Deal")
deal_fields = {
field.fieldname: {"label": field.label, "options": field.options} for field in deal_meta.fields
}
avoid_fields = [
"lead",
"response_by",
"sla_creation",
"sla",
"first_response_time",
"first_responded_on",
]
pg = jingrow.db.get_values("CRM Deal", name, ["creation", "owner", "lead"])[0]
lead = pg[2]
activities = []
calls = []
notes = []
tasks = []
attachments = []
creation_text = "created this deal"
if lead:
activities, calls, notes, tasks, attachments = get_lead_activities(lead)
creation_text = "converted the lead to this deal"
activities.append(
{
"activity_type": "creation",
"creation": pg[0],
"owner": pg[1],
"data": creation_text,
"is_lead": False,
}
)
docinfo.versions.reverse()
for version in docinfo.versions:
data = json.loads(version.data)
if not data.get("changed"):
continue
if change := data.get("changed")[0]:
field = deal_fields.get(change[0], None)
if not field or change[0] in avoid_fields or (not change[1] and not change[2]):
continue
field_label = field.get("label") or change[0]
field_option = field.get("options") or None
activity_type = "changed"
data = {
"field": change[0],
"field_label": field_label,
"old_value": change[1],
"value": change[2],
}
if not change[1] and change[2]:
activity_type = "added"
data = {
"field": change[0],
"field_label": field_label,
"value": change[2],
}
elif change[1] and not change[2]:
activity_type = "removed"
data = {
"field": change[0],
"field_label": field_label,
"value": change[1],
}
activity = {
"activity_type": activity_type,
"creation": version.creation,
"owner": version.owner,
"data": data,
"is_lead": False,
"options": field_option,
}
activities.append(activity)
for comment in docinfo.comments:
activity = {
"name": comment.name,
"activity_type": "comment",
"creation": comment.creation,
"owner": comment.owner,
"content": comment.content,
"attachments": get_attachments("Comment", comment.name),
"is_lead": False,
}
activities.append(activity)
for communication in docinfo.communications + docinfo.automated_messages:
activity = {
"activity_type": "communication",
"communication_type": communication.communication_type,
"communication_date": communication.communication_date or communication.creation,
"creation": communication.creation,
"data": {
"subject": communication.subject,
"content": communication.content,
"sender_full_name": communication.sender_full_name,
"sender": communication.sender,
"recipients": communication.recipients,
"cc": communication.cc,
"bcc": communication.bcc,
"attachments": get_attachments("Communication", communication.name),
"read_by_recipient": communication.read_by_recipient,
"delivery_status": communication.delivery_status,
},
"is_lead": False,
}
activities.append(activity)
for attachment_log in docinfo.attachment_logs:
activity = {
"name": attachment_log.name,
"activity_type": "attachment_log",
"creation": attachment_log.creation,
"owner": attachment_log.owner,
"data": parse_attachment_log(attachment_log.content, attachment_log.comment_type),
"is_lead": False,
}
activities.append(activity)
calls = calls + get_linked_calls(name).get("calls", [])
notes = notes + get_linked_notes(name) + get_linked_calls(name).get("notes", [])
tasks = tasks + get_linked_tasks(name) + get_linked_calls(name).get("tasks", [])
attachments = attachments + get_attachments("CRM Deal", name)
activities.sort(key=lambda x: x["creation"], reverse=True)
activities = handle_multiple_versions(activities)
return activities, calls, notes, tasks, attachments
def get_lead_activities(name):
get_docinfo("", "CRM Lead", name)
docinfo = jingrow.response["docinfo"]
lead_meta = jingrow.get_meta("CRM Lead")
lead_fields = {
field.fieldname: {"label": field.label, "options": field.options} for field in lead_meta.fields
}
avoid_fields = [
"converted",
"response_by",
"sla_creation",
"sla",
"first_response_time",
"first_responded_on",
]
pg = jingrow.db.get_values("CRM Lead", name, ["creation", "owner"])[0]
activities = [
{
"activity_type": "creation",
"creation": pg[0],
"owner": pg[1],
"data": "created this lead",
"is_lead": True,
}
]
docinfo.versions.reverse()
for version in docinfo.versions:
data = json.loads(version.data)
if not data.get("changed"):
continue
if change := data.get("changed")[0]:
field = lead_fields.get(change[0], None)
if not field or change[0] in avoid_fields or (not change[1] and not change[2]):
continue
field_label = field.get("label") or change[0]
field_option = field.get("options") or None
activity_type = "changed"
data = {
"field": change[0],
"field_label": field_label,
"old_value": change[1],
"value": change[2],
}
if not change[1] and change[2]:
activity_type = "added"
data = {
"field": change[0],
"field_label": field_label,
"value": change[2],
}
elif change[1] and not change[2]:
activity_type = "removed"
data = {
"field": change[0],
"field_label": field_label,
"value": change[1],
}
activity = {
"activity_type": activity_type,
"creation": version.creation,
"owner": version.owner,
"data": data,
"is_lead": True,
"options": field_option,
}
activities.append(activity)
for comment in docinfo.comments:
activity = {
"name": comment.name,
"activity_type": "comment",
"creation": comment.creation,
"owner": comment.owner,
"content": comment.content,
"attachments": get_attachments("Comment", comment.name),
"is_lead": True,
}
activities.append(activity)
for communication in docinfo.communications + docinfo.automated_messages:
activity = {
"activity_type": "communication",
"communication_type": communication.communication_type,
"communication_date": communication.communication_date or communication.creation,
"creation": communication.creation,
"data": {
"subject": communication.subject,
"content": communication.content,
"sender_full_name": communication.sender_full_name,
"sender": communication.sender,
"recipients": communication.recipients,
"cc": communication.cc,
"bcc": communication.bcc,
"attachments": get_attachments("Communication", communication.name),
"read_by_recipient": communication.read_by_recipient,
"delivery_status": communication.delivery_status,
},
"is_lead": True,
}
activities.append(activity)
for attachment_log in docinfo.attachment_logs:
activity = {
"name": attachment_log.name,
"activity_type": "attachment_log",
"creation": attachment_log.creation,
"owner": attachment_log.owner,
"data": parse_attachment_log(attachment_log.content, attachment_log.comment_type),
"is_lead": True,
}
activities.append(activity)
calls = get_linked_calls(name).get("calls", [])
notes = get_linked_notes(name) + get_linked_calls(name).get("notes", [])
tasks = get_linked_tasks(name) + get_linked_calls(name).get("tasks", [])
attachments = get_attachments("CRM Lead", name)
activities.sort(key=lambda x: x["creation"], reverse=True)
activities = handle_multiple_versions(activities)
return activities, calls, notes, tasks, attachments
def get_attachments(pagetype, name):
return (
jingrow.db.get_all(
"File",
filters={"attached_to_pagetype": pagetype, "attached_to_name": name},
fields=[
"name",
"file_name",
"file_type",
"file_url",
"file_size",
"is_private",
"modified",
"creation",
"owner",
],
)
or []
)
def handle_multiple_versions(versions):
activities = []
grouped_versions = []
old_version = None
for version in versions:
is_version = version["activity_type"] in ["changed", "added", "removed"]
if not is_version:
activities.append(version)
if not old_version:
old_version = version
if is_version:
grouped_versions.append(version)
continue
if is_version and old_version.get("owner") and version["owner"] == old_version["owner"]:
grouped_versions.append(version)
else:
if grouped_versions:
activities.append(parse_grouped_versions(grouped_versions))
grouped_versions = []
if is_version:
grouped_versions.append(version)
old_version = version
if version == versions[-1] and grouped_versions:
activities.append(parse_grouped_versions(grouped_versions))
return activities
def parse_grouped_versions(versions):
version = versions[0]
if len(versions) == 1:
return version
other_versions = versions[1:]
version["other_versions"] = other_versions
return version
def get_linked_calls(name):
calls = jingrow.db.get_all(
"CRM Call Log",
filters={"reference_docname": name},
fields=[
"name",
"caller",
"receiver",
"from",
"to",
"duration",
"start_time",
"end_time",
"status",
"type",
"recording_url",
"creation",
"note",
],
)
linked_calls = jingrow.db.get_all(
"Dynamic Link", filters={"link_name": name, "parenttype": "CRM Call Log"}, pluck="parent"
)
notes = []
tasks = []
if linked_calls:
CallLog = jingrow.qb.PageType("CRM Call Log")
Link = jingrow.qb.PageType("Dynamic Link")
query = (
jingrow.qb.from_(CallLog)
.select(
CallLog.name,
CallLog.caller,
CallLog.receiver,
CallLog["from"],
CallLog.to,
CallLog.duration,
CallLog.start_time,
CallLog.end_time,
CallLog.status,
CallLog.type,
CallLog.recording_url,
CallLog.creation,
CallLog.note,
Link.link_pagetype,
Link.link_name,
)
.join(Link, JoinType.inner)
.on(Link.parent == CallLog.name)
.where(CallLog.name.isin(linked_calls))
)
_calls = query.run(as_dict=True)
for call in _calls:
if call.get("link_pagetype") == "FCRM Note":
notes.append(call.link_name)
elif call.get("link_pagetype") == "CRM Task":
tasks.append(call.link_name)
_calls = [call for call in _calls if call.get("link_pagetype") not in ["FCRM Note", "CRM Task"]]
if _calls:
calls = calls + _calls
if notes:
notes = jingrow.db.get_all(
"FCRM Note",
filters={"name": ("in", notes)},
fields=["name", "title", "content", "owner", "modified"],
)
if tasks:
tasks = jingrow.db.get_all(
"CRM Task",
filters={"name": ("in", tasks)},
fields=[
"name",
"title",
"description",
"assigned_to",
"due_date",
"priority",
"status",
"modified",
],
)
calls = [parse_call_log(call) for call in calls] if calls else []
return {"calls": calls, "notes": notes, "tasks": tasks}
def get_linked_notes(name):
notes = jingrow.db.get_all(
"FCRM Note",
filters={"reference_docname": name},
fields=["name", "title", "content", "owner", "modified"],
)
return notes or []
def get_linked_tasks(name):
tasks = jingrow.db.get_all(
"CRM Task",
filters={"reference_docname": name},
fields=[
"name",
"title",
"description",
"assigned_to",
"due_date",
"priority",
"status",
"modified",
],
)
return tasks or []
def parse_attachment_log(html, type):
soup = BeautifulSoup(html, "html.parser")
a_tag = soup.find("a")
type = "added" if type == "Attachment" else "removed"
if not a_tag:
return {
"type": type,
"file_name": html.replace("Removed ", ""),
"file_url": "",
"is_private": False,
}
is_private = False
if "private/files" in a_tag["href"]:
is_private = True
return {
"type": type,
"file_name": a_tag.text,
"file_url": a_tag["href"],
"is_private": is_private,
}

View File

@ -0,0 +1,32 @@
import jingrow
@jingrow.whitelist()
def get_assignment_rules_list():
assignment_rules = []
for docname in jingrow.get_all(
"Assignment Rule", filters={"document_type": ["in", ["CRM Lead", "CRM Deal"]]}
):
pg = jingrow.get_value(
"Assignment Rule",
docname,
fieldname=[
"name",
"description",
"disabled",
"priority",
],
as_dict=True,
)
users_exists = bool(jingrow.db.exists("Assignment Rule User", {"parent": docname.name}))
assignment_rules.append({**pg, "users_exists": users_exists})
return assignment_rules
@jingrow.whitelist()
def duplicate_assignment_rule(docname, new_name):
pg = jingrow.get_pg("Assignment Rule", docname)
pg.name = new_name
pg.assignment_rule_name = new_name
pg.insert()
return pg

38
crm/api/auth.py Normal file
View File

@ -0,0 +1,38 @@
import jingrow
@jingrow.whitelist(allow_guest=True)
def oauth_providers():
from jingrow.utils.html_utils import get_icon_html
from jingrow.utils.password import get_decrypted_password
from jingrow.utils.oauth import get_oauth2_authorize_url, get_oauth_keys
out = []
providers = jingrow.get_all(
"Social Login Key",
filters={"enable_social_login": 1},
fields=["name", "client_id", "base_url", "provider_name", "icon"],
order_by="name",
)
for provider in providers:
client_secret = get_decrypted_password("Social Login Key", provider.name, "client_secret")
if not client_secret:
continue
icon = None
if provider.icon:
if provider.provider_name == "Custom":
icon = get_icon_html(provider.icon, small=True)
else:
icon = f"<img src='{provider.icon}' alt={provider.provider_name}>"
if provider.client_id and provider.base_url and get_oauth_keys(provider.name):
out.append(
{
"name": provider.name,
"provider_name": provider.provider_name,
"auth_url": get_oauth2_authorize_url(provider.name, "/crm"),
"icon": icon,
}
)
return out

104
crm/api/comment.py Normal file
View File

@ -0,0 +1,104 @@
from collections.abc import Iterable
import jingrow
from jingrow import _
from bs4 import BeautifulSoup
from crm.fcrm.pagetype.crm_notification.crm_notification import notify_user
def on_update(self, method):
notify_mentions(self)
def notify_mentions(pg):
"""
Extract mentions from `content`, and notify.
`content` must have `HTML` content.
"""
content = getattr(pg, "content", None)
if not content:
return
mentions = extract_mentions(content)
reference_pg = jingrow.get_pg(pg.reference_pagetype, pg.reference_name)
for mention in mentions:
owner = jingrow.get_cached_value("User", pg.owner, "full_name")
pagetype = pg.reference_pagetype
if pagetype.startswith("CRM "):
pagetype = pagetype[4:].lower()
name = (
reference_pg.lead_name
if pagetype == "lead"
else reference_pg.organization or reference_pg.lead_name
)
notification_text = f"""
<div class="mb-2 leading-5 text-ink-gray-5">
<span class="font-medium text-ink-gray-9">{ owner }</span>
<span>{ _('mentioned you in {0}').format(pagetype) }</span>
<span class="font-medium text-ink-gray-9">{ name }</span>
</div>
"""
notify_user(
{
"owner": pg.owner,
"assigned_to": mention.email,
"notification_type": "Mention",
"message": pg.content,
"notification_text": notification_text,
"reference_pagetype": "Comment",
"reference_docname": pg.name,
"redirect_to_pagetype": pg.reference_pagetype,
"redirect_to_docname": pg.reference_name,
}
)
def extract_mentions(html):
if not html:
return []
soup = BeautifulSoup(html, "html.parser")
mentions = []
for d in soup.find_all("span", attrs={"data-type": "mention"}):
mentions.append(
jingrow._dict(full_name=d.get("data-label"), email=d.get("data-id"))
)
return mentions
@jingrow.whitelist()
def add_attachments(name: str, attachments: Iterable[str | dict]) -> None:
"""Add attachments to the given Comment
:param name: Comment name
:param attachments: File names or dicts with keys "fname" and "fcontent"
"""
# loop through attachments
for a in attachments:
if isinstance(a, str):
attach = jingrow.db.get_value(
"File", {"name": a}, ["file_url", "is_private"], as_dict=1
)
file_args = {
"file_url": attach.file_url,
"is_private": attach.is_private,
}
elif isinstance(a, dict) and "fcontent" in a and "fname" in a:
# dict returned by jingrow.attach_print()
file_args = {
"file_name": a["fname"],
"content": a["fcontent"],
"is_private": 1,
}
else:
continue
file_args.update(
{
"attached_to_pagetype": "Comment",
"attached_to_name": name,
"folder": "Home/Attachments",
}
)
_file = jingrow.new_pg("File")
_file.update(file_args)
_file.save(ignore_permissions=True)

145
crm/api/contact.py Normal file
View File

@ -0,0 +1,145 @@
import jingrow
from jingrow import _
def validate(pg, method):
update_deals_email_mobile_no(pg)
def update_deals_email_mobile_no(pg):
linked_deals = jingrow.get_all(
"CRM Contacts",
filters={"contact": pg.name, "is_primary": 1},
fields=["parent"],
)
for linked_deal in linked_deals:
deal = jingrow.db.get_values("CRM Deal", linked_deal.parent, ["email", "mobile_no"], as_dict=True)[0]
if deal.email != pg.email_id or deal.mobile_no != pg.mobile_no:
jingrow.db.set_value(
"CRM Deal",
linked_deal.parent,
{
"email": pg.email_id,
"mobile_no": pg.mobile_no,
},
)
@jingrow.whitelist()
def get_linked_deals(contact):
"""Get linked deals for a contact"""
if not jingrow.has_permission("Contact", "read", contact):
jingrow.throw("Not permitted", jingrow.PermissionError)
deal_names = jingrow.get_all(
"CRM Contacts",
filters={"contact": contact, "parenttype": "CRM Deal"},
fields=["parent"],
distinct=True,
)
# get deals data
deals = []
for d in deal_names:
deal = jingrow.get_cached_pg(
"CRM Deal",
d.parent,
fields=[
"name",
"organization",
"currency",
"annual_revenue",
"status",
"email",
"mobile_no",
"deal_owner",
"modified",
],
)
deals.append(deal.as_dict())
return deals
@jingrow.whitelist()
def create_new(contact, field, value):
"""Create new email or phone for a contact"""
if not jingrow.has_permission("Contact", "write", contact):
jingrow.throw("Not permitted", jingrow.PermissionError)
contact = jingrow.get_cached_pg("Contact", contact)
if field == "email":
email = {"email_id": value, "is_primary": 1 if len(contact.email_ids) == 0 else 0}
contact.append("email_ids", email)
elif field in ("mobile_no", "phone"):
mobile_no = {"phone": value, "is_primary_mobile_no": 1 if len(contact.phone_nos) == 0 else 0}
contact.append("phone_nos", mobile_no)
else:
jingrow.throw("Invalid field")
contact.save()
return True
@jingrow.whitelist()
def set_as_primary(contact, field, value):
"""Set email or phone as primary for a contact"""
if not jingrow.has_permission("Contact", "write", contact):
jingrow.throw("Not permitted", jingrow.PermissionError)
contact = jingrow.get_pg("Contact", contact)
if field == "email":
for email in contact.email_ids:
if email.email_id == value:
email.is_primary = 1
else:
email.is_primary = 0
elif field in ("mobile_no", "phone"):
name = "is_primary_mobile_no" if field == "mobile_no" else "is_primary_phone"
for phone in contact.phone_nos:
if phone.phone == value:
phone.set(name, 1)
else:
phone.set(name, 0)
else:
jingrow.throw("Invalid field")
contact.save()
return True
@jingrow.whitelist()
def search_emails(txt: str):
pagetype = "Contact"
meta = jingrow.get_meta(pagetype)
filters = [["Contact", "email_id", "is", "set"]]
if meta.get("fields", {"fieldname": "enabled", "fieldtype": "Check"}):
filters.append([pagetype, "enabled", "=", 1])
if meta.get("fields", {"fieldname": "disabled", "fieldtype": "Check"}):
filters.append([pagetype, "disabled", "!=", 1])
or_filters = []
search_fields = ["full_name", "email_id", "name"]
if txt:
for f in search_fields:
or_filters.append([pagetype, f.strip(), "like", f"%{txt}%"])
results = jingrow.get_list(
pagetype,
filters=filters,
fields=search_fields,
or_filters=or_filters,
limit_start=0,
limit_page_length=20,
order_by="email_id, full_name, name",
ignore_permissions=False,
as_list=True,
strict=False,
)
return results

1142
crm/api/dashboard.py Normal file

File diff suppressed because it is too large Load Diff

31
crm/api/demo.py Normal file
View File

@ -0,0 +1,31 @@
import jingrow
from jingrow import _
from jingrow.auth import LoginManager
@jingrow.whitelist(allow_guest=True)
def login():
if not jingrow.conf.demo_username or not jingrow.conf.demo_password:
return
jingrow.local.response["redirect_to"] = "/crm"
login_manager = LoginManager()
login_manager.authenticate(jingrow.conf.demo_username, jingrow.conf.demo_password)
login_manager.post_login()
jingrow.local.response["type"] = "redirect"
jingrow.local.response["location"] = jingrow.local.response["redirect_to"]
def validate_reset_password(pg, event):
if jingrow.conf.demo_username and jingrow.session.user == jingrow.conf.demo_username:
jingrow.throw(
_("Password cannot be reset by Demo User {}").format(jingrow.bold(jingrow.conf.demo_username)),
jingrow.PermissionError,
)
def validate_user(pg, event):
if jingrow.conf.demo_username and jingrow.session.user == jingrow.conf.demo_username and pg.new_password:
jingrow.throw(
_("Password cannot be reset by Demo User {}").format(jingrow.bold(jingrow.conf.demo_username)),
jingrow.PermissionError,
)

74
crm/api/notifications.py Normal file
View File

@ -0,0 +1,74 @@
import jingrow
from jingrow.query_builder import Order
@jingrow.whitelist()
def get_notifications():
Notification = jingrow.qb.PageType("CRM Notification")
query = (
jingrow.qb.from_(Notification)
.select("*")
.where(Notification.to_user == jingrow.session.user)
.orderby("creation", order=Order.desc)
)
notifications = query.run(as_dict=True)
_notifications = []
for notification in notifications:
_notifications.append(
{
"creation": notification.creation,
"from_user": {
"name": notification.from_user,
"full_name": jingrow.get_value(
"User", notification.from_user, "full_name"
),
},
"type": notification.type,
"to_user": notification.to_user,
"read": notification.read,
"hash": get_hash(notification),
"notification_text": notification.notification_text,
"notification_type_pagetype": notification.notification_type_pagetype,
"notification_type_pg": notification.notification_type_pg,
"reference_pagetype": (
"deal" if notification.reference_pagetype == "CRM Deal" else "lead"
),
"reference_name": notification.reference_name,
"route_name": (
"Deal" if notification.reference_pagetype == "CRM Deal" else "Lead"
),
}
)
return _notifications
@jingrow.whitelist()
def mark_as_read(user=None, pg=None):
user = user or jingrow.session.user
filters = {"to_user": user, "read": False}
or_filters = []
if pg:
or_filters = [
{"comment": pg},
{"notification_type_pg": pg},
]
for n in jingrow.get_all("CRM Notification", filters=filters, or_filters=or_filters):
d = jingrow.get_pg("CRM Notification", n.name)
d.read = True
d.save()
def get_hash(notification):
_hash = ""
if notification.type == "Mention" and notification.notification_type_pg:
_hash = "#" + notification.notification_type_pg
if notification.type == "WhatsApp":
_hash = "#whatsapp"
if notification.type == "Assignment" and notification.notification_type_pagetype == "CRM Task":
_hash = "#tasks"
if "has been removed by" in notification.message:
_hash = ""
return _hash

24
crm/api/onboarding.py Normal file
View File

@ -0,0 +1,24 @@
import jingrow
@jingrow.whitelist()
def get_first_lead():
lead = jingrow.get_all(
"CRM Lead",
filters={"converted": 0},
fields=["name"],
order_by="creation",
limit=1,
)
return lead[0].name if lead else None
@jingrow.whitelist()
def get_first_deal():
deal = jingrow.get_all(
"CRM Deal",
fields=["name"],
order_by="creation",
limit=1,
)
return deal[0].name if deal else None

910
crm/api/pg.py Normal file
View File

@ -0,0 +1,910 @@
import json
import jingrow
from jingrow import _
from jingrow.custom.pagetype.property_setter.property_setter import make_property_setter
from jingrow.desk.form.assign_to import set_status
from jingrow.model import no_value_fields
from jingrow.model.page import get_controller
from jingrow.utils import make_filter_tuple
from pypika import Criterion
from crm.api.views import get_views
from crm.fcrm.pagetype.crm_form_script.crm_form_script import get_form_script
from crm.utils import get_dynamic_linked_docs, get_linked_docs
@jingrow.whitelist()
def sort_options(pagetype: str):
fields = jingrow.get_meta(pagetype).fields
fields = [field for field in fields if field.fieldtype not in no_value_fields]
fields = [
{
"label": _(field.label),
"value": field.fieldname,
"fieldname": field.fieldname,
}
for field in fields
if field.label and field.fieldname
]
standard_fields = [
{"label": "Name", "fieldname": "name"},
{"label": "Created On", "fieldname": "creation"},
{"label": "Last Modified", "fieldname": "modified"},
{"label": "Modified By", "fieldname": "modified_by"},
{"label": "Owner", "fieldname": "owner"},
]
for field in standard_fields:
field["label"] = _(field["label"])
field["value"] = field["fieldname"]
fields.append(field)
return fields
@jingrow.whitelist()
def get_filterable_fields(pagetype: str):
allowed_fieldtypes = [
"Check",
"Data",
"Float",
"Int",
"Currency",
"Dynamic Link",
"Link",
"Long Text",
"Select",
"Small Text",
"Text Editor",
"Text",
"Duration",
"Date",
"Datetime",
]
c = get_controller(pagetype)
restricted_fields = []
if hasattr(c, "get_non_filterable_fields"):
restricted_fields = c.get_non_filterable_fields()
res = []
# append PageFields
PageField = jingrow.qb.PageType("PageField")
pg_fields = get_pagetype_fields_meta(PageField, pagetype, allowed_fieldtypes, restricted_fields)
res.extend(pg_fields)
# append Custom Fields
CustomField = jingrow.qb.PageType("Custom Field")
custom_fields = get_pagetype_fields_meta(CustomField, pagetype, allowed_fieldtypes, restricted_fields)
res.extend(custom_fields)
# append standard fields (getting error when using jingrow.model.std_fields)
standard_fields = [
{"fieldname": "name", "fieldtype": "Link", "label": "ID", "options": pagetype},
{"fieldname": "owner", "fieldtype": "Link", "label": "Created By", "options": "User"},
{
"fieldname": "modified_by",
"fieldtype": "Link",
"label": "Last Updated By",
"options": "User",
},
{"fieldname": "_user_tags", "fieldtype": "Data", "label": "Tags"},
{"fieldname": "_liked_by", "fieldtype": "Data", "label": "Like"},
{"fieldname": "_comments", "fieldtype": "Text", "label": "Comments"},
{"fieldname": "_assign", "fieldtype": "Text", "label": "Assigned To"},
{"fieldname": "creation", "fieldtype": "Datetime", "label": "Created On"},
{"fieldname": "modified", "fieldtype": "Datetime", "label": "Last Updated On"},
]
for field in standard_fields:
if field.get("fieldname") not in restricted_fields and field.get("fieldtype") in allowed_fieldtypes:
field["name"] = field.get("fieldname")
res.append(field)
for field in res:
field["label"] = _(field.get("label"))
field["value"] = field.get("fieldname")
return res
@jingrow.whitelist()
def get_group_by_fields(pagetype: str):
allowed_fieldtypes = [
"Check",
"Data",
"Float",
"Int",
"Currency",
"Dynamic Link",
"Link",
"Select",
"Duration",
"Date",
"Datetime",
]
fields = jingrow.get_meta(pagetype).fields
fields = [
field
for field in fields
if field.fieldtype not in no_value_fields and field.fieldtype in allowed_fieldtypes
]
fields = [
{
"label": _(field.label),
"fieldname": field.fieldname,
}
for field in fields
if field.label and field.fieldname
]
standard_fields = [
{"label": "Name", "fieldname": "name"},
{"label": "Created On", "fieldname": "creation"},
{"label": "Last Modified", "fieldname": "modified"},
{"label": "Modified By", "fieldname": "modified_by"},
{"label": "Owner", "fieldname": "owner"},
{"label": "Liked By", "fieldname": "_liked_by"},
{"label": "Assigned To", "fieldname": "_assign"},
{"label": "Comments", "fieldname": "_comments"},
{"label": "Created On", "fieldname": "creation"},
{"label": "Modified On", "fieldname": "modified"},
]
for field in standard_fields:
field["label"] = _(field["label"])
fields.append(field)
return fields
def get_pagetype_fields_meta(PageField, pagetype, allowed_fieldtypes, restricted_fields):
parent = "parent" if PageField._table_name == "tabPageField" else "dt"
return (
jingrow.qb.from_(PageField)
.select(
PageField.fieldname,
PageField.fieldtype,
PageField.label,
PageField.name,
PageField.options,
)
.where(PageField[parent] == pagetype)
.where(PageField.hidden == False) # noqa: E712
.where(Criterion.any([PageField.fieldtype == i for i in allowed_fieldtypes]))
.where(Criterion.all([PageField.fieldname != i for i in restricted_fields]))
.run(as_dict=True)
)
@jingrow.whitelist()
def get_quick_filters(pagetype: str, cached: bool = True):
meta = jingrow.get_meta(pagetype, cached)
quick_filters = []
if global_settings := jingrow.db.exists("CRM Global Settings", {"dt": pagetype, "type": "Quick Filters"}):
_quick_filters = jingrow.db.get_value("CRM Global Settings", global_settings, "json")
_quick_filters = json.loads(_quick_filters) or []
fields = []
for filter in _quick_filters:
if filter == "name":
fields.append({"label": "Name", "fieldname": "name", "fieldtype": "Data"})
else:
field = next((f for f in meta.fields if f.fieldname == filter), None)
if field:
fields.append(field)
else:
fields = [field for field in meta.fields if field.in_standard_filter]
for field in fields:
options = field.get("options")
if field.get("fieldtype") == "Select" and options and isinstance(options, str):
options = options.split("\n")
options = [{"label": option, "value": option} for option in options]
if not any([not option.get("value") for option in options]):
options.insert(0, {"label": "", "value": ""})
quick_filters.append(
{
"label": _(field.get("label")),
"fieldname": field.get("fieldname"),
"fieldtype": field.get("fieldtype"),
"options": options,
}
)
if pagetype == "CRM Lead":
quick_filters = [filter for filter in quick_filters if filter.get("fieldname") != "converted"]
return quick_filters
@jingrow.whitelist()
def update_quick_filters(quick_filters: str, old_filters: str, pagetype: str):
quick_filters = json.loads(quick_filters)
old_filters = json.loads(old_filters)
new_filters = [filter for filter in quick_filters if filter not in old_filters]
removed_filters = [filter for filter in old_filters if filter not in quick_filters]
# update or create global quick filter settings
create_update_global_settings(pagetype, quick_filters)
# remove old filters
for filter in removed_filters:
update_in_standard_filter(filter, pagetype, 0)
# add new filters
for filter in new_filters:
update_in_standard_filter(filter, pagetype, 1)
def create_update_global_settings(pagetype, quick_filters):
if global_settings := jingrow.db.exists("CRM Global Settings", {"dt": pagetype, "type": "Quick Filters"}):
jingrow.db.set_value("CRM Global Settings", global_settings, "json", json.dumps(quick_filters))
else:
# create CRM Global Settings pg
pg = jingrow.new_pg("CRM Global Settings")
pg.dt = pagetype
pg.type = "Quick Filters"
pg.json = json.dumps(quick_filters)
pg.insert()
def update_in_standard_filter(fieldname, pagetype, value):
if property_name := jingrow.db.exists(
"Property Setter",
{"pg_type": pagetype, "field_name": fieldname, "property": "in_standard_filter"},
):
jingrow.db.set_value("Property Setter", property_name, "value", value)
else:
make_property_setter(
pagetype,
fieldname,
"in_standard_filter",
value,
"Check",
validate_fields_for_pagetype=False,
)
@jingrow.whitelist()
def get_data(
pagetype: str,
filters: dict,
order_by: str,
page_length=20,
page_length_count=20,
column_field=None,
title_field=None,
columns=[],
rows=[],
kanban_columns=[],
kanban_fields=[],
view=None,
default_filters=None,
):
custom_view = False
filters = jingrow._dict(filters)
rows = jingrow.parse_json(rows or "[]")
columns = jingrow.parse_json(columns or "[]")
kanban_fields = jingrow.parse_json(kanban_fields or "[]")
kanban_columns = jingrow.parse_json(kanban_columns or "[]")
custom_view_name = view.get("custom_view_name") if view else None
view_type = view.get("view_type") if view else None
group_by_field = view.get("group_by_field") if view else None
for key in filters:
value = filters[key]
if isinstance(value, list):
if "@me" in value:
value[value.index("@me")] = jingrow.session.user
elif "%@me%" in value:
index = [i for i, v in enumerate(value) if v == "%@me%"]
for i in index:
value[i] = "%" + jingrow.session.user + "%"
elif value == "@me":
filters[key] = jingrow.session.user
if default_filters:
default_filters = jingrow.parse_json(default_filters)
filters.update(default_filters)
is_default = True
data = []
_list = get_controller(pagetype)
default_rows = []
if hasattr(_list, "default_list_data"):
default_rows = _list.default_list_data().get("rows")
meta = jingrow.get_meta(pagetype)
if view_type != "kanban":
if columns or rows:
custom_view = True
is_default = False
columns = jingrow.parse_json(columns)
rows = jingrow.parse_json(rows)
if not columns:
columns = [
{"label": "Name", "type": "Data", "key": "name", "width": "16rem"},
{"label": "Last Modified", "type": "Datetime", "key": "modified", "width": "8rem"},
]
if not rows:
rows = ["name"]
default_view_filters = {
"dt": pagetype,
"type": view_type or "list",
"is_standard": 1,
"user": jingrow.session.user,
}
if not custom_view and jingrow.db.exists("CRM View Settings", default_view_filters):
list_view_settings = jingrow.get_pg("CRM View Settings", default_view_filters)
columns = jingrow.parse_json(list_view_settings.columns)
rows = jingrow.parse_json(list_view_settings.rows)
is_default = False
elif not custom_view or (is_default and hasattr(_list, "default_list_data")):
rows = default_rows
columns = _list.default_list_data().get("columns")
# check if rows has all keys from columns if not add them
for column in columns:
if column.get("key") not in rows:
rows.append(column.get("key"))
column["label"] = _(column.get("label"))
if column.get("key") == "_liked_by" and column.get("width") == "10rem":
column["width"] = "50px"
# remove column if column.hidden is True
column_meta = meta.get_field(column.get("key"))
if column_meta and column_meta.get("hidden"):
columns.remove(column)
# check if rows has group_by_field if not add it
if group_by_field and group_by_field not in rows:
rows.append(group_by_field)
data = (
jingrow.get_list(
pagetype,
fields=rows,
filters=filters,
order_by=order_by,
page_length=page_length,
)
or []
)
data = parse_list_data(data, pagetype)
if view_type == "kanban":
if not rows:
rows = default_rows
if not kanban_columns and column_field:
field_meta = jingrow.get_meta(pagetype).get_field(column_field)
if field_meta.fieldtype == "Link":
kanban_columns = jingrow.get_all(
field_meta.options,
fields=["name"],
order_by="modified asc",
)
elif field_meta.fieldtype == "Select":
kanban_columns = [{"name": option} for option in field_meta.options.split("\n")]
if not title_field:
title_field = "name"
if hasattr(_list, "default_kanban_settings"):
title_field = _list.default_kanban_settings().get("title_field")
if title_field not in rows:
rows.append(title_field)
if not kanban_fields:
kanban_fields = ["name"]
if hasattr(_list, "default_kanban_settings"):
kanban_fields = json.loads(_list.default_kanban_settings().get("kanban_fields"))
for field in kanban_fields:
if field not in rows:
rows.append(field)
for kc in kanban_columns:
column_filters = {column_field: kc.get("name")}
order = kc.get("order")
if (column_field in filters and filters.get(column_field) != kc.get("name")) or kc.get("delete"):
column_data = []
else:
column_filters.update(filters.copy())
page_length = 20
if kc.get("page_length"):
page_length = kc.get("page_length")
if order:
column_data = get_records_based_on_order(
pagetype, rows, column_filters, page_length, order
)
else:
column_data = jingrow.get_list(
pagetype,
fields=rows,
filters=convert_filter_to_tuple(pagetype, column_filters),
order_by=order_by,
page_length=page_length,
)
new_filters = filters.copy()
new_filters.update({column_field: kc.get("name")})
all_count = jingrow.get_list(
pagetype,
filters=convert_filter_to_tuple(pagetype, new_filters),
fields="count(*) as total_count",
)[0].total_count
kc["all_count"] = all_count
kc["count"] = len(column_data)
for d in column_data:
getCounts(d, pagetype)
if order:
column_data = sorted(
column_data,
key=lambda x: order.index(x.get("name")) if x.get("name") in order else len(order),
)
data.append({"column": kc, "fields": kanban_fields, "data": column_data})
fields = jingrow.get_meta(pagetype).fields
fields = [field for field in fields if field.fieldtype not in no_value_fields]
fields = [
{
"label": _(field.label),
"fieldtype": field.fieldtype,
"fieldname": field.fieldname,
"options": field.options,
}
for field in fields
if field.label and field.fieldname
]
std_fields = [
{"label": "Name", "fieldtype": "Data", "fieldname": "name"},
{"label": "Created On", "fieldtype": "Datetime", "fieldname": "creation"},
{"label": "Last Modified", "fieldtype": "Datetime", "fieldname": "modified"},
{
"label": "Modified By",
"fieldtype": "Link",
"fieldname": "modified_by",
"options": "User",
},
{"label": "Assigned To", "fieldtype": "Text", "fieldname": "_assign"},
{"label": "Owner", "fieldtype": "Link", "fieldname": "owner", "options": "User"},
{"label": "Like", "fieldtype": "Data", "fieldname": "_liked_by"},
]
for field in std_fields:
if field.get("fieldname") not in rows:
rows.append(field.get("fieldname"))
if field not in fields:
field["label"] = _(field["label"])
fields.append(field)
if not is_default and custom_view_name:
is_default = jingrow.db.get_value("CRM View Settings", custom_view_name, "load_default_columns")
if group_by_field and view_type == "group_by":
def get_options(type, options):
if type == "Select":
return [option for option in options.split("\n")]
else:
has_empty_values = any([not d.get(group_by_field) for d in data])
options = list(set([d.get(group_by_field) for d in data]))
options = [u for u in options if u]
if has_empty_values:
options.append("")
if order_by and group_by_field in order_by:
order_by_fields = order_by.split(",")
order_by_fields = [
(field.split(" ")[0], field.split(" ")[1]) for field in order_by_fields
]
if (group_by_field, "asc") in order_by_fields:
options.sort()
elif (group_by_field, "desc") in order_by_fields:
options.sort(reverse=True)
else:
options.sort()
return options
for field in fields:
if field.get("fieldname") == group_by_field:
group_by_field = {
"label": field.get("label"),
"fieldname": field.get("fieldname"),
"fieldtype": field.get("fieldtype"),
"options": get_options(field.get("fieldtype"), field.get("options")),
}
return {
"data": data,
"columns": columns,
"rows": rows,
"fields": fields,
"column_field": column_field,
"title_field": title_field,
"kanban_columns": kanban_columns,
"kanban_fields": kanban_fields,
"group_by_field": group_by_field,
"page_length": page_length,
"page_length_count": page_length_count,
"is_default": is_default,
"views": get_views(pagetype),
"total_count": jingrow.get_list(pagetype, filters=filters, fields="count(*) as total_count")[
0
].total_count,
"row_count": len(data),
"form_script": get_form_script(pagetype),
"list_script": get_form_script(pagetype, "List"),
"view_type": view_type,
}
def parse_list_data(data, pagetype):
_list = get_controller(pagetype)
if hasattr(_list, "parse_list_data"):
data = _list.parse_list_data(data)
return data
def convert_filter_to_tuple(pagetype, filters):
if isinstance(filters, dict):
filters_items = filters.items()
filters = []
for key, value in filters_items:
filters.append(make_filter_tuple(pagetype, key, value))
return filters
def get_records_based_on_order(pagetype, rows, filters, page_length, order):
records = []
filters = convert_filter_to_tuple(pagetype, filters)
in_filters = filters.copy()
in_filters.append([pagetype, "name", "in", order[:page_length]])
records = jingrow.get_list(
pagetype,
fields=rows,
filters=in_filters,
order_by="creation desc",
page_length=page_length,
)
if len(records) < page_length:
not_in_filters = filters.copy()
not_in_filters.append([pagetype, "name", "not in", order])
remaining_records = jingrow.get_list(
pagetype,
fields=rows,
filters=not_in_filters,
order_by="creation desc",
page_length=page_length - len(records),
)
for record in remaining_records:
records.append(record)
return records
@jingrow.whitelist()
def get_fields_meta(pagetype, restricted_fieldtypes=None, as_array=False, only_required=False):
not_allowed_fieldtypes = [
"Tab Break",
"Section Break",
"Column Break",
]
if restricted_fieldtypes:
restricted_fieldtypes = jingrow.parse_json(restricted_fieldtypes)
not_allowed_fieldtypes += restricted_fieldtypes
fields = jingrow.get_meta(pagetype).fields
fields = [field for field in fields if field.fieldtype not in not_allowed_fieldtypes]
standard_fields = [
{"fieldname": "name", "fieldtype": "Link", "label": "ID", "options": pagetype},
{"fieldname": "owner", "fieldtype": "Link", "label": "Created By", "options": "User"},
{
"fieldname": "modified_by",
"fieldtype": "Link",
"label": "Last Updated By",
"options": "User",
},
{"fieldname": "_user_tags", "fieldtype": "Data", "label": "Tags"},
{"fieldname": "_liked_by", "fieldtype": "Data", "label": "Like"},
{"fieldname": "_comments", "fieldtype": "Text", "label": "Comments"},
{"fieldname": "_assign", "fieldtype": "Text", "label": "Assigned To"},
{"fieldname": "creation", "fieldtype": "Datetime", "label": "Created On"},
{"fieldname": "modified", "fieldtype": "Datetime", "label": "Last Updated On"},
]
for field in standard_fields:
if not restricted_fieldtypes or field.get("fieldtype") not in restricted_fieldtypes:
fields.append(field)
if only_required:
fields = [field for field in fields if field.get("reqd")]
if as_array:
return fields
fields_meta = {}
for field in fields:
fields_meta[field.get("fieldname")] = field
if field.get("fieldtype") == "Table":
_fields = jingrow.get_meta(field.get("options")).fields
fields_meta[field.get("fieldname")] = {"df": field, "fields": _fields}
return fields_meta
@jingrow.whitelist()
def remove_assignments(pagetype, name, assignees, ignore_permissions=False):
assignees = jingrow.parse_json(assignees)
if not assignees:
return
for assign_to in assignees:
set_status(
pagetype,
name,
todo=None,
assign_to=assign_to,
status="Cancelled",
ignore_permissions=ignore_permissions,
)
@jingrow.whitelist()
def get_assigned_users(pagetype, name, default_assigned_to=None):
assigned_users = jingrow.get_all(
"ToDo",
fields=["allocated_to"],
filters={
"reference_type": pagetype,
"reference_name": name,
"status": ("!=", "Cancelled"),
},
pluck="allocated_to",
)
users = list(set(assigned_users))
# if users is empty, add default_assigned_to
if not users and default_assigned_to:
users = [default_assigned_to]
return users
@jingrow.whitelist()
def get_fields(pagetype: str, allow_all_fieldtypes: bool = False):
not_allowed_fieldtypes = [*list(jingrow.model.no_value_fields), "Read Only"]
if allow_all_fieldtypes:
not_allowed_fieldtypes = []
fields = jingrow.get_meta(pagetype).fields
_fields = []
for field in fields:
if field.fieldtype not in not_allowed_fieldtypes and field.fieldname:
_fields.append(field)
return _fields
def getCounts(d, pagetype):
d["_email_count"] = (
jingrow.db.count(
"Communication",
filters={
"reference_pagetype": pagetype,
"reference_name": d.get("name"),
"communication_type": "Communication",
},
)
or 0
)
d["_email_count"] = d["_email_count"] + jingrow.db.count(
"Communication",
filters={
"reference_pagetype": pagetype,
"reference_name": d.get("name"),
"communication_type": "Automated Message",
},
)
d["_comment_count"] = jingrow.db.count(
"Comment",
filters={"reference_pagetype": pagetype, "reference_name": d.get("name"), "comment_type": "Comment"},
)
d["_task_count"] = jingrow.db.count(
"CRM Task", filters={"reference_pagetype": pagetype, "reference_docname": d.get("name")}
)
d["_note_count"] = jingrow.db.count(
"FCRM Note", filters={"reference_pagetype": pagetype, "reference_docname": d.get("name")}
)
return d
@jingrow.whitelist()
def get_linked_docs_of_document(pagetype, docname):
try:
pg = jingrow.get_pg(pagetype, docname)
except jingrow.DoesNotExistError:
return []
linked_docs = get_linked_docs(pg)
dynamic_linked_docs = get_dynamic_linked_docs(pg)
linked_docs.extend(dynamic_linked_docs)
linked_docs = list({pg["reference_docname"]: pg for pg in linked_docs}.values())
docs_data = []
for pg in linked_docs:
if not pg.get("reference_pagetype") or not pg.get("reference_docname"):
continue
try:
data = jingrow.get_pg(pg["reference_pagetype"], pg["reference_docname"])
except (jingrow.DoesNotExistError, jingrow.ValidationError):
continue
title = data.get("title")
if data.pagetype == "CRM Call Log":
title = f"Call from {data.get('from')} to {data.get('to')}"
if data.pagetype == "CRM Deal":
title = data.get("organization")
if data.pagetype == "CRM Notification":
title = data.get("message")
docs_data.append(
{
"pg": data.pagetype,
"title": title or data.get("name"),
"reference_docname": pg["reference_docname"],
"reference_pagetype": pg["reference_pagetype"],
}
)
return docs_data
def remove_pg_link(pagetype, docname):
if not pagetype or not docname:
return
try:
linked_pg_data = jingrow.get_pg(pagetype, docname)
if pagetype == "CRM Notification":
delete_notification_type = {
"notification_type_pagetype": "",
"notification_type_pg": "",
}
delete_references = {
"reference_pagetype": "",
"reference_name": "",
}
if linked_pg_data.get("notification_type_pagetype") == linked_pg_data.get("reference_pagetype"):
delete_references.update(delete_notification_type)
linked_pg_data.update(delete_references)
else:
linked_pg_data.update(
{
"reference_pagetype": "",
"reference_docname": "",
}
)
linked_pg_data.save(ignore_permissions=True)
except (jingrow.DoesNotExistError, jingrow.ValidationError):
pass
def remove_contact_link(pagetype, docname):
if not pagetype or not docname:
return
try:
linked_pg_data = jingrow.get_pg(pagetype, docname)
linked_pg_data.update(
{
"contact": None,
"contacts": [],
}
)
linked_pg_data.save(ignore_permissions=True)
except (jingrow.DoesNotExistError, jingrow.ValidationError):
pass
@jingrow.whitelist()
def remove_linked_pg_reference(items, remove_contact=None, delete=False):
if isinstance(items, str):
items = jingrow.parse_json(items)
for item in items:
if not item.get("pagetype") or not item.get("docname"):
continue
try:
if remove_contact:
remove_contact_link(item["pagetype"], item["docname"])
else:
remove_pg_link(item["pagetype"], item["docname"])
if delete:
jingrow.delete_pg(item["pagetype"], item["docname"])
except (jingrow.DoesNotExistError, jingrow.ValidationError):
# Skip if document doesn't exist or has validation errors
continue
return "success"
@jingrow.whitelist()
def delete_bulk_docs(pagetype, items, delete_linked=False):
from jingrow.desk.reportview import delete_bulk
if not pagetype:
jingrow.throw("Pagetype is required")
if not items:
jingrow.throw("Items are required")
items = jingrow.parse_json(items)
if not isinstance(items, list):
jingrow.throw("Items must be a list")
for pg in items:
try:
if not jingrow.db.exists(pagetype, pg):
jingrow.log_error(f"Document {pagetype} {pg} does not exist", "Bulk Delete Error")
continue
linked_docs = get_linked_docs_of_document(pagetype, pg)
for linked_pg in linked_docs:
if not linked_pg.get("reference_pagetype") or not linked_pg.get("reference_docname"):
continue
remove_linked_pg_reference(
[
{
"pagetype": linked_pg["reference_pagetype"],
"docname": linked_pg["reference_docname"],
}
],
remove_contact=pagetype == "Contact",
delete=delete_linked,
)
except Exception as e:
jingrow.log_error(
f"Error processing linked docs for {pagetype} {pg}: {str(e)}", "Bulk Delete Error"
)
if len(items) > 10:
jingrow.enqueue("jingrow.desk.reportview.delete_bulk", pagetype=pagetype, items=items)
else:
delete_bulk(pagetype, items)
return "success"

63
crm/api/session.py Normal file
View File

@ -0,0 +1,63 @@
import jingrow
@jingrow.whitelist()
def get_users():
users = jingrow.qb.get_query(
"User",
fields=[
"name",
"email",
"enabled",
"user_image",
"first_name",
"last_name",
"full_name",
"user_type",
],
order_by="full_name asc",
distinct=True,
).run(as_dict=1)
for user in users:
if jingrow.session.user == user.name:
user.session_user = True
user.roles = jingrow.get_roles(user.name)
user.role = ""
if "System Manager" in user.roles:
user.role = "System Manager"
elif "Sales Manager" in user.roles:
user.role = "Sales Manager"
elif "Sales User" in user.roles:
user.role = "Sales User"
elif "Guest" in user.roles:
user.role = "Guest"
if jingrow.session.user == user.name:
user.session_user = True
user.is_telephony_agent = jingrow.db.exists("CRM Telephony Agent", {"user": user.name})
crm_users = []
# crm users are users with role Sales User or Sales Manager
for user in users:
if "Sales User" in user.roles or "Sales Manager" in user.roles:
crm_users.append(user)
return users, crm_users
@jingrow.whitelist()
def get_organizations():
organizations = jingrow.qb.get_query(
"CRM Organization",
fields=["*"],
order_by="name asc",
distinct=True,
).run(as_dict=1)
return organizations

99
crm/api/settings.py Normal file
View File

@ -0,0 +1,99 @@
import jingrow
@jingrow.whitelist()
def create_email_account(data):
service = data.get("service")
service_config = email_service_config.get(service)
if not service_config:
return "Service not supported"
try:
email_pg = jingrow.get_pg(
{
"pagetype": "Email Account",
"email_id": data.get("email_id"),
"email_account_name": data.get("email_account_name"),
"service": service,
"enable_incoming": data.get("enable_incoming"),
"enable_outgoing": data.get("enable_outgoing"),
"default_incoming": data.get("default_incoming"),
"default_outgoing": data.get("default_outgoing"),
"email_sync_option": "ALL",
"initial_sync_count": 100,
"create_contact": 1,
"track_email_status": 1,
"use_tls": 1,
"use_imap": 1,
"smtp_port": 587,
**service_config,
}
)
if service == "Jingrow Mail":
email_pg.api_key = data.get("api_key")
email_pg.api_secret = data.get("api_secret")
email_pg.jingrow_mail_site = data.get("jingrow_mail_site")
email_pg.append_to = "CRM Lead"
else:
email_pg.append("imap_folder", {"append_to": "CRM Lead", "folder_name": "INBOX"})
email_pg.password = data.get("password")
# validate whether the credentials are correct
email_pg.get_incoming_server()
# if correct credentials, save the email account
email_pg.save()
except Exception as e:
jingrow.throw(str(e))
email_service_config = {
"Jingrow Mail": {
"domain": None,
"password": None,
"awaiting_password": 0,
"ascii_encode_password": 0,
"login_id_is_different": 0,
"login_id": None,
"use_imap": 0,
"use_ssl": 0,
"validate_ssl_certificate": 0,
"use_starttls": 0,
"email_server": None,
"incoming_port": 0,
"always_use_account_email_id_as_sender": 1,
"use_tls": 0,
"use_ssl_for_outgoing": 0,
"smtp_server": None,
"smtp_port": None,
"no_smtp_authentication": 0,
},
"GMail": {
"email_server": "imap.gmail.com",
"use_ssl": 1,
"smtp_server": "smtp.gmail.com",
},
"Outlook": {
"email_server": "imap-mail.outlook.com",
"use_ssl": 1,
"smtp_server": "smtp-mail.outlook.com",
},
"Sendgrid": {
"smtp_server": "smtp.sendgrid.net",
"smtp_port": 587,
},
"SparkPost": {
"smtp_server": "smtp.sparkpostmail.com",
},
"Yahoo": {
"email_server": "imap.mail.yahoo.com",
"use_ssl": 1,
"smtp_server": "smtp.mail.yahoo.com",
"smtp_port": 587,
},
"Yandex": {
"email_server": "imap.yandex.com",
"use_ssl": 1,
"smtp_server": "smtp.yandex.com",
"smtp_port": 587,
},
}

121
crm/api/todo.py Normal file
View File

@ -0,0 +1,121 @@
import jingrow
from jingrow import _
from crm.fcrm.pagetype.crm_notification.crm_notification import notify_user
def after_insert(pg, method):
if pg.reference_type in ["CRM Lead", "CRM Deal"] and pg.reference_name and pg.allocated_to:
fieldname = "lead_owner" if pg.reference_type == "CRM Lead" else "deal_owner"
owner = jingrow.db.get_value(pg.reference_type, pg.reference_name, fieldname)
if not owner:
jingrow.db.set_value(
pg.reference_type, pg.reference_name, fieldname, pg.allocated_to, update_modified=False
)
if pg.reference_type in ["CRM Lead", "CRM Deal", "CRM Task"] and pg.reference_name and pg.allocated_to:
notify_assigned_user(pg)
def on_update(pg, method):
if (
pg.has_value_changed("status")
and pg.status == "Cancelled"
and pg.reference_type in ["CRM Lead", "CRM Deal", "CRM Task"]
and pg.reference_name
and pg.allocated_to
):
notify_assigned_user(pg, is_cancelled=True)
def notify_assigned_user(pg, is_cancelled=False):
_pg = jingrow.get_pg(pg.reference_type, pg.reference_name)
owner = jingrow.get_cached_value("User", jingrow.session.user, "full_name")
notification_text = get_notification_text(owner, pg, _pg, is_cancelled)
message = (
_("Your assignment on {0} {1} has been removed by {2}").format(
pg.reference_type, pg.reference_name, owner
)
if is_cancelled
else _("{0} assigned a {1} {2} to you").format(owner, pg.reference_type, pg.reference_name)
)
redirect_to_pagetype, redirect_to_name = get_redirect_to_pg(pg)
notify_user(
{
"owner": jingrow.session.user,
"assigned_to": pg.allocated_to,
"notification_type": "Assignment",
"message": message,
"notification_text": notification_text,
"reference_pagetype": pg.reference_type,
"reference_docname": pg.reference_name,
"redirect_to_pagetype": redirect_to_pagetype,
"redirect_to_docname": redirect_to_name,
}
)
def get_notification_text(owner, pg, reference_pg, is_cancelled=False):
name = pg.reference_name
pagetype = pg.reference_type
if pagetype.startswith("CRM "):
pagetype = pagetype[4:].lower()
if pagetype in ["lead", "deal"]:
name = (
reference_pg.lead_name or name
if pagetype == "lead"
else reference_pg.organization or reference_pg.lead_name or name
)
if is_cancelled:
return f"""
<div class="mb-2 leading-5 text-ink-gray-5">
<span>{ _('Your assignment on {0} {1} has been removed by {2}').format(
pagetype,
f'<span class="font-medium text-ink-gray-9">{ name }</span>',
f'<span class="font-medium text-ink-gray-9">{ owner }</span>'
) }</span>
</div>
"""
return f"""
<div class="mb-2 leading-5 text-ink-gray-5">
<span class="font-medium text-ink-gray-9">{ owner }</span>
<span>{ _('assigned a {0} {1} to you').format(
pagetype,
f'<span class="font-medium text-ink-gray-9">{ name }</span>'
) }</span>
</div>
"""
if pagetype == "task":
if is_cancelled:
return f"""
<div class="mb-2 leading-5 text-ink-gray-5">
<span>{ _('Your assignment on task {0} has been removed by {1}').format(
f'<span class="font-medium text-ink-gray-9">{ reference_pg.title }</span>',
f'<span class="font-medium text-ink-gray-9">{ owner }</span>'
) }</span>
</div>
"""
return f"""
<div class="mb-2 leading-5 text-ink-gray-5">
<span class="font-medium text-ink-gray-9">{ owner }</span>
<span>{ _('assigned a new task {0} to you').format(
f'<span class="font-medium text-ink-gray-9">{ reference_pg.title }</span>'
) }</span>
</div>
"""
def get_redirect_to_pg(pg):
if pg.reference_type == "CRM Task":
reference_pg = jingrow.get_pg(pg.reference_type, pg.reference_name)
return reference_pg.reference_pagetype, reference_pg.reference_docname
return pg.reference_type, pg.reference_name

84
crm/api/user.py Normal file
View File

@ -0,0 +1,84 @@
import jingrow
@jingrow.whitelist()
def add_existing_users(users, role="Sales User"):
"""
Add existing users to the CRM by assigning them a role (Sales User or Sales Manager).
:param users: List of user names to be added
"""
jingrow.only_for(["System Manager", "Sales Manager"])
users = jingrow.parse_json(users)
for user in users:
add_user(user, role)
@jingrow.whitelist()
def update_user_role(user, new_role):
"""
Update the role of the user to Sales Manager, Sales User, or System Manager.
:param user: The name of the user
:param new_role: The new role to assign (Sales Manager or Sales User)
"""
jingrow.only_for(["System Manager", "Sales Manager"])
if new_role not in ["System Manager", "Sales Manager", "Sales User"]:
jingrow.throw("Cannot assign this role")
user_pg = jingrow.get_pg("User", user)
if new_role == "System Manager":
user_pg.append_roles("System Manager", "Sales Manager", "Sales User")
user_pg.set("block_modules", [])
if new_role == "Sales Manager":
user_pg.append_roles("Sales Manager", "Sales User")
user_pg.remove_roles("System Manager")
if new_role == "Sales User":
user_pg.append_roles("Sales User")
user_pg.remove_roles("Sales Manager", "System Manager")
update_module_in_user(user_pg, "FCRM")
user_pg.save(ignore_permissions=True)
@jingrow.whitelist()
def add_user(user, role):
"""
Add a user means adding role (Sales User or/and Sales Manager) to the user.
:param user: The name of the user to be added
:param role: The role to be assigned (Sales User or Sales Manager)
"""
update_user_role(user, role)
@jingrow.whitelist()
def remove_user(user):
"""
Remove a user means removing Sales User & Sales Manager roles from the user.
:param user: The name of the user to be removed
"""
jingrow.only_for(["System Manager", "Sales Manager"])
user_pg = jingrow.get_pg("User", user)
roles = [d.role for d in user_pg.roles]
if "Sales User" in roles:
user_pg.remove_roles("Sales User")
if "Sales Manager" in roles:
user_pg.remove_roles("Sales Manager")
user_pg.save(ignore_permissions=True)
jingrow.msgprint(f"User {user} has been removed from CRM roles.")
def update_module_in_user(user, module):
block_modules = jingrow.get_all(
"Module Def",
fields=["name as module"],
filters={"name": ["!=", module]},
)
if block_modules:
user.set("block_modules", block_modules)

16
crm/api/views.py Normal file
View File

@ -0,0 +1,16 @@
import jingrow
from pypika import Criterion
@jingrow.whitelist()
def get_views(pagetype):
View = jingrow.qb.PageType("CRM View Settings")
query = (
jingrow.qb.from_(View)
.select("*")
.where(Criterion.any([View.user == "", View.user == jingrow.session.user]))
)
if pagetype:
query = query.where(View.dt == pagetype)
views = query.run(as_dict=True)
return views

346
crm/api/whatsapp.py Normal file
View File

@ -0,0 +1,346 @@
import json
import jingrow
from jingrow import _
from crm.api.pg import get_assigned_users
from crm.fcrm.pagetype.crm_notification.crm_notification import notify_user
def validate(pg, method):
if pg.type == "Incoming" and pg.get("from"):
name, pagetype = get_lead_or_deal_from_number(pg.get("from"))
if name != None:
pg.reference_pagetype = pagetype
pg.reference_name = name
if pg.type == "Outgoing" and pg.get("to"):
name, pagetype = get_lead_or_deal_from_number(pg.get("to"))
if name != None:
pg.reference_pagetype = pagetype
pg.reference_name = name
def on_update(pg, method):
jingrow.publish_realtime(
"whatsapp_message",
{
"reference_pagetype": pg.reference_pagetype,
"reference_name": pg.reference_name,
},
)
notify_agent(pg)
def notify_agent(pg):
if pg.type == "Incoming":
pagetype = pg.reference_pagetype
if pagetype and pagetype.startswith("CRM "):
pagetype = pagetype[4:].lower()
notification_text = f"""
<div class="mb-2 leading-5 text-ink-gray-5">
<span class="font-medium text-ink-gray-9">{ _('You') }</span>
<span>{ _('received a whatsapp message in {0}').format(pagetype) }</span>
<span class="font-medium text-ink-gray-9">{ pg.reference_name }</span>
</div>
"""
assigned_users = get_assigned_users(pg.reference_pagetype, pg.reference_name)
for user in assigned_users:
notify_user(
{
"owner": pg.owner,
"assigned_to": user,
"notification_type": "WhatsApp",
"message": pg.message,
"notification_text": notification_text,
"reference_pagetype": "WhatsApp Message",
"reference_docname": pg.name,
"redirect_to_pagetype": pg.reference_pagetype,
"redirect_to_docname": pg.reference_name,
}
)
def get_lead_or_deal_from_number(number):
"""Get lead/deal from the given number."""
def find_record(pagetype, mobile_no, where=""):
mobile_no = parse_mobile_no(mobile_no)
query = f"""
SELECT name, mobile_no
FROM `tab{pagetype}`
WHERE CONCAT('+', REGEXP_REPLACE(mobile_no, '[^0-9]', '')) = {mobile_no}
"""
data = jingrow.db.sql(query + where, as_dict=True)
return data[0].name if data else None
pagetype = "CRM Deal"
pg = find_record(pagetype, number) or None
if not pg:
pagetype = "CRM Lead"
pg = find_record(pagetype, number, "AND converted is not True")
if not pg:
pg = find_record(pagetype, number)
return pg, pagetype
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 == "+"])
@jingrow.whitelist()
def is_whatsapp_enabled():
if not jingrow.db.exists("PageType", "WhatsApp Settings"):
return False
return jingrow.get_cached_value("WhatsApp Settings", "WhatsApp Settings", "enabled")
@jingrow.whitelist()
def is_whatsapp_installed():
if not jingrow.db.exists("PageType", "WhatsApp Settings"):
return False
return True
@jingrow.whitelist()
def get_whatsapp_messages(reference_pagetype, reference_name):
# twilio integration app is not compatible with crm app
# crm has its own twilio integration in built
if "twilio_integration" in jingrow.get_installed_apps():
return []
if not jingrow.db.exists("PageType", "WhatsApp Message"):
return []
messages = []
if reference_pagetype == "CRM Deal":
lead = jingrow.db.get_value(reference_pagetype, reference_name, "lead")
if lead:
messages = jingrow.get_all(
"WhatsApp Message",
filters={
"reference_pagetype": "CRM Lead",
"reference_name": lead,
},
fields=[
"name",
"type",
"to",
"from",
"content_type",
"message_type",
"attach",
"template",
"use_template",
"message_id",
"is_reply",
"reply_to_message_id",
"creation",
"message",
"status",
"reference_pagetype",
"reference_name",
"template_parameters",
"template_header_parameters",
],
)
messages += jingrow.get_all(
"WhatsApp Message",
filters={
"reference_pagetype": reference_pagetype,
"reference_name": reference_name,
},
fields=[
"name",
"type",
"to",
"from",
"content_type",
"message_type",
"attach",
"template",
"use_template",
"message_id",
"is_reply",
"reply_to_message_id",
"creation",
"message",
"status",
"reference_pagetype",
"reference_name",
"template_parameters",
"template_header_parameters",
],
)
# Filter messages to get only Template messages
template_messages = [message for message in messages if message["message_type"] == "Template"]
# Iterate through template messages
for template_message in template_messages:
# Find the template that this message is using
template = jingrow.get_pg("WhatsApp Templates", template_message["template"])
# If the template is found, add the template details to the template message
if template:
template_message["template_name"] = template.template_name
if template_message["template_parameters"]:
parameters = json.loads(template_message["template_parameters"])
template.template = parse_template_parameters(template.template, parameters)
template_message["template"] = template.template
if template_message["template_header_parameters"]:
header_parameters = json.loads(template_message["template_header_parameters"])
template.header = parse_template_parameters(template.header, header_parameters)
template_message["header"] = template.header
template_message["footer"] = template.footer
# Filter messages to get only reaction messages
reaction_messages = [message for message in messages if message["content_type"] == "reaction"]
# Iterate through reaction messages
for reaction_message in reaction_messages:
# Find the message that this reaction is reacting to
reacted_message = next(
(m for m in messages if m["message_id"] == reaction_message["reply_to_message_id"]),
None,
)
# If the reacted message is found, add the reaction to it
if reacted_message:
reacted_message["reaction"] = reaction_message["message"]
for message in messages:
from_name = get_from_name(message) if message["from"] else _("You")
message["from_name"] = from_name
# Filter messages to get only replies
reply_messages = [message for message in messages if message["is_reply"]]
# Iterate through reply messages
for reply_message in reply_messages:
# Find the message that this message is replying to
replied_message = next(
(m for m in messages if m["message_id"] == reply_message["reply_to_message_id"]),
None,
)
# If the replied message is found, add the reply details to the reply message
from_name = get_from_name(reply_message) if replied_message["from"] else _("You")
if replied_message:
message = replied_message["message"]
if replied_message["message_type"] == "Template":
message = replied_message["template"]
reply_message["reply_message"] = message
reply_message["header"] = replied_message.get("header") or ""
reply_message["footer"] = replied_message.get("footer") or ""
reply_message["reply_to"] = replied_message["name"]
reply_message["reply_to_type"] = replied_message["type"]
reply_message["reply_to_from"] = from_name
return [message for message in messages if message["content_type"] != "reaction"]
@jingrow.whitelist()
def create_whatsapp_message(
reference_pagetype,
reference_name,
message,
to,
attach,
reply_to,
content_type="text",
):
pg = jingrow.new_pg("WhatsApp Message")
if reply_to:
reply_pg = jingrow.get_pg("WhatsApp Message", reply_to)
pg.update(
{
"is_reply": True,
"reply_to_message_id": reply_pg.message_id,
}
)
pg.update(
{
"reference_pagetype": reference_pagetype,
"reference_name": reference_name,
"message": message or attach,
"to": to,
"attach": attach,
"content_type": content_type,
}
)
pg.insert(ignore_permissions=True)
return pg.name
@jingrow.whitelist()
def send_whatsapp_template(reference_pagetype, reference_name, template, to):
pg = jingrow.new_pg("WhatsApp Message")
pg.update(
{
"reference_pagetype": reference_pagetype,
"reference_name": reference_name,
"message_type": "Template",
"message": "Template message",
"content_type": "text",
"use_template": True,
"template": template,
"to": to,
}
)
pg.insert(ignore_permissions=True)
return pg.name
@jingrow.whitelist()
def react_on_whatsapp_message(emoji, reply_to_name):
reply_to_pg = jingrow.get_pg("WhatsApp Message", reply_to_name)
to = reply_to_pg.type == "Incoming" and reply_to_pg.get("from") or reply_to_pg.to
pg = jingrow.new_pg("WhatsApp Message")
pg.update(
{
"reference_pagetype": reply_to_pg.reference_pagetype,
"reference_name": reply_to_pg.reference_name,
"message": emoji,
"to": to,
"reply_to_message_id": reply_to_pg.message_id,
"content_type": "reaction",
}
)
pg.insert(ignore_permissions=True)
return pg.name
def parse_template_parameters(string, parameters):
for i, parameter in enumerate(parameters, start=1):
placeholder = "{{" + str(i) + "}}"
string = string.replace(placeholder, parameter)
return string
def get_from_name(message):
pg = jingrow.get_pg(message["reference_pagetype"], message["reference_name"])
from_name = ""
if message["reference_pagetype"] == "CRM Deal":
if pg.get("contacts"):
for c in pg.get("contacts"):
if c.is_primary:
from_name = c.full_name or c.mobile_no
break
else:
from_name = pg.get("lead_name")
else:
from_name = " ".join(filter(None, [pg.get("first_name"), pg.get("last_name")]))
return from_name

0
crm/config/__init__.py Normal file
View File

8
crm/crowdin.yml Normal file
View File

@ -0,0 +1,8 @@
files:
- source: /crm/locale/main.pot
translation: /crm/locale/%two_letters_code%.po
pull_request_title: "chore: sync translations from crowdin"
pull_request_labels:
- translation
commit_message: "chore: %language% translations"
append_commit_message: false

0
crm/fcrm/__init__.py Normal file
View File

View File

View File

@ -0,0 +1,8 @@
// Copyright (c) 2023, JINGROW and contributors
// For license information, please see license.txt
// jingrow.ui.form.on("CRM Call Log", {
// refresh(frm) {
// },
// });

View File

@ -0,0 +1,195 @@
{
"actions": [],
"allow_import": 1,
"allow_rename": 1,
"autoname": "field:id",
"creation": "2023-08-28 00:23:36.229137",
"default_view": "List",
"pagetype": "PageType",
"editable_grid": 1,
"engine": "InnoDB",
"field_order": [
"telephony_medium",
"section_break_gyqe",
"id",
"from",
"status",
"duration",
"medium",
"start_time",
"reference_pagetype",
"reference_docname",
"column_break_ufnp",
"to",
"type",
"receiver",
"caller",
"recording_url",
"end_time",
"note",
"section_break_kebz",
"links"
],
"fields": [
{
"fieldname": "id",
"fieldtype": "Data",
"label": "ID",
"unique": 1
},
{
"fieldname": "from",
"fieldtype": "Data",
"in_list_view": 1,
"label": "From",
"reqd": 1
},
{
"fieldname": "status",
"fieldtype": "Select",
"label": "Status",
"options": "Initiated\nRinging\nIn Progress\nCompleted\nFailed\nBusy\nNo Answer\nQueued\nCanceled",
"reqd": 1
},
{
"fieldname": "start_time",
"fieldtype": "Datetime",
"label": "Start Time"
},
{
"fieldname": "medium",
"fieldtype": "Data",
"label": "Medium"
},
{
"fieldname": "column_break_ufnp",
"fieldtype": "Column Break"
},
{
"fieldname": "type",
"fieldtype": "Select",
"in_list_view": 1,
"in_standard_filter": 1,
"label": "Type",
"options": "Incoming\nOutgoing",
"reqd": 1
},
{
"fieldname": "to",
"fieldtype": "Data",
"in_list_view": 1,
"label": "To",
"reqd": 1
},
{
"description": "Call duration in seconds",
"fieldname": "duration",
"fieldtype": "Duration",
"in_list_view": 1,
"label": "Duration"
},
{
"fieldname": "recording_url",
"fieldtype": "Data",
"label": "Recording URL"
},
{
"fieldname": "end_time",
"fieldtype": "Datetime",
"label": "End Time"
},
{
"fieldname": "note",
"fieldtype": "Link",
"label": "Note",
"options": "FCRM Note"
},
{
"depends_on": "eval:pg.type == 'Incoming'",
"fieldname": "receiver",
"fieldtype": "Link",
"label": "Call Received By",
"options": "User"
},
{
"depends_on": "eval:pg.type == 'Outgoing'",
"fieldname": "caller",
"fieldtype": "Link",
"label": "Caller",
"options": "User"
},
{
"default": "CRM Lead",
"fieldname": "reference_pagetype",
"fieldtype": "Link",
"label": "Reference Document Type",
"options": "PageType"
},
{
"fieldname": "reference_docname",
"fieldtype": "Dynamic Link",
"label": "Reference Name",
"options": "reference_pagetype"
},
{
"fieldname": "section_break_kebz",
"fieldtype": "Section Break"
},
{
"fieldname": "links",
"fieldtype": "Table",
"label": "Links",
"options": "Dynamic Link"
},
{
"fieldname": "telephony_medium",
"fieldtype": "Select",
"in_list_view": 1,
"in_standard_filter": 1,
"label": "Telephony Medium",
"options": "\nManual\nTwilio\nExotel",
"read_only": 1
},
{
"fieldname": "section_break_gyqe",
"fieldtype": "Section Break"
}
],
"index_web_pages_for_search": 1,
"links": [],
"modified": "2025-04-01 16:01:54.479309",
"modified_by": "Administrator",
"module": "FCRM",
"name": "CRM Call Log",
"naming_rule": "By fieldname",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "Sales User",
"share": 1,
"write": 1
},
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "Sales Manager",
"share": 1,
"write": 1
}
],
"sort_field": "modified",
"sort_order": "DESC",
"states": []
}

View File

@ -0,0 +1,214 @@
# Copyright (c) 2023, JINGROW and contributors
# For license information, please see license.txt
import jingrow
from jingrow.model.page import Page
from crm.integrations.api import get_contact_by_phone_number
from crm.utils import seconds_to_duration
class CRMCallLog(Page):
@staticmethod
def default_list_data():
columns = [
{
"label": "Caller",
"type": "Link",
"key": "caller",
"options": "User",
"width": "9rem",
},
{
"label": "Receiver",
"type": "Link",
"key": "receiver",
"options": "User",
"width": "9rem",
},
{
"label": "Type",
"type": "Select",
"key": "type",
"width": "9rem",
},
{
"label": "Status",
"type": "Select",
"key": "status",
"width": "9rem",
},
{
"label": "Duration",
"type": "Duration",
"key": "duration",
"width": "6rem",
},
{
"label": "From (number)",
"type": "Data",
"key": "from",
"width": "9rem",
},
{
"label": "To (number)",
"type": "Data",
"key": "to",
"width": "9rem",
},
{
"label": "Created On",
"type": "Datetime",
"key": "creation",
"width": "8rem",
},
]
rows = [
"name",
"caller",
"receiver",
"type",
"status",
"duration",
"from",
"to",
"note",
"recording_url",
"reference_pagetype",
"reference_docname",
"creation",
]
return {"columns": columns, "rows": rows}
def parse_list_data(calls):
return [parse_call_log(call) for call in calls] if calls else []
def has_link(self, pagetype, name):
for link in self.links:
if link.link_pagetype == pagetype and link.link_name == name:
return True
def link_with_reference_pg(self, reference_pagetype, reference_name):
if self.has_link(reference_pagetype, reference_name):
return
self.append("links", {"link_pagetype": reference_pagetype, "link_name": reference_name})
def parse_call_log(call):
call["show_recording"] = False
call["_duration"] = seconds_to_duration(call.get("duration"))
if call.get("type") == "Incoming":
call["activity_type"] = "incoming_call"
contact = get_contact_by_phone_number(call.get("from"))
receiver = (
jingrow.db.get_values("User", call.get("receiver"), ["full_name", "user_image"])[0]
if call.get("receiver")
else [None, None]
)
call["_caller"] = {
"label": contact.get("full_name", "Unknown"),
"image": contact.get("image"),
}
call["_receiver"] = {
"label": receiver[0],
"image": receiver[1],
}
elif call.get("type") == "Outgoing":
call["activity_type"] = "outgoing_call"
contact = get_contact_by_phone_number(call.get("to"))
caller = (
jingrow.db.get_values("User", call.get("caller"), ["full_name", "user_image"])[0]
if call.get("caller")
else [None, None]
)
call["_caller"] = {
"label": caller[0],
"image": caller[1],
}
call["_receiver"] = {
"label": contact.get("full_name", "Unknown"),
"image": contact.get("image"),
}
return call
@jingrow.whitelist()
def get_call_log(name):
call = jingrow.get_cached_pg(
"CRM Call Log",
name,
fields=[
"name",
"caller",
"receiver",
"duration",
"type",
"status",
"from",
"to",
"note",
"recording_url",
"reference_pagetype",
"reference_docname",
"creation",
],
).as_dict()
call = parse_call_log(call)
notes = []
tasks = []
if call.get("note"):
note = jingrow.get_cached_pg("FCRM Note", call.get("note")).as_dict()
notes.append(note)
if call.get("reference_pagetype") and call.get("reference_docname"):
if call.get("reference_pagetype") == "CRM Lead":
call["_lead"] = call.get("reference_docname")
elif call.get("reference_pagetype") == "CRM Deal":
call["_deal"] = call.get("reference_docname")
if call.get("links"):
for link in call.get("links"):
if link.get("link_pagetype") == "CRM Task":
task = jingrow.get_cached_pg("CRM Task", link.get("link_name")).as_dict()
tasks.append(task)
elif link.get("link_pagetype") == "FCRM Note":
note = jingrow.get_cached_pg("FCRM Note", link.get("link_name")).as_dict()
notes.append(note)
elif link.get("link_pagetype") == "CRM Lead":
call["_lead"] = link.get("link_name")
elif link.get("link_pagetype") == "CRM Deal":
call["_deal"] = link.get("link_name")
call["_tasks"] = tasks
call["_notes"] = notes
return call
@jingrow.whitelist()
def create_lead_from_call_log(call_log, lead_details=None):
lead = jingrow.new_pg("CRM Lead")
lead_details = jingrow.parse_json(lead_details or "{}")
if not lead_details.get("lead_owner"):
lead_details["lead_owner"] = jingrow.session.user
if not lead_details.get("mobile_no"):
lead_details["mobile_no"] = call_log.get("from") or ""
if not lead_details.get("first_name"):
lead_details["first_name"] = "Lead from call " + (
lead_details.get("mobile_no") or call_log.get("name")
)
lead.update(lead_details)
lead.save(ignore_permissions=True)
# link call log with lead
call_log = jingrow.get_pg("CRM Call Log", call_log.get("name"))
call_log.link_with_reference_pg("CRM Lead", lead.name)
call_log.save(ignore_permissions=True)
return lead.name

View File

@ -0,0 +1,9 @@
# Copyright (c) 2023, JINGROW and Contributors
# See license.txt
# import jingrow
from jingrow.tests import UnitTestCase
class TestCRMCallLog(UnitTestCase):
pass

View File

@ -0,0 +1,8 @@
// Copyright (c) 2023, JINGROW and contributors
// For license information, please see license.txt
// jingrow.ui.form.on("CRM Communication Status", {
// refresh(frm) {
// },
// });

View File

@ -0,0 +1,59 @@
{
"actions": [],
"allow_rename": 1,
"autoname": "field:status",
"creation": "2023-12-13 13:25:07.213100",
"pagetype": "PageType",
"engine": "InnoDB",
"field_order": [
"status"
],
"fields": [
{
"fieldname": "status",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Status",
"reqd": 1,
"unique": 1
}
],
"index_web_pages_for_search": 1,
"links": [],
"modified": "2024-01-19 21:55:17.952032",
"modified_by": "Administrator",
"module": "FCRM",
"name": "CRM Communication Status",
"naming_rule": "By fieldname",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "Sales User",
"share": 1,
"write": 1
},
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "Sales Manager",
"share": 1,
"write": 1
}
],
"quick_entry": 1,
"sort_field": "modified",
"sort_order": "DESC",
"states": []
}

View File

@ -0,0 +1,9 @@
# Copyright (c) 2023, JINGROW and contributors
# For license information, please see license.txt
# import jingrow
from jingrow.model.page import Page
class CRMCommunicationStatus(Page):
pass

View File

@ -0,0 +1,9 @@
# Copyright (c) 2023, JINGROW and Contributors
# See license.txt
# import jingrow
from jingrow.tests import UnitTestCase
class TestCRMCommunicationStatus(UnitTestCase):
pass

View File

@ -0,0 +1,91 @@
{
"actions": [],
"allow_rename": 1,
"creation": "2023-08-25 19:08:36.356133",
"pagetype": "PageType",
"editable_grid": 1,
"engine": "InnoDB",
"field_order": [
"contact",
"full_name",
"email",
"column_break_uvny",
"gender",
"mobile_no",
"phone",
"is_primary"
],
"fields": [
{
"fieldname": "contact",
"fieldtype": "Link",
"in_list_view": 1,
"label": "Contact",
"options": "Contact"
},
{
"fetch_from": "contact.full_name",
"fieldname": "full_name",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Full Name",
"read_only": 1
},
{
"fetch_from": "contact.email_id",
"fieldname": "email",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Email",
"read_only": 1
},
{
"fieldname": "column_break_uvny",
"fieldtype": "Column Break"
},
{
"fetch_from": "contact.mobile_no",
"fieldname": "mobile_no",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Mobile No",
"options": "Phone",
"read_only": 1
},
{
"fetch_from": "contact.phone",
"fieldname": "phone",
"fieldtype": "Data",
"label": "Phone",
"options": "Phone",
"read_only": 1
},
{
"fetch_from": "contact.gender",
"fieldname": "gender",
"fieldtype": "Link",
"label": "Gender",
"options": "Gender",
"read_only": 1
},
{
"default": "0",
"fieldname": "is_primary",
"fieldtype": "Check",
"in_list_view": 1,
"label": "Is Primary"
}
],
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
"modified": "2023-11-12 14:58:18.846919",
"modified_by": "Administrator",
"module": "FCRM",
"name": "CRM Contacts",
"owner": "Administrator",
"permissions": [],
"sort_field": "modified",
"sort_order": "DESC",
"states": []
}

View File

@ -0,0 +1,9 @@
# Copyright (c) 2023, JINGROW and contributors
# For license information, please see license.txt
# import jingrow
from jingrow.model.page import Page
class CRMContacts(Page):
pass

View File

@ -0,0 +1,8 @@
// Copyright (c) 2025, JINGROW and contributors
// For license information, please see license.txt
// jingrow.ui.form.on("CRM Dashboard", {
// refresh(frm) {
// },
// });

View File

@ -0,0 +1,105 @@
{
"actions": [],
"allow_rename": 1,
"autoname": "field:title",
"creation": "2025-07-14 12:19:49.725022",
"pagetype": "PageType",
"engine": "InnoDB",
"field_order": [
"title",
"private",
"column_break_exbw",
"user",
"section_break_hfza",
"layout"
],
"fields": [
{
"fieldname": "column_break_exbw",
"fieldtype": "Column Break"
},
{
"fieldname": "section_break_hfza",
"fieldtype": "Section Break"
},
{
"default": "[]",
"fieldname": "layout",
"fieldtype": "Code",
"label": "Layout",
"options": "JSON"
},
{
"fieldname": "title",
"fieldtype": "Data",
"label": "Name",
"unique": 1
},
{
"depends_on": "private",
"fieldname": "user",
"fieldtype": "Link",
"label": "User",
"mandatory_depends_on": "private",
"options": "User"
},
{
"default": "0",
"fieldname": "private",
"fieldtype": "Check",
"label": "Private"
}
],
"grid_page_length": 50,
"index_web_pages_for_search": 1,
"links": [],
"modified": "2025-07-14 12:36:10.831351",
"modified_by": "Administrator",
"module": "FCRM",
"name": "CRM Dashboard",
"naming_rule": "By fieldname",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "System Manager",
"share": 1,
"write": 1
},
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "Sales Manager",
"share": 1,
"write": 1
},
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "Sales User",
"share": 1,
"write": 1
}
],
"row_format": "Dynamic",
"sort_field": "creation",
"sort_order": "DESC",
"states": [],
"title_field": "title"
}

View File

@ -0,0 +1,34 @@
# Copyright (c) 2025, JINGROW and contributors
# For license information, please see license.txt
import jingrow
from jingrow import _
from jingrow.model.page import Page
class CRMDashboard(Page):
pass
def default_manager_dashboard_layout():
"""
Returns the default layout for the CRM Manager Dashboard.
"""
return '[{"name":"total_leads","type":"number_chart","tooltip":"Total number of leads","layout":{"x":0,"y":0,"w":4,"h":3,"i":"total_leads"}},{"name":"ongoing_deals","type":"number_chart","tooltip":"Total number of ongoing deals","layout":{"x":8,"y":0,"w":4,"h":3,"i":"ongoing_deals"}},{"name":"won_deals","type":"number_chart","tooltip":"Total number of won deals","layout":{"x":12,"y":0,"w":4,"h":3,"i":"won_deals"}},{"name":"average_won_deal_value","type":"number_chart","tooltip":"Average value of won deals","layout":{"x":16,"y":0,"w":4,"h":3,"i":"average_won_deal_value"}},{"name":"average_deal_value","type":"number_chart","tooltip":"Average deal value of ongoing and won deals","layout":{"x":0,"y":2,"w":4,"h":3,"i":"average_deal_value"}},{"name":"average_time_to_close_a_lead","type":"number_chart","tooltip":"Average time taken to close a lead","layout":{"x":4,"y":0,"w":4,"h":3,"i":"average_time_to_close_a_lead"}},{"name":"average_time_to_close_a_deal","type":"number_chart","layout":{"x":4,"y":2,"w":4,"h":3,"i":"average_time_to_close_a_deal"}},{"name":"spacer","type":"spacer","layout":{"x":8,"y":2,"w":12,"h":3,"i":"spacer"}},{"name":"sales_trend","type":"axis_chart","layout":{"x":0,"y":4,"w":10,"h":9,"i":"sales_trend"}},{"name":"forecasted_revenue","type":"axis_chart","layout":{"x":10,"y":4,"w":10,"h":9,"i":"forecasted_revenue"}},{"name":"funnel_conversion","type":"axis_chart","layout":{"x":0,"y":11,"w":10,"h":9,"i":"funnel_conversion"}},{"name":"deals_by_stage_donut","type":"donut_chart","layout":{"x":10,"y":11,"w":10,"h":9,"i":"deals_by_stage_donut"}},{"name":"lost_deal_reasons","type":"axis_chart","layout":{"x":0,"y":32,"w":20,"h":9,"i":"lost_deal_reasons"}},{"name":"leads_by_source","type":"donut_chart","layout":{"x":0,"y":18,"w":10,"h":9,"i":"leads_by_source"}},{"name":"deals_by_source","type":"donut_chart","layout":{"x":10,"y":18,"w":10,"h":9,"i":"deals_by_source"}},{"name":"deals_by_territory","type":"axis_chart","layout":{"x":0,"y":25,"w":10,"h":9,"i":"deals_by_territory"}},{"name":"deals_by_salesperson","type":"axis_chart","layout":{"x":10,"y":25,"w":10,"h":9,"i":"deals_by_salesperson"}}]'
def create_default_manager_dashboard(force=False):
"""
Creates the default CRM Manager Dashboard if it does not exist.
"""
if not jingrow.db.exists("CRM Dashboard", "Manager Dashboard"):
pg = jingrow.new_pg("CRM Dashboard")
pg.title = "Manager Dashboard"
pg.layout = default_manager_dashboard_layout()
pg.insert(ignore_permissions=True)
else:
pg = jingrow.get_pg("CRM Dashboard", "Manager Dashboard")
if force:
pg.layout = default_manager_dashboard_layout()
pg.save(ignore_permissions=True)
return pg.layout

View File

@ -0,0 +1,30 @@
# Copyright (c) 2025, JINGROW and Contributors
# See license.txt
# import jingrow
from jingrow.tests import IntegrationTestCase, UnitTestCase
# On IntegrationTestCase, the pagetype test records and all
# link-field test record dependencies are recursively loaded
# Use these module variables to add/remove to/from that list
EXTRA_TEST_RECORD_DEPENDENCIES = [] # eg. ["User"]
IGNORE_TEST_RECORD_DEPENDENCIES = [] # eg. ["User"]
class UnitTestCRMDashboard(UnitTestCase):
"""
Unit tests for CRMDashboard.
Use this class for testing individual functions and methods.
"""
pass
class IntegrationTestCRMDashboard(IntegrationTestCase):
"""
Integration tests for CRMDashboard.
Use this class for testing interactions between multiple components.
"""
pass

View File

View File

@ -0,0 +1,29 @@
import jingrow
@jingrow.whitelist()
def get_deal_contacts(name):
contacts = jingrow.get_all(
"CRM Contacts",
filters={"parenttype": "CRM Deal", "parent": name},
fields=["contact", "is_primary"],
distinct=True,
)
deal_contacts = []
for contact in contacts:
if not contact.contact:
continue
is_primary = contact.is_primary
contact = jingrow.get_pg("Contact", contact.contact).as_dict()
_contact = {
"name": contact.name,
"image": contact.image,
"full_name": contact.full_name,
"email": contact.email_id,
"mobile_no": contact.mobile_no,
"is_primary": is_primary,
}
deal_contacts.append(_contact)
return deal_contacts

View File

@ -0,0 +1,72 @@
// Copyright (c) 2023, JINGROW and contributors
// For license information, please see license.txt
jingrow.ui.form.on("CRM Deal", {
refresh(frm) {
frm.add_web_link(`/crm/deals/${frm.pg.name}`, __("Open in Portal"));
},
update_total: function (frm) {
let total = 0;
let total_qty = 0;
let net_total = 0;
frm.pg.products.forEach((d) => {
total += d.amount;
total_qty += d.qty;
net_total += d.net_amount;
});
jingrow.model.set_value(frm.pagetype, frm.docname, "total", total);
jingrow.model.set_value(
frm.pagetype,
frm.docname,
"net_total",
net_total || total
);
}
});
jingrow.ui.form.on("CRM Products", {
products_add: function (frm, cdt, cdn) {
frm.trigger("update_total");
},
products_remove: function (frm, cdt, cdn) {
frm.trigger("update_total");
},
product_code: function (frm, cdt, cdn) {
let d = jingrow.get_pg(cdt, cdn);
jingrow.model.set_value(cdt, cdn, "product_name", d.product_code);
},
rate: function (frm, cdt, cdn) {
let d = jingrow.get_pg(cdt, cdn);
if (d.rate && d.qty) {
jingrow.model.set_value(cdt, cdn, "amount", d.rate * d.qty);
}
frm.trigger("update_total");
},
qty: function (frm, cdt, cdn) {
let d = jingrow.get_pg(cdt, cdn);
if (d.rate && d.qty) {
jingrow.model.set_value(cdt, cdn, "amount", d.rate * d.qty);
}
frm.trigger("update_total");
},
discount_percentage: function (frm, cdt, cdn) {
let d = jingrow.get_pg(cdt, cdn);
if (d.discount_percentage && d.amount) {
discount_amount = (d.discount_percentage / 100) * d.amount;
jingrow.model.set_value(
cdt,
cdn,
"discount_amount",
discount_amount
);
jingrow.model.set_value(
cdt,
cdn,
"net_amount",
d.amount - discount_amount
);
}
frm.trigger("update_total");
}
});

View File

@ -0,0 +1,474 @@
{
"actions": [],
"allow_import": 1,
"allow_rename": 1,
"autoname": "naming_series:",
"creation": "2023-11-06 17:56:25.210449",
"pagetype": "PageType",
"engine": "InnoDB",
"field_order": [
"organization_tab",
"naming_series",
"organization",
"next_step",
"column_break_ijan",
"status",
"deal_owner",
"lost_reason",
"lost_notes",
"section_break_jgpm",
"probability",
"expected_deal_value",
"deal_value",
"column_break_kpxa",
"expected_closure_date",
"closed_date",
"contacts_tab",
"contacts",
"contact",
"lead_details_tab",
"lead",
"source",
"column_break_wsde",
"lead_name",
"organization_details_section",
"organization_name",
"website",
"no_of_employees",
"job_title",
"column_break_xbyf",
"territory",
"currency",
"exchange_rate",
"annual_revenue",
"industry",
"person_section",
"salutation",
"first_name",
"last_name",
"column_break_xjmy",
"email",
"mobile_no",
"phone",
"gender",
"products_tab",
"products",
"section_break_ccbj",
"total",
"column_break_udbq",
"net_total",
"sla_tab",
"sla",
"sla_creation",
"column_break_pfvq",
"sla_status",
"communication_status",
"response_details_section",
"response_by",
"column_break_hpvj",
"first_response_time",
"first_responded_on",
"log_tab",
"status_change_log"
],
"fields": [
{
"fieldname": "organization",
"fieldtype": "Link",
"label": "Organization",
"options": "CRM Organization"
},
{
"fieldname": "probability",
"fieldtype": "Percent",
"label": "Probability"
},
{
"fetch_from": ".annual_revenue",
"fieldname": "annual_revenue",
"fieldtype": "Currency",
"label": "Annual Revenue",
"options": "currency"
},
{
"fetch_from": ".website",
"fieldname": "website",
"fieldtype": "Data",
"label": "Website"
},
{
"fieldname": "next_step",
"fieldtype": "Data",
"label": "Next Step"
},
{
"fieldname": "lead",
"fieldtype": "Link",
"label": "Lead",
"options": "CRM Lead"
},
{
"fieldname": "deal_owner",
"fieldtype": "Link",
"label": "Deal Owner",
"options": "User"
},
{
"default": "CRM-DEAL-.YYYY.-",
"fieldname": "naming_series",
"fieldtype": "Select",
"label": "Naming Series",
"options": "CRM-DEAL-.YYYY.-"
},
{
"fieldname": "contacts_tab",
"fieldtype": "Tab Break",
"label": "Contacts"
},
{
"fieldname": "email",
"fieldtype": "Data",
"label": "Primary Email",
"options": "Email"
},
{
"fieldname": "mobile_no",
"fieldtype": "Data",
"label": "Primary Mobile No",
"options": "Phone"
},
{
"default": "Qualification",
"fieldname": "status",
"fieldtype": "Link",
"in_list_view": 1,
"label": "Status",
"options": "CRM Deal Status",
"reqd": 1,
"search_index": 1
},
{
"fieldname": "contacts",
"fieldtype": "Table",
"label": "Contacts",
"options": "CRM Contacts"
},
{
"fieldname": "organization_tab",
"fieldtype": "Tab Break",
"label": "Organization"
},
{
"fieldname": "sla_tab",
"fieldtype": "Tab Break",
"label": "SLA",
"read_only": 1
},
{
"fieldname": "sla",
"fieldtype": "Link",
"label": "SLA",
"options": "CRM Service Level Agreement"
},
{
"fieldname": "response_by",
"fieldtype": "Datetime",
"label": "Response By",
"read_only": 1
},
{
"fieldname": "column_break_pfvq",
"fieldtype": "Column Break"
},
{
"fieldname": "sla_status",
"fieldtype": "Select",
"label": "SLA Status",
"options": "\nFirst Response Due\nFailed\nFulfilled",
"read_only": 1
},
{
"fieldname": "sla_creation",
"fieldtype": "Datetime",
"label": "SLA Creation",
"read_only": 1
},
{
"fieldname": "response_details_section",
"fieldtype": "Section Break",
"label": "Response Details"
},
{
"fieldname": "column_break_hpvj",
"fieldtype": "Column Break"
},
{
"fieldname": "first_response_time",
"fieldtype": "Duration",
"label": "First Response Time",
"read_only": 1
},
{
"fieldname": "first_responded_on",
"fieldtype": "Datetime",
"label": "First Responded On",
"read_only": 1
},
{
"default": "Open",
"fieldname": "communication_status",
"fieldtype": "Link",
"label": "Communication Status",
"options": "CRM Communication Status"
},
{
"fetch_from": ".territory",
"fieldname": "territory",
"fieldtype": "Link",
"label": "Territory",
"options": "CRM Territory"
},
{
"fieldname": "source",
"fieldtype": "Link",
"label": "Source",
"options": "CRM Lead Source"
},
{
"fieldname": "no_of_employees",
"fieldtype": "Select",
"label": "No. of Employees",
"options": "1-10\n11-50\n51-200\n201-500\n501-1000\n1000+"
},
{
"fieldname": "job_title",
"fieldtype": "Data",
"label": "Job Title"
},
{
"fieldname": "phone",
"fieldtype": "Data",
"label": "Primary Phone",
"options": "Phone"
},
{
"fieldname": "log_tab",
"fieldtype": "Tab Break",
"label": "Log",
"read_only": 1
},
{
"fieldname": "status_change_log",
"fieldtype": "Table",
"label": "Status Change Log",
"options": "CRM Status Change Log"
},
{
"fieldname": "lead_name",
"fieldtype": "Data",
"label": "Lead Name"
},
{
"fieldname": "column_break_ijan",
"fieldtype": "Column Break"
},
{
"fieldname": "lead_details_tab",
"fieldtype": "Tab Break",
"label": "Lead Details"
},
{
"fieldname": "column_break_wsde",
"fieldtype": "Column Break"
},
{
"fieldname": "organization_details_section",
"fieldtype": "Section Break",
"label": "Organization Details"
},
{
"fieldname": "organization_name",
"fieldtype": "Data",
"label": "Organization Name"
},
{
"fieldname": "column_break_xbyf",
"fieldtype": "Column Break"
},
{
"fieldname": "industry",
"fieldtype": "Link",
"label": "Industry",
"options": "CRM Industry"
},
{
"fieldname": "person_section",
"fieldtype": "Section Break",
"label": "Person"
},
{
"fieldname": "salutation",
"fieldtype": "Link",
"label": "Salutation",
"options": "Salutation"
},
{
"fieldname": "first_name",
"fieldtype": "Data",
"label": "First Name"
},
{
"fieldname": "last_name",
"fieldtype": "Data",
"label": "Last Name"
},
{
"fieldname": "column_break_xjmy",
"fieldtype": "Column Break"
},
{
"fieldname": "gender",
"fieldtype": "Link",
"label": "Gender",
"options": "Gender"
},
{
"fieldname": "contact",
"fieldtype": "Link",
"label": "Contact",
"options": "Contact"
},
{
"fieldname": "currency",
"fieldtype": "Link",
"label": "Currency",
"options": "Currency"
},
{
"fieldname": "products_tab",
"fieldtype": "Tab Break",
"label": "Products"
},
{
"fieldname": "products",
"fieldtype": "Table",
"label": "Products",
"options": "CRM Products"
},
{
"fieldname": "section_break_ccbj",
"fieldtype": "Section Break"
},
{
"fieldname": "column_break_udbq",
"fieldtype": "Column Break"
},
{
"fieldname": "total",
"fieldtype": "Currency",
"label": "Total",
"options": "currency",
"read_only": 1
},
{
"description": "Total after discount",
"fieldname": "net_total",
"fieldtype": "Currency",
"label": "Net Total",
"options": "currency",
"read_only": 1
},
{
"fieldname": "section_break_jgpm",
"fieldtype": "Section Break"
},
{
"fieldname": "deal_value",
"fieldtype": "Currency",
"label": "Deal Value",
"options": "currency"
},
{
"fieldname": "column_break_kpxa",
"fieldtype": "Column Break"
},
{
"fieldname": "lost_reason",
"fieldtype": "Link",
"label": "Lost Reason",
"mandatory_depends_on": "eval: pg.status == \"Lost\"",
"options": "CRM Lost Reason"
},
{
"fieldname": "lost_notes",
"fieldtype": "Text",
"label": "Lost Notes",
"mandatory_depends_on": "eval: pg.lost_reason == \"Other\""
},
{
"default": "1",
"description": "The rate used to convert the deal\u2019s currency to your crm's base currency (set in CRM Settings). It is set once when the currency is first added and doesn't change automatically.",
"fieldname": "exchange_rate",
"fieldtype": "Float",
"label": "Exchange Rate"
},
{
"fieldname": "expected_deal_value",
"fieldtype": "Currency",
"label": "Expected Deal Value",
"options": "currency"
},
{
"fieldname": "expected_closure_date",
"fieldtype": "Date",
"label": "Expected Closure Date"
},
{
"fieldname": "closed_date",
"fieldtype": "Date",
"label": "Closed Date"
}
],
"grid_page_length": 50,
"index_web_pages_for_search": 1,
"links": [],
"modified": "2025-08-26 12:12:56.324245",
"modified_by": "Administrator",
"module": "FCRM",
"name": "CRM Deal",
"naming_rule": "By \"Naming Series\" field",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "Sales User",
"share": 1,
"write": 1
},
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "Sales Manager",
"share": 1,
"write": 1
}
],
"row_format": "Dynamic",
"show_title_field_in_link": 1,
"sort_field": "modified",
"sort_order": "DESC",
"states": [],
"title_field": "organization",
"track_changes": 1
}

View File

@ -0,0 +1,388 @@
# Copyright (c) 2023, JINGROW and contributors
# For license information, please see license.txt
import jingrow
from jingrow import _
from jingrow.desk.form.assign_to import add as assign
from jingrow.model.page import Page
from crm.fcrm.pagetype.crm_service_level_agreement.utils import get_sla
from crm.fcrm.pagetype.crm_status_change_log.crm_status_change_log import add_status_change_log
from crm.fcrm.pagetype.fcrm_settings.fcrm_settings import get_exchange_rate
class CRMDeal(Page):
def before_validate(self):
self.set_sla()
def validate(self):
self.set_primary_contact()
self.set_primary_email_mobile_no()
if not self.is_new() and self.has_value_changed("deal_owner") and self.deal_owner:
self.share_with_agent(self.deal_owner)
self.assign_agent(self.deal_owner)
if self.has_value_changed("status"):
add_status_change_log(self)
if jingrow.db.get_value("CRM Deal Status", self.status, "type") == "Won":
self.closed_date = jingrow.utils.nowdate()
self.validate_forecasting_fields()
self.validate_lost_reason()
self.update_exchange_rate()
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:
jingrow.throw(_("Only one {0} can be set as primary.").format(jingrow.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], "pagetype": "CRM Deal", "name": self.name}, ignore_permissions=True)
def share_with_agent(self, agent):
if not agent:
return
docshares = jingrow.get_all(
"DocShare",
filters={"share_name": self.name, "share_pagetype": self.pagetype},
fields=["name", "user"],
)
shared_with = [d.user for d in docshares] + [agent]
for user in shared_with:
if user == agent and not jingrow.db.exists(
"DocShare",
{"user": agent, "share_name": self.name, "share_pagetype": self.pagetype},
):
jingrow.share.add_docshare(
self.pagetype,
self.name,
agent,
write=1,
flags={"ignore_share_permission": True},
)
elif user != agent:
jingrow.share.remove(self.pagetype, 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 = jingrow.get_last_pg("CRM Service Level Agreement", {"name": self.sla})
if sla:
sla.apply(self)
def update_closed_date(self):
"""
Update the closed date based on the "Won" status.
"""
if self.status == "Won" and not self.closed_date:
self.closed_date = jingrow.utils.nowdate()
def update_default_probability(self):
"""
Update the default probability based on the status.
"""
if not self.probability or self.probability == 0:
self.probability = jingrow.db.get_value("CRM Deal Status", self.status, "probability") or 0
def update_expected_deal_value(self):
"""
Update the expected deal value based on the net total or total.
"""
if (
jingrow.db.get_single_value("FCRM Settings", "auto_update_expected_deal_value")
and (self.net_total or self.total)
and self.expected_deal_value
):
self.expected_deal_value = self.net_total or self.total
def validate_forecasting_fields(self):
self.update_closed_date()
self.update_default_probability()
self.update_expected_deal_value()
if jingrow.db.get_single_value("FCRM Settings", "enable_forecasting"):
if not self.expected_deal_value or self.expected_deal_value == 0:
jingrow.throw(_("Expected Deal Value is required."), jingrow.MandatoryError)
if not self.expected_closure_date:
jingrow.throw(_("Expected Closure Date is required."), jingrow.MandatoryError)
def validate_lost_reason(self):
"""
Validate the lost reason if the status is set to "Lost".
"""
if self.status and jingrow.get_cached_value("CRM Deal Status", self.status, "type") == "Lost":
if not self.lost_reason:
jingrow.throw(_("Please specify a reason for losing the deal."), jingrow.ValidationError)
elif self.lost_reason == "Other" and not self.lost_notes:
jingrow.throw(_("Please specify the reason for losing the deal."), jingrow.ValidationError)
def update_exchange_rate(self):
if self.has_value_changed("currency") or not self.exchange_rate:
system_currency = jingrow.db.get_single_value("FCRM Settings", "currency") or "USD"
exchange_rate = 1
if self.currency and self.currency != system_currency:
exchange_rate = get_exchange_rate(self.currency, system_currency)
self.db_set("exchange_rate", exchange_rate)
@staticmethod
def default_list_data():
columns = [
{
"label": "Organization",
"type": "Link",
"key": "organization",
"options": "CRM Organization",
"width": "11rem",
},
{
"label": "Annual Revenue",
"type": "Currency",
"key": "annual_revenue",
"align": "right",
"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"]',
}
@jingrow.whitelist()
def add_contact(deal, contact):
if not jingrow.has_permission("CRM Deal", "write", deal):
jingrow.throw(_("Not allowed to add contact to Deal"), jingrow.PermissionError)
deal = jingrow.get_cached_pg("CRM Deal", deal)
deal.append("contacts", {"contact": contact})
deal.save()
return True
@jingrow.whitelist()
def remove_contact(deal, contact):
if not jingrow.has_permission("CRM Deal", "write", deal):
jingrow.throw(_("Not allowed to remove contact from Deal"), jingrow.PermissionError)
deal = jingrow.get_cached_pg("CRM Deal", deal)
deal.contacts = [d for d in deal.contacts if d.contact != contact]
deal.save()
return True
@jingrow.whitelist()
def set_primary_contact(deal, contact):
if not jingrow.has_permission("CRM Deal", "write", deal):
jingrow.throw(_("Not allowed to set primary contact for Deal"), jingrow.PermissionError)
deal = jingrow.get_cached_pg("CRM Deal", deal)
deal.set_primary_contact(contact)
deal.save()
return True
def create_organization(pg):
if not pg.get("organization_name"):
return
existing_organization = jingrow.db.exists(
"CRM Organization", {"organization_name": pg.get("organization_name")}
)
if existing_organization:
return existing_organization
organization = jingrow.new_pg("CRM Organization")
organization.update(
{
"organization_name": pg.get("organization_name"),
"website": pg.get("website"),
"territory": pg.get("territory"),
"industry": pg.get("industry"),
"annual_revenue": pg.get("annual_revenue"),
}
)
organization.insert(ignore_permissions=True)
return organization.name
def contact_exists(pg):
email_exist = jingrow.db.exists("Contact Email", {"email_id": pg.get("email")})
mobile_exist = jingrow.db.exists("Contact Phone", {"phone": pg.get("mobile_no")})
pagetype = "Contact Email" if email_exist else "Contact Phone"
name = email_exist or mobile_exist
if name:
return jingrow.db.get_value(pagetype, name, "parent")
return False
def create_contact(pg):
existing_contact = contact_exists(pg)
if existing_contact:
return existing_contact
contact = jingrow.new_pg("Contact")
contact.update(
{
"first_name": pg.get("first_name"),
"last_name": pg.get("last_name"),
"salutation": pg.get("salutation"),
"company_name": pg.get("organization") or pg.get("organization_name"),
}
)
if pg.get("email"):
contact.append("email_ids", {"email_id": pg.get("email"), "is_primary": 1})
if pg.get("mobile_no"):
contact.append("phone_nos", {"phone": pg.get("mobile_no"), "is_primary_mobile_no": 1})
contact.insert(ignore_permissions=True)
contact.reload() # load changes by hooks on contact
return contact.name
@jingrow.whitelist()
def create_deal(args):
deal = jingrow.new_pg("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

View File

@ -0,0 +1,9 @@
# Copyright (c) 2023, JINGROW and Contributors
# See license.txt
# import jingrow
from jingrow.tests import UnitTestCase
class TestCRMDeal(UnitTestCase):
pass

View File

@ -0,0 +1,8 @@
// Copyright (c) 2023, JINGROW and contributors
// For license information, please see license.txt
// jingrow.ui.form.on("CRM Deal Status", {
// refresh(frm) {
// },
// });

View File

@ -0,0 +1,97 @@
{
"actions": [],
"allow_rename": 1,
"autoname": "field:deal_status",
"creation": "2023-11-29 11:24:55.543387",
"pagetype": "PageType",
"engine": "InnoDB",
"field_order": [
"deal_status",
"type",
"position",
"column_break_ojiu",
"probability",
"color"
],
"fields": [
{
"default": "gray",
"fieldname": "color",
"fieldtype": "Select",
"in_list_view": 1,
"label": "Color",
"options": "black\ngray\nblue\ngreen\nred\npink\norange\namber\nyellow\ncyan\nteal\nviolet\npurple"
},
{
"fieldname": "deal_status",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Status",
"reqd": 1,
"unique": 1
},
{
"fieldname": "position",
"fieldtype": "Int",
"in_list_view": 1,
"label": "Position"
},
{
"fieldname": "probability",
"fieldtype": "Percent",
"in_list_view": 1,
"label": "Probability"
},
{
"default": "Open",
"fieldname": "type",
"fieldtype": "Select",
"in_list_view": 1,
"label": "Type",
"options": "Open\nOngoing\nOn Hold\nWon\nLost"
},
{
"fieldname": "column_break_ojiu",
"fieldtype": "Column Break"
}
],
"grid_page_length": 50,
"index_web_pages_for_search": 1,
"links": [],
"modified": "2025-07-11 16:03:28.077955",
"modified_by": "Administrator",
"module": "FCRM",
"name": "CRM Deal Status",
"naming_rule": "By fieldname",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "Sales User",
"share": 1,
"write": 1
},
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "Sales Manager",
"share": 1,
"write": 1
}
],
"row_format": "Dynamic",
"sort_field": "modified",
"sort_order": "DESC",
"states": []
}

View File

@ -0,0 +1,9 @@
# Copyright (c) 2023, JINGROW and contributors
# For license information, please see license.txt
# import jingrow
from jingrow.model.page import Page
class CRMDealStatus(Page):
pass

View File

@ -0,0 +1,9 @@
# Copyright (c) 2023, JINGROW and Contributors
# See license.txt
# import jingrow
from jingrow.tests import UnitTestCase
class TestCRMDealStatus(UnitTestCase):
pass

View File

@ -0,0 +1,94 @@
{
"actions": [],
"allow_rename": 1,
"creation": "2024-12-27 17:42:33.089685",
"pagetype": "PageType",
"engine": "InnoDB",
"field_order": [
"name1",
"label",
"type",
"route",
"open_in_new_window",
"hidden",
"is_standard",
"column_break_mvbq",
"icon"
],
"fields": [
{
"fieldname": "label",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Label",
"mandatory_depends_on": "eval:pg.type == 'Route'"
},
{
"fieldname": "type",
"fieldtype": "Select",
"in_list_view": 1,
"label": "Type",
"options": "Route\nSeparator",
"read_only_depends_on": "eval:pg.is_standard"
},
{
"depends_on": "eval:pg.type == 'Route'",
"fieldname": "route",
"fieldtype": "Data",
"in_list_view": 1,
"label": "Route",
"mandatory_depends_on": "eval:pg.type == 'Route'"
},
{
"default": "0",
"fieldname": "hidden",
"fieldtype": "Check",
"in_list_view": 1,
"label": "Hidden"
},
{
"default": "0",
"fieldname": "is_standard",
"fieldtype": "Check",
"label": "Is Standard",
"read_only": 1
},
{
"fieldname": "column_break_mvbq",
"fieldtype": "Column Break"
},
{
"description": "Add svg code or use feather icons e.g 'settings'",
"fieldname": "icon",
"fieldtype": "Code",
"label": "Icon"
},
{
"default": "1",
"depends_on": "eval:pg.type == 'Route'",
"fieldname": "open_in_new_window",
"fieldtype": "Check",
"label": "Open in new window"
},
{
"depends_on": "eval:pg.is_standard",
"fieldname": "name1",
"fieldtype": "Data",
"label": "Name",
"read_only": 1,
"unique": 1
}
],
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
"modified": "2024-12-27 19:35:53.012508",
"modified_by": "Administrator",
"module": "FCRM",
"name": "CRM Dropdown Item",
"owner": "Administrator",
"permissions": [],
"sort_field": "creation",
"sort_order": "DESC",
"states": []
}

View File

@ -0,0 +1,9 @@
# Copyright (c) 2024, JINGROW and contributors
# For license information, please see license.txt
# import jingrow
from jingrow.model.page import Page
class CRMDropdownItem(Page):
pass

View File

@ -0,0 +1,8 @@
// Copyright (c) 2025, JINGROW and contributors
// For license information, please see license.txt
// jingrow.ui.form.on("CRM Exotel Settings", {
// refresh(frm) {
// },
// });

View File

@ -0,0 +1,136 @@
{
"actions": [],
"allow_rename": 1,
"creation": "2025-01-08 15:55:50.710356",
"pagetype": "PageType",
"engine": "InnoDB",
"field_order": [
"enabled",
"column_break_uxtz",
"record_call",
"section_break_kfez",
"account_sid",
"subdomain",
"column_break_qwfn",
"webhook_verify_token",
"section_break_iuct",
"api_key",
"column_break_hyen",
"api_token"
],
"fields": [
{
"default": "0",
"fieldname": "enabled",
"fieldtype": "Check",
"label": "Enabled"
},
{
"fieldname": "section_break_kfez",
"fieldtype": "Section Break",
"hide_border": 1
},
{
"depends_on": "enabled",
"fieldname": "account_sid",
"fieldtype": "Data",
"label": "Account SID",
"mandatory_depends_on": "enabled"
},
{
"depends_on": "enabled",
"fieldname": "section_break_iuct",
"fieldtype": "Section Break",
"hide_border": 1
},
{
"fieldname": "column_break_hyen",
"fieldtype": "Column Break"
},
{
"depends_on": "enabled",
"fieldname": "api_key",
"fieldtype": "Data",
"in_list_view": 1,
"label": "API Key",
"mandatory_depends_on": "enabled"
},
{
"fieldname": "column_break_uxtz",
"fieldtype": "Column Break"
},
{
"depends_on": "enabled",
"fieldname": "api_token",
"fieldtype": "Password",
"in_list_view": 1,
"label": "API Token",
"mandatory_depends_on": "enabled"
},
{
"default": "0",
"depends_on": "enabled",
"fieldname": "record_call",
"fieldtype": "Check",
"label": "Record Outgoing Calls"
},
{
"fieldname": "column_break_qwfn",
"fieldtype": "Column Break"
},
{
"depends_on": "enabled",
"fieldname": "webhook_verify_token",
"fieldtype": "Data",
"label": "Webhook Verify Token",
"mandatory_depends_on": "enabled"
},
{
"depends_on": "enabled",
"fieldname": "subdomain",
"fieldtype": "Data",
"label": "Subdomain",
"mandatory_depends_on": "enabled"
}
],
"index_web_pages_for_search": 1,
"issingle": 1,
"links": [],
"modified": "2025-01-22 19:54:20.074393",
"modified_by": "Administrator",
"module": "FCRM",
"name": "CRM Exotel Settings",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"print": 1,
"read": 1,
"role": "System Manager",
"share": 1,
"write": 1
},
{
"create": 1,
"delete": 1,
"email": 1,
"print": 1,
"read": 1,
"role": "Sales Manager",
"share": 1,
"write": 1
},
{
"email": 1,
"print": 1,
"read": 1,
"role": "All",
"share": 1
}
],
"sort_field": "creation",
"sort_order": "DESC",
"states": []
}

View File

@ -0,0 +1,26 @@
# Copyright (c) 2025, JINGROW and contributors
# For license information, please see license.txt
import jingrow
import requests
from jingrow import _
from jingrow.model.page import Page
class CRMExotelSettings(Page):
def validate(self):
self.verify_credentials()
def verify_credentials(self):
if self.enabled:
response = requests.get(
"https://{subdomain}/v1/Accounts/{sid}".format(
subdomain=self.subdomain, sid=self.account_sid
),
auth=(self.api_key, self.get_password("api_token")),
)
if response.status_code != 200:
jingrow.throw(
_(f"Please enter valid exotel Account SID, API key & API token: {response.reason}"),
title=_("Invalid credentials"),
)

View File

@ -0,0 +1,29 @@
# Copyright (c) 2025, JINGROW and Contributors
# See license.txt
# import jingrow
from jingrow.tests import IntegrationTestCase, UnitTestCase
# On IntegrationTestCase, the pagetype test records and all
# link-field test record dependencies are recursively loaded
# Use these module variables to add/remove to/from that list
EXTRA_TEST_RECORD_DEPENDENCIES = [] # eg. ["User"]
IGNORE_TEST_RECORD_DEPENDENCIES = [] # eg. ["User"]
class UnitTestCRMExotelSettings(UnitTestCase):
"""
Unit tests for CRMExotelSettings.
Use this class for testing individual functions and methods.
"""
pass
class IntegrationTestCRMExotelSettings(IntegrationTestCase):
"""
Integration tests for CRMExotelSettings.
Use this class for testing interactions between multiple components.
"""
pass

View File

@ -0,0 +1,8 @@
// Copyright (c) 2024, JINGROW and contributors
// For license information, please see license.txt
// jingrow.ui.form.on("CRM Fields Layout", {
// refresh(frm) {
// },
// });

View File

@ -0,0 +1,81 @@
{
"actions": [],
"allow_rename": 1,
"autoname": "format:{dt}-{type}",
"creation": "2024-06-07 16:42:05.495324",
"pagetype": "PageType",
"engine": "InnoDB",
"field_order": [
"dt",
"column_break_post",
"type",
"section_break_ttpm",
"layout"
],
"fields": [
{
"fieldname": "dt",
"fieldtype": "Link",
"in_list_view": 1,
"in_standard_filter": 1,
"label": "Document Type",
"options": "PageType"
},
{
"fieldname": "type",
"fieldtype": "Select",
"in_list_view": 1,
"in_standard_filter": 1,
"label": "Type",
"options": "Quick Entry\nSide Panel\nData Fields\nGrid Row\nRequired Fields"
},
{
"fieldname": "section_break_ttpm",
"fieldtype": "Section Break"
},
{
"fieldname": "layout",
"fieldtype": "Code",
"label": "Layout",
"options": "JSON"
},
{
"fieldname": "column_break_post",
"fieldtype": "Column Break"
}
],
"index_web_pages_for_search": 1,
"links": [],
"modified": "2025-02-21 13:09:49.573515",
"modified_by": "Administrator",
"module": "FCRM",
"name": "CRM Fields Layout",
"naming_rule": "Expression",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "System Manager",
"share": 1,
"write": 1
},
{
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "All",
"share": 1
}
],
"sort_field": "creation",
"sort_order": "DESC",
"states": []
}

View File

@ -0,0 +1,277 @@
# Copyright (c) 2024, JINGROW and contributors
# For license information, please see license.txt
import json
import jingrow
from jingrow import _
from jingrow.model.page import Page
from jingrow.utils import random_string
class CRMFieldsLayout(Page):
pass
@jingrow.whitelist()
def get_fields_layout(pagetype: str, type: str, parent_pagetype: str | None = None):
tabs = []
layout = None
if jingrow.db.exists("CRM Fields Layout", {"dt": pagetype, "type": type}):
layout = jingrow.get_pg("CRM Fields Layout", {"dt": pagetype, "type": type})
if layout and layout.layout:
tabs = json.loads(layout.layout)
if not tabs and type != "Required Fields":
tabs = get_default_layout(pagetype)
has_tabs = False
if isinstance(tabs, list) and len(tabs) > 0 and isinstance(tabs[0], dict):
has_tabs = any("sections" in tab for tab in tabs)
if not has_tabs:
tabs = [{"name": "first_tab", "sections": tabs}]
allowed_fields = []
for tab in tabs:
for section in tab.get("sections"):
if "columns" not in section:
continue
for column in section.get("columns"):
if not column.get("fields"):
continue
allowed_fields.extend(column.get("fields"))
fields = jingrow.get_meta(pagetype).fields
fields = [field for field in fields if field.fieldname in allowed_fields]
required_fields = []
if type == "Required Fields":
required_fields = [
field for field in jingrow.get_meta(pagetype, False).fields if field.reqd and not field.default
]
for tab in tabs:
for section in tab.get("sections"):
if section.get("columns"):
section["columns"] = [column for column in section.get("columns") if column]
for column in section.get("columns") if section.get("columns") else []:
column["fields"] = [field for field in column.get("fields") if field]
for field in column.get("fields") if column.get("fields") else []:
field = next((f for f in fields if f.fieldname == field), None)
if field:
field = field.as_dict()
handle_perm_level_restrictions(field, pagetype, parent_pagetype)
column["fields"][column.get("fields").index(field["fieldname"])] = field
# remove field from required_fields if it is already present
if (
type == "Required Fields"
and field.reqd
and any(f.get("fieldname") == field.get("fieldname") for f in required_fields)
):
required_fields = [
f for f in required_fields if f.get("fieldname") != field.get("fieldname")
]
if type == "Required Fields" and required_fields and tabs:
tabs[-1].get("sections").append(
{
"label": "Required Fields",
"name": "required_fields_section_" + str(random_string(4)),
"opened": True,
"hideLabel": True,
"columns": [
{
"name": "required_fields_column_" + str(random_string(4)),
"fields": [field.as_dict() for field in required_fields],
}
],
}
)
return tabs or []
@jingrow.whitelist()
def get_sidepanel_sections(pagetype):
if not jingrow.db.exists("CRM Fields Layout", {"dt": pagetype, "type": "Side Panel"}):
return []
layout = jingrow.get_pg("CRM Fields Layout", {"dt": pagetype, "type": "Side Panel"}).layout
if not layout:
return []
layout = json.loads(layout)
not_allowed_fieldtypes = [
"Tab Break",
"Section Break",
"Column Break",
]
fields = jingrow.get_meta(pagetype).fields
fields = [field for field in fields if field.fieldtype not in not_allowed_fieldtypes]
add_forecasting_section(layout, pagetype)
for section in layout:
section["name"] = section.get("name") or section.get("label")
for column in section.get("columns") if section.get("columns") else []:
for field in column.get("fields") if column.get("fields") else []:
field_obj = next((f for f in fields if f.fieldname == field), None)
if field_obj:
field_obj = field_obj.as_dict()
handle_perm_level_restrictions(field_obj, pagetype)
column["fields"][column.get("fields").index(field)] = get_field_obj(field_obj)
fields_meta = {}
for field in fields:
fields_meta[field.fieldname] = field
return layout
def add_forecasting_section(layout, pagetype):
if (
pagetype == "CRM Deal"
and jingrow.db.get_single_value("FCRM Settings", "enable_forecasting")
and not any(section.get("name") == "forecasted_sales_section" for section in layout)
):
contacts_section_index = next(
(
i
for i, section in enumerate(layout)
if section.get("name") == "contacts_section" or section.get("label") == "Contacts"
),
None,
)
if contacts_section_index is not None:
layout.insert(
contacts_section_index + 1,
{
"name": "forecasted_sales_section",
"label": "Forecasted Sales",
"opened": True,
"columns": [
{
"name": "column_" + str(random_string(4)),
"fields": ["expected_closure_date", "probability", "expected_deal_value"],
}
],
},
)
def handle_perm_level_restrictions(field, pagetype, parent_pagetype=None):
if field.permlevel == 0:
return
field_has_write_access = field.permlevel in get_permlevel_access("write", pagetype, parent_pagetype)
field_has_read_access = field.permlevel in get_permlevel_access("read", pagetype, parent_pagetype)
if not field_has_write_access and field_has_read_access:
field.read_only = 1
if not field_has_read_access and not field_has_write_access:
field.hidden = 1
def get_permlevel_access(permission_type="write", pagetype=None, parent_pagetype=None):
allowed_permlevels = []
roles = jingrow.get_roles()
meta = jingrow.get_meta(pagetype)
if meta.istable and parent_pagetype:
meta = jingrow.get_meta(parent_pagetype)
elif meta.istable and not parent_pagetype:
return [1, 0]
for perm in meta.permissions:
if perm.role in roles and perm.get(permission_type) and perm.permlevel not in allowed_permlevels:
allowed_permlevels.append(perm.permlevel)
return allowed_permlevels
def get_field_obj(field):
field["placeholder"] = field.get("placeholder") or "Add " + field.label + "..."
if field.fieldtype == "Link":
field["placeholder"] = field.get("placeholder") or "Select " + field.label + "..."
elif field.fieldtype == "Select" and field.options:
field["placeholder"] = field.get("placeholder") or "Select " + field.label + "..."
field["options"] = [{"label": option, "value": option} for option in field.options.split("\n")]
if field.read_only:
field["tooltip"] = "This field is read only and cannot be edited."
return field
@jingrow.whitelist()
def save_fields_layout(pagetype: str, type: str, layout: str):
if jingrow.db.exists("CRM Fields Layout", {"dt": pagetype, "type": type}):
pg = jingrow.get_pg("CRM Fields Layout", {"dt": pagetype, "type": type})
else:
pg = jingrow.new_pg("CRM Fields Layout")
pg.update(
{
"dt": pagetype,
"type": type,
"layout": layout,
}
)
pg.save(ignore_permissions=True)
return pg.layout
def get_default_layout(pagetype: str):
fields = jingrow.get_meta(pagetype).fields
tabs = []
if fields and fields[0].fieldtype != "Tab Break":
sections = []
if fields and fields[0].fieldtype != "Section Break":
sections.append(
{
"name": "section_" + str(random_string(4)),
"columns": [{"name": "column_" + str(random_string(4)), "fields": []}],
}
)
tabs.append({"name": "tab_" + str(random_string(4)), "sections": sections})
for field in fields:
if field.fieldtype == "Tab Break":
tabs.append(
{
"name": "tab_" + str(random_string(4)),
"sections": [
{
"name": "section_" + str(random_string(4)),
"columns": [{"name": "column_" + str(random_string(4)), "fields": []}],
}
],
}
)
elif field.fieldtype == "Section Break":
tabs[-1]["sections"].append(
{
"name": "section_" + str(random_string(4)),
"columns": [{"name": "column_" + str(random_string(4)), "fields": []}],
}
)
elif field.fieldtype == "Column Break":
tabs[-1]["sections"][-1]["columns"].append(
{"name": "column_" + str(random_string(4)), "fields": []}
)
else:
tabs[-1]["sections"][-1]["columns"][-1]["fields"].append(field.fieldname)
return tabs

View File

@ -0,0 +1,9 @@
# Copyright (c) 2024, JINGROW and Contributors
# See license.txt
# import jingrow
from jingrow.tests import UnitTestCase
class TestCRMFieldsLayout(UnitTestCase):
pass

View File

@ -0,0 +1,65 @@
// Copyright (c) 2023, JINGROW and contributors
// For license information, please see license.txt
jingrow.ui.form.on("CRM Form Script", {
refresh(frm) {
frm.set_query("dt", {
filters: {
istable: 0,
},
});
if (frm.pg.is_standard && !jingrow.boot.developer_mode) {
frm.disable_form();
jingrow.show_alert(
__(
"Standard Form Scripts can not be modified, duplicate the Form Script instead."
)
);
}
if (!jingrow.boot.developer_mode) {
frm.toggle_enable("is_standard", 0);
}
frm.trigger("add_enable_button");
},
add_enable_button(frm) {
frm.add_custom_button(
frm.pg.enabled ? __("Disable") : __("Enable"),
() => {
frm.set_value("enabled", !frm.pg.enabled);
frm.save();
}
);
},
view(frm) {
let has_form_boilerplate = frm.pg.script.includes(
"function setupForm("
);
let has_list_boilerplate = frm.pg.script.includes(
"function setupList("
);
if (frm.pg.view == "Form" && !has_form_boilerplate) {
frm.pg.script = `
function setupForm({ pg }) {
return {
actions: [],
statuses: [],
}
}`.trim();
}
if (frm.pg.view == "List" && !has_list_boilerplate) {
frm.pg.script = `
function setupList({ list }) {
return {
actions: [],
bulk_actions: [],
}
}`.trim();
}
},
});

View File

@ -0,0 +1,101 @@
{
"actions": [],
"allow_rename": 1,
"autoname": "prompt",
"creation": "2023-12-28 14:18:09.329868",
"pagetype": "PageType",
"engine": "InnoDB",
"field_order": [
"dt",
"view",
"column_break_gboh",
"enabled",
"is_standard",
"section_break_xeox",
"script"
],
"fields": [
{
"fieldname": "column_break_gboh",
"fieldtype": "Column Break"
},
{
"fieldname": "section_break_xeox",
"fieldtype": "Section Break"
},
{
"fieldname": "dt",
"fieldtype": "Link",
"in_list_view": 1,
"label": "PageType",
"options": "PageType",
"reqd": 1
},
{
"default": "0",
"fieldname": "enabled",
"fieldtype": "Check",
"hidden": 1,
"label": "Enabled"
},
{
"default": "function setupForm({ pg }) {\n return {\n actions: [],\n }\n}",
"documentation_url": "https://docs.jingrow.com/crm/custom-actions",
"fieldname": "script",
"fieldtype": "Code",
"label": "Script",
"options": "JS"
},
{
"default": "Form",
"fieldname": "view",
"fieldtype": "Select",
"in_list_view": 1,
"label": "Apply To",
"options": "Form\nList",
"set_only_once": 1
},
{
"default": "0",
"fieldname": "is_standard",
"fieldtype": "Check",
"label": "Is Standard",
"no_copy": 1
}
],
"index_web_pages_for_search": 1,
"links": [],
"modified": "2025-05-19 17:57:24.610295",
"modified_by": "Administrator",
"module": "FCRM",
"name": "CRM Form Script",
"naming_rule": "Set by user",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "Sales Manager",
"share": 1,
"write": 1
},
{
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "All",
"share": 1
}
],
"row_format": "Dynamic",
"sort_field": "modified",
"sort_order": "DESC",
"states": []
}

View File

@ -0,0 +1,41 @@
# Copyright (c) 2023, JINGROW and contributors
# For license information, please see license.txt
import jingrow
from jingrow import _
from jingrow.model.page import Page
class CRMFormScript(Page):
def validate(self):
in_user_env = not (
jingrow.flags.in_install
or jingrow.flags.in_patch
or jingrow.flags.in_test
or jingrow.flags.in_fixtures
)
if in_user_env and not self.is_new() and self.is_standard and not jingrow.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:
jingrow.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 pagetype"""
FormScript = jingrow.qb.PageType("CRM Form Script")
query = (
jingrow.qb.from_(FormScript)
.select("script")
.where(FormScript.dt == dt)
.where(FormScript.view == view)
.where(FormScript.enabled == 1)
)
pg = query.run(as_dict=True)
if pg:
return [d.script for d in pg] if len(pg) > 1 else pg[0].script
else:
return None

View File

@ -0,0 +1,9 @@
# Copyright (c) 2023, JINGROW and Contributors
# See license.txt
# import jingrow
from jingrow.tests import UnitTestCase
class TestCRMFormScript(UnitTestCase):
pass

View File

@ -0,0 +1,8 @@
// Copyright (c) 2025, JINGROW and contributors
// For license information, please see license.txt
// jingrow.ui.form.on("CRM Global Settings", {
// refresh(frm) {
// },
// });

View File

@ -0,0 +1,98 @@
{
"actions": [],
"allow_rename": 1,
"autoname": "format:{type}-{dt}",
"creation": "2025-02-28 14:37:10.002433",
"pagetype": "PageType",
"engine": "InnoDB",
"field_order": [
"dt",
"column_break_kipp",
"type",
"section_break_vass",
"json"
],
"fields": [
{
"default": "PageType",
"fieldname": "dt",
"fieldtype": "Link",
"in_list_view": 1,
"label": "PageType",
"options": "PageType",
"reqd": 1
},
{
"fieldname": "column_break_kipp",
"fieldtype": "Column Break"
},
{
"fieldname": "type",
"fieldtype": "Select",
"in_list_view": 1,
"label": "Type",
"options": "Quick Filters\nSidebar Items",
"reqd": 1
},
{
"fieldname": "section_break_vass",
"fieldtype": "Section Break"
},
{
"fieldname": "json",
"fieldtype": "JSON",
"label": "JSON"
}
],
"grid_page_length": 50,
"index_web_pages_for_search": 1,
"links": [],
"modified": "2025-03-02 14:03:49.372132",
"modified_by": "Administrator",
"module": "FCRM",
"name": "CRM Global Settings",
"naming_rule": "Expression",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "System Manager",
"share": 1,
"write": 1
},
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "Sales User",
"share": 1,
"write": 1
},
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "Sales Manager",
"share": 1,
"write": 1
}
],
"row_format": "Dynamic",
"sort_field": "creation",
"sort_order": "DESC",
"states": []
}

View File

@ -0,0 +1,9 @@
# Copyright (c) 2025, JINGROW and contributors
# For license information, please see license.txt
# import jingrow
from jingrow.model.page import Page
class CRMGlobalSettings(Page):
pass

View File

@ -0,0 +1,30 @@
# Copyright (c) 2025, JINGROW and Contributors
# See license.txt
# import jingrow
from jingrow.tests import IntegrationTestCase, UnitTestCase
# On IntegrationTestCase, the pagetype test records and all
# link-field test record dependencies are recursively loaded
# Use these module variables to add/remove to/from that list
EXTRA_TEST_RECORD_DEPENDENCIES = [] # eg. ["User"]
IGNORE_TEST_RECORD_DEPENDENCIES = [] # eg. ["User"]
class UnitTestCRMGlobalSettings(UnitTestCase):
"""
Unit tests for CRMGlobalSettings.
Use this class for testing individual functions and methods.
"""
pass
class IntegrationTestCRMGlobalSettings(IntegrationTestCase):
"""
Integration tests for CRMGlobalSettings.
Use this class for testing interactions between multiple components.
"""
pass

Some files were not shown because too many files have changed in this diff Show More