salla-common-lib 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
File without changes
@@ -0,0 +1,221 @@
1
+ # field_manager.py
2
+ import frappe
3
+ from frappe import _
4
+
5
+ # Field configurations for each integration type
6
+ INTEGRATION_FIELDS = {
7
+ 'pos_invoice': {
8
+ 'Salla Order': [
9
+ {
10
+ 'fieldname': 'custom_pos_invoice_name',
11
+ 'label': 'POS Invoice Name',
12
+ 'fieldtype': 'Link',
13
+ 'options': 'POS Invoice',
14
+ 'read_only': 1,
15
+ 'insert_after': 'connections_tab'
16
+ }
17
+ ],
18
+ 'POS Invoice': [
19
+ {
20
+ 'fieldname': 'custom_is_salla_item',
21
+ 'label': 'Is Salla Item',
22
+ 'fieldtype': 'Check',
23
+ 'default': '0',
24
+ 'insert_after': 'online_order'
25
+ }
26
+ ]
27
+ },
28
+ 'sales_invoice': {
29
+ 'Salla Order': [
30
+ {
31
+ 'fieldname': 'custom_sales_invoice_name',
32
+ 'label': 'Sales Invoice Name',
33
+ 'fieldtype': 'Link',
34
+ 'options': 'Sales Invoice',
35
+ 'read_only': 1,
36
+ 'insert_after': 'connections_tab'
37
+ }
38
+ ]
39
+ },
40
+ 'sales_order': {
41
+ 'Salla Order': [
42
+ {
43
+ 'fieldname': 'custom_sales_order_name',
44
+ 'label': 'Sales Order Name',
45
+ 'fieldtype': 'Link',
46
+ 'options': 'Sales Order',
47
+ 'read_only': 0,
48
+ 'insert_after': 'connections_tab'
49
+ },
50
+ {
51
+ 'fieldname': 'custom_payment_entry_name',
52
+ 'label': 'Payment Entry Name',
53
+ 'fieldtype': 'Link',
54
+ 'options': 'Payment Entry',
55
+ 'read_only': 0,
56
+ 'insert_after': 'custom_sales_order_name'
57
+ }
58
+ ],
59
+ 'Sales Order': [
60
+ {
61
+ 'fieldname': 'custom_salla_order_name',
62
+ 'label': 'Salla Order Name',
63
+ 'fieldtype': 'Data',
64
+ 'insert_after': 'order_type'
65
+ },
66
+ {
67
+ 'fieldname': 'custom_salla_order_custom_status',
68
+ 'label': 'Salla Order Custom Status',
69
+ 'fieldtype': 'Data',
70
+ 'allow_on_submit': 1,
71
+ 'insert_after': 'custom_salla_order_name'
72
+ }
73
+ ],
74
+ 'Payment Entry': [
75
+ {
76
+ 'fieldname': 'custom_salla_order_name',
77
+ 'label': 'Salla Order Name',
78
+ 'fieldtype': 'Data',
79
+ 'insert_after': 'mode_of_payment'
80
+ }
81
+ ]
82
+ }
83
+ }
84
+
85
+ # Core fields that are always present
86
+ CORE_FIELDS = {
87
+ 'Salla Defaults': [
88
+ {
89
+ 'fieldname': 'integration_type',
90
+ 'label': 'Integration Type',
91
+ 'fieldtype': 'Select',
92
+ 'options': 'pos_invoice\nsales_invoice\nsales_order',
93
+ 'default': 'pos_invoice',
94
+ 'reqd': 1,
95
+ 'insert_after': 'price_list'
96
+ },
97
+ {
98
+ 'fieldname': 'custom_warehouse',
99
+ 'label': 'Warehouse',
100
+ 'fieldtype': 'Link',
101
+ 'options': 'Warehouse',
102
+ 'depends_on': 'eval:doc.integration_type=="sales_order"',
103
+ 'insert_after': 'custom_days_to_delivery_order'
104
+ },
105
+ {
106
+ 'fieldname': 'custom_days_to_delivery_order',
107
+ 'label': 'Days To Delivery Order',
108
+ 'fieldtype': 'Int',
109
+ 'insert_after': 'price_list'
110
+ }
111
+ ]
112
+ }
113
+
114
+ def manage_custom_fields(doc, method=None):
115
+ """
116
+ Dynamically manage custom fields based on integration type
117
+ """
118
+ if not doc.integration_type:
119
+ return
120
+
121
+ # Remove all integration-specific fields first
122
+ remove_all_integration_fields()
123
+
124
+ # Create core fields
125
+ create_core_fields()
126
+
127
+ # Create fields for selected integration type
128
+ create_integration_fields(doc.integration_type)
129
+
130
+ frappe.clear_cache()
131
+
132
+ def create_core_fields():
133
+ """Create core fields that are always present"""
134
+ for doctype, fields in CORE_FIELDS.items():
135
+ for field_config in fields:
136
+ create_custom_field(doctype, field_config)
137
+
138
+ def create_integration_fields(integration_type):
139
+ """Create fields for specific integration type"""
140
+ if integration_type not in INTEGRATION_FIELDS:
141
+ return
142
+
143
+ for doctype, fields in INTEGRATION_FIELDS[integration_type].items():
144
+ for field_config in fields:
145
+ create_custom_field(doctype, field_config)
146
+
147
+ def remove_all_integration_fields():
148
+ """Remove all integration-specific custom fields"""
149
+ all_fields = []
150
+
151
+ for integration_type, doctypes in INTEGRATION_FIELDS.items():
152
+ for doctype, fields in doctypes.items():
153
+ for field_config in fields:
154
+ field_name = f"{doctype}-{field_config['fieldname']}"
155
+ all_fields.append(field_name)
156
+
157
+ # Delete existing custom fields
158
+ for field_name in all_fields:
159
+ if frappe.db.exists("Custom Field", field_name):
160
+ try:
161
+ frappe.delete_doc("Custom Field", field_name)
162
+ except Exception as e:
163
+ frappe.log_error(f"Error deleting custom field {field_name}: {str(e)}")
164
+
165
+ def create_custom_field(doctype, field_config):
166
+ """Create a single custom field if it doesn't exist"""
167
+ field_name = f"{doctype}-{field_config['fieldname']}"
168
+
169
+ if frappe.db.exists("Custom Field", field_name):
170
+ return
171
+
172
+ try:
173
+ custom_field = frappe.get_doc({
174
+ "doctype": "Custom Field",
175
+ "dt": doctype,
176
+ "fieldname": field_config['fieldname'],
177
+ "label": field_config['label'],
178
+ "fieldtype": field_config['fieldtype'],
179
+ "options": field_config.get('options', ''),
180
+ "insert_after": field_config.get('insert_after', ''),
181
+ "read_only": field_config.get('read_only', 0),
182
+ "reqd": field_config.get('reqd', 0),
183
+ "default": field_config.get('default', ''),
184
+ "depends_on": field_config.get('depends_on', ''),
185
+ "description": field_config.get('description', '')
186
+ })
187
+ custom_field.insert()
188
+
189
+ except Exception as e:
190
+ frappe.log_error(f"Error creating custom field {field_name}: {str(e)}")
191
+
192
+ def get_integration_type():
193
+ """Get current integration type from Salla Defaults"""
194
+ try:
195
+ salla_defaults = frappe.get_single("Salla Defaults")
196
+ return salla_defaults.get('integration_type', 'pos_invoice')
197
+ except:
198
+ return 'pos_invoice'
199
+
200
+ def setup_integration_fields():
201
+ """Initial setup of integration fields (called during install)"""
202
+ integration_type = get_integration_type()
203
+
204
+ # Create core fields
205
+ create_core_fields()
206
+
207
+ # Create fields for current integration type
208
+ create_integration_fields(integration_type)
209
+
210
+ frappe.clear_cache()
211
+
212
+ # Utility function to check if field exists for current integration
213
+ def has_integration_field(doctype, fieldname):
214
+ """Check if a field exists for current integration type"""
215
+ integration_type = get_integration_type()
216
+
217
+ if integration_type in INTEGRATION_FIELDS:
218
+ doctype_fields = INTEGRATION_FIELDS[integration_type].get(doctype, [])
219
+ return any(field['fieldname'] == fieldname for field in doctype_fields)
220
+
221
+ return False
@@ -0,0 +1,69 @@
1
+ import frappe
2
+ from salla_common.utils import is_app_installed
3
+
4
+ def before_save(doc, method):
5
+ if is_app_installed("salla_connector"):
6
+ from salla_connector.salla_utils import Update_salla_online_qty, has_barcode, setup_variant_data, update_item_barcode
7
+ if doc.custom_update_pending_online_quantity and doc.custom_is_salla_item:
8
+ Update_salla_online_qty(doc)
9
+ doc.custom_update_pending_online_quantity = 0
10
+ update_item_barcode(doc)
11
+ handle_variant(doc, has_barcode, setup_variant_data)
12
+
13
+ if is_app_installed("salla_client"):
14
+ from salla_client.salla_utils import Update_salla_online_qty, has_barcode, setup_variant_data, update_item_barcode
15
+ if doc.custom_update_pending_online_quantity and doc.custom_is_salla_item:
16
+ Update_salla_online_qty(doc)
17
+ doc.custom_update_pending_online_quantity = 0
18
+ update_item_barcode(doc)
19
+ handle_variant(doc, has_barcode, setup_variant_data)
20
+
21
+
22
+ def handle_variant(doc, has_barcode, setup_variant_data):
23
+ if doc.variant_of and not has_barcode(doc):
24
+ parent = frappe.get_doc("Item", doc.variant_of)
25
+ send_to_salla = parent.custom_send_item_to_salla == 1
26
+ merchant_name = parent.custom_salla_item[0].merchant if send_to_salla else None
27
+ setup_variant_data(doc, send_to_salla, merchant_name)
28
+
29
+
30
+ def on_update(doc, method):
31
+ for row in doc.custom_salla_item:
32
+ print("ON UPDATE !!!!!")
33
+ barcode = frappe.get_doc(
34
+ "Item Barcode", {"parent": doc.name, "custom_is_salla_barcode": 1}
35
+ )
36
+ payload = {
37
+ "name": doc.name,
38
+ "item_name": doc.item_name,
39
+ "standard_rate": doc.standard_rate if doc.standard_rate else 0,
40
+ "custom_product_type": doc.custom_product_type,
41
+ "description": doc.description,
42
+ "custom_send_item_to_salla": doc.custom_send_item_to_salla,
43
+ "barcode": barcode.barcode,
44
+ "custom_product_image": doc.custom_product_image,
45
+ "variant_of": doc.variant_of,
46
+ "weight_per_unit": doc.weight_per_unit,
47
+ }
48
+
49
+ if doc.variant_of:
50
+ barcode = frappe.get_doc(
51
+ "Item Barcode", {"parent": doc.variant_of, "custom_is_salla_barcode": 1}
52
+ )
53
+
54
+ payload.update({
55
+ "parent_barcode": barcode.barcode,
56
+ "custom_salla_variant_id": doc.custom_salla_variant_id,
57
+ "attributes": [row.as_dict() for row in doc.attributes]
58
+ })
59
+ ## This should be optimized for bulk processing to reduce api calls
60
+ is_salla_connector_installed = is_app_installed("salla_connector")
61
+ if is_salla_connector_installed:
62
+ from salla_connector.salla_utils import create_or_update_salla_item
63
+ create_or_update_salla_item(payload, row.merchant)
64
+
65
+ is_salla_client_installed = is_app_installed("salla_client")
66
+ if is_salla_client_installed :
67
+ from salla_client.salla_utils import create_or_update_salla_item
68
+ if not doc.custom_is_synced:
69
+ create_or_update_salla_item(payload, row.merchant)
@@ -0,0 +1,62 @@
1
+ import frappe
2
+ import frappe.utils
3
+ import frappe.utils.logger
4
+ from salla_common.utils import is_app_installed
5
+
6
+
7
+ def before_save(doc, method):
8
+ frappe.utils.logger.set_log_level("DEBUG")
9
+ logger = frappe.logger("update_price", allow_site=1)
10
+
11
+ logger.info(f'Item Price Doc Before Adding The Other Values: {doc.as_dict()}')
12
+
13
+ is_salla_item, variant_of, salla_variant_id = frappe.get_value(
14
+ "Item", doc.item_code, ["custom_is_salla_item", "variant_of", "custom_salla_variant_id"]
15
+ ) or (None, None, None)
16
+
17
+ logger.info(f'The Fields I got From Item: {is_salla_item}, {variant_of}, {salla_variant_id}')
18
+
19
+ if is_salla_item:
20
+ barcode_list = frappe.get_all("Item Barcode", {"parent": doc.item_code, "custom_is_salla_barcode": 1})
21
+ if barcode_list and len(barcode_list) > 0:
22
+ barcode = frappe.get_doc("Item Barcode", barcode_list[0].name)
23
+ merchant_salla_setting_list = frappe.get_list(
24
+ "Salla Defaults", filters={"price_list": doc.price_list}, fields=["name"]
25
+ )
26
+ else:
27
+ logger.error(f'No Salla Barcode found for Item: {doc.item_code}')
28
+ return
29
+ for salla_setting in merchant_salla_setting_list:
30
+ payload = {
31
+ "selling": doc.selling,
32
+ "valid_from": doc.valid_from,
33
+ "price_list": doc.price_list,
34
+ "price_list_rate": doc.price_list_rate,
35
+ "item_code": doc.item_code,
36
+ "barcode": barcode.barcode,
37
+ "custom_is_salla_item": is_salla_item,
38
+ "variant_of": variant_of,
39
+ "custom_salla_variant_id": salla_variant_id,
40
+ "merchant": salla_setting.name
41
+ }
42
+
43
+ logger.info(f'Merchant is {salla_setting.name}')
44
+ logger.info(f'Payload being sent: {payload}')
45
+
46
+ if is_app_installed("salla_connector"):
47
+ try:
48
+ from salla_connector.salla_utils import update_salla_price
49
+ update_salla_price(payload)
50
+ except ImportError:
51
+ frappe.log_error("Failed to import from salla_connector")
52
+
53
+ if is_app_installed("salla_client"):
54
+ try:
55
+ from salla_client.salla_utils import update_salla_price
56
+ update_salla_price(payload)
57
+ logger.info(f"After sending to salla_client: {payload}")
58
+ except ImportError:
59
+ frappe.log_error("Failed to import from salla_client")
60
+
61
+
62
+
@@ -0,0 +1,204 @@
1
+ import frappe
2
+ from http.client import HTTPException
3
+ from frappe import _, msgprint
4
+
5
+ def validate(doc, method=None):
6
+ if not frappe.db.exists("Salla Defaults", doc.merchant):
7
+ frappe.throw(f"Merchant {doc.merchant} Defaults Not Exist.")
8
+
9
+ def before_insert(doc, method=None):
10
+ salla_default = frappe.get_doc("Salla Defaults", doc.merchant)
11
+ doc.pos_profile = salla_default.pos_profile
12
+ doc.old_order_status = ""
13
+
14
+ def before_save(doc, method=None):
15
+ salla_default = frappe.get_doc("Salla Defaults", doc.merchant)
16
+ if not doc.company:
17
+ doc.company = salla_default.company
18
+
19
+ ready_to_complete = 0
20
+ for salla_item in doc.items:
21
+ salla_item.order_status = doc.order_status
22
+ if not salla_item.merchant:
23
+ salla_item.merchant = doc.merchant
24
+
25
+ bundle_barcode_separator = salla_default.bundle_barcode_separator
26
+ print(f"bundle_barcode_separator : {bundle_barcode_separator} ")
27
+ if bundle_barcode_separator and bundle_barcode_separator in salla_item.barcode:
28
+ salla_item.is_bundle = 1
29
+ if salla_item.barcode and not salla_item.item_code:
30
+ barcode_data = frappe.db.get_value(
31
+ "Item Barcode",
32
+ {"barcode": salla_item.barcode, "custom_is_salla_barcode": 1},
33
+ ["barcode", "parent as item_code"],
34
+ as_dict=True,
35
+ )
36
+
37
+ if barcode_data:
38
+ item = frappe.get_doc("Item",barcode_data.item_code)
39
+ salla_item.item_code = item.name
40
+ salla_item.item_name = item.item_name
41
+ ready_to_complete = 1
42
+ if salla_item.item_code :
43
+ item = frappe.get_doc("Item",salla_item.item_code)
44
+ qty = get_chqanged_quantity(salla_item, doc)
45
+ if doc.order_status != doc.old_order_status and doc.order_status == "ملغي":
46
+ qty = -1 * salla_item.qty
47
+ # if we get order with canceled status for first time (old_order_status = "")
48
+ if doc.old_order_status == "" and doc.order_status == "ملغي":
49
+ qty = 0 #(qty = 0) to avoid negative pending online quantity when canceling order for first time
50
+ if qty != 0:
51
+ salla_item_info = get_salla_item_info(item, doc.merchant)
52
+ update_pending_onlin_qty(salla_item_info, qty)
53
+ item.save()
54
+ if salla_item.is_bundle :
55
+ barcodeList = salla_item.barcode.split(bundle_barcode_separator)
56
+ for barcode in barcodeList:
57
+ item_code = frappe.db.get_value(
58
+ "Item Barcode",
59
+ {"barcode": barcode, "custom_is_salla_barcode": 1},
60
+ ["barcode", "parent as item_code"],
61
+ as_dict=True,
62
+ )
63
+ if item_code:
64
+ item = frappe.get_doc("Item", item_code)
65
+ salla_item_info = get_salla_item_info(item, doc.merchant)
66
+ update_pending_onlin_qty(salla_item_info, qty)
67
+ item.save()
68
+
69
+ doc.old_order_status = doc.order_status
70
+ doc.ready_to_complete = ready_to_complete
71
+
72
+ def get_chqanged_quantity(salla_item, doc):
73
+ old_doc = doc.get_doc_before_save()
74
+ qty = salla_item.qty
75
+ if old_doc :
76
+ old_salla_item = next((item for item in old_doc.items if item.name == salla_item.name), None)
77
+ if old_salla_item:
78
+ qty = salla_item.qty - old_salla_item.qty
79
+ return qty
80
+
81
+ def get_salla_item_info(item, merchant):
82
+ salla_item_info_list = [item_info for item_info in item.custom_salla_item if item_info.merchant == merchant]
83
+ if len(salla_item_info_list) > 0 :
84
+ salla_item_info = salla_item_info_list[0]
85
+ else:
86
+ salla_item_info = frappe.get_doc({"doctype": "Salla Item Info"})
87
+ salla_item_info.parent = item.item_code
88
+ salla_item_info.merchant = merchant
89
+ item.append("custom_salla_item", salla_item_info)
90
+ print(f"salla_item_info : {salla_item_info.name} , pending_online_quantity : {salla_item_info.pending_online_quantity}")
91
+ return salla_item_info
92
+
93
+ def update_pending_onlin_qty(salla_item_info, qty):
94
+ print(f"salla_item_info : {salla_item_info.name} , qty : {qty}")
95
+ if qty < 0 and salla_item_info.pending_online_quantity < abs(qty):
96
+ salla_item_info.pending_online_quantity = 0
97
+ print(f"salla_item_info : {salla_item_info.name} , salla_item_info : {salla_item_info.pending_online_quantity}")
98
+ else:
99
+ salla_item_info.pending_online_quantity = salla_item_info.pending_online_quantity + qty
100
+ print(f"salla_item_info : {salla_item_info.name} , pending_online_quantity : {salla_item_info.pending_online_quantity}")
101
+
102
+
103
+ def before_update_after_submit(doc,method=None):
104
+ for salla_item in doc.items:
105
+ salla_item.is_document_submitted = 1
106
+ salla_item.order_status = doc.order_status
107
+
108
+ def on_cancel(doc, method=None):
109
+ try:
110
+ msgprint(
111
+ _(
112
+ "The task has been enqueued as a background job. In case there is any issue on processing in background, the system will add a comment about the error on this Salla Order and revert to the Submitted stage"
113
+ )
114
+ )
115
+ doc.queue_action("cancel", timeout=2000)
116
+ except HTTPException as e:
117
+ doc.status = "Failed"
118
+ return e
119
+
120
+ def before_submit(doc, method=None):
121
+ salla_default = frappe.get_doc("Salla Defaults", doc.merchant)
122
+
123
+ if not doc.customer:
124
+ CustomerList = frappe.get_all(
125
+ "Customer",
126
+ filters=[["mobile_no", "=", doc.phone_number]],
127
+ fields=["name", "customer_name"],
128
+ )
129
+ if len(CustomerList) > 0:
130
+ doc.customer = CustomerList[0].name
131
+ doc.customer_full_name = CustomerList[0].customer_name
132
+ else:
133
+ customer = frappe.get_doc({"doctype": "Customer"})
134
+
135
+ last_name = ""
136
+ if doc.customer_last_name:
137
+ last_name = doc.customer_last_name
138
+
139
+ customer.customer_name = (
140
+ doc.customer_first_name + " " + last_name
141
+ ) # + " - "+doc.phone_number
142
+ customer.mobile_no = doc.phone_number
143
+ customer.customer_name_in_arabic = customer.customer_name
144
+ customer.mobile_number = doc.phone_number
145
+ if frappe.db.exists(
146
+ "Salla Currency Mapping", {"name": doc.customer_currency}
147
+ ):
148
+ currency_mapping_customer_group = frappe.get_doc(
149
+ "Salla Currency Mapping", doc.customer_currency
150
+ )
151
+ customer.customer_group = currency_mapping_customer_group.customer_group
152
+ else:
153
+ frappe.throw(
154
+ f"This Customer Cannot Be Created because This Currency {doc.customer_currency} Didn't Mapped To Customer Group"
155
+ )
156
+ customer.territory = salla_default.territory
157
+ customer.customer_type = doc.customer_type
158
+ customer.email_id = doc.customer_email
159
+
160
+ customer.insert()
161
+ doc.customer = customer.name
162
+ doc.customer_full_name = customer.customer_name
163
+
164
+ if salla_default.taxe_included_in_basic_rate and doc.total_tax:
165
+ frappe.throw("Total tax must be zero when 'Tax Included In Basic Rate' is enabled in Salla Default Settings.")
166
+
167
+ for item in doc.items:
168
+ if not item.barcode:
169
+ frappe.throw("All items must have a barcode!")
170
+
171
+ ItemCodeList = frappe.get_all(
172
+ "Item Barcode",
173
+ filters=[
174
+ [
175
+ "barcode",
176
+ "=",
177
+ item.barcode,
178
+ ],
179
+ [
180
+ "custom_is_salla_barcode",
181
+ "=",
182
+ 1
183
+ ]
184
+ ],
185
+ fields=["parent"],
186
+ )
187
+
188
+ if len(ItemCodeList) > 0:
189
+ item_doc = frappe.get_doc('Item', ItemCodeList[0].parent)
190
+ salla_item_info = None
191
+ salla_item_info_exist = frappe.db.exists('Salla Item Info', {"merchant": doc.merchant, "parent": item_doc.name})
192
+ if salla_item_info_exist:
193
+ salla_item_info = frappe.get_doc('Salla Item Info', {"merchant": doc.merchant, "parent": item_doc.name})
194
+ else :
195
+ salla_item_info = frappe.get_doc({'doctype':'Salla Item Info'})
196
+ salla_item_info.parent = item_doc.name
197
+ salla_item_info.merchant = doc.merchant
198
+
199
+ if salla_item_info.pending_online_quantity and salla_item_info.pending_online_quantity >= item.qty :
200
+ salla_item_info.pending_online_quantity = salla_item_info.pending_online_quantity - item.qty
201
+ else :
202
+ salla_item_info.pending_online_quantity = 0
203
+ item_doc.append('custom_salla_item',salla_item_info)
204
+ salla_item_info.save()