code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class InsightsQueryColumn(Document):
pass
|
2302_79757062/insights
|
insights/insights/doctype/insights_query_column/insights_query_column.py
|
Python
|
agpl-3.0
| 227
|
// Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Insights Query Execution Log", {
// refresh(frm) {
// },
// });
|
2302_79757062/insights
|
insights/insights/doctype/insights_query_execution_log/insights_query_execution_log.js
|
JavaScript
|
agpl-3.0
| 211
|
// Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Insights Query Result", {
// refresh(frm) {
// },
// });
|
2302_79757062/insights
|
insights/insights/doctype/insights_query_result/insights_query_result.js
|
JavaScript
|
agpl-3.0
| 204
|
# Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class InsightsQueryResult(Document):
pass
|
2302_79757062/insights
|
insights/insights/doctype/insights_query_result/insights_query_result.py
|
Python
|
agpl-3.0
| 227
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class InsightsQueryTable(Document):
pass
|
2302_79757062/insights
|
insights/insights/doctype/insights_query_table/insights_query_table.py
|
Python
|
agpl-3.0
| 226
|
// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Insights Query Transform", {
// refresh: function(frm) {
// }
});
|
2302_79757062/insights
|
insights/insights/doctype/insights_query_transform/insights_query_transform.js
|
JavaScript
|
agpl-3.0
| 209
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class InsightsQueryTransform(Document):
pass
|
2302_79757062/insights
|
insights/insights/doctype/insights_query_transform/insights_query_transform.py
|
Python
|
agpl-3.0
| 230
|
# Copyright (c) 2023, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class InsightsQueryVariable(Document):
pass
|
2302_79757062/insights
|
insights/insights/doctype/insights_query_variable/insights_query_variable.py
|
Python
|
agpl-3.0
| 229
|
// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on('Insights Settings', {
// refresh: function(frm) {
// }
})
|
2302_79757062/insights
|
insights/insights/doctype/insights_settings/insights_settings.js
|
JavaScript
|
agpl-3.0
| 201
|
// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on('Insights Table', {
// refresh: function(frm) {
// }
})
|
2302_79757062/insights
|
insights/insights/doctype/insights_table/insights_table.js
|
JavaScript
|
agpl-3.0
| 198
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
class InsightsTable(Document):
def on_update(self):
if not self.columns:
self.update_columns()
@frappe.whitelist()
def sync_table(self):
source = frappe.get_doc("Insights Data Source", self.data_source)
source.sync_tables([self.table], force=True)
@frappe.whitelist()
def update_visibility(self, hidden):
self.hidden = hidden
self.save()
@frappe.whitelist()
def get_preview(self):
if self.is_query_based:
return []
data_source = frappe.get_doc("Insights Data Source", self.data_source)
return data_source.get_table_preview(self.table)
def get_columns(self):
if not self.columns:
self.update_columns()
return self.columns
def update_columns(self):
if self.is_query_based:
return
data_source = frappe.get_doc("Insights Data Source", self.data_source)
if columns := data_source.get_table_columns(self.table):
self.columns = []
for column in columns:
self.append(
"columns",
{
"column": column.get("column"),
"label": column.get("label"),
"type": column.get("type"),
},
)
@frappe.whitelist()
def update_column_type(self, column, newtype):
for col in self.columns:
if col.column == column and col.type != newtype:
col.type = newtype
break
self.save()
def on_doctype_update():
fields = ["data_source", "table"]
if frappe.db.db_type == "mariadb":
fields = ["`data_source`", "`table`"]
frappe.db.add_index("Insights Table", fields, "data_source_table_index")
|
2302_79757062/insights
|
insights/insights/doctype/insights_table/insights_table.py
|
Python
|
agpl-3.0
| 2,002
|
import frappe
def execute():
delete_duplicate_records()
def delete_duplicate_records():
"""
Delete records in Insights Table with duplicate
table, data_source, and is_query_based.
"""
data_sources = frappe.get_all("Insights Data Source", pluck="name")
for data_source in data_sources:
tables = frappe.get_all(
"Insights Table",
filters={"data_source": data_source},
fields=["table", "is_query_based"],
as_list=True,
)
for table in tables:
duplicates = frappe.get_all(
"Insights Table",
filters={
"table": table[0],
"is_query_based": table[1],
"data_source": data_source,
},
pluck="name",
)
if len(duplicates) > 1:
frappe.db.sql(
"DELETE FROM `tabInsights Table` WHERE name IN %(duplicates)s",
{"duplicates": tuple(duplicates[1:])},
)
|
2302_79757062/insights
|
insights/insights/doctype/insights_table/patches/delete_duplicate_records.py
|
Python
|
agpl-3.0
| 1,070
|
import frappe
def execute():
"""delete_unused_query_based_tables"""
# get all insights tables
insights_tables = frappe.get_all(
"Insights Table", filters={"is_query_based": 1}, fields=["name", "table"]
)
# get all generate sqls
generated_sqls = frappe.get_all("Insights Query", pluck="sql")
# delete insights table if `table` not present in any sql
for table in insights_tables:
for sql in generated_sqls:
if sql and table.table in sql:
break
else:
frappe.delete_doc("Insights Table", table.name)
|
2302_79757062/insights
|
insights/insights/doctype/insights_table/patches/delete_unused_query_based_tables.py
|
Python
|
agpl-3.0
| 598
|
import click
import frappe
from insights.insights.doctype.insights_data_source.sources.frappe_db import FrappeDB
def execute():
data_sources = frappe.get_all(
"Insights Data Source",
{
"database_type": "MariaDB",
"status": "Active",
},
pluck="name",
)
for data_source in data_sources:
doc = frappe.get_doc("Insights Data Source", data_source)
try:
if not isinstance(doc._db, FrappeDB) and not doc.is_site_db:
click.echo(f"Skipping {data_source} as it is not a MariaDB data source")
continue
click.echo(f"Syncing tables for {data_source}")
with doc._db.engine.begin() as connection:
doc._db.table_factory.db_conn = connection
table_names = doc._db.table_factory.get_columns_by_tables().keys()
with click.progressbar(list(table_names)) as tables:
for table_name in tables:
table = get_table(table_name, data_source)
if not table:
continue
clear_table_links(table.name)
table_links = doc._db.table_factory.get_table_links(table.label)
insert_table_links(table.name, table_links)
frappe.db.commit()
except Exception as e:
frappe.db.rollback()
print(f"Failed to sync tables for {data_source}: {e}")
def get_table(table_name, data_source):
return frappe.db.get_value(
"Insights Table",
{"table": table_name, "data_source": data_source},
["name", "label"],
as_dict=True,
)
def clear_table_links(table_docname):
frappe.db.delete("Insights Table Link", {"parent": table_docname})
def insert_table_links(table_docname, table_links):
for idx, table_link in enumerate(table_links):
frappe.get_doc(
{
"doctype": "Insights Table Link",
"idx": idx + 1,
"parent": table_docname,
"parenttype": "Insights Table",
"parentfield": "table_links",
"primary_key": table_link.get("primary_key"),
"foreign_key": table_link.get("foreign_key"),
"foreign_table": table_link.get("foreign_table"),
"foreign_table_label": table_link.get("foreign_table_label"),
"cardinality": table_link.get("cardinality"),
}
).db_insert(ignore_if_duplicate=True)
|
2302_79757062/insights
|
insights/insights/doctype/insights_table/patches/sync_table_links.py
|
Python
|
agpl-3.0
| 2,584
|
// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on('Insights Table Column', {
// refresh: function(frm) {
// }
})
|
2302_79757062/insights
|
insights/insights/doctype/insights_table_column/insights_table_column.js
|
JavaScript
|
agpl-3.0
| 205
|
// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Insights Table Import", {
// refresh: function(frm) {
// }
});
|
2302_79757062/insights
|
insights/insights/doctype/insights_table_import/insights_table_import.js
|
JavaScript
|
agpl-3.0
| 206
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import csv
import os
from functools import cached_property
import frappe
from frappe import task
from frappe.model.document import Document
from insights.utils import detect_encoding
class InsightsTableImport(Document):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._filepath = None
@cached_property
def _data_source(self):
return frappe.get_doc("Insights Data Source", self.data_source)
def validate(self):
if not self._data_source.allow_imports:
frappe.throw("Data source does not allow imports")
if self.source and not self.source.endswith(".csv"):
frappe.throw("Please attach a CSV file")
if self._data_source._db.table_exists(self.table_name) and self.if_exists == "Fail":
frappe.throw("Table already exists. Enter a new different table name")
def before_save(self):
if not self._filepath and frappe.db.exists("File", {"file_url": self.source}):
file = frappe.get_doc("File", {"file_url": self.source})
self._filepath = file.get_full_path()
if not self._filepath or not os.path.exists(self._filepath):
return
if self.is_new():
self.set_columns_and_no_of_rows()
def set_columns_and_no_of_rows(self):
encoding = detect_encoding(self._filepath)
with open(self._filepath, "r", encoding=encoding, errors="replace") as f:
# read only the first line to get the column names
csv_reader = csv.DictReader(f)
column_names = csv_reader.fieldnames
rows = list(csv_reader)
no_of_rows = len(rows)
self.db_set("rows", no_of_rows)
for column in column_names:
if not self.get("columns", {"column": frappe.scrub(column)}):
self.append(
"columns",
{
"type": "String",
"column": frappe.scrub(column),
"label": frappe.unscrub(column),
},
)
def on_submit(self):
if not self._filepath:
self.db_set("status", "Failed")
self.db_set("error", "Attached file not found")
print("Attached file not found")
return
self.db_set("status", "Queued")
self.start_import.enqueue(name=self.name, filepath=self._filepath, now=True)
@staticmethod
@task(queue="long")
def start_import(name, filepath=None):
table_import = frappe.get_doc("Insights Table Import", name)
table_import._filepath = filepath or table_import._filepath
table_import.db_set("status", "Started")
try:
table_import._data_source._db.import_table(table_import)
table_import.db_set("status", "Success")
except Exception as e:
print(f"Error importing table {table_import.table_name}", e)
frappe.log_error(title=f"Insights: Failed to import table - {table_import.table_name}")
table_import.db_set("status", "Failed")
table_import.db_set("error", "Failed to import table. Check error log for details")
|
2302_79757062/insights
|
insights/insights/doctype/insights_table_import/insights_table_import.py
|
Python
|
agpl-3.0
| 3,343
|
// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on('Insights Table Link', {
// refresh: function(frm) {
// }
})
|
2302_79757062/insights
|
insights/insights/doctype/insights_table_link/insights_table_link.js
|
JavaScript
|
agpl-3.0
| 203
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class InsightsTableLink(Document):
pass
|
2302_79757062/insights
|
insights/insights/doctype/insights_table_link/insights_table_link.py
|
Python
|
agpl-3.0
| 225
|
// Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Insights Table Link v3", {
// refresh(frm) {
// },
// });
|
2302_79757062/insights
|
insights/insights/doctype/insights_table_link_v3/insights_table_link_v3.js
|
JavaScript
|
agpl-3.0
| 205
|
// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Insights Table v3", {
// refresh: function(frm) {
// }
});
|
2302_79757062/insights
|
insights/insights/doctype/insights_table_v3/insights_table_v3.js
|
JavaScript
|
agpl-3.0
| 202
|
import frappe
from insights.insights.doctype.insights_data_source_v3.insights_data_source_v3 import (
after_request,
before_request,
)
def execute():
"""
`name` of Insights Table v3 is changed from `autoincrement` to `varchar(140)`
This patch will delete all the tables and recreate them with the new name
The new name will be a reproducible hash of the data_source and table name
"""
data_sources = frappe.get_all(
"Insights Data Source v3", filters={"status": "Active"}, pluck="name"
)
doctype_doc = frappe.get_doc("DocType", "Insights Table v3")
doctype_doc.setup_autoincrement_and_sequence()
before_request()
for source in data_sources:
doc = frappe.get_doc("Insights Data Source v3", source)
try:
doc.update_table_list(force=True)
except Exception:
print(f"Error syncing {source}")
frappe.db.rollback()
frappe.db.delete("Insights Table v3", {"data_source": source})
finally:
frappe.db.commit()
after_request()
|
2302_79757062/insights
|
insights/insights/doctype/insights_table_v3/patches/force_sync_tables.py
|
Python
|
agpl-3.0
| 1,081
|
// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on("Insights Team", {
// refresh: function(frm) {
// }
});
|
2302_79757062/insights
|
insights/insights/doctype/insights_team/insights_team.js
|
JavaScript
|
agpl-3.0
| 198
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe.utils.user import get_users_with_role
from insights import notify
from insights.decorators import check_permission, check_role
class InsightsTeamClient:
@frappe.whitelist()
def get_members_and_resources(self):
members = self.get_members()
resources = []
for resource in self.team_permissions:
title_field = (
"label" if resource.resource_type == "Insights Table" else "title"
)
resources.append(
{
"type": resource.resource_type,
"name": resource.resource_name,
"title": frappe.db.get_value(
resource.resource_type, resource.resource_name, title_field
),
}
)
return {
"members": members,
"resources": resources,
}
@frappe.whitelist()
def search_team_members(self, query):
# get all users who are not in the team
members = [m.user for m in self.team_members]
insights_users = get_users_with_role("Insights User")
insights_users = list(set(insights_users) - set(members))
if not insights_users:
return []
User = frappe.qb.DocType("User")
conditions = (User.name.isin(insights_users)) & (User.enabled == 1)
if query:
conditions &= (User.full_name.like(f"%{query}%")) | (
User.email.like(f"%{query}%")
)
return (
frappe.qb.from_(User)
.select(User.name, User.full_name, User.email, User.user_image)
.where(conditions)
.run(as_dict=True)
)
@frappe.whitelist()
def search_team_resources(self, resource_type, query):
resources = []
if resource_type == "Insights Data Source":
InsightsDataSource = frappe.qb.DocType("Insights Data Source")
exclude_sources = [
r.resource_name
for r in self.team_permissions
if r.resource_type == "Insights Data Source"
]
conditions = InsightsDataSource.title.like(f"%{query}%") | (
InsightsDataSource.database_type.like(f"%{query}%")
)
if exclude_sources:
conditions = conditions & (
InsightsDataSource.name.notin(exclude_sources)
)
data_sources = (
frappe.qb.from_(InsightsDataSource)
.select(
InsightsDataSource.name,
InsightsDataSource.title,
InsightsDataSource.database_type,
)
.where(conditions)
.limit(25)
.run(as_dict=True)
)
for source in data_sources:
resources.append(
{
"name": source.name,
"title": source.title,
"database_type": source.database_type,
"type": "Insights Data Source",
}
)
if resource_type == "Insights Table":
# get all tables
InsightsTable = frappe.qb.DocType("Insights Table")
exclude_tables = [
r.resource_name
for r in self.team_permissions
if r.resource_type == "Insights Table"
]
conditions = InsightsTable.label.like(f"%{query}%") | (
InsightsTable.data_source.like(f"%{query}%")
)
if exclude_tables:
conditions = conditions & (InsightsTable.name.notin(exclude_tables))
tables = (
frappe.qb.from_(InsightsTable)
.select(
InsightsTable.name,
InsightsTable.label,
InsightsTable.data_source,
)
.where(conditions)
.limit(25)
.run(as_dict=True)
)
for table in tables:
resources.append(
{
"name": table.name,
"title": table.label,
"type": "Insights Table",
"data_source": table.data_source,
}
)
if resource_type == "Insights Query":
InsightsQuery = frappe.qb.DocType("Insights Query")
exclude_queries = [
r.resource_name
for r in self.team_permissions
if r.resource_type == "Insights Query"
]
conditions = InsightsQuery.title.like(f"%{query}%") | (
InsightsQuery.data_source.like(f"%{query}%")
)
if exclude_queries:
conditions = conditions & (InsightsQuery.name.notin(exclude_queries))
queries = (
frappe.qb.from_(InsightsQuery)
.select(
InsightsQuery.name,
InsightsQuery.title,
InsightsQuery.data_source,
)
.where(conditions)
.limit(25)
.run(as_dict=True)
)
for query in queries:
resources.append(
{
"name": query.name,
"title": query.title,
"data_source": query.data_source,
"type": "Insights Query",
}
)
if resource_type == "Insights Dashboard":
InsightsDashboard = frappe.qb.DocType("Insights Dashboard")
exclude_dashboards = [
r.resource_name
for r in self.team_permissions
if r.resource_type == "Insights Dashboard"
]
conditions = InsightsDashboard.title.like(f"%{query}%")
if exclude_dashboards:
conditions = conditions & (
InsightsDashboard.name.notin(exclude_dashboards)
)
dashboards = (
frappe.qb.from_(InsightsDashboard)
.select(InsightsDashboard.name, InsightsDashboard.title)
.where(conditions)
.limit(25)
.run(as_dict=True)
)
for dashboard in dashboards:
resources.append(
{
"name": dashboard.name,
"title": dashboard.title,
"type": "Insights Dashboard",
}
)
return resources
@frappe.whitelist()
def add_team_member(self, user):
self.append("team_members", {"user": user})
self.save()
@frappe.whitelist()
def add_team_members(self, users):
for user in users:
self.append("team_members", {"user": user})
self.save()
@frappe.whitelist()
def remove_team_member(self, user):
for member in self.team_members:
if member.user == user:
self.remove(member)
break
self.save()
@frappe.whitelist()
def add_team_resource(self, resource):
resource = frappe._dict(resource)
self.append(
"team_permissions",
{"resource_type": resource.type, "resource_name": resource.name},
)
self.save()
@frappe.whitelist()
def add_team_resources(self, resources):
for resource in resources:
resource = frappe._dict(resource)
self.append(
"team_permissions",
{"resource_type": resource.type, "resource_name": resource.name},
)
self.save()
@frappe.whitelist()
def remove_team_resource(self, resource):
resource = frappe._dict(resource)
for permission in self.team_permissions:
if (
permission.resource_type == resource.type
and permission.resource_name == resource.name
):
self.remove(permission)
break
self.save()
@frappe.whitelist()
def delete_team(self):
frappe.delete_doc("Insights Team", self.name)
notify(
type="success",
message=f"Team {self.team_name} deleted successfully",
)
@frappe.whitelist()
@check_role("Insights Admin")
@check_permission("Insights Team")
def get_teams():
User = frappe.qb.DocType("User")
Team = frappe.qb.DocType("Insights Team")
TeamMember = frappe.qb.DocType("Insights Team Member")
# get all teams and their member's full name, email and user image
team_users = (
frappe.qb.from_(Team)
.select(Team.name, Team.team_name, User.full_name, User.email, User.user_image)
.left_join(TeamMember)
.on(Team.name == TeamMember.parent)
.left_join(User)
.on(TeamMember.user == User.name)
.run(as_dict=True)
)
teams = {}
for team_user in team_users:
if (team_user.name, team_user.team_name) not in teams:
team_doc = frappe.get_cached_doc("Insights Team", team_user.name)
teams[(team_user.name, team_user.team_name)] = {
"name": team_user.name,
"team_name": team_user.team_name,
"source_count": len(team_doc.get_allowed_sources() or []),
"table_count": len(team_doc.get_allowed_tables() or []),
"query_count": len(team_doc.get_allowed_queries() or []),
"dashboard_count": len(team_doc.get_allowed_dashboards() or []),
"members": [],
}
if not team_user.full_name:
continue
teams[(team_user.name, team_user.team_name)]["members"].append(
{
"full_name": team_user.full_name,
"user_image": team_user.user_image,
"email": team_user.email,
}
)
return list(teams.values())
@frappe.whitelist()
def add_new_team(team_name):
doc = frappe.new_doc("Insights Team")
doc.team_name = team_name
doc.save()
notify(
type="success",
message=f"Team {team_name} has been created",
)
|
2302_79757062/insights
|
insights/insights/doctype/insights_team/insights_team_client.py
|
Python
|
agpl-3.0
| 10,570
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class InsightsTeamMember(Document):
pass
|
2302_79757062/insights
|
insights/insights/doctype/insights_team_member/insights_team_member.py
|
Python
|
agpl-3.0
| 226
|
// Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Insights User Invitation", {
// refresh(frm) {
// },
// });
|
2302_79757062/insights
|
insights/insights/doctype/insights_user_invitation/insights_user_invitation.js
|
JavaScript
|
agpl-3.0
| 207
|
// Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
// frappe.ui.form.on("Insights Workbook", {
// refresh(frm) {
// },
// });
|
2302_79757062/insights
|
insights/insights/doctype/insights_workbook/insights_workbook.js
|
JavaScript
|
agpl-3.0
| 200
|
frappe.pages['insights'].on_page_load = function (wrapper) {
window.location.href = '/insights'
}
|
2302_79757062/insights
|
insights/insights/page/insights/insights.js
|
JavaScript
|
agpl-3.0
| 99
|
from contextlib import suppress
from frappe import _dict, parse_json
from sqlalchemy import column as sa_column
from sqlalchemy import select, table
from sqlalchemy.sql import and_, or_, text
from .sql_functions import Aggregations, BinaryOperations, ColumnFormatter, Functions
class LegacyQueryBuilder:
def __init__(self, engine) -> None:
self.functions = Functions
self.aggregations = Aggregations
self.column_formatter = ColumnFormatter
self.expression_processor = ExpressionProcessor(self)
self.engine = engine
def build(self, query):
self.query = query
self.process_tables_and_joins()
self.process_columns()
self.process_filters()
compiled = self.make_query()
return str(compiled) if compiled else ""
def make_table(self, name):
if not hasattr(self, "_tables"):
self._tables = {}
if name not in self._tables:
self._tables[name] = table(name).alias(f"{name}")
return self._tables[name]
def make_column(self, columnname, tablename):
_table = self.make_table(tablename)
return sa_column(columnname, _selectable=_table)
def process_tables_and_joins(self):
self._joins = []
for row in self.query.tables:
if not row.join:
continue
_join = parse_json(row.join)
join_type = _join.get("type", {}).get("value")
left_table = self.make_table(row.table)
right_table = self.make_table(_join.get("with", {}).get("value"))
condition = _join.get("condition")
left_key = condition.get("left", {}).get("value")
right_key = condition.get("right", {}).get("value")
if not left_key or not right_key:
continue
left_key = self.make_column(left_key, row.table)
right_key = self.make_column(right_key, _join.get("with", {}).get("value"))
self._joins.append(
_dict(
{
"left": left_table,
"right": right_table,
"type": join_type,
"left_key": left_key,
"right_key": right_key,
}
)
)
def process_columns(self):
self._columns = []
self._group_by_columns = []
self._order_by_columns = []
for row in self.query.columns:
if not row.is_expression:
_column = self.make_column(row.column, row.table)
_column = self.column_formatter.format(
parse_json(row.format_option), row.type, _column
)
_column = self.aggregations.apply(row.aggregation, _column)
else:
expression = parse_json(row.expression)
_column = self.expression_processor.process(expression.get("ast"))
_column = self.column_formatter.format(
parse_json(row.format_option), row.type, _column
)
if row.order_by:
self._order_by_columns.append(
_column.asc() if row.order_by == "asc" else _column.desc()
)
_column = _column.label(row.label) if row.label else _column
if row.aggregation == "Group By":
self._group_by_columns.append(_column)
self._columns.append(_column)
def process_filters(self):
filters = parse_json(self.query.filters)
self._filters = self.expression_processor.process(filters)
def make_query(self):
if not self.query.tables:
return
main_table = self.query.tables[0].table
sql = None
if not self._columns:
# hack: to avoid duplicate columns error if tables have same column names
sql = select(text(f"`{main_table}`.*"))
else:
sql = select(*self._columns)
sql = sql.select_from(self.make_table(main_table))
if self._joins:
sql = self.do_join(sql)
if self._group_by_columns:
sql = sql.group_by(*self._group_by_columns)
if self._order_by_columns:
sql = sql.order_by(*self._order_by_columns)
if self._filters is not None:
sql = sql.filter(self._filters)
sql = sql.limit(self.query.limit or self._limit)
return sql.compile(self.engine, compile_kwargs={"literal_binds": True})
def do_join(self, sql):
# TODO: add right and full joins
for join in self._joins:
isouter, full = False, False
if join.type == "left":
isouter = True
elif join.type == "full":
isouter = True
full = True
sql = sql.join_from(
join.left,
join.right,
join.left_key == join.right_key,
isouter=isouter,
full=full,
)
return sql
class ExpressionProcessor:
def __init__(self, builder: "LegacyQueryBuilder"):
self.builder = builder
def process(self, expression):
expression = _dict(expression)
if expression.type == "LogicalExpression":
return self.process_logical_expression(expression)
if expression.type == "BinaryExpression":
return self.process_binary_expression(expression)
if expression.type == "CallExpression":
return self.process_call_expression(expression)
if expression.type == "Column":
column = expression.value.get("column")
table = expression.value.get("table")
return self.builder.make_column(column, table)
if expression.type == "String":
return expression.value
if expression.type == "Number":
return expression.value
raise NotImplementedError(f"Invalid expression type: {expression.type}")
def process_logical_expression(self, expression):
conditions = []
GroupCriteria = and_ if expression.operator == "&&" else or_
for condition in expression.get("conditions"):
condition = _dict(condition)
conditions.append(self.process(condition))
if conditions:
return GroupCriteria(*conditions)
def process_binary_expression(self, expression):
left = self.process(expression.left)
right = self.process(expression.right)
operator = expression.operator
operation = BinaryOperations.get_operation(operator)
return operation(left, right)
def process_call_expression(self, expression):
function = expression.function
arguments = [self.process(arg) for arg in expression.arguments]
with suppress(NotImplementedError):
return self.builder.functions.apply(function, *arguments)
if len(arguments) <= 2:
with suppress(NotImplementedError):
return self.builder.aggregations.apply(function, *arguments)
raise NotImplementedError(f"Function {function} not implemented")
|
2302_79757062/insights
|
insights/insights/query_builders/legacy_query_builder.py
|
Python
|
agpl-3.0
| 7,241
|
from sqlalchemy import Column
from sqlalchemy.sql import func
from ..sql_builder import ColumnFormatter, Functions, SQLQueryBuilder
class PostgresColumnFormatter(ColumnFormatter):
@classmethod
def format_date(cls, format, column: Column):
match format:
case "Minute":
return func.to_char(column, "YYYY-MM-DD HH24:MI")
case "Hour":
return func.to_char(column, "YYYY-MM-DD HH24:00")
case "Day" | "Day Short":
return func.to_char(column, "YYYY-MM-DD 00:00")
case "Week":
return func.date_trunc("week", column)
case "Month" | "Mon":
return func.to_char(column, "YYYY-MM-01")
case "Year":
return func.to_char(column, "YYYY-01-01")
case "Minute of Hour":
return func.to_char(column, "00:MI")
case "Hour of Day":
return func.to_char(column, "HH:00")
case "Day of Week":
return func.to_char(column, "Day")
case "Day of Month":
return func.to_char(column, "DD")
case "Day of Year":
return func.to_char(column, "DDD")
case "Month of Year":
return func.to_char(column, "MM")
case "Quarter of Year":
return func.date_part("quarter", column)
case "Quarter":
return func.to_date(
func.concat(
func.extract("year", column),
"-",
(func.extract("quarter", column) * 3) - 2,
"-01",
),
"YYYY-MM-DD",
)
case _:
return func.to_char(column, format)
class PostgresQueryBuilder(SQLQueryBuilder):
def __init__(self, engine):
super().__init__(engine)
self.engine = engine
self.functions = Functions
self.column_formatter = PostgresColumnFormatter
|
2302_79757062/insights
|
insights/insights/query_builders/postgresql/builder.py
|
Python
|
agpl-3.0
| 2,070
|
from typing import List
import frappe
from frappe import _dict
from sqlalchemy import Column, TextClause
from sqlalchemy import column as sa_column
from sqlalchemy import select, table
from sqlalchemy.sql import and_, func, text
from insights.insights.doctype.insights_query.utils import Column as AssistedQueryColumn
from insights.insights.doctype.insights_query.utils import Filter as AssistedQueryFilter
from insights.insights.doctype.insights_query.utils import Join as AssistedQueryJoin
from insights.insights.doctype.insights_query.utils import Query as AssistedQuery
from .legacy_query_builder import LegacyQueryBuilder
from .sql_functions import (
Aggregations,
BinaryOperations,
ColumnFormatter,
Functions,
call_function,
get_eval_globals,
)
from .utils import process_raw_expression
class SQLQueryBuilder:
def __init__(self, engine) -> None:
self.engine = engine
self.functions = Functions
self.aggregations = Aggregations
self.column_formatter = ColumnFormatter
def build(self, query):
if query.is_native_query:
return query.sql.strip().rstrip(";") if query.sql else ""
elif query.is_assisted_query:
return self.process_and_build(query)
return LegacyQueryBuilder(self.engine).build(query)
def process_and_build(self, query) -> str:
assisted_query: AssistedQuery = query.variant_controller.query_json
if not assisted_query or not assisted_query.is_valid():
return ""
query = ""
frappe.flags._current_query_dialect = self.engine.dialect
try:
self._process(assisted_query)
query = self._build(assisted_query)
query = self.compile_query(query)
finally:
frappe.flags._current_query_dialect = None
return query
def _process(self, assisted_query: AssistedQuery):
self._tables = {}
self._joins = []
self._filters = None
self._columns = []
self._measures = []
self._dimensions = []
self._order_by_columns = []
self._limit = None
self.process_joins(assisted_query.joins)
self.process_filters(assisted_query.filters)
self.process_columns(assisted_query.columns)
self._limit = assisted_query.limit or None
def process_joins(self, joins: List[AssistedQueryJoin]):
if not joins:
return
for join in joins:
if not join.is_valid():
continue
self._joins.append(
_dict(
left=self.make_table(join.left_table.table),
right=self.make_table(join.right_table.table),
type=join.join_type.value,
left_key=self.make_column(
join.left_column.column, join.left_table.table
),
right_key=self.make_column(
join.right_column.column, join.right_table.table
),
)
)
def process_column(self, column: AssistedQueryColumn, for_filter=False):
_column = self.make_column(column.column, column.table)
if column.is_expression():
_column = self.evaluate_expression(column.expression.raw)
if column.is_aggregate():
_column = self.aggregations.apply(column.aggregation, _column)
if column.has_granularity() and not for_filter:
_column = self.column_formatter.format_date(column.granularity, _column)
if isinstance(_column, TextClause):
return _column
return _column.label(column.alias)
def process_filters(self, filters: List[AssistedQueryFilter]):
if not filters:
return
_filters = []
for fltr in filters:
if not fltr.is_valid():
continue
if fltr.expression:
_filter = self.evaluate_expression(fltr.expression.raw)
_filters.append(_filter)
continue
_column = self.process_column(fltr.column, for_filter=True)
operator = fltr.operator.value
filter_value = fltr.value.value or ""
if BinaryOperations.is_binary_operator(operator):
operation = BinaryOperations.get_operation(operator)
_filter = operation(_column, filter_value)
elif "set" in operator: # is set, is not set
_filter = call_function(operator, _column)
elif operator == "is":
operator_fn = (
"is_set" if filter_value.lower() == "set" else "is_not_set"
)
_filter = call_function(operator_fn, _column)
elif operator == "between":
from_to = filter_value.split(",")
_filter = call_function(operator, _column, *from_to)
elif operator == "in" or operator == "not_in":
args = filter_value
if filter_value and isinstance(filter_value[0], dict):
args = [val["value"] for val in filter_value]
_filter = call_function(operator, _column, *args)
else:
_filter = call_function(operator, _column, filter_value)
_filters.append(_filter)
if _filters:
self._filters = and_(*_filters)
def process_columns(self, columns: List[AssistedQueryColumn]):
for column in columns:
if not column.is_valid():
continue
if column.is_measure():
self._measures.append(self.process_column(column))
if column.is_dimension():
self._dimensions.append(self.process_column(column))
if column.order:
_column = self.process_column(column)
self._order_by_columns.append(
_column.asc() if column.order == "asc" else _column.desc()
)
def quote_identifier(self, identifier):
return self.engine.dialect.identifier_preparer.quote_identifier(identifier)
def _build(self, assisted_query):
main_table = assisted_query.table.table
main_table = self.make_table(main_table)
columns = self._dimensions + self._measures
if not columns:
columns = [text(f"{self.quote_identifier(main_table.name)}.*")]
query = select(*columns).select_from(main_table)
for join in self._joins:
query = query.join_from(
join.left,
join.right,
join.left_key == join.right_key,
isouter=join.type != "inner",
full=join.type == "full",
)
if self._filters is not None:
query = query.where(self._filters)
if self._dimensions:
query = query.group_by(*self._dimensions)
if self._order_by_columns:
query = query.order_by(*self._order_by_columns)
if self._limit:
query = query.limit(self._limit)
if not columns:
# if select * query then limit to 50 rows
query = query.limit(50)
return query
def make_table(self, name):
if name not in self._tables:
self._tables[name] = table(name).alias(name)
return self._tables[name]
def make_column(self, columnname, tablename):
_table = self.make_table(tablename)
return sa_column(columnname, _selectable=_table)
def evaluate_expression(self, raw_expression):
raw = raw_expression
try:
raw = process_raw_expression(raw_expression)
eval_globals = get_eval_globals()
eval_globals["column"] = lambda table, column: self.make_column(
column, table
)
return frappe.safe_eval(raw, eval_globals=eval_globals)
except Exception as e:
raise Exception(f"Invalid expression {raw} - {e}")
def compile_query(self, query):
return query.compile(
dialect=self.engine.dialect,
compile_kwargs={"literal_binds": True},
)
|
2302_79757062/insights
|
insights/insights/query_builders/sql_builder.py
|
Python
|
agpl-3.0
| 8,236
|
import operator
from contextlib import suppress
from datetime import date, datetime
import frappe
from frappe.utils.data import (
add_to_date,
get_date_str,
get_first_day,
get_first_day_of_week,
get_last_day,
get_last_day_of_week,
get_quarter_ending,
get_quarter_start,
get_year_ending,
get_year_start,
getdate,
nowdate,
)
from sqlalchemy import Column
from sqlalchemy import column as sa_column
from sqlalchemy import select, table
from sqlalchemy.sql import and_, case, distinct, func, or_, text
DATE_TYPES = ("Date", "Datetime")
class Aggregations:
@classmethod
def apply(cls, aggregation: str, column=None):
if not aggregation:
return column
if aggregation == "Group By":
return column
agg_lower = aggregation.lower()
if agg_lower == "sum" or agg_lower == "cumulative sum":
return func.sum(column)
if agg_lower == "min":
return func.min(column)
if agg_lower == "max":
return func.max(column)
if agg_lower == "avg":
return func.avg(column)
if agg_lower == "count" or agg_lower == "cumulative count":
return func.count(text("*"))
if agg_lower == "distinct":
return distinct(column)
if agg_lower == "distinct_count":
return func.count(distinct(column))
raise NotImplementedError(f"Aggregation {aggregation} not implemented")
class ColumnFormatter:
@classmethod
def format(cls, format_options: dict, column_type: str, column: Column) -> Column:
if format_options and format_options.date_format and column_type in DATE_TYPES:
date_format = format_options.date_format
date_format = (
date_format if type(date_format) == str else date_format.get("value")
)
return cls.format_date(date_format, column)
return column
@classmethod
def format_date(cls, format, column: Column):
if format == "Minute":
return func.date_format(column, "%Y-%m-%d %H:%i")
if format == "Hour":
return func.date_format(column, "%Y-%m-%d %H:00")
if format == "Day" or format == "Day Short":
return func.date_format(column, "%Y-%m-%d 00:00")
if format == "Week":
# DATE_FORMAT(install_date, '%Y-%m-%d') - INTERVAL (DAYOFWEEK(install_date) - 1) DAY,
date = func.date_format(column, "%Y-%m-%d")
dialect = frappe.flags._current_query_dialect
compiled = column.compile(dialect=dialect)
return func.DATE_SUB(
date, text(f"INTERVAL (DAYOFWEEK({compiled}) - 1) DAY")
)
if format == "Month" or format == "Mon":
return func.date_format(column, "%Y-%m-01")
if format == "Year":
return func.date_format(column, "%Y-01-01")
if format == "Minute of Hour":
return func.date_format(column, "00:%M")
if format == "Hour of Day":
return func.date_format(column, "%H:00")
if format == "Day of Week":
return func.date_format(column, "%W")
if format == "Day of Month":
return func.date_format(column, "%d")
if format == "Day of Year":
return func.date_format(column, "%j")
if format == "Month of Year":
return func.date_format(column, "%M")
if format == "Quarter of Year":
return func.quarter(column)
if format == "Quarter":
# 2022-02-12 -> 2022-01-01
# STR_TO_DATE(CONCAT(YEAR(CURRENT_DATE), '-', (QUARTER(CURRENT_DATE) * 3) - 2, '-01'), '%Y-%m-%d')
return func.str_to_date(
func.concat(
func.year(column), # 2018
"-", # 2018-
(func.quarter(column) * 3) - 2, # 2018-4
"-01", # 2018-4-01
),
"%Y-%m-%d",
)
else:
return func.date_format(column, format)
class Functions:
@classmethod
def apply(cls, function, *args):
if function == "now":
return func.now()
if function == "today":
return func.date(func.now())
if function == "sql":
assert isinstance(args[0], str)
return text(args[0])
if function == "abs":
return func.abs(args[0])
if function == "floor":
return func.floor(args[0])
if function == "lower":
return func.lower(args[0])
if function == "upper":
return func.upper(args[0])
if function == "ceil":
return func.ceil(args[0])
if function == "round":
return func.round(args[0])
if function == "is_set":
return args[0].isnot(None)
if function == "is_not_set":
return args[0].is_(None)
if function == "count_if":
return func.sum(case((args[0], 1), else_=0))
if function == "distinct":
return distinct(args[0])
if function == "distinct_count":
return func.count(distinct(args[0]))
if function == "in_":
# args = [column, value1, value2, ...]
return args[0].in_(args[1:])
if function == "not_in":
# args = [column, value1, value2, ...]
return args[0].notin_(args[1:])
if function == "contains":
return args[0].like("%" + args[1] + "%")
if function == "not_contains":
return ~args[0].like("%" + args[1] + "%")
if function == "ends_with":
return args[0].like("%" + args[1])
if function == "starts_with":
return args[0].like(args[1] + "%")
if function == "if_null":
return func.ifnull(args[0], args[1])
if function == "sum_if":
return func.sum(case((args[0], args[1]), else_=0))
if function == "between":
dates = add_start_and_end_time([args[1], args[2]])
return args[0].between(*dates)
if function == "replace":
return func.replace(args[0], args[1], args[2])
if function == "substring":
return func.substring(args[0], args[1], args[2])
if function == "concat":
return func.concat(*args)
if function == "coalesce":
return func.coalesce(*args)
if function == "case":
_args = list(args)
if len(_args) % 2 == 0:
raise Exception("Case function requires an odd number of arguments")
default = _args.pop()
conditions = []
for i in range(0, len(_args), 2):
conditions.append((_args[i], _args[i + 1]))
# return case(conditions, else_=default)
return case(*conditions, else_=default)
if function == "timespan":
return handle_timespan(args[0], args[1])
if function == "time_elapsed":
VALID_UNITS = [
"MICROSECOND",
"SECOND",
"MINUTE",
"HOUR",
"DAY",
"WEEK",
"MONTH",
"QUARTER",
"YEAR",
]
unit = args[0].upper()
if unit not in VALID_UNITS:
raise Exception(
f"Invalid unit {unit}. Valid units are {', '.join(VALID_UNITS)}"
)
return func.timestampdiff(text(unit), args[1], args[2])
if function == "descendants":
node = args[0] # "India"
tree = args[1] # "territory"
field = args[2] # salesorder.territory
query = get_descendants(node, tree, include_self=False)
return field.in_(query)
if function == "descendants_and_self":
node = args[0] # "India"
tree = args[1] # "territory"
field = args[2] # salesorder.territory
query = get_descendants(node, tree, include_self=True)
return field.in_(query)
if function == "date_format":
return ColumnFormatter.format_date(args[1], args[0])
if function == "start_of":
valid_units = ["day", "week", "month", "quarter", "year"]
unit = args[0].lower()
if unit not in valid_units:
raise Exception(
f"Invalid unit {unit}. Valid units are {', '.join(valid_units)}"
)
return ColumnFormatter.format_date(args[0].title(), args[1])
raise NotImplementedError(f"Function {function} not implemented")
def handle_timespan(column, timespan):
if isinstance(timespan, list):
timespan = " ".join(timespan)
timespan = timespan.lower() # "last 7 days"
timespan = timespan[:-1] if timespan.endswith("s") else timespan # "last 7 day"
units = [
"day",
"week",
"month",
"quarter",
"year",
"fiscal year",
]
if not any(timespan.endswith(unit) for unit in units):
raise Exception(f"Invalid timespan unit - {timespan}")
dates = get_date_range(timespan)
if not dates:
raise Exception(f"Invalid timespan {timespan}")
dates_str = add_start_and_end_time(dates)
return column.between(*dates_str)
def get_descendants(node, tree, include_self=False):
Tree = table(tree, sa_column("lft"), sa_column("rgt"), sa_column("name"))
lft_rgt = select(Tree.c.lft, Tree.c.rgt).where(Tree.c.name == node).alias("lft_rgt")
return (
(
select(Tree.c.name)
.where(Tree.c.lft > lft_rgt.c.lft)
.where(Tree.c.rgt < lft_rgt.c.rgt)
)
if not include_self
else (
select(Tree.c.name)
.where(Tree.c.lft >= lft_rgt.c.lft)
.where(Tree.c.rgt <= lft_rgt.c.rgt)
)
)
def get_current_date_range(unit):
today = nowdate()
if unit == "day":
return [today, today]
if unit == "week":
return [get_first_day_of_week(today), get_last_day_of_week(today)]
if unit == "month":
return [get_first_day(today), get_last_day(today)]
if unit == "quarter":
return [get_quarter_start(today), get_quarter_ending(today)]
if unit == "year":
return [get_year_start(today), get_year_ending(today)]
if unit == "fiscal year":
return [get_fy_start(today), get_fiscal_year_ending(today)]
def get_fiscal_year_start_date():
fiscal_year_start = frappe.db.get_single_value(
"Insights Settings", "fiscal_year_start"
)
if not fiscal_year_start or get_date_str(fiscal_year_start) == "0001-01-01":
return getdate("1995-04-01")
return getdate(fiscal_year_start)
def get_fy_start(date):
fy_start = get_fiscal_year_start_date()
dt = getdate(date) # eg. 2019-01-01
if dt.month < fy_start.month:
return getdate(
f"{dt.year - 1}-{fy_start.month}-{fy_start.day}"
) # eg. 2018-04-01
return getdate(f"{dt.year}-{fy_start.month}-{fy_start.day}") # eg. 2019-04-01
def get_fiscal_year_ending(date):
fy_start = get_fiscal_year_start_date()
fy_end = add_to_date(fy_start, years=1, days=-1)
dt = getdate(date) # eg. 2019-04-01
if dt.month < fy_start.month:
return getdate(f"{dt.year}-{fy_end.month}-{fy_end.day}") # eg. 2018-03-31
return getdate(f"{dt.year + 1}-{fy_end.month}-{fy_end.day}") # eg. 2019-03-31
def get_directional_date_range(direction, unit, number_of_unit):
dates = []
today = nowdate()
if unit == "day":
dates = [
add_to_date(today, days=direction * number_of_unit),
add_to_date(today, days=direction),
]
if unit == "week":
dates = [
get_first_day_of_week(
add_to_date(today, days=direction * 7 * number_of_unit)
),
get_last_day_of_week(add_to_date(today, days=direction * 7)),
]
if unit == "month":
dates = [
get_first_day(add_to_date(today, months=direction * number_of_unit)),
get_last_day(add_to_date(today, months=direction)),
]
if unit == "quarter":
dates = [
get_quarter_start(
add_to_date(today, months=direction * 3 * number_of_unit)
),
get_quarter_ending(add_to_date(today, months=direction * 3)),
]
if unit == "year":
dates = [
get_year_start(add_to_date(today, years=direction * number_of_unit)),
get_year_ending(add_to_date(today, years=direction)),
]
if unit == "fiscal year":
dates = [
get_fy_start(add_to_date(today, years=direction * number_of_unit)),
get_fiscal_year_ending(add_to_date(today, years=direction)),
]
if isinstance(dates[0], str):
dates[0] = getdate(dates[0])
if isinstance(dates[1], str):
dates[1] = getdate(dates[1])
if dates[0] > dates[1]:
dates.reverse()
return dates
def get_date_range(timespan, include_current=False):
# timespan = "last 7 days" or "next 3 months"
time_direction = timespan.lower().split(" ")[0] # "last" or "next" or "current"
# "day", "week", "month", "quarter", "year", "fiscal year"
if "fiscal year" in timespan.lower():
unit = "fiscal year"
else:
unit = timespan.lower().split(" ")[-1]
if time_direction == "current":
return get_current_date_range(unit)
number_of_unit = int(timespan.split(" ")[1]) # 7, 3, etc
if time_direction == "last" or time_direction == "next":
time_direction = -1 if time_direction == "last" else 1
dates = get_directional_date_range(time_direction, unit, number_of_unit)
if include_current:
current_dates = get_current_date_range(unit)
dates[0] = min(dates[0], current_dates[0])
dates[1] = max(dates[1], current_dates[1])
return dates
def add_start_and_end_time(dates):
if not dates:
return dates
if type(dates[0]) == str:
return [dates[0] + " 00:00:00", dates[1] + " 23:59:59"]
if type(dates[0]) == datetime or type(dates[0]) == date:
return [
dates[0].strftime("%Y-%m-%d 00:00:00"),
dates[1].strftime("%Y-%m-%d 23:59:59"),
]
class BinaryOperations:
ARITHMETIC_OPERATIONS = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
}
COMPARE_OPERATIONS = {
"=": operator.eq,
"!=": operator.ne,
"<": operator.lt,
">": operator.gt,
"<=": operator.le,
">=": operator.ge,
}
LOGICAL_OPERATIONS = {
"&&": lambda a, b: and_(a, b),
"||": lambda a, b: or_(a, b),
}
@classmethod
def get_operation(cls, operator):
if operator in cls.ARITHMETIC_OPERATIONS:
return cls.ARITHMETIC_OPERATIONS[operator]
if operator in cls.COMPARE_OPERATIONS:
return cls.COMPARE_OPERATIONS[operator]
if operator in cls.LOGICAL_OPERATIONS:
return cls.LOGICAL_OPERATIONS[operator]
raise NotImplementedError(f"Operation {operator} not implemented")
@classmethod
def is_binary_operator(cls, operator):
return (
operator in cls.ARITHMETIC_OPERATIONS
or operator in cls.COMPARE_OPERATIONS
or operator in cls.LOGICAL_OPERATIONS
)
def get_eval_globals():
function_list = [
"now",
"today",
"sql",
"abs",
"floor",
"lower",
"upper",
"ceil",
"round",
"is_set",
"is_not_set",
"count_if",
"distinct",
"distinct_count",
"in_",
"not_in",
"contains",
"not_contains",
"ends_with",
"starts_with",
"if_null",
"sum_if",
"between",
"replace",
"concat",
"coalesce",
"case",
"timespan",
"time_elapsed",
"descendants",
"descendants_and_self",
"date_format",
"start_of",
"substring",
"sum",
"min",
"max",
"avg",
"count",
"distinct",
"distinct_count",
"and_",
"or_",
]
eval_globals = {}
for fn in function_list:
eval_globals[fn] = lambda *args, fn=fn: call_function(fn, *args)
return eval_globals
def call_function(function, *args):
if not function:
return None
if function == "and_":
return and_(*args)
if function == "or_":
return or_(*args)
with suppress(NotImplementedError):
_func = "in_" if function == "in" else function
return Functions.apply(_func, *args)
if len(args) <= 2:
with suppress(NotImplementedError):
return Aggregations.apply(function, *args)
raise NotImplementedError(f"Function {function} not implemented")
|
2302_79757062/insights
|
insights/insights/query_builders/sql_functions.py
|
Python
|
agpl-3.0
| 17,186
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from sqlalchemy import Column
from sqlalchemy.sql import func
from ..sql_builder import ColumnFormatter, Functions, SQLQueryBuilder
class SQLiteColumnFormatter(ColumnFormatter):
@classmethod
def format_date(cls, format, column: Column):
if format == "Minute":
return func.strftime("%Y-%m-%d %H:%M:00", column)
if format == "Hour":
return func.strftime("%Y-%m-%d %H:00", column)
if format == "Day" or format == "Day Short":
return func.strftime("%Y-%m-%d 00:00", column)
if format == "Week":
date = func.strftime("%Y-%m-%d", column)
return func.date(date, "-1 day", "weekday 0")
if format == "Month" or format == "Mon":
return func.strftime("%Y-%m-01", column)
if format == "Year":
return func.strftime("%Y-01-01", column)
if format == "Minute of Hour":
return func.strftime("00:%M", column)
if format == "Hour of Day":
return func.strftime("%H:00", column)
if format == "Day of Week":
return func.strftime("%w", column)
if format == "Day of Month":
return func.strftime("%d", column)
if format == "Day of Year":
return func.strftime("%j", column)
if format == "Month of Year":
return func.strftime("%m", column)
if format == "Quarter of Year":
month = func.strftime("%m", column)
return ((month - 1) / 3) + 1
if format == "Quarter":
date = func.strftime("%Y-%m-01", column)
month = func.strftime("%m", column)
# DATE(date, ('-' || (month - 1) % 3 || ' months'))
return func.date(
date,
("-" + func.mod((month - 1), 3) + " months"),
)
else:
return func.strftime(format, column)
return column
class SQLiteFunctions(Functions):
@classmethod
def apply(cls, function, *args):
if function == "floor":
return func.round(args[0] - 0.5)
if function == "ceil":
return func.round(args[0] + 0.5)
if function == "concat":
from functools import reduce
return reduce(lambda x, y: x + y, args)
if function == "time_elapsed":
VALID_UNITS = [
"MICROSECOND",
"SECOND",
"MINUTE",
"HOUR",
"DAY",
"WEEK",
"MONTH",
"QUARTER",
"YEAR",
]
unit = args[0].upper()
if unit not in VALID_UNITS:
raise Exception(
f"Invalid unit {unit}. Valid units are {', '.join(VALID_UNITS)}"
)
day_diff = func.julianday(args[1]) - func.julianday(args[2])
if unit == "MICROSECOND":
return day_diff * 86400000000
if unit == "SECOND":
return day_diff * 86400
if unit == "MINUTE":
return day_diff * 1440
if unit == "HOUR":
return day_diff * 24
if unit == "DAY":
return day_diff
if unit == "WEEK":
return day_diff / 7
if unit == "MONTH":
return day_diff / 30
if unit == "QUARTER":
return day_diff / 90
if unit == "YEAR":
return day_diff / 365
if function == "date_format":
return SQLiteColumnFormatter.format_date(args[1], args[0])
if function == "start_of":
valid_units = ["day", "week", "month", "quarter", "year"]
unit = args[0].lower()
if unit not in valid_units:
raise Exception(
f"Invalid unit {unit}. Valid units are {', '.join(valid_units)}"
)
return SQLiteColumnFormatter.format_date(args[0].title(), args[1])
if function == "today":
return func.date()
return super().apply(function, *args)
class SQLiteQueryBuilder(SQLQueryBuilder):
def __init__(self, engine):
super().__init__(engine)
self.engine = engine
self.functions = SQLiteFunctions
self.column_formatter = SQLiteColumnFormatter
|
2302_79757062/insights
|
insights/insights/query_builders/sqlite/sqlite_query_builder.py
|
Python
|
agpl-3.0
| 4,494
|
import ast
import re
class AndOrReplacer(ast.NodeTransformer):
"""
AST Node Transformer to replace 'and' and 'or' with 'and_(...)' and 'or_(...)' respectively.
"""
def visit_BoolOp(self, node):
# First, visit all children nodes
self.generic_visit(node)
# Check if the node is 'and' or 'or' type
if isinstance(node.op, (ast.And, ast.Or)):
return self._create_new_node(node)
return node
def _create_new_node(self, node):
"""
Create a new node with 'and_' or 'or_' function call.
"""
new_values = [self.visit(value) for value in node.values]
fn_name = "and_" if isinstance(node.op, ast.And) else "or_"
while len(new_values) > 1:
left, right = new_values[:2]
new_values = [self._create_call_node(fn_name, left, right)] + new_values[2:]
return new_values[0]
def _create_call_node(self, fn_name, left, right):
"""
Helper method to create an ast.Call node.
"""
return ast.Call(
func=ast.Name(id=fn_name, ctx=ast.Load()), args=[left, right], keywords=[]
)
def replace_and_or_expressions(source_code):
"""
Replace 'and' with 'and_' and 'or' with 'or_' in the given source code.
"""
tree = ast.parse(source_code)
modified_tree = AndOrReplacer().visit(tree)
return ast.unparse(modified_tree)
def replace_equals_with_double_equals(code):
code = code.replace("=", "==")
code = code.replace("===", "==")
code = code.replace("!==", "!=")
code = code.replace(">==", ">=")
code = code.replace("<==", "<=")
return code
def replace_column_names(raw_expression):
# all the columns are referred as `table_name.column_name`
# we need to replace them with column(table_name, column_name)
# so that we can use them in frappe.safe_eval
# eg. `tabSales Order.name` -> column("tabSales Order", "name")
# we have to make sure this doesn't replaces `tabSales Order`.`name` with `column("tabSales Order", "name")`
# match only `xxx.xxx` and not `xxx`.`xxx`
# where x can be any character except `
match_pattern = r"`([^\`]+)\.([^\`]+)`"
matches = re.findall(match_pattern, raw_expression)
for match in matches:
raw_expression = raw_expression.replace(
f"`{match[0]}.{match[1]}`", f'column("{match[0]}", "{match[1]}")'
)
return raw_expression
def process_raw_expression(raw_expression):
# replace `=` with `==` without affecting other operators
raw_expression = replace_equals_with_double_equals(raw_expression)
# replace column names with column function
# eg. `tabSales Order.name` -> column("tabSales Order", "name")
raw_expression = replace_column_names(raw_expression)
# replace `in()` with `in_()`
regex = r"in\s*\("
raw_expression = re.sub(regex, "in_(", raw_expression)
# the above regex also replaces `not_in()` with `not_in_()` which is not required
# so we replace `not_in_()` with `not_in()` again
raw_expression = raw_expression.replace("not_in_(", "not_in(")
raw_expression = raw_expression.replace("&&", " and ")
raw_expression = raw_expression.replace("||", " or ")
raw_expression = replace_and_or_expressions(raw_expression)
return raw_expression
|
2302_79757062/insights
|
insights/insights/query_builders/utils.py
|
Python
|
agpl-3.0
| 3,339
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
# import frappe
def after_migrate():
pass
|
2302_79757062/insights
|
insights/migrate.py
|
Python
|
agpl-3.0
| 137
|
from json import dumps
import click
import frappe
def execute():
if not frappe.db.a_row_exists("Insights Query"):
return
queries = frappe.get_all("Insights Query", pluck="name")
for query in queries:
try:
doc = frappe.get_doc("Insights Query", query)
results = frappe.parse_json(doc.results)
if not results or "::" in str(results[0][0]):
continue
columns = [f"{c.label or c.column}::{c.type}" for c in doc.get_columns()]
results.insert(0, columns)
frappe.db.set_value(
"Insights Query", query, "result", dumps(results), update_modified=False
)
frappe.db.commit()
except Exception:
frappe.db.rollback()
frappe.log_error(title="Error while adding column row for - " + query)
click.secho("Error while adding column row for - " + query, fg="red")
|
2302_79757062/insights
|
insights/patches/add_column_row_to_result.py
|
Python
|
agpl-3.0
| 947
|
import frappe
def execute():
if not frappe.db.a_row_exists("Insights Query"):
return
Query = frappe.qb.DocType("Insights Query")
frappe.qb.update(Query).set(Query.last_execution, Query.modified).run()
|
2302_79757062/insights
|
insights/patches/add_last_execution_field.py
|
Python
|
agpl-3.0
| 224
|
import json
import frappe
from frappe.utils import cstr
def execute():
if not frappe.db.a_row_exists("Insights Query"):
return
queries = frappe.get_all("Insights Query", fields=["name", "filters"])
for query in queries:
_filters = json.loads(query.get("filters"))
set_default_position(_filters)
_filters = json.dumps(_filters, indent=2, default=cstr)
frappe.db.set_value(
"Query", query.get("name"), "filters", _filters, update_modified=False
)
def set_default_position(filters):
if "conditions" not in filters:
return
filters["position"] = filters.get("position") or 1
for condition in filters.get("conditions"):
set_default_position(condition)
|
2302_79757062/insights
|
insights/patches/add_position_key_to_filter.py
|
Python
|
agpl-3.0
| 754
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from insights.setup import create_roles
def execute():
create_roles()
|
2302_79757062/insights
|
insights/patches/add_roles.py
|
Python
|
agpl-3.0
| 196
|
import frappe
def execute():
if not frappe.db.a_row_exists("Insights Query"):
return
Query = frappe.qb.DocType("Insights Query")
frappe.qb.update(Query).set(Query.execution_time, 0).run()
|
2302_79757062/insights
|
insights/patches/convert_duration_to_float.py
|
Python
|
agpl-3.0
| 211
|
import frappe
def execute():
if not frappe.db.a_row_exists("Insights Query"):
return
if not frappe.db.exists("Insights Data Source", "Query Store"):
frappe.get_doc(
{
"status": "Active",
"name": "Query Store",
"title": "Query Store",
"database_type": "MariaDB",
"doctype": "Insights Data Source",
"modified": "2022-01-01 00:01:00.000000",
"creation": "2022-01-01 00:01:00.000000",
}
).insert()
for query_name in frappe.get_all("Insights Query", pluck="name"):
query = frappe.get_doc("Insights Query", query_name)
query.update_query_table()
|
2302_79757062/insights
|
insights/patches/create_query_tables.py
|
Python
|
agpl-3.0
| 732
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
def execute():
# when the doctype Query was renamed, the options like "Permission Query" in Server Script was renamed to "Permission Insights Query"
# this patch fixes the options in the docfields
frappe.db.sql(
"update `tabDocField` set `options` = replace(`options`, 'Insights ', '') where fieldtype = 'Select' and options like '%Insights %'"
)
frappe.db.sql(
"update `tabCustom Field` set `options` = replace(`options`, 'Insights ', '') where fieldtype = 'Select' and options like '%Insights %'"
)
frappe.db.sql(
"update `tabProperty Setter` set `value` = replace(`value`, 'Insights ', '') where property = 'options' and value like '%Insights %'"
)
|
2302_79757062/insights
|
insights/patches/fix_select_options_after_rename.py
|
Python
|
agpl-3.0
| 845
|
import frappe
def execute():
if not frappe.db.a_row_exists("Insights Dashboard Item"):
return
dashboard_items = frappe.get_all(
"Insights Dashboard Item",
filters={"item_type": "Chart"},
fields=["chart", "parent", "chart_filters"],
)
filters_by_filter_name = {}
for chart_item in dashboard_items:
chart_filters = frappe.parse_json(chart_item.chart_filters) or []
for chart_filter in chart_filters:
chart_filter = frappe._dict(chart_filter)
filter_item_name = frappe.db.get_value(
"Insights Dashboard Item",
{
"parent": chart_item.parent,
"item_type": "Filter",
"filter_label": chart_filter.filter.get("label"),
},
"name",
)
if not filter_item_name:
continue
filters_by_filter_name.setdefault(filter_item_name, {})
filters_by_filter_name[filter_item_name].setdefault(
chart_item.chart,
{
"label": chart_filter.column.get("label"),
"table": chart_filter.column.get("value").split(".")[0],
"column": chart_filter.column.get("value").split(".")[1],
"value": chart_filter.column.get("value"),
},
)
for filter_name, filter_value in filters_by_filter_name.items():
frappe.db.set_value(
"Insights Dashboard Item",
filter_name,
"filter_links",
frappe.as_json(filter_value),
)
# update chart_title field in Insights Dashboard Item if chart is set
# set as title of Insights Query Chart with name = chart
frappe.db.sql(
"""
UPDATE `tabInsights Dashboard Item`
SET chart_title = (
SELECT title
FROM `tabInsights Query Chart`
WHERE name = chart
)
WHERE item_type = 'Chart'
AND chart IS NOT NULL
AND chart != ''
"""
)
|
2302_79757062/insights
|
insights/patches/make_filter_links.py
|
Python
|
agpl-3.0
| 2,110
|
import click
import frappe
def execute():
if not frappe.db.a_row_exists("Insights Query"):
return
for query in frappe.get_all("Insights Query", pluck="name"):
try:
frappe.get_doc("Insights Query", query).update_insights_table()
except Exception as e:
click.secho(f"Failed to create table for {query}: {e}", fg="orange")
|
2302_79757062/insights
|
insights/patches/make_query_tables.py
|
Python
|
agpl-3.0
| 379
|
import frappe
def execute():
if not frappe.db.a_row_exists("Insights Dashboard Item"):
return
frappe.db.sql(
"""
UPDATE
`tabInsights Dashboard Item`
SET
`item_type` = 'Chart',
`chart` = `query_chart`
WHERE
`item_type` IS NULL
OR `item_type` = ''
"""
)
|
2302_79757062/insights
|
insights/patches/migrate_dashboard_charts.py
|
Python
|
agpl-3.0
| 375
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import math
from json import dumps
import frappe
def execute():
DASHBOARD_ITEM = "Insights Dashboard Item"
layouts = frappe.get_all(DASHBOARD_ITEM, fields=["name", "layout"])
for row in layouts:
layout = frappe.parse_json(row.layout or {})
new_layout = dumps({"w": 4, "h": 4}, indent=2)
if layout.width or layout.height:
new_layout = update_width_height(layout)
frappe.db.set_value(
DASHBOARD_ITEM,
row.name,
"layout",
new_layout,
update_modified=False,
)
def update_width_height(layout):
COL_WIDTH = 55
ROW_HEIGHT = 30
if layout.width:
layout.w = math.ceil(int(layout.width) / COL_WIDTH)
del layout["width"]
if layout.height:
layout.h = math.ceil(int(layout.height) / ROW_HEIGHT)
del layout["height"]
return dumps(layout, indent=2)
|
2302_79757062/insights
|
insights/patches/modify_dashboard_layout.py
|
Python
|
agpl-3.0
| 1,036
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
def execute():
if not frappe.db.a_row_exists("Insights Query Table"):
return
QueryTable = frappe.qb.DocType("Insights Query Table")
query = (
frappe.qb.from_(QueryTable)
.select(QueryTable.join, QueryTable.name)
.where(QueryTable.join.like("%condition%"))
)
tables = query.run(as_dict=True)
for table in tables:
join = frappe.parse_json(table.join)
if join.get("condition"):
condition = join.get("condition").get("value")
if not condition:
continue
left = condition.split("=")[0].strip()
right = condition.split("=")[1].strip()
if not left or not right:
continue
join["condition"] = {
"left": {
"value": left,
"label": left,
},
"right": {
"value": right,
"label": right,
},
}
frappe.db.set_value(
"Insights Query Table", table.name, "join", frappe.as_json(join)
)
|
2302_79757062/insights
|
insights/patches/modify_join_condition.py
|
Python
|
agpl-3.0
| 1,274
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import click
import frappe
def execute():
dashboards = frappe.get_all(
"Insights Dashboard Item", filters={"item_type": "Filter"}, pluck="parent"
)
for dashboard in dashboards:
try:
doc = frappe.get_doc("Insights Dashboard", dashboard)
chart = [item for item in doc.items if item.item_type == "Chart"][0]
data_source = frappe.db.get_value(
"Insights Query", chart.query, "data_source"
)
modified = False
for item in doc.items:
if item.item_type == "Filter":
filter_links = frappe.parse_json(item.filter_links)
filter_column = list(filter_links.values())[0]
filter_column["data_source"] = data_source
item.filter_column = frappe.as_json(filter_column)
modified = True
if modified:
doc.save()
except Exception:
click.secho(f"Error in dashboard {dashboard}", fg="red")
|
2302_79757062/insights
|
insights/patches/refactor_dashboard_filter.py
|
Python
|
agpl-3.0
| 1,168
|
import random
import click
import frappe
def execute():
if not frappe.db.exists("DocType", "Insights Query Chart"):
return
"""
Each Dashboard Item had a link to Chart record, which stores the query and chart config.
This patch moves the query and chart config to the Dashboard Item record.
It also replaces `markdown`, `filter_column`, `filter_links` and `filter_label`
with single JSON field called `options`.
"""
for item_name in frappe.get_all("Insights Dashboard Item", pluck="name"):
try:
item = frappe.get_doc("Insights Dashboard Item", item_name)
if item.item_id and frappe.parse_json(item.options):
continue
item.item_id = random.randint(1, 999999)
new_options = {}
if item.item_type == "Text":
new_options = {"markdown": item.markdown}
if item.chart:
chart = frappe.get_doc("Insights Query Chart", item.chart)
old_config = frappe.parse_json(chart.config)
old_options = old_config.get("options", {})
if chart.type == "Number":
item.item_type = "Number"
new_options = {
"query": item.query,
"title": chart.title,
"column": old_config.get("valueColumn", {}).get("label"),
"suffix": old_options.get("suffix"),
"prefix": old_options.get("prefix"),
"decimals": old_options.get("decimals"),
}
elif chart.type == "Progress":
item.item_type = "Progress"
targetType = old_config.get("targetType")
target = (
old_config.get("target", {}).get("label")
if targetType == "Column"
else old_config.get("target")
)
new_options = {
"query": item.query,
"title": chart.title,
"suffix": old_options.get("suffix"),
"prefix": old_options.get("prefix"),
"decimals": old_options.get("decimals"),
"target": target,
"targetType": targetType,
"progress": old_config.get("progressColumn", {}).get("label"),
"shorten": old_options.get("shorten"),
}
elif chart.type == "Bar":
item.item_type = "Bar"
new_options = {
"query": item.query,
"title": chart.title,
"xAxis": old_config.get("labelColumn", {}).get("label"),
"yAxis": [v["label"] for v in old_config.get("valueColumn")],
"referenceLine": old_options.get("referenceLine", {}).get(
"label"
),
"colors": old_options.get("colors"),
"rotateLabels": old_options.get("rotateLabels"),
"stack": old_options.get("stack"),
"invertAxis": old_options.get("invertAxis"),
}
elif chart.type == "Line":
item.item_type = "Line"
new_options = {
"query": item.query,
"title": chart.title,
"xAxis": old_config.get("labelColumn", {}).get("label"),
"yAxis": [v["label"] for v in old_config.get("valueColumn")],
"referenceLine": old_options.get("referenceLine", {}).get(
"label"
),
"colors": old_options.get("colors"),
"smoothLines": old_options.get("smoothLines"),
"showPoints": old_options.get("showPoints"),
}
elif chart.type == "Pie":
item.item_type = "Pie"
new_options = {
"query": item.query,
"title": chart.title,
"xAxis": old_config.get("labelColumn", {}).get("label"),
"yAxis": old_config.get("valueColumn", {}).get("label"),
"maxSlices": old_options.get("maxSlices"),
"colors": old_options.get("colors"),
"labelPosition": old_options.get("labelPosition", {}).get(
"label"
),
"inlineLabels": old_options.get("inlineLabels"),
"scrollLabels": old_options.get("scrollLabels"),
}
elif chart.type == "Table":
item.item_type = "Table"
new_options = {
"query": item.query,
"title": chart.title,
"columns": [v["label"] for v in old_config.get("columns")],
"index": old_options.get("index"),
"showTotal": old_options.get("showTotal"),
}
# remove falsy values from options
new_options = {k: v for k, v in new_options.items() if v}
item.options = new_options
item.item_type = item.item_type or "Bar"
item.db_update()
except Exception as e:
click.secho(f"Error at {item_name}: {e}", fg="red")
frappe.log_error(title="Error in Insights Patch: Refactor Dashboard Item")
finally:
frappe.db.commit()
item_id_by_chart_name = {
item.chart: item.item_id
for item in frappe.get_all(
"Insights Dashboard Item",
filters={"chart": ["is", "set"]},
fields=["chart", "item_id"],
)
}
for item_name in frappe.get_all(
"Insights Dashboard Item", {"item_type": "Filter"}, pluck="name"
):
try:
item = frappe.get_doc("Insights Dashboard Item", item_name)
if item.item_id and frappe.parse_json(item.options):
continue
filter_column = frappe.parse_json(item.filter_column)
filter_links = frappe.parse_json(item.filter_links)
new_filter_links = {}
if filter_links:
filtered_charts = filter_links.keys()
for chart_name in filtered_charts:
if chart_name not in item_id_by_chart_name:
click.secho(f"Chart {chart_name} not found", fg="red")
continue
new_filter_links[item_id_by_chart_name[chart_name]] = filter_links[
chart_name
]
new_options = {
"label": item.filter_label,
"column": filter_column,
"links": new_filter_links,
}
item.options = new_options
item.db_update()
except Exception as e:
click.secho(f"Error at {item_name}: {e}", fg="red")
frappe.log_error(title="Error in Insights Patch: Refactor Dashboard Item")
finally:
frappe.db.commit()
|
2302_79757062/insights
|
insights/patches/refactor_dashboard_item.py
|
Python
|
agpl-3.0
| 7,496
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import click
import frappe
def execute():
# demo data is now merged with site db
Tables = frappe.qb.DocType("Insights Table")
(
frappe.qb.update(Tables)
.set(Tables.data_source, "Site DB")
.where(Tables.data_source == "Demo Data")
.run()
)
Query = frappe.qb.DocType("Insights Query")
(
frappe.qb.update(Query)
.set(Query.data_source, "Site DB")
.where(Query.data_source == "Demo Data")
.run()
)
frappe.delete_doc("Insights Data Source", "Demo Data")
if not frappe.db.exists("Insights Data Source", "Site DB"):
site_db = frappe.new_doc("Insights Data Source")
site_db.title = "Site DB"
site_db.is_site_db = 1
site_db.save()
else:
site_db = frappe.get_doc("Insights Data Source", "Site DB")
site_db.sync_tables()
site_db.save()
|
2302_79757062/insights
|
insights/patches/refresh_tables.py
|
Python
|
agpl-3.0
| 1,001
|
import frappe
def execute():
if not frappe.db.a_row_exists("Insights Query Column"):
return
QueryColumn = frappe.qb.DocType("Insights Query Column")
replace_map = {
"Varchar": "String",
"Int": "Integer",
"Float": "Decimal",
"Timestamp": "Datetime",
"Longtext": "Text",
}
for old, new in replace_map.items():
(
frappe.qb.update(QueryColumn)
.set(QueryColumn.type, new)
.where(QueryColumn.type == old)
.run()
)
|
2302_79757062/insights
|
insights/patches/rename_column_type.py
|
Python
|
agpl-3.0
| 544
|
import frappe
from pypika import Criterion
def execute():
if not frappe.db.a_row_exists("Insights Query"):
return
frappe.db.sql(
"""
UPDATE
`tabInsights Query Column`
SET
`column` = '*'
WHERE
`column` = '__count' OR `column` = 'count'
"""
)
|
2302_79757062/insights
|
insights/patches/rename_count_column_name.py
|
Python
|
agpl-3.0
| 340
|
import frappe
def execute():
Chart = frappe.qb.DocType("Insights Query Chart")
frappe.qb.update(Chart).set(Chart.config, Chart.data).run()
|
2302_79757062/insights
|
insights/patches/rename_data_to_config.py
|
Python
|
agpl-3.0
| 149
|
import click
import frappe
def execute():
rename_map = {
"Query": "Insights Query",
"Table": "Insights Table",
"Table Link": "Insights Table Link",
"Query Visualization": "Insights Query Chart",
"Data Source": "Insights Data Source",
"Query Table": "Insights Query Table",
"Query Column": "Insights Query Column",
}
for oldname, newname in rename_map.items():
if frappe.db.exists("DocType", {"module": "Insights", "name": oldname}):
try:
frappe.rename_doc("DocType", oldname, newname, force=True)
except Exception as e:
frappe.log_error(title=f"Insights: Error renaming DocType {oldname}")
click.echo(
f"Error renaming {oldname} to {newname}: {str(e)}", color="orange"
)
|
2302_79757062/insights
|
insights/patches/rename_doctypes.py
|
Python
|
agpl-3.0
| 857
|
import frappe
def execute():
if not frappe.db.a_row_exists("Insights Query"):
return
queries = frappe.get_all("Insights Query", fields=["name", "filters"])
for query in queries:
new_filter = query.filters.replace("like", "contains")
frappe.db.set_value(
"Query", query.name, "filters", new_filter, update_modified=False
)
|
2302_79757062/insights
|
insights/patches/rename_like_to_contains.py
|
Python
|
agpl-3.0
| 382
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import click
import frappe
def execute():
for chart in frappe.get_all(
"Insights Query Chart",
filters={"config": ("like", "%targetColumn%")},
fields=["name", "config"],
):
try:
chart_doc = frappe.get_doc("Insights Query Chart", chart.name)
config = frappe.parse_json(chart_doc.config)
config.target = config.targetColumn
config.targetType = "Column"
del config.targetColumn
chart_doc.config = frappe.as_json(config)
chart_doc.save()
except Exception:
click.secho(f"Failed to update {chart.name}", fg="red")
frappe.log_error(title="Insights: Failed to update chart")
|
2302_79757062/insights
|
insights/patches/rename_target_column_field.py
|
Python
|
agpl-3.0
| 844
|
import frappe
from frappe.model.utils.rename_field import rename_field
def execute():
try:
rename_field("Insights Dashboard Item", "visualization", "query_chart")
InsightsDashboardItem = frappe.qb.DocType("Insights Dashboard Item")
(
frappe.qb.update(InsightsDashboardItem)
.set(InsightsDashboardItem.parentfield, "items")
.where(InsightsDashboardItem.parentfield == "visualizations")
.run()
)
except Exception as e:
if e.args[0] != 1054:
raise
|
2302_79757062/insights
|
insights/patches/rename_visualization.py
|
Python
|
agpl-3.0
| 556
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from insights.setup.demo import DemoDataFactory
def execute():
factory = DemoDataFactory().run(force=True)
if not factory.demo_data_exists():
frappe.throw("Demo data not imported")
demo_tables = [
"Customers",
"Geolocation",
"OrderItems",
"OrderPayments",
"OrderReviews",
"Orders",
"Products",
"Sellers",
]
InsightsTable = frappe.qb.DocType("Insights Table")
(
frappe.qb.update(InsightsTable)
.set(InsightsTable.data_source, "Demo Data")
.where(InsightsTable.name.isin(demo_tables))
.run()
)
InsightsQuery = frappe.qb.DocType("Insights Query")
InsightsQueryTable = frappe.qb.DocType("Insights Query Table")
queries = (
frappe.qb.from_(InsightsQuery)
.join(InsightsQueryTable)
.on(InsightsQuery.name == InsightsQueryTable.parent)
.select(InsightsQuery.name)
.distinct()
.where(InsightsQueryTable.table.isin(demo_tables))
.run(pluck="name")
)
if queries:
(
frappe.qb.update(InsightsQuery)
.set(InsightsQuery.data_source, "Demo Data")
.where(InsightsQuery.name.isin(queries))
.run()
)
|
2302_79757062/insights
|
insights/patches/replace_demo_data_source.py
|
Python
|
agpl-3.0
| 1,396
|
import frappe
def execute():
if not frappe.db.a_row_exists("Insights Query Transform"):
return
transforms = frappe.get_all(
"Insights Query Transform",
filters={"type": "Pivot", "options": ["is", "set"]},
fields=["name", "options", "parent"],
)
for transform in transforms:
options = frappe.parse_json(transform.options)
new_options = {}
# options.key = InsightsQueryColumn.column
# since InsightsQueryColumn.label is the unique identifier so
# that should be used instead of InsightsQueryColumn.column
for key in ["column", "index", "value"]:
# get the column name from the label
column_label = frappe.db.get_value(
"Insights Query Column",
{"column": options.get(key), "parent": transform.parent},
"label",
)
if column_label:
new_options[key] = column_label
frappe.db.set_value(
"Insights Query Transform",
transform.name,
"options",
frappe.as_json(new_options),
)
|
2302_79757062/insights
|
insights/patches/replace_pivot_column_with_label.py
|
Python
|
agpl-3.0
| 1,147
|
import json
import frappe
def execute():
if not frappe.db.a_row_exists("Insights Query"):
return
Query = frappe.qb.DocType("Insights Query")
default_filters = json.dumps(
{
"type": "LogicalExpression",
"operator": "&&",
"level": 1,
"position": 1,
"conditions": [],
},
indent=2,
)
frappe.qb.update(Query).set(Query.filters, default_filters).run()
|
2302_79757062/insights
|
insights/patches/reset_query_filters.py
|
Python
|
agpl-3.0
| 462
|
import frappe
from insights.api.subscription import get_subscription_key
def execute():
if get_subscription_key():
notify_users()
def notify_users():
# notify users about the support portal access
note = frappe.new_doc("Note")
note.title = "Insights Support Portal"
note.public = 1
note.notify_on_login = 1
note.content = """
<div class="ql-editor read-mode"><h3>Insights Support Portal</h3><br><p>You have an active subscription (or trial) for Frappe Insights. You can now access the Insights Support Portal to get help from the Frappe team.</p><br><p>To access the portal go to <a href="/insights/settings" target="_blank">Settings</a> -> Send Login Link</p><img class="mt-2" src="https://user-images.githubusercontent.com/25369014/229565675-fb96d7f0-cd0d-472e-8c9f-d0e1b7a36439.png" alt="support_portal_1.png"><p><br></p></div>
"""
note.insert(ignore_mandatory=True)
|
2302_79757062/insights
|
insights/patches/show_support_login_message.py
|
Python
|
agpl-3.0
| 923
|
import frappe
from insights.insights.doctype.insights_data_source.sources.query_store import (
sync_query_store,
)
def execute():
if not frappe.db.a_row_exists("Insights Query"):
return
Query = frappe.qb.DocType("Insights Query")
queries_on_query_store = frappe.get_all(
"Insights Query", filters={"data_source": "Query Store"}, pluck="name"
)
queries_to_stored = []
for query in queries_on_query_store:
tables = frappe.get_all(
"Insights Query Table", filters={"parent": query}, pluck="table"
)
for table in tables:
if frappe.db.exists("Insights Query", table):
queries_to_stored.append(table)
if queries_to_stored:
(
frappe.qb.update(Query)
.set(Query.is_stored, 1)
.where(Query.name.isin(queries_to_stored))
.run()
)
sync_query_store(tables=queries_to_stored, force=True)
|
2302_79757062/insights
|
insights/patches/store_queries.py
|
Python
|
agpl-3.0
| 965
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from insights.insights.doctype.insights_team.insights_team import (
get_allowed_resources_for_user,
get_teams,
is_admin,
)
def has_doc_permission(doc, ptype, user):
if doc.doctype not in [
"Insights Data Source v3",
"Insights Table v3",
]:
return True
# only check if doc exists
if not doc.name:
return True
if not frappe.db.get_single_value("Insights Settings", "enable_permissions"):
return True
if not user:
user = frappe.session.user
if is_admin(user):
return True
allowed_resources = get_allowed_resources_for_user(doc.doctype, user)
if doc.name in allowed_resources:
return True
return False
def get_data_source_query_conditions(user):
allowed_sources = get_allowed_resources_for_user("Insights Data Source v3", user)
if not allowed_sources:
return """(`tabInsights Data Source v3`.name is NULL)"""
return """(`tabInsights Data Source v3`.name in ({sources}))""".format(
sources=", ".join(frappe.db.escape(sources) for sources in allowed_sources)
)
def get_table_query_conditions(user):
allowed_tables = get_allowed_resources_for_user("Insights Table v3", user)
if not allowed_tables:
return """(`tabInsights Table v3`.name is NULL)"""
return """(`tabInsights Table v3`.name in ({tables}))""".format(
tables=", ".join(frappe.db.escape(tables) for tables in allowed_tables)
)
def get_team_query_conditions(user):
if is_admin(user):
return ""
user_teams = get_teams(user)
if not user_teams:
return """(`tabInsights Team`.name is NULL)"""
return """(`tabInsights Team`.name in ({teams}))""".format(
teams=", ".join(frappe.db.escape(team) for team in user_teams)
)
|
2302_79757062/insights
|
insights/permissions.py
|
Python
|
agpl-3.0
| 1,944
|
// redirect to desk page 'insights' after setup wizard is complete
// 'insights' desk page redirects to '/insights'
frappe.setup.welcome_page = "/app/insights";
|
2302_79757062/insights
|
insights/public/js/setup_wizard.js
|
JavaScript
|
agpl-3.0
| 161
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import os
import shutil
import frappe
from insights.api.data_sources import get_data_source_tables
from insights.insights.doctype.insights_data_source_v3.insights_data_source_v3 import (
after_request,
before_request,
)
from insights.insights.doctype.insights_table_link_v3.insights_table_link_v3 import (
InsightsTableLinkv3,
)
def update_progress(message, progress):
print(message, progress)
frappe.publish_realtime(
event="insights_demo_setup_progress",
user=frappe.session.user,
message={
"message": message,
"progress": progress,
"user": frappe.session.user,
},
)
class DemoDataFactory:
def __init__(self) -> None:
self.initialize()
@staticmethod
def run(force=False):
factory = DemoDataFactory()
if factory.demo_data_exists() and not force:
factory.create_table_links()
update_progress("Done", 99)
return factory
update_progress("Downloading data...", 5)
factory.download_demo_data()
update_progress("Syncing tables...", 60)
factory.sync_tables()
update_progress("Done", 99)
return factory
def initialize(self):
self.db_url = "https://drive.google.com/uc?export=download&id=1l43RqU0KWKr04fx54PLsrHpWqMijRKTa"
self.files_folder = frappe.get_site_path("private", "files")
self.db_filename = "insights_demo_data.duckdb"
self.db_file_path = os.path.join(self.files_folder, self.db_filename)
self.setup_demo_data_source()
if frappe.flags.in_test or os.environ.get("CI"):
test_db_path = os.path.join(os.path.dirname(__file__), self.db_filename)
shutil.copyfile(test_db_path, self.db_file_path)
def setup_demo_data_source(self):
if not frappe.db.exists("Insights Data Source v3", "demo_data"):
data_source = frappe.new_doc("Insights Data Source v3")
data_source.name = "demo_data"
data_source.title = "Demo Data"
data_source.database_type = "DuckDB"
data_source.database_name = "insights_demo_data"
data_source.insert(ignore_permissions=True)
frappe.db.commit()
self.data_source = frappe.get_doc("Insights Data Source v3", "demo_data")
def demo_data_exists(self):
tables = get_data_source_tables(self.data_source.name)
return len(tables) == 8
def download_demo_data(self):
if frappe.flags.in_test or os.environ.get("CI"):
return
import requests
try:
with requests.get(self.db_url, stream=True) as r:
r.raise_for_status()
with open(self.db_file_path, "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
except Exception as e:
frappe.log_error(
"Error downloading demo data. Please check your Internet connection."
)
update_progress("Error...", -1)
raise e
def sync_tables(self):
before_request()
self.data_source.update_table_list()
self.data_source.save(ignore_permissions=True)
after_request()
self.create_table_links()
def create_table_links(self):
table_links = [
{
"left_table": "customers",
"right_table": "orders",
"left_column": "customer_id",
"right_column": "customer_id",
},
{
"left_table": "geolocation",
"right_table": "customers",
"left_column": "geolocation_zip_code_prefix",
"right_column": "customer_zip_code_prefix",
},
{
"left_table": "geolocation",
"right_table": "sellers",
"left_column": "geolocation_zip_code_prefix",
"right_column": "seller_zip_code_prefix",
},
{
"left_table": "orders",
"right_table": "orderitems",
"left_column": "order_id",
"right_column": "order_id",
},
{
"left_table": "orders",
"right_table": "orderpayments",
"left_column": "order_id",
"right_column": "order_id",
},
{
"left_table": "orders",
"right_table": "orderreviews",
"left_column": "order_id",
"right_column": "order_id",
},
{
"left_table": "products",
"right_table": "orderitems",
"left_column": "product_id",
"right_column": "product_id",
},
{
"left_table": "sellers",
"right_table": "orderitems",
"left_column": "seller_id",
"right_column": "seller_id",
},
]
frappe.db.delete(
"Insights Table Link v3", {"data_source": self.data_source.name}
)
for link in table_links:
InsightsTableLinkv3.create(
self.data_source.name,
link["left_table"],
link["right_table"],
link["left_column"],
link["right_column"],
)
|
2302_79757062/insights
|
insights/setup/demo.py
|
Python
|
agpl-3.0
| 5,590
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import os
import frappe
from frappe import _
from insights.setup.demo import DemoDataFactory
def get_setup_stages(args=None):
return [
{
"status": _("Setting up demo data"),
"fail_msg": _("Failed to setup demo data"),
"tasks": [
{
"fn": setup_demo_data,
"args": args,
"fail_msg": _("Failed to setup demo data"),
}
],
},
{
"status": _("Wrapping up"),
"fail_msg": _("Failed to login"),
"tasks": [{"fn": wrap_up, "args": args, "fail_msg": _("Failed to login")}],
},
]
def setup_demo_data(args):
if frappe.flags.in_test or os.environ.get("CI"):
return
factory = DemoDataFactory()
factory.run()
frappe.db.commit()
def wrap_up(args):
frappe.local.message_log = []
set_user_as_insights_admin(args)
login_as_first_user(args)
def set_user_as_insights_admin(args):
# if developer mode is enabled, first user step is skipped, hence no user is created
if not args.get("email") or not frappe.db.exists("User", args.get("email")):
return
user = frappe.get_doc("User", args.get("email"))
user.add_roles("Insights Admin", "Insights User")
def login_as_first_user(args):
if args.get("email") and hasattr(frappe.local, "login_manager"):
frappe.local.login_manager.login_as(args.get("email"))
|
2302_79757062/insights
|
insights/setup/setup_wizard.py
|
Python
|
agpl-3.0
| 1,603
|
<div>
<style>
.alert-container {
max-width: 38rem;
margin: 0 auto;
padding: 0.5rem 2rem;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-weight: 600;
}
.alert-container table {
border-collapse: collapse;
border: 1px solid #e2e2e2;
width: 100%;
table-layout: fixed;
position: relative;
}
.alert-container table th,
.alert-container table td {
border: 1px solid #e2e2e2;
padding: 0.5rem;
text-align: left;
}
.alert-container table th {
background-color: #f2f2f2;
position: sticky;
top: 0;
z-index: 1;
}
.results {
margin-top: 1rem;
max-height: 20rem;
overflow: scroll;
position: relative;
padding: 0.25rem 0rem;
}
</style>
<div class="alert-container">{{ message }}</div>
</div>
|
2302_79757062/insights
|
insights/templates/alert.html
|
HTML
|
agpl-3.0
| 865
|
<h2>You have been invited to use Insights</h2>
<p>
<a class="btn btn-primary" href="{{ invite_link }}">Accept Invitation</a>
</p>
|
2302_79757062/insights
|
insights/templates/emails/insights_invitation.html
|
HTML
|
agpl-3.0
| 132
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
import frappe
from insights.insights.doctype.insights_query.insights_query import InsightsQuery
def before_tests():
delete_all_records()
create_site_db()
create_sqlite_db()
complete_setup_wizard()
frappe.db.commit()
def complete_setup_wizard():
frappe.clear_cache()
from frappe.desk.page.setup_wizard.setup_wizard import setup_complete
if not frappe.db.get_single_value("System Settings", "setup_complete"):
setup_complete(
{
"language": "English",
"email": "test@erpnext.com",
"full_name": "Test User",
"password": "test",
"country": "United States",
"timezone": "America/New_York",
"currency": "USD",
}
)
def delete_all_records():
frappe.db.delete("Version", {"ref_doctype": ("like", "Insights%")})
frappe.db.delete("View Log", {"reference_doctype": ("like", "Insights%")})
for doctype in frappe.get_all(
"DocType", filters={"module": "Insights", "issingle": 0}, pluck="name"
):
frappe.db.delete(doctype)
def create_query_store():
query_store = frappe.new_doc("Insights Data Source")
query_store.title = "Query Store"
query_store.save()
def create_site_db():
site_db = frappe.new_doc("Insights Data Source")
site_db.title = "Site DB"
site_db.is_site_db = 1
site_db.save()
def create_sqlite_db():
db = frappe.new_doc("Insights Data Source")
db.title = "Test SQLite DB"
db.database_type = "SQLite"
db.database_name = "test_sqlite_db"
import_todo_table(db)
db.save()
def import_todo_table(db):
# need to create todo table for test_insights_query.py
import pandas as pd
data = [
[
"name",
"docstatus",
"description",
"status",
"date",
"owner",
"modified_by",
"modified",
"creation",
],
[
0,
0,
"Test 1",
"Open",
"2021-09-01 00:00:00",
"Administrator",
"Administrator",
"2021-09-01 00:00:00",
"2021-09-01 00:00:00",
],
]
df = pd.DataFrame(data[1:], columns=data[0])
df.to_sql(
name="tabToDo",
con=db._db.engine,
index=False,
if_exists="replace",
)
def create_insights_query(title=None, data_source=None) -> InsightsQuery:
query = frappe.new_doc("Insights Query")
query.title = title or "Test Query"
query.data_source = data_source or "Site DB"
query.save()
return query
|
2302_79757062/insights
|
insights/tests/utils.py
|
Python
|
agpl-3.0
| 2,770
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import pathlib
import chardet
import frappe
import pandas as pd
from frappe.model.base_document import BaseDocument
from frappe.website.page_renderers.template_page import TemplatePage
class ResultColumn:
label: str
type: str | list[str]
options: dict = {}
@staticmethod
def from_args(label, type="String", options=None) -> "ResultColumn":
return frappe._dict(
{
"label": label or "Unnamed",
"type": type or "String",
"options": options or {},
}
)
@classmethod
def from_dict(cls, data: dict) -> "ResultColumn":
return frappe._dict(
label=data.get("alias") or data.get("label") or "Unnamed",
type=data.get("type") or "String",
options=data.get("format_option")
or data.get("options")
or data.get("format_options"),
)
@classmethod
def from_dicts(cls, data: list[dict]) -> list["ResultColumn"]:
return [cls.from_dict(d) for d in data]
class DoctypeBase(BaseDocument):
doctype: str
@classmethod
def get_name(cls, *args, **kwargs):
return frappe.db.exists(cls.doctype, args[0] if len(args) > 0 else kwargs)
@classmethod
def exists(cls, *args, **kwargs):
return cls.get_name(*args, **kwargs) is not None
@classmethod
def get_doc(cls, *args, **kwargs) -> "DoctypeBase":
return frappe.get_doc(cls.doctype, args[0] if len(args) > 0 else kwargs)
@classmethod
def get_cached_doc(cls, *args, **kwargs) -> "DoctypeBase":
return frappe.get_cached_doc(cls.doctype, args[0] if len(args) > 0 else kwargs)
@classmethod
def new_doc(cls, **kwargs) -> "DoctypeBase":
new_doc = frappe.new_doc(cls.doctype)
new_doc.update(kwargs)
return new_doc
@classmethod
def get_or_create_doc(cls, *args, **kwargs) -> "DoctypeBase":
name = cls.get_name(*args, **kwargs)
if name:
return cls.get_doc(name)
else:
return cls.new_doc(**kwargs)
@classmethod
def get_value(cls, *args, **kwargs):
return frappe.db.get_value(cls.doctype, *args, **kwargs)
@classmethod
def delete_doc(cls, name):
return frappe.delete_doc(cls.doctype, name)
class InsightsChart(DoctypeBase):
doctype = "Insights Chart"
class InsightsTable(DoctypeBase):
doctype = "Insights Table"
class InsightsQuery(DoctypeBase):
doctype = "Insights Query"
class InsightsDataSource(DoctypeBase):
doctype = "Insights Data Source"
class InsightsQueryResult(DoctypeBase):
doctype = "Insights Query Result"
class InsightsSettings:
@classmethod
def get(cls, key):
return frappe.db.get_single_value("Insights Settings", key)
def deep_convert_dict_to_dict(d):
if isinstance(d, dict):
new_dict = frappe._dict()
for k, v in d.items():
new_dict[k] = deep_convert_dict_to_dict(v)
return new_dict
if isinstance(d, list):
new_list = []
for v in d:
new_list.append(deep_convert_dict_to_dict(v))
return new_list
return d
def create_execution_log(sql, time_taken=0, query_name=None):
frappe.get_doc(
{
"doctype": "Insights Query Execution Log",
"time_taken": time_taken,
"query": query_name,
"sql": sql,
}
).insert(ignore_permissions=True)
def detect_encoding(file_path: str):
file_path: pathlib.Path = pathlib.Path(file_path)
with open(file_path, "rb") as file:
result = chardet.detect(file.read())
return result["encoding"]
def anonymize_data(df, columns_to_anonymize, prefix_by_column=None):
"""
Anonymizes the data in the specified columns of a DataFrame.
Args:
df (pandas.DataFrame): The DataFrame containing the data to be anonymized.
columns_to_anonymize (list): A list of column names to be anonymized.
prefix_by_column (dict, optional): A dictionary mapping column names to prefixes.
If provided, the anonymized values will be prefixed with the corresponding value.
Defaults to None.
Returns:
pandas.DataFrame: The DataFrame with the anonymized data.
"""
for column in columns_to_anonymize:
codes = pd.factorize(df[column])[0] + 1
prefix = prefix_by_column[column] if prefix_by_column else column
df[column] = prefix + pd.Series(codes).astype(str)
return df
def xls_to_df(file_path: str) -> list[pd.DataFrame]:
file_extension = file_path.split(".")[-1].lower()
if file_extension != "xlsx" or file_extension != "xls":
frappe.throw(f"Unsupported file extension: {file_extension}")
sheets = {}
excel_file = pd.ExcelFile(file_path)
for sheet_name in excel_file.sheet_names:
sheets[sheet_name] = excel_file.parse(sheet_name)
return sheets
class InsightsPageRenderer(TemplatePage):
def can_render(self):
try:
path = frappe.request.path
except BaseException:
path = self.path
embed_urls = [
"/insights_v2/public",
"/insights/public",
]
if not any(path.startswith(url) for url in embed_urls):
return False
return super().can_render()
def render(self):
self.set_headers()
return super().render()
def set_headers(self):
allowed_origins = frappe.db.get_single_value(
"Insights Settings", "allowed_origins"
)
if not allowed_origins:
return
self.headers = self.headers or {}
allowed_origins = allowed_origins.split(",") if allowed_origins else []
allowed_origins = [origin.strip() for origin in allowed_origins]
allowed_origins = " ".join(allowed_origins)
self.headers[
"Content-Security-Policy"
] = f"frame-ancestors 'self' {allowed_origins}"
|
2302_79757062/insights
|
insights/utils.py
|
Python
|
agpl-3.0
| 6,115
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
# GNU GPLv3 License. See license.txt
import frappe
from frappe.defaults import get_user_default
from insights.api.telemetry import track_active_site
no_cache = 1
def get_context(context):
is_v2_user = frappe.db.count("Insights Query", cache=True) > 0
# if not v2 user continue to v3
if not is_v2_user:
continue_to_v3(context)
return
# go to v2 if user has not visited v3 yet
has_visited_v3 = (
get_user_default("insights_has_visited_v3", frappe.session.user) == "1"
)
if not has_visited_v3:
redirect_to_v2()
return
v2_routes = [
"/insights/query",
"/insights/query/build",
"/insights/dashboard",
"/insights/public/dashboard",
"/insights/public/chart",
]
if any(route in frappe.request.path for route in v2_routes):
redirect_to_v2()
return
is_v3_default = (
get_user_default("insights_default_version", frappe.session.user) == "v3"
)
is_v2_default = (
get_user_default("insights_default_version", frappe.session.user) == "v2"
)
if is_v3_default:
continue_to_v3(context)
elif is_v2_default:
redirect_to_v2()
else:
continue_to_v3(context)
def continue_to_v3(context):
csrf_token = frappe.sessions.get_csrf_token()
frappe.db.commit()
context.csrf_token = csrf_token
context.site_name = frappe.local.site
track_active_site(is_v3=True)
def redirect_to_v2():
path = frappe.request.full_path
frappe.local.flags.redirect_location = path.replace("/insights", "/insights_v2")
raise frappe.Redirect
|
2302_79757062/insights
|
insights/www/insights.py
|
Python
|
agpl-3.0
| 1,706
|
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
# GNU GPLv3 License. See license.txt
import frappe
from insights.api.telemetry import track_active_site
no_cache = 1
def get_context(context):
is_v2_user = frappe.db.count("Insights Query", cache=True) > 0
if not is_v2_user:
frappe.local.flags.redirect_location = "/insights"
raise frappe.Redirect
csrf_token = frappe.sessions.get_csrf_token()
frappe.db.commit()
context.csrf_token = csrf_token
context.site_name = frappe.local.site
track_active_site()
|
2302_79757062/insights
|
insights/www/insights_v2.py
|
Python
|
agpl-3.0
| 573
|
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>太空生日庆祝</title>
<style>
/* 顶部导航栏 */
/* 顶部导航栏 */
.top-navbar {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 60px;
background: #000; /* 改为纯黑色 */
display: flex;
align-items: center;
justify-content: center; /* 改为居中对齐 */
padding: 0 20px;
z-index: 2000;
/* 移除边框和下划线 */
border-bottom: none;
}
.nav-back-btn {
position: absolute; /* 绝对定位,不影响主题居中 */
left: 20px; /* 固定在左侧 */
width: auto; /* 自动宽度 */
height: auto; /* 自动高度 */
background: transparent; /* 透明背景 */
color: #ba68c8; /* 紫色文字 */
border-radius: 0; /* 移除圆角 */
display: flex;
justify-content: center;
align-items: center;
font-size: 2rem; /* 增大字体 */
font-weight: bold;
cursor: pointer;
/* 移除所有边框和阴影 */
border: none;
box-shadow: none;
transition: all 0.3s ease;
padding: 10px; /* 增加点击区域 */
}
.nav-back-btn:hover {
color: #ab47bc; /* 深一点的紫色 */
transform: scale(1.1);
background: transparent; /* 保持透明背景 */
}
.nav-title {
color: white;
font-size: 1.3rem;
font-weight: bold;
text-align: center;
/* 移除flex:1和margin,让标题自然居中 */
}
/* 删除占位符样式 */
.nav-placeholder {
display: none;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Arial', sans-serif;
overflow: hidden;
height: 100vh;
background: #000;
color: white;
}
.space-background {
position: fixed;
width: 100%;
height: 100%;
background: linear-gradient(to bottom, #0b0b2d, #000);
z-index: -2;
}
.stars-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
overflow: hidden;
}
.star {
position: absolute;
background-color: #ffffff;
border-radius: 50%;
}
.star.small {
width: 1px;
height: 1px;
animation: twinkle-small 4s infinite ease-in-out;
}
.star.medium {
width: 2px;
height: 2px;
animation: twinkle-medium 3s infinite ease-in-out;
}
.star.large {
width: 3px;
height: 3px;
animation: twinkle-large 5s infinite ease-in-out;
}
@keyframes twinkle-small {
0%, 100% { opacity: 0.3; }
50% { opacity: 1; }
}
@keyframes twinkle-medium {
0%, 100% { opacity: 0.4; }
50% { opacity: 1; }
}
@keyframes twinkle-large {
0%, 100% { opacity: 0.2; }
50% { opacity: 0.8; }
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
text-align: center;
padding: 20px;
position: relative;
z-index: 1;
/* 添加顶部内边距,避免被导航栏遮挡 */
padding-top: 80px;
box-sizing: border-box;
}
.title {
font-size: 3rem;
margin-bottom: 40px;
text-shadow: 0 0 10px rgba(255, 255, 255, 0.7);
background: linear-gradient(to right, #ff7eb3, #ff758c, #ff7eb3);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
animation: glow 2s ease-in-out infinite alternate;
}
@keyframes glow {
from { text-shadow: 0 0 10px rgba(255, 255, 255, 0.7); }
to { text-shadow: 0 0 20px rgba(255, 255, 255, 0.9), 0 0 30px rgba(255, 118, 140, 0.6); }
}
.start-btn {
background-color: #ff7eb3;
color: white;
border: none;
padding: 15px 40px;
font-size: 1.5rem;
border-radius: 50px;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 0 15px rgba(255, 126, 179, 0.7);
font-weight: bold;
letter-spacing: 2px;
position: relative;
z-index: 2;
}
.start-btn:hover {
background-color: #ff5c9a;
transform: scale(1.05);
box-shadow: 0 0 25px rgba(255, 126, 179, 0.9);
}
.stars-page {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(to bottom, #0b0b2d, #000);
z-index: 10;
/* 添加顶部内边距 */
padding-top: 60px;
box-sizing: border-box;
}
.big-star {
position: absolute;
border-radius: 50%;
cursor: pointer;
animation: cosmic-twinkle 4s infinite ease-in-out;
z-index: 5;
transition: all 0.5s ease;
margin-left: -40px;
margin-top: -40px;
/* 多层光晕效果 */
box-shadow:
0 0 15px currentColor,
0 0 30px currentColor,
0 0 60px rgba(255, 255, 255, 0.3),
inset 0 0 25px rgba(255, 255, 255, 0.4),
inset 0 0 50px rgba(255, 255, 255, 0.2);
border: 1px solid rgba(255, 255, 255, 0.6);
/* 基础渐变 */
background:
radial-gradient(circle at 30% 30%,
rgba(255, 255, 255, 0.9) 0%,
rgba(255, 255, 255, 0.7) 15%,
var(--star-color) 45%,
var(--star-dark) 80%,
rgba(0, 0, 0, 0.3) 100%);
filter: drop-shadow(0 0 8px currentColor);
}
.big-star:hover {
transform: scale(1.25) rotate(5deg);
animation-play-state: paused;
box-shadow:
0 0 25px currentColor,
0 0 50px currentColor,
0 0 100px rgba(255, 255, 255, 0.5),
inset 0 0 35px rgba(255, 255, 255, 0.6),
inset 0 0 70px rgba(255, 255, 255, 0.3);
}
@keyframes cosmic-twinkle {
0%, 100% {
transform: scale(1) rotate(0deg);
opacity: 0.7;
box-shadow:
0 0 15px currentColor,
0 0 30px currentColor,
0 0 60px rgba(255, 255, 255, 0.3),
inset 0 0 25px rgba(255, 255, 255, 0.4);
}
25% {
transform: scale(1.08) rotate(1deg);
opacity: 0.9;
box-shadow:
0 0 20px currentColor,
0 0 40px currentColor,
0 0 80px rgba(255, 255, 255, 0.4),
inset 0 0 30px rgba(255, 255, 255, 0.5);
}
50% {
transform: scale(1.05) rotate(-1deg);
opacity: 1;
box-shadow:
0 0 25px currentColor,
0 0 50px currentColor,
0 0 100px rgba(255, 255, 255, 0.5),
inset 0 0 35px rgba(255, 255, 255, 0.6);
}
75% {
transform: scale(1.12) rotate(2deg);
opacity: 0.8;
box-shadow:
0 0 18px currentColor,
0 0 35px currentColor,
0 0 70px rgba(255, 255, 255, 0.4),
inset 0 0 28px rgba(255, 255, 255, 0.5);
}
}
/* 中心星星 - 标准圆形,中等大小 */
/* 中心星星 - 调整中心亮部位置 */
.big-star.yellow {
--star-color: rgba(255, 235, 59, 0.95);
--star-dark: rgba(251, 192, 45, 0.9);
color: #ffeb3b;
animation-delay: 0s;
width: 80px;
height: 80px;
margin-left: -40px;
margin-top: -40px;
/* 轻微不规则边缘 - 与蓝色对齐 */
border-radius: 49% 51% 48% 52% / 51% 49% 51% 49%;
/* 调整中心亮部位置 - 与蓝色对齐但不同 */
background:
radial-gradient(circle at 50% 35%, /* 调整Y轴位置,比蓝色稍低 */
rgba(255, 255, 255, 0.8) 0%,
rgba(255, 255, 255, 0.6) 20%,
var(--star-color) 50%,
var(--star-dark) 85%,
rgba(0, 0, 0, 0.05) 100%),
radial-gradient(circle at 50% 50%,
rgba(255, 235, 59, 0.08) 0%,
rgba(255, 235, 59, 0.04) 30%,
transparent 60%);
}
/* 左上角星星 - 调整边缘与黄色对齐 */
.big-star.pink {
--star-color: rgba(255, 126, 179, 0.9);
--star-dark: rgba(255, 92, 154, 0.8);
color: #ff7eb3;
animation-delay: 0.5s;
width: 75px;
height: 75px;
margin-left: -37.5px;
margin-top: -37.5px;
/* 调整边缘与黄色对齐但保持差异 */
border-radius: 49.5% 50.5% 48.5% 51.5% / 51.5% 48.5% 51.5% 48.5%;
/* 调整中心亮部位置 */
background:
radial-gradient(circle at 50% 40%, /* 与黄色蓝色对齐但不同位置 */
rgba(255, 255, 255, 0.95) 0%,
rgba(255, 255, 255, 0.8) 18%,
var(--star-color) 45%,
var(--star-dark) 80%,
rgba(0, 0, 0, 0.2) 100%),
repeating-radial-gradient(
circle at 50% 50%,
transparent 0px,
rgba(255, 255, 255, 0.1) 2px,
transparent 4px
);
}
/* 右上角星星 - 保持现有但作为基准 */
.big-star.blue {
--star-color: rgba(79, 195, 247, 0.9);
--star-dark: rgba(41, 182, 246, 0.8);
color: #4fc3f7;
animation-delay: 1s;
width: 85px;
height: 85px;
margin-left: -42.5px;
margin-top: -42.5px;
/* 保持作为基准 */
border-radius: 49% 51% 48% 52% / 51% 49% 51% 49%;
/* 中心偏上的亮部 - 作为基准位置 */
background:
radial-gradient(circle at 50% 30%,
rgba(255, 255, 255, 0.95) 0%,
rgba(255, 255, 255, 0.8) 20%,
var(--star-color) 50%,
var(--star-dark) 85%,
rgba(0, 0, 0, 0.2) 100%),
repeating-radial-gradient(
circle at 50% 50%,
transparent 0px,
rgba(255, 255, 255, 0.05) 3px,
transparent 6px
);
}
/* 左下角星星 - 调整边缘与黄色对齐 */
.big-star.purple {
--star-color: rgba(186, 104, 200, 0.9);
--star-dark: rgba(171, 71, 188, 0.8);
color: #ba68c8;
animation-delay: 1.5s;
width: 78px;
height: 82px;
margin-left: -39px;
margin-top: -41px;
/* 调整边缘与黄色对齐 */
border-radius: 49.2% 50.8% 48.8% 51.2% / 51.2% 48.8% 51.2% 48.8%;
/* 调整中心亮部位置 */
background:
radial-gradient(circle at 50% 38%, /* 与黄色蓝色对齐但不同位置 */
rgba(255, 255, 255, 0.95) 0%,
rgba(255, 255, 255, 0.8) 22%,
var(--star-color) 48%,
var(--star-dark) 82%,
rgba(0, 0, 0, 0.2) 100%),
radial-gradient(circle at 70% 30%, rgba(255, 255, 255, 0.2) 2%, transparent 4%),
radial-gradient(circle at 30% 70%, rgba(255, 255, 255, 0.2) 2%, transparent 4%),
radial-gradient(circle at 60% 60%, rgba(255, 255, 255, 0.15) 1%, transparent 3%);
}
/* 右下角星星 - 调整边缘与黄色对齐 */
.big-star.green {
--star-color: rgba(129, 199, 132, 0.9);
--star-dark: rgba(102, 187, 106, 0.8);
color: #81c784;
animation-delay: 2s;
width: 72px;
height: 72px;
margin-left: -36px;
margin-top: -36px;
/* 调整边缘与黄色对齐 */
border-radius: 49.8% 50.2% 48.2% 51.8% / 51.8% 48.2% 51.8% 48.2%;
/* 调整中心亮部位置 */
background:
radial-gradient(circle at 50% 42%, /* 与黄色蓝色对齐但不同位置 */
rgba(255, 255, 255, 0.95) 0%,
rgba(255, 255, 255, 0.8) 25%,
var(--star-color) 52%,
var(--star-dark) 88%,
rgba(0, 0, 0, 0.2) 100%),
repeating-linear-gradient(
45deg,
transparent,
transparent 5px,
rgba(255, 255, 255, 0.1) 5px,
rgba(255, 255, 255, 0.1) 6px
);
}
/* 调整不同大小的悬停效果 */
.big-star.pink:hover { transform: scale(1.25); }
.big-star.blue:hover { transform: scale(1.25); }
.big-star.purple:hover { transform: scale(1.25); }
.big-star.green:hover { transform: scale(1.25); }
.star-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.75);
z-index: 100;
justify-content: center;
align-items: flex-start;
padding-top: 13vh;
}
.star-content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
max-width: 80vw;
max-height: 80vh;
}
.image-container {
width: 60vmin;
height: 60vmin;
min-width: 300px;
min-height: 300px;
max-width: 500px;
max-height: 500px;
border-radius: 50%;
position: relative;
overflow: hidden;
background: transparent;
}
.image-container img {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 50%;
position: relative;
z-index: 1;
animation: none;
-webkit-mask-image: radial-gradient(
circle,
rgba(0,0,0,1) 0%, rgba(0,0,0,1) 40%, rgba(0,0,0,0.95) 45%,
rgba(0,0,0,0.85) 50%, rgba(0,0,0,0.7) 55%, rgba(0,0,0,0.5) 60%,
rgba(0,0,0,0.3) 65%, rgba(0,0,0,0.1) 70%, rgba(0,0,0,0) 75%
);
mask-image: radial-gradient(
circle,
rgba(0,0,0,1) 0%, rgba(0,0,0,1) 40%, rgba(0,0,0,0.95) 45%,
rgba(0,0,0,0.85) 50%, rgba(0,0,0,0.7) 55%, rgba(0,0,0,0.5) 60%,
rgba(0,0,0,0.3) 65%, rgba(0,0,0,0.1) 70%, rgba(0,0,0,0) 75%
);
filter: contrast(1.2) saturate(1.1);
}
.particle-layer {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border-radius: 50%;
pointer-events: none;
z-index: 2;
overflow: hidden;
}
.particle {
position: absolute;
background: rgba(255, 255, 255, 0.8);
border-radius: 50%;
animation: gentle-pulse 3s infinite ease-in-out;
}
@keyframes gentle-pulse {
0%, 100% {
opacity: 0.3;
transform: scale(1);
}
50% {
opacity: 0.8;
transform: scale(1.3);
}
}
.blessing-text {
margin-top: 30px;
background: rgba(0, 0, 0, 0.7);
color: white;
padding: 20px 40px;
border-radius: 25px;
font-size: 1.4rem;
text-align: center;
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.3);
box-shadow: 0 0 30px rgba(255, 255, 255, 0.2);
max-width: 80%;
line-height: 1.6;
}
/* 进度条包装器 */
.progress-wrapper {
position: fixed;
bottom: 40px;
left: 10%;
width: 80%;
z-index: 20;
display: flex;
flex-direction: column;
gap: 12px;
}
/* 进度提示文字 - 纯色发光效果 */
.progress-text {
color: #ff7eb3;
font-size: 1.1rem;
font-weight: bold;
text-align: center;
text-shadow:
0 0 10px #ff7eb3,
0 0 20px #ffeb3b,
0 0 30px #4fc3f7;
letter-spacing: 1px;
padding: 8px 0;
backdrop-filter: blur(5px);
animation: text-pulse 1.5s ease-in-out infinite alternate;
}
@keyframes text-pulse {
from {
text-shadow:
0 0 10px #ff7eb3,
0 0 20px rgba(255, 235, 59, 0.5),
0 0 30px rgba(79, 195, 247, 0.3);
}
to {
text-shadow:
0 0 15px #ff7eb3,
0 0 25px #ffeb3b,
0 0 35px #4fc3f7,
0 0 45px rgba(255, 126, 179, 0.5);
}
}
/* 进度条容器 */
.progress-container {
width: 100%;
height: 10px;
background: rgba(255, 255, 255, 0.15);
border-radius: 12px;
overflow: hidden;
box-shadow: 0 0 20px rgba(255, 126, 179, 0.3);
border: 1px solid rgba(255, 255, 255, 0.2);
}
/* 进度条 */
.progress-bar {
height: 100%;
background: linear-gradient(90deg, #ff7eb3, #ff5c9a, #ff7eb3);
border-radius: 12px;
width: 0%;
transition: width 0.5s ease;
box-shadow:
0 0 20px rgba(255, 126, 179, 0.6),
inset 0 0 10px rgba(255, 255, 255, 0.3);
}
@keyframes birthday-popup {
0% {
transform: translate(-50%, -50%) scale(0);
opacity: 0;
}
50% {
transform: translate(-50%, -50%) scale(1.3);
opacity: 1;
}
100% {
transform: translate(-50%, -50%) scale(1);
opacity: 1;
}
}
/* 添加在style标签内的任意位置 */
@keyframes firework-explode {
0% {
transform: translate(0, 0) scale(1);
opacity: 1;
}
50% {
opacity: 1;
}
100% {
transform: translate(var(--tx), var(--ty)) scale(0);
opacity: 0;
}
}
.firework-particle {
position: absolute;
border-radius: 50%;
pointer-events: none;
animation: firework-explode 1.5s ease-out forwards;
}
/* 烟花遮罩层 */
.fireworks-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.85);
z-index: 1000;
/* 确保在导航栏下面 */
padding-top: 60px;
box-sizing: border-box;
}
.fireworks-overlay #fireworksCanvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1001;
}
/* 蛋糕容器 - 放在烟花遮罩层内 */
.cake-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1003;
pointer-events: none;
display: none;
}
/* 整合的蛋糕组件 */
.cake-group {
position: absolute;
top: 30%; /* 蛋糕位置 - 在页面上方 */
left: 50%;
transform: translateX(-50%);
display: flex;
flex-direction: column;
align-items: center;
z-index: 1004;
}
/* 蛋糕主体 */
.cake {
width: 200px;
height: 60px;
background: #f9fdff;
border-radius: 100%;
box-shadow:
0px 4px 0px #f4f9fd,
0px 8px 0px #dba9ff,
0px 12px 0px #fec3b3,
0px 16px 0px #f7f6fb,
0px 20px 0px #f7f6fb,
0px 24px 0px #f7f6fb,
0px 28px 0px #f7f6fb,
0px 32px 0px #fea0bb,
0px 36px 0px #fea0bb,
0px 40px 0px #9cef9d,
0px 44px 0px #9cef9d,
0px 48px 0px #f7f6fb,
0px 52px 0px #f7f6fb,
0px 56px 0px #f7f6fb,
0px 60px 0px #f7f6fb,
0px 64px 0px #f7f6fb,
0px 68px 0px #dfa5fc,
0px 72px 0px #dfa5fc,
0px 76px 0px #fafffe,
0px 80px 0px #fafffe;
position: relative;
z-index: 2;
}
/* 蜡烛 */
.candle {
position: absolute;
top: -20px; /* 蜡烛在蛋糕上方 */
left: 50%;
transform: translateX(-50%);
height: 50px;
width: 12px;
background: linear-gradient(0deg, #b7f4a7 0%, white 100%);
border-radius: 4px;
z-index: 3;
}
/* 火焰 */
.flame {
position: absolute;
top: -25px; /* 火焰在蜡烛上方 */
left: 50%;
transform: translateX(-50%);
background: linear-gradient(to bottom, #FFF6D9, #FBC36C);
width: 15px;
height: 35px;
border-top-left-radius: 10px 35px;
border-top-right-radius: 10px 35px;
border-bottom-right-radius: 10px 10px;
border-bottom-left-radius: 10px 10px;
box-shadow: 0 0 17px 7px rgba(251, 246, 190, 0.71);
transform-origin: bottom;
animation: flicker 1s ease-in-out alternate infinite;
z-index: 4;
}
/* 蛋糕盘子 */
.plate {
position: absolute;
top: 60px; /* 盘子在蛋糕下方 */
left: 50%;
transform: translateX(-50%);
height: 90px;
width: 300px;
border-radius: 100%;
background: radial-gradient(ellipse closest-side at center, #08c7fe 0%, #04d7f2 71%, #02ffd0 100%);
box-shadow: 0px 3px 0px #00e2e1, 0px 6px 0px #00d3fb;
z-index: 1;
}
@keyframes flicker {
0% {
transform: translateX(-50%) skewX(5deg);
box-shadow: 0 0 17px 10px rgba(251, 246, 190, 0.71);
}
25% {
transform: translateX(-50%) skewX(-5deg);
box-shadow: 0 0 17px 5px rgba(251, 246, 190, 0.71);
}
50% {
transform: translateX(-50%) skewX(10deg);
box-shadow: 0 0 17px 7px rgba(251, 246, 190, 0.71);
}
75% {
transform: translateX(-50%) skewX(-10deg);
box-shadow: 0 0 17px 5px rgba(251, 246, 190, 0.71);
}
100% {
transform: translateX(-50%) skewX(5deg);
box-shadow: 0 0 17px 10px rgba(251, 246, 190, 0.71);
}
}
.fireworks-overlay .birthday-text {
position: absolute;
top: 55%; /* 生日文字在蛋糕下方 */
left: 50%;
transform: translate(-50%, -50%) scale(0);
z-index: 1002;
font-size: 4rem;
font-weight: bold;
text-align: center;
display: none;
background: linear-gradient(45deg, #ff7eb3, #ff5c9a, #ffeb3b, #4fc3f7);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
text-shadow:
0 0 20px rgba(255, 126, 179, 0.8),
0 0 40px rgba(255, 235, 59, 0.6),
0 0 60px rgba(79, 195, 247, 0.4);
animation: birthday-popup 2s ease-out forwards;
white-space: nowrap;
padding: 0 20px;
}
/* 手机端适配 */
@media (max-width: 768px) {
.fireworks-overlay .birthday-text {
font-size: 3rem; /* 在手机上使用更小的字体 */
}
}
@media (max-width: 480px) {
.fireworks-overlay .birthday-text {
font-size: 2.5rem; /* 在小手机上进一步减小字体 */
}
}
@keyframes particle-move {
0% {
transform: translate(0, 0) scale(1);
opacity: 1;
}
100% {
transform: translate(var(--tx), var(--ty)) scale(0);
opacity: 0;
}
}
</style>
</head>
<!-- 顶部导航栏 -->
<div class="top-navbar">
<div class="nav-back-btn" id="navBackBtn" style="display: none;"><</div>
<div class="nav-title">太空生日庆祝</div>
</div>
<body>
<div class="space-background"></div>
<div class="stars-container" id="stars"></div>
<div class="container">
<h1 class="title">收集星星解锁烟花秀</h1>
<button class="start-btn" id="startBtn">开始旅程</button>
</div>
<div class="stars-page" id="starsPage">
<div class="stars-container" id="stars2"></div>
<div class="big-star yellow" id="bigStarCenter" data-content="center"></div>
<div class="big-star pink" id="bigStarTopLeft" data-content="topleft"></div>
<div class="big-star blue" id="bigStarTopRight" data-content="topright"></div>
<div class="big-star purple" id="bigStarBottomLeft" data-content="bottomleft"></div>
<div class="big-star green" id="bigStarBottomRight" data-content="bottomright"></div>
<div class="star-overlay" id="starOverlay">
<div class="star-content" id="starContent">
<div class="image-container">
<img src="" alt="星星内容" id="starImage">
<div class="particle-layer" id="particleLayer"></div>
</div>
<div class="blessing-text" id="starText"></div>
</div>
</div>
<!-- 进度条 -->
<!-- 进度条 -->
<div class="progress-wrapper">
<div class="progress-text">点击星星为进度充能:</div>
<div class="progress-container">
<div class="progress-bar" id="progressBar"></div>
</div>
</div>
<!-- 烟花遮罩层 -->
<div class="fireworks-overlay" id="fireworksOverlay">
<canvas id="fireworksCanvas"></canvas>
<!-- 蛋糕容器 -->
<div class="cake-container" id="cakeContainer">
<div class="cake-group">
<div class="cake">
<div class="candle">
<div class="flame"></div>
</div>
</div>
<div class="plate"></div>
</div>
</div>
<!-- 生日文字 -->
<div class="birthday-text" id="birthdayText">生日快乐!</div>
</div>
<script>
let collectedStars = new Set();
let totalStars = 5;
function createStars(containerId, count) {
const container = document.getElementById(containerId);
if (!container) return;
container.innerHTML = '';
for (let i = 0; i < count; i++) {
const star = document.createElement('div');
const sizes = ['small', 'medium', 'large'];
const size = sizes[Math.floor(Math.random() * sizes.length)];
star.className = 'star ' + size;
star.style.left = Math.random() * 100 + '%';
star.style.top = Math.random() * 100 + '%';
star.style.animationDelay = (Math.random() * 5) + 's';
container.appendChild(star);
}
}
function setupBigStars() {
const positions = [
{ id: 'bigStarCenter', area: 'center' },
{ id: 'bigStarTopLeft', area: 'topleft' },
{ id: 'bigStarTopRight', area: 'topright' },
{ id: 'bigStarBottomLeft', area: 'bottomleft' },
{ id: 'bigStarBottomRight', area: 'bottomright' }
];
const areaBounds = {
center: { leftMin: 45, leftMax: 55, topMin: 45, topMax: 55 },
topleft: { leftMin: 20, leftMax: 30, topMin: 20, topMax: 30 },
topright: { leftMin: 70, leftMax: 80, topMin: 20, topMax: 30 },
bottomleft: { leftMin: 20, leftMax: 30, topMin: 70, topMax: 80 },
bottomright: { leftMin: 70, leftMax: 80, topMin: 70, topMax: 80 }
};
positions.forEach(pos => {
const star = document.getElementById(pos.id);
if (star) {
const bounds = areaBounds[pos.area];
const randomLeft = bounds.leftMin + Math.random() * (bounds.leftMax - bounds.leftMin);
const randomTop = bounds.topMin + Math.random() * (bounds.topMax - bounds.topMin);
star.style.left = randomLeft + '%';
star.style.top = randomTop + '%';
}
});
}
// 修改星星点击事件,避免重复触发
function setupStarClickEvents() {
const starContents = {
center: { text: "中心星星的祝福!", image: "images/魔仙堡女王登基.jpg" },
topleft: { text: "左上角星星的惊喜!", image: "images/想起一位故人.jpg" },
topright: { text: "右上角星星的礼物!", image: "images/每一天都很开心.jpg" },
bottomleft: { text: "左下角星星的愿望!", image: "images/听歌听的是心情.jpg" },
bottomright: { text: "右下角星星的梦想!", image: "images/爱是毛茸茸的信号.jpg" }
};
document.querySelectorAll('.big-star').forEach(star => {
star.addEventListener('click', function() {
// 如果已经在放烟花,不再处理点击
if (document.getElementById('fireworksOverlay').style.display === 'block') {
return;
}
const contentKey = this.getAttribute('data-content');
const content = starContents[contentKey];
document.getElementById('starImage').src = content.image;
document.getElementById('starText').textContent = content.text;
document.getElementById('starOverlay').style.display = 'flex';
createParticles();
// 记录收集的星星
if (!collectedStars.has(contentKey)) {
collectedStars.add(contentKey);
console.log('已收集星星:', Array.from(collectedStars));
console.log('进度:', collectedStars.size + '/' + totalStars);
updateProgress();
// 如果收集完所有星星,立即触发烟花
if (collectedStars.size === totalStars) {
console.log('所有星星收集完成!触发烟花!');
// 延迟一点触发,让用户看到最后一颗星星的内容
setTimeout(() => {
showFireworks();
}, 1000);
}
}
});
});
document.getElementById('starOverlay').addEventListener('click', function(e) {
if (e.target === this) {
this.style.display = 'none';
}
});
}
function updateProgress() {
const progress = (collectedStars.size / totalStars) * 100;
document.getElementById('progressBar').style.width = progress + '%';
// 移除了进度提示的更新代码
}
function initCanvasFireworks() {
const canvas = document.getElementById('fireworksCanvas');
const container = document.getElementById('fireworksOverlay');
// 设置Canvas尺寸
canvas.width = container.clientWidth;
canvas.height = container.clientHeight;
const ctx = canvas.getContext('2d');
// 烟花参数
const listFire = [];
const listFirework = [];
const fireNumber = 10;
// 初始化上升的火花
for (let i = 0; i < fireNumber; i++) {
const fire = {
x: Math.random() * canvas.width,
y: canvas.height,
size: Math.random() + 1,
fill: '#ffeb3b',
vx: (Math.random() - 0.5) * 2,
vy: -(Math.random() * 3 + 5),
ax: Math.random() * 0.02 - 0.01,
far: Math.random() * (canvas.height / 2) + 100
};
listFire.push(fire);
}
// 随机颜色
function randColor() {
const colors = ['#ff7eb3', '#ff5c9a', '#ffeb3b', '#4fc3f7', '#ba68c8', '#81c784', '#ff9a76'];
return colors[Math.floor(Math.random() * colors.length)];
}
// 动画循环
function loop() {
window.fireworksAnimationId = requestAnimationFrame(loop);
update();
draw();
}
function update() {
// 更新上升火花
for (let i = 0; i < listFire.length; i++) {
const fire = listFire[i];
// 到达目标高度时爆炸
if (fire.y <= fire.far) {
// 创建爆炸粒子
const color = randColor();
for (let j = 0; j < 60; j++) {
const firework = {
x: fire.x,
y: fire.y,
size: Math.random() * 3 + 1,
fill: color,
vx: (Math.random() - 0.5) * 8,
vy: (Math.random() - 0.5) * 8,
ay: 0.03,
alpha: 1,
life: 100 + Math.random() * 50
};
listFirework.push(firework);
}
// 重置火花
fire.y = canvas.height;
fire.x = Math.random() * canvas.width;
fire.far = Math.random() * (canvas.height / 2) + 100;
}
// 更新位置
fire.x += fire.vx;
fire.y += fire.vy;
fire.vx += fire.ax;
}
// 更新爆炸粒子
for (let i = listFirework.length - 1; i >= 0; i--) {
const firework = listFirework[i];
firework.x += firework.vx;
firework.y += firework.vy;
firework.vy += firework.ay;
firework.alpha = firework.life / 150;
firework.life--;
if (firework.life <= 0) {
listFirework.splice(i, 1);
}
}
}
function draw() {
// 半透明黑色背景,产生拖尾效果
ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制上升火花
for (let i = 0; i < listFire.length; i++) {
const fire = listFire[i];
ctx.beginPath();
ctx.arc(fire.x, fire.y, fire.size, 0, Math.PI * 2);
ctx.fillStyle = fire.fill;
ctx.fill();
}
// 绘制爆炸粒子
for (let i = 0; i < listFirework.length; i++) {
const firework = listFirework[i];
ctx.globalAlpha = firework.alpha;
ctx.beginPath();
ctx.arc(firework.x, firework.y, firework.size, 0, Math.PI * 2);
ctx.fillStyle = firework.fill;
ctx.fill();
}
ctx.globalAlpha = 1;
}
// 开始动画
loop();
}
// 显示烟花效果
// 显示烟花效果
function showFireworks() {
console.log('showFireworks函数被调用');
const fireworksOverlay = document.getElementById('fireworksOverlay');
const birthdayText = document.getElementById('birthdayText');
const cakeContainer = document.getElementById('cakeContainer');
const navBackBtn = document.getElementById('navBackBtn');
const starOverlay = document.getElementById('starOverlay');
// 关闭星星遮罩层
starOverlay.style.display = 'none';
// 显示烟花遮罩层
fireworksOverlay.style.display = 'block';
// 初始化Canvas烟花
initCanvasFireworks();
// 显示蛋糕
cakeContainer.style.display = 'block';
// 同时显示生日文字和导航栏返回按钮
birthdayText.style.display = 'block';
navBackBtn.style.display = 'flex';
birthdayText.style.animation = 'none';
setTimeout(() => {
birthdayText.style.animation = 'birthday-popup 2s ease-out forwards';
}, 10);
}
// 确保烟花动画CSS已添加
if (!document.getElementById('firework-animation')) {
const fireworkStyle = document.createElement('style');
fireworkStyle.id = 'firework-animation';
fireworkStyle.textContent = `
@keyframes firework-explode {
0% {
transform: translate(0, 0) scale(1);
opacity: 1;
}
100% {
transform: translate(var(--tx), var(--ty)) scale(0);
opacity: 0;
}
}
`;
document.head.appendChild(fireworkStyle);
}
function createParticles() {
const particleLayer = document.getElementById('particleLayer');
if (!particleLayer) return;
particleLayer.innerHTML = '';
for (let i = 0; i < 50; i++) {
const particle = document.createElement('div');
particle.className = 'particle';
const size = Math.random() * 4 + 1;
particle.style.width = particle.style.height = size + 'px';
particle.style.left = Math.random() * 100 + '%';
particle.style.top = Math.random() * 100 + '%';
particle.style.animationDelay = (Math.random() * 4) + 's';
particleLayer.appendChild(particle);
}
}
window.addEventListener('load', function() {
createStars('stars', 150);
createStars('stars2', 120);
collectedStars = new Set();
totalStars = 5;
if (progressBar) {
progressBar.style.width = '0%';
}
document.getElementById('startBtn').addEventListener('click', function() {
document.getElementById('starsPage').style.display = 'block';
});
// 添加导航栏返回按钮点击事件
document.getElementById('navBackBtn').addEventListener('click', function() {
const fireworksOverlay = document.getElementById('fireworksOverlay');
const birthdayText = document.getElementById('birthdayText');
const starsPage = document.getElementById('starsPage');
const navBackBtn = document.getElementById('navBackBtn');
// 如果正在显示烟花,则返回星星页面
if (fireworksOverlay.style.display === 'block') {
// 隐藏烟花遮罩层
fireworksOverlay.style.display = 'none';
birthdayText.style.display = 'none';
// 停止烟花动画
if (window.fireworksAnimationId) {
cancelAnimationFrame(window.fireworksAnimationId);
}
// 重置星星收集状态
collectedStars.clear();
document.getElementById('progressBar').style.width = '0%';
// 显示星星页面
starsPage.style.display = 'block';
}
// 如果在星星页面,则返回首页
else if (starsPage.style.display === 'block') {
starsPage.style.display = 'none';
navBackBtn.style.display = 'none'; // 只在首页隐藏返回按钮
}
});
setupBigStars();
setupStarClickEvents();
});
</script>
</body>
</html>
|
2302_77155773/my-website
|
index.html
|
HTML
|
unknown
| 39,674
|
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[] /* Custom plugin to extend the functionality of Hvigor. */
}
|
2302_80329073/Electron_gitcodeV1.0.0
|
electron/hvigorfile.ts
|
TypeScript
|
unknown
| 234
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello HarmonyOS!</title>
</head>
<body>
<h1>欢迎使用 Electron on HarmonyOS!</h1>
<p>这是运行在鸿蒙系统上的 Electron 应用</p>
</body>
</html>
|
2302_80329073/Electron_gitcodeV1.0.0
|
electron/src/main/resources/resfile/app/index.html
|
HTML
|
unknown
| 226
|
const { app, BrowserWindow } = require('electron');
const path = require('path');
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
win.loadFile('index.html');
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
|
2302_80329073/Electron_gitcodeV1.0.0
|
electron/src/main/resources/resfile/app/main.js
|
JavaScript
|
unknown
| 481
|
import { appTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[] /* Custom plugin to extend the functionality of Hvigor. */
}
|
2302_80329073/Electron_gitcodeV1.0.0
|
hvigorfile.ts
|
TypeScript
|
unknown
| 234
|
import { harTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: harTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[] /* Custom plugin to extend the functionality of Hvigor. */
}
|
2302_80329073/Electron_gitcodeV1.0.0
|
web_engine/hvigorfile.ts
|
TypeScript
|
unknown
| 234
|
// Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import LogUtil from '../utils/LogUtil';
const TAG: string = 'LogMethodCall';
/**
* Method log decorator
*/
const LogMethod = (
target: Object,
methodName: string,
propertyDescriptor: PropertyDescriptor): PropertyDescriptor => {
const method = propertyDescriptor.value;
propertyDescriptor.value = function (...args: object[]) {
const params = args.map(a => JSON.stringify(a)).join();
LogUtil.info(TAG, `${target.constructor.name}#${methodName}(${params}) in `);
const result = method.apply(this, args);
const r = JSON.stringify(result);
LogUtil.info(TAG, `${target.constructor.name}#${methodName}(${params}) out => ${r}`);
return result;
};
return propertyDescriptor;
};
/**
* Class decorator to log all methods
*/
export const LogAll = (target: ObjectConstructor) => {
Reflect.ownKeys(target.prototype).forEach(propertyKey => {
let propertyDescriptor: PropertyDescriptor = Object.getOwnPropertyDescriptor(target.prototype, propertyKey);
const method = propertyDescriptor.value;
if (method) {
propertyDescriptor.value = function (...args: object[]) {
const params = args.map(a => JSON.stringify(a)).join();
LogUtil.info(TAG, `${target.name}#${propertyKey.toString()}(${params}) in `);
const result = method.apply(this, args);
const r = JSON.stringify(result);
LogUtil.info(TAG, `${target.name}#${propertyKey.toString()}(${params}) out => ${r}`);
return result;
};
Object.defineProperty(target.prototype, propertyKey, propertyDescriptor);
}
});
};
export default LogMethod;
|
2302_80329073/Electron_gitcodeV1.0.0
|
web_engine/src/main/ets/common/LogDecorator.ts
|
TypeScript
|
unknown
| 1,784
|
// Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const MODULE_TYPE = {
Context: Symbol.for('Context'),
};
export { MODULE_TYPE };
|
2302_80329073/Electron_gitcodeV1.0.0
|
web_engine/src/main/ets/common/ModuleType.ts
|
TypeScript
|
unknown
| 255
|
// Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import type image from '@ohos.multimedia.image';
import type inputMethod from '@ohos.inputMethod';
import type GestureEvent from '@ohos.multimodalInput.gestureEvent';
import type ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant';
import type common from '@ohos.app.ability.common';
import type window from '@ohos.window';
export interface ILoginInfo {
status: boolean;
authCode: string;
unionId: string;
openId: string;
idToken: string;
anonymousPhone: string;
}
export interface ILogin {
loginCallbackFunc: (loginInfo: ILoginInfo) => void;
};
export interface WindowBound {
left: number;
top: number;
width: number;
height: number;
}
export interface CaptionButtonRect {
right: number;
top: number;
width: number;
height: number;
}
export class JSBind {
bindFunction: (name: string, func: Function) => number;
}
export interface CommandParameter {
url?: string;
user_data?: string;
is_sync?: boolean;
is_webapp?: boolean;
}
export interface CommandResult {
ret_code: number;
widget_Id: number;
last_widget_Id: number;
}
export interface WindowLimits {
maxHeight: number;
maxWidth: number;
minHeight: number;
minWidth: number;
}
export interface NativeContext {
runBrowser: (vec_args: string[]) => void;
BrowserDestroyed: () => boolean;
runOtherProcessType: (processType: number) => void;
registerLifecycle: () => void;
openFile: (filePath: string) => void;
readImageFromReceiver: (receiver: image.ImageReceiver) => image.Image;
JSBind: JSBind;
OnPanEventCB: (action: number, id: string, event: GestureEvent) => void;
OnPinchEventCB: (pinch_step: string, id: string, event: GestureEvent) => void;
InsertTextCallback: (text: string) => void;
DeleteBackCallback: (length: number) => void;
DeleteForwardCallback: (length: number) => void;
SendEnterKeyEventCallback: () => void;
MoveCursorCallback: (direction: inputMethod.Direction) => void;
SetThemeSource: (themeSource: ConfigurationConstant.ColorMode) => void;
OnDragEnterCB: (id: string, dragInfo: OhosDropData, fileUris: Array<string>) => void;
OnDragLeaveCB: (id: string) => void;
OnDragEndCB: (id: string) => void;
OnDragMoveCB: (id: string, windowX: number, windowY: number) => void;
OnDropCB: (id: string, dragInfo: OhosDropData, fileUris: Array<string>) => void;
OnFontSizeChangeCallback:(fontSizeZoom :number) => void;
OnWindowInitSize: (windowRect: WindowBound, drawableRect: WindowBound, displayId: number) => void;
OnWindowStatusChange: (id: string, status: window.WindowStatusType) => void;
OnWindowVisibleChange: (windowId: String, visible: boolean) => void;
OnWindowInitState: (state: window.WindowStatusType) => void;
OnWindowRectChange: (id: string, event: WindowBound, reason: number) => void;
OnWindowSizeChange: (id: string, event: WindowBound) => void;
OnWindowEvent: (id: string, event: number) => void;
OnWindowVisibilityChange: (id: string, visible: boolean) => void;
OnKeyboardHeightChange: (id: string, height: number) => void;
OnNotificationClickCallback: (id: number) => void;
OnNotificationCloseCallback: (id: number) => void;
OnNotificationButtonClickCallback: (id: number, buttonIndex) => void;
OnDisplayChangeCallback: (even: string, id: number) => void;
ExecuteCommand: (id: number, param: CommandParameter) => CommandResult;
GetBrowserCloseResponse: (id: number) => BrowserCloseResponse;
GetAppCloseResponse: () => BrowserCloseResponse;
RegisterWindowEventFilter: (origin_window_id: number) => void;
ClearWindowEventFilter: (origin_window_id: number) => void;
OnCaptionButtonRectChange: (id: string, event: CaptionButtonRect) => void;
UpdateWindowDeviceModeSwitchCB: (mode: DeviceMode) => void;
SetSystemWindowLimits: (windowLimits: WindowLimits) => void;
OnWindowDisplayIdChange: (xcomponent_id: string, display_id: number) => void;
OnDeviceModeChange: (id: string, event: ChangeEventType, status: window.WindowStatusType) => void;
}
export interface IParams {
callback: (id: string) => void,
id: string,
size: number[], // [width, height]
initColorRgb: string,
}
export interface OhosDragParamToJs {
text: string;
url: string;
urlTitle: string;
html: string;
webImageFilePath: string;
electronFilePath: string;
bookmarkBuffer: ArrayBuffer;
webCustomBuffer: ArrayBuffer;
pixelMapBuffer: ArrayBuffer;
pixelMapWidth: number;
pixelMapHeight: number;
pixelMapTouchX: number;
pixelMapTouchY: number;
windowId: string;
}
export interface OhosDropData {
text: string;
url: string;
urlTitle: string;
html: string;
fileUris: Array<string>;
bookmarkBuffer: ArrayBuffer | undefined;
webCustomBuffer: ArrayBuffer | undefined;
}
export interface IMFAdapterInputAttribute {
inputPattern: inputMethod.TextInputType;
enterKeyType: inputMethod.EnterKeyType;
}
export interface IMFAdapterCursorInfo {
left: number;
top: number;
width: number;
height: number;
}
export interface IMFAdapterTextConfig {
inputAttribute: IMFAdapterInputAttribute;
cursorInfo: IMFAdapterCursorInfo;
}
export interface NotificationAdapterImage {
width: number;
height: number;
buff: ArrayBuffer;
}
export interface NotificationAdapterButton {
title: string;
buttonIndex: number;
}
export interface NotificationAdapterRequest {
notificationId: number;
title: string;
message: string;
requireInteraction: boolean;
silent: boolean;
timestamp: number;
icon: NotificationAdapterImage;
buttons: NotificationAdapterButton[];
}
export interface OhosPasteDataRecord {
html_text: string;
mime_type: string;
plain_text: string;
}
export interface SpeakingParamsExtraParams {
speed?: number;
volume?: number;
pitch?: number;
languageContext?: string;
audioType?: string;
playType?: number;
soundChannel?: number;
queueMode?: number;
}
export interface SpeakingParams {
requestId: string;
extraParams?: SpeakingParamsExtraParams;
}
export interface EngineCreationParamsExtraParams {
style?: string;
locate?: string;
name?: string;
}
export interface EngineCreationParams {
language: string;
online: number;
person: number;
extraParams?: EngineCreationParamsExtraParams;
}
export interface VoiceQueryExtraParams {
language?: string;
person?: number;
}
export interface VoiceQuery {
requestId: string;
online: number;
extraParams?: VoiceQueryExtraParams
}
export interface VoiceInfo {
language: string;
person: number;
style: string;
status: string;
gender: string;
description: string;
}
export interface AdvertisingParam {
connectable: boolean;
service_uuids: string[];
manufacturer_data: Map<number, Uint8Array>;
service_data: Map<string, Uint8Array>;
scan_response_data: Map<number, Uint8Array>;
}
// see the file
// src/ohos/adapter/common/constants.h
// The enumeration order should be kept the same
export enum WindowType {
INVALID = -1,
MAIN_WINDOW = 0,
SUB_WINDOW,
FLOAT_WINDOW
}
export interface NewWindowParam {
parent_id: string,
window_id: string,
bounds: WindowBound,
init_color_argb: string,
hide_title_bar: boolean,
use_dark_mode: boolean,
show: boolean,
minimizable: boolean,
maximizable: boolean,
closable: boolean,
always_on_top: boolean,
resizable: boolean,
is_modal: boolean,
is_panel: boolean,
display_id: number,
ability_type: AbilityType,
app_id: string
}
export interface ISubWindowInfo {
id: string,
parentId: string,
subWindow: window.Window,
localStorage: LocalStorage,
}
export interface SelectFileDialogParams {
multi_files: boolean,
extensions: Array<Array<string>>,
descriptions: Array<string>,
include_all_files: boolean
}
export interface SaveAsDialogParams {
file_name: string,
dir_name: string,
extensions: Array<Array<string>>,
descriptions: Array<string>,
include_all_files: boolean
}
export interface PointCoordinate {
x: number
y: number,
displayId: number,
}
export enum BrowserCloseResponse {
kUndetermined,
kClosingContinue,
kClosingInterrupt,
kClosed,
kCloseCancelled,
kClosedAnyway,
}
// Electron
export interface WindowPreferences {
hideTitleBar: boolean,
minimizable: boolean,
maximizable: boolean,
closable: boolean,
}
export enum DeviceMode {
kPcMode = 0,
kNormalWindowMode,
kFreeWindowsMode,
};
export enum ChangeEventType {
CHANGE_TO_NORMAL_MODE = 0,
CHANGE_TO_FREE_MODE
};
export enum AbilityType {
kEntryAbility = 0,
kStatelessAbility,
kTaskManagerAbility,
};
export interface DesktopShortcut {
shortcutId: string;
label: string;
foregroundIconPath: string;
backgroundIconPath: string;
openAsWindow: boolean;
};
export interface IWebAppInfo {
openAsWindow: boolean;
label: string;
icon: string;
appId: string;
}
export const kAbilityMap = new Map<AbilityType, string>([
[AbilityType.kEntryAbility, 'EntryAbility'],
[AbilityType.kStatelessAbility, 'StatelessAbility'],
[AbilityType.kTaskManagerAbility, 'TaskManagerAbility']
])
|
2302_80329073/Electron_gitcodeV1.0.0
|
web_engine/src/main/ets/interface/CommonInterface.ts
|
TypeScript
|
unknown
| 9,182
|
// Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
export default class CheckEmptyUtils {
/**
* Check obj is empty.
*
* @param {any} obj
* @return {boolean} true(empty)
*/
static isEmpty(obj: any): boolean {
return (typeof obj === 'undefined' || obj === null || obj === '');
}
/**
* Check str is empty.
*
* @param {string} str
* @return {boolean} true(empty)
*/
static checkStrIsEmpty(str: string): boolean {
return str === undefined || str === null || str.trim().length === 0;
}
/**
* Check array is empty.
*
* @param {Array} arr An array to check if is empty.
* @return {boolean} true(empty)
*/
static isEmptyArr<T>(arr: T[]): boolean {
return arr === undefined || arr === null || arr.length === 0;
}
};
|
2302_80329073/Electron_gitcodeV1.0.0
|
web_engine/src/main/ets/utils/CheckEmptyUtils.ts
|
TypeScript
|
unknown
| 904
|
// Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
export class GlobalContext {
private static instance: GlobalContext;
private _objects = new Map<string, Object>();
public static getInstance(): GlobalContext {
if (GlobalContext.instance == null) {
GlobalContext.instance = new GlobalContext();
}
return GlobalContext.instance;
}
public getObject(key: string): Object | undefined {
let result = this._objects.get(key);
return result;
}
public hasObject(key: string): boolean {
return this._objects.has(key);
}
public setObject(key: string, objectClass: Object): void {
this._objects.set(key, objectClass);
}
}
|
2302_80329073/Electron_gitcodeV1.0.0
|
web_engine/src/main/ets/utils/GlobalContext.ts
|
TypeScript
|
unknown
| 788
|
// Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import hilog from '@ohos.hilog';
/**
* log package tool class
*/
export default class LogUtil {
private static DOMAIN: number = 0x0000;
private static TAG: string = '[WebEngine]';
/**
* print debug level log
*
* @param {string} tag - Page or class tag
* @param {string} msg - Log needs to be printed
*/
static debug(tag: string, msg: string): void {
hilog.debug(LogUtil.DOMAIN, LogUtil.TAG, 'tag: %{public}s --> %{public}s', tag, msg);
}
/**
* print info level log
*
* @param {string} tag - Page or class tag
* @param {string} msg - Log needs to be printed
*/
static info(tag: string, msg: string): void {
hilog.info(LogUtil.DOMAIN, LogUtil.TAG, 'tag: %{public}s --> %{public}s', tag, msg);
}
/**
* print warn level log
*
* @param {string} tag - Page or class tag
* @param {string} msg - Log needs to be printed
*/
static warn(tag: string, msg: string): void {
hilog.warn(LogUtil.DOMAIN, LogUtil.TAG, 'tag: %{public}s --> %{public}s', tag, msg);
}
/**
* print error level log
*
* @param {string} tag - Page or class tag
* @param {string} msg - Log needs to be printed
*/
static error(tag: string, msg: string): void {
hilog.error(LogUtil.DOMAIN, LogUtil.TAG, 'tag: %{public}s --> %{public}s', tag, msg);
}
}
|
2302_80329073/Electron_gitcodeV1.0.0
|
web_engine/src/main/ets/utils/LogUtil.ts
|
TypeScript
|
unknown
| 1,492
|
// Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
export default class ObjUtil {
public static isInvalid(obj): boolean {
return obj === undefined || obj === null;
}
}
|
2302_80329073/Electron_gitcodeV1.0.0
|
web_engine/src/main/ets/utils/ObjUtil.ts
|
TypeScript
|
unknown
| 296
|
// Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
export class StringStack {
private stack: string[] = [];
public push(element: string): void {
this.stack.push(element);
}
public remove(element: string): void {
const index = this.stack.indexOf(element);
if (index > -1) {
this.stack.splice(index, 1);
}
}
public peek(): string {
return this.stack[this.stack.length - 1];
}
public isEmpty(): boolean {
return this.stack.length === 0;
}
}
|
2302_80329073/Electron_gitcodeV1.0.0
|
web_engine/src/main/ets/utils/StringStackUtil.ts
|
TypeScript
|
unknown
| 611
|
// Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import fileUri from '@ohos.file.fileuri';
export default class StringUtil {
private static TAG: string = 'StringUtil';
static uriConvert(docs: string[]): string[] {
let copy: string[] = [];
docs.forEach((path) => {
// Resolve Chinese garbled characters
path = decodeURI(path);
// Convert to uri get systeam path
let uri = new fileUri.FileUri(path);
copy.push(uri.path);
});
return copy;
}
}
|
2302_80329073/Electron_gitcodeV1.0.0
|
web_engine/src/main/ets/utils/StringUtil.ts
|
TypeScript
|
unknown
| 617
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>烟雨江南</title>
</head>
<body>
<!-- 头部 -->
<div class="nav">
<div class="logo">
烟 雨 江 南
</div>
<div class="navright">
<ul>
<li ><a href="index.html">主页</a></li>
<li ><a href="delicacies.html">美食</a></li>
<li><a href="tourism.html">旅游</a></li>
<li><a href="login.html">登录</a></li>
<li ><a href="enroll.html">注册</a></li>
<li class="borderbox"><a href="Aboutwebsite.html">关于网站</a></li>
</ul>
</div>
<div class="navtitle">
关于网站
</div>
<div class="positioning">
主页 > 关于网站
</div>
</div>
<!-- 内容 -->
<div class="bannertitle">
关于我们
</div>
<div class="intellectual ">
烟雨江南旅游网是专业的旅游产品网络营销推广平台,目前已吸引全国2000余家旅行社、20000余家酒店、5000余家景区加盟合作
<p> 烟雨江南旅游网为旅游消费者提供最专业的最实时的旅游线路、酒店、门票服务,帮助消费者从供货商提供的海量旅游信息中快速找到自己最需要的最合适的旅游信息。旅游消费者可以通过烟雨江南旅游网快速获得旅游供应商的网上、网下咨询和预订服务。</p>
<p>烟雨江南旅游网还为广大游客提供国内外所有旅游城市和景点最详尽的旅游参考信息。通过“目的地+旅游”的推广方式,使游客能够更方便地找到自己需要的旅游产品。</p>
</div>
<div class="bannertitle">
关于知识产权
</div>
<div class="intellectual ">
烟雨江南旅游网上刊登的文章及图片,均为网友发布。对于涉嫌侵犯任何单位或个人合法权益的内容,请权利人及时向全程旅游网书面反馈,并提供身份证明、权属证明、
详细侵权情况证明及所提供资料真实性的书面保证,烟雨江南旅游网在收到上述文件后,将会尽快删除相关侵权内容。
<p> 烟雨江南旅游网的行为适用于中华人民共和国法律法规规定的其它有关免责规定。</p>
</div>
<div class="bannertitle">
关于网站服务
</div>
<div class="intellectual ">
烟雨江南旅游网仅提供旅游信息服务,不提供交易服务。本站的旅游信息均为旅行社会员所发。由于旅游行情变化频繁,所有信息以咨询发布人为准。与供应商达成交易前务必签订正式旅游合同
</div>
<!-- 底部 -->
<div class="foot">
<div class="footlogo">
烟 雨 江 南
</div>
<div class="nickname">
“我本无意入江南,奈何江南入我心”
</div>
<div class="Companyaddress">
公司地址:烟雨江南
</div>
<div class="Customerservicehotline">
客服热线:+ 010 854 6578
</div>
<div class="OfficialWeibo">
官方微博:烟雨江南
</div>
<div class="WeChatpublicaccount">
微信公众号:烟雨江南
</div>
</body>
<script src="/js/jquery-3.7.1.js"></script>
<script>
//导航下划线
$lis = $('.navright ul li')
$lis.hover(function() {
$(this).addClass('borderbox'); // 添加样式类
$(this).siblings().removeClass('borderbox'); // 移除兄弟元素的样式类
}, function() {
$(this).removeClass('borderbox'); // 移除样式类
});
//鼠标离开头部显示导航下划线
//鼠标触摸头部显示透明色
$nav=$('.nav')
$nav.hover(function() {
}, function() {
$lis.eq(5).addClass('borderbox')
});
</script>
<style>
.nav{
position: relative;
width: 100%;
height: 250px;
background-color: rgb(159, 10, 14);
}
.logo{
width: 130px;
height: 80px;
/* background-color: rgb(8, 84, 84); */
font-weight: bold;
font-size: 25px;
line-height: 80px;
margin-left: 30px;
color: white;
float: left;
}
.navright{
float: right;
width: 600px;
height: 80px;
/* background-color: yellow; */
margin-right: 10px;
}
.navright ul li{
list-style: none;
float: left;
margin-right: 10px;
line-height: 45px;
font-weight: bold;
font-size: 16px;
width: 80px;
height: 40px;
margin-top: 20px;
text-align: center;
/* background-color: aquamarine; */
}
.navright ul li a{
color: white;
text-decoration: none;
}
.borderbox{
border-bottom: 1px solid white;
}
.navtitle{
width: 80px;
height: 40px;
/* background-color: blue; */
font-weight: bold;
text-align: center;
margin-left: 50px;
line-height: 40px;
font-size: 18px;
color: white;
position: absolute;
top: 130px;
}
.positioning{
width: 150px;
height: 40px;
/* background-color: blue; */
font-weight: bold;
text-align: center;
margin-left: 20px;
line-height: 40px;
font-size: 14px;
color: white;
position: absolute;
top: 180px;
}
.bannertitle{
margin-top: 40px;
width: 280px;
height: 40px;
/* background-color: blue; */
font-weight: bold;
text-align: center;
margin-left: 50px;
line-height: 40px;
font-size: 20px;
color: black;
}
.intellectual{
line-height: 30px;
width: 1000px;
margin-top: 20px;
margin-left: 140px;
margin-bottom: 30px;
/* height: 200px; */
/* background-color: brown; */
}
/* 底部 */
.foot{
position: relative;
width: 100%;
height: 150px;
background-color: black;
}
.footlogo{
position: absolute;
left: 200px;
width: 130px;
height: 80px;
/* background-color: rgb(8, 84, 84); */
font-weight: bold;
font-size: 25px;
line-height: 80px;
/* margin-left: 30px; */
color: white;
float: left;
}
.nickname{
position: absolute;
top: 100px;
left: 190px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 16px;
color: white;
/* background-color: aquamarine; */
}
.Companyaddress{
position: absolute;
top: 50px;
left: 600px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
.Customerservicehotline{
position: absolute;
top: 100px;
left: 600px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
.OfficialWeibo{
position: absolute;
top: 100px;
left: 1000px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
.WeChatpublicaccount{
position: absolute;
top: 50px;
left: 1000px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
</style>
</html>
|
2202_75337835/Jiangnan
|
Aboutwebsite.html
|
HTML
|
unknown
| 7,293
|
body{
margin: 0;
padding: 0;
}
#top-image {
background: linear-gradient(
rgba(0, 0, 0, 0.2),
rgba(0, 0, 0, 0.2)
), url('../images/gz.jpeg') no-repeat fixed;
position:fixed ;
top:0;
width:100%;
z-index:0;
height:100%;
}
|
2202_75337835/Jiangnan
|
css/style.css
|
CSS
|
unknown
| 251
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>烟雨江南</title>
</head>
<body>
<!-- 头部 -->
<div class="nav">
<div class="logo">
烟 雨 江 南
</div>
<div class="navright">
<ul>
<li ><a href="index.html">主页</a></li>
<li class="borderbox"><a href="delicacies.html">美食</a></li>
<li><a href="tourism.html">旅游</a></li>
<li><a href="login.html">登录</a></li>
<li><a href="enroll.html">注册</a></li>
<li><a href="Aboutwebsite.html">关于网站</a></li>
</ul>
</div>
<div class="navtitle">
美食
</div>
<div class="positioning">
主页 > 美食
</div>
</div>
<!-- 内容 -->
<div class="bannertitle">
美食分享
</div>
<div class="bannerswiper">
<!-- 图片展示 -->
<div class="all">
<div style="background-image: url(images/foods/3.jpg);">
<span></span><img src="images/foods/3.jpg"/>
</div>
<div style="background-image: url(images/foods/1.jpg);">
<span></span><img src="images/foods/1.jpg"/>
</div>
<div style="background-image: url(images/foods/2.jpg);">
<span></span><img src="images/foods/2.jpg"/>
</div>
<div data-index="3" style="background-image: url(images/foods/0.jpg);">
<span></span><img src="images/foods/0.jpg"/>
</div>
<div style="background-image: url(images/foods/4.jpg);">
<span></span><img src="images/foods/4.jpg"/>
</div>
<div style="background-image: url(images/foods/5.jpg);">
<span></span><img src="images/foods/5.jpg"/>
</div>
<div style="background-image: url(images/foods/6.jpg);">
<span></span><img src="images/foods/6.jpg"/>
</div>
</div>
</div>
<!-- 美食推荐 -->
<div class="foodrecommend">
<div class="recommend">
美食推荐
</div>
<div class="recommedimg">
<ul>
<li>
<div class="topimg">
<img src="images/foods/ydx.webp" alt="">
</div>
<div class="bottomtext">腌笃鲜</div>
</li>
<li>
<div class="topimg">
<img src="images/foods/ljxr.webp" alt="">
</div>
<div class="bottomtext">龙井虾仁</div>
</li>
<li>
<div class="topimg">
<img src="images/foods/cbh.webp" alt="">
</div>
<div class="bottomtext">葱包烩</div>
</li>
<li>
<div class="topimg">
<img src="images/foods/dpr.webp" alt="">
</div>
<div class="bottomtext">东坡肉</div>
</li>
<li>
<div class="topimg">
<img src="images/foods/acqt.webp" alt="">
</div>
<div class="bottomtext">艾草青团</div>
</li>
<li>
<div class="topimg">
<img src="images/foods/ghg.webp" alt="">
</div>
<div class="bottomtext">桂花糕</div>
</li>
<li>
<div class="topimg">
<img src="images/foods/thcd.webp" alt="">
</div>
<div class="bottomtext">太湖船点</div>
</li>
<li>
<div class="topimg">
<img src="images/foods/azm.webp" alt="">
</div>
<div class="bottomtext">奥灶面</div>
</li>
</ul>
</div>
</div>
<!-- 底部 -->
<div class="foot">
<div class="footlogo">
烟 雨 江 南
</div>
<div class="nickname">
“我本无意入江南,奈何江南入我心”
</div>
<div class="Companyaddress">
公司地址:烟雨江南
</div>
<div class="Customerservicehotline">
客服热线:+ 010 854 6578
</div>
<div class="OfficialWeibo">
官方微博:烟雨江南
</div>
<div class="WeChatpublicaccount">
微信公众号:烟雨江南
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
//导航下划线
$lis = $('.navright ul li')
$lis.hover(function() {
$(this).addClass('borderbox'); // 添加样式类
$(this).siblings().removeClass('borderbox'); // 移除兄弟元素的样式类
}, function() {
$(this).removeClass('borderbox'); // 移除样式类
});
//鼠标离开头部显示导航下划线
//鼠标触摸头部显示透明色
$nav=$('.nav')
$nav.hover(function() {
}, function() {
$lis.eq(1).addClass('borderbox')
});
//轮播图逻辑
//图片展示逻辑
// 只需要变化图片的高以及div的宽即可。
$(function () {
// 设置初始图片的宽高
setWAndH($(".all>div:nth-of-type(4)").attr("data-index"));
// 当图片被点击时触发事件
$(".all>div").on("click", function () {
// 设置对应索引的图片宽高
setWAndH($(this).attr("data-index"));
});
// 定义设置图片和div宽高的函数
function setWAndH(indexTemp) {
// 遍历所有图片展示区域的div
$(".all>div").each(function (index) {
// 如果当前div没有data-index属性,则为其设置默认值
if (!$(this).attr("data-index")) {
$(this).attr("data-index", index);
}
// 初始化左边距值
var leftTemp = 0;
// 根据传入的索引值设置当前div的宽高和位置
if (indexTemp == index) {
// 计算左边距
leftTemp = index * 60;
// 设置当前div的宽高和位置,并使用动画效果
$(this).stop(false, true).animate({
width: 800,
height: 500 - Math.abs(indexTemp - index) * 22,
left: leftTemp
}).children("img").stop(false, true).animate({
height: "100%",
opacity: 1,
top: 0
}, 300);
} else {
// 计算左边距
if (index > indexTemp) {
leftTemp = (index - 1) * 60 + 800;
} else {
leftTemp = index * 60;
}
// 设置当前div的宽高和位置,并使用动画效果
$(this).stop(false, true).animate({
width: 60,
height: 500 - Math.abs(indexTemp - index) * 32,
left: leftTemp
}).children("img").stop(false, true).animate({
height: 0,
opacity: 0,
top: "50%"
}, 300);
}
// 设置高度
});
}
});
</script>
<style>
.nav{
position: relative;
width: 100%;
height: 250px;
background-color: rgb(159, 10, 14);
}
.logo{
width: 130px;
height: 80px;
/* background-color: rgb(8, 84, 84); */
font-weight: bold;
font-size: 25px;
line-height: 80px;
margin-left: 30px;
color: white;
float: left;
}
.navright{
float: right;
width: 600px;
height: 80px;
/* background-color: yellow; */
margin-right: 10px;
}
.navright ul li{
list-style: none;
float: left;
margin-right: 10px;
line-height: 45px;
font-weight: bold;
font-size: 16px;
width: 80px;
height: 40px;
margin-top: 20px;
text-align: center;
/* background-color: aquamarine; */
}
.navright ul li a{
color: white;
text-decoration: none;
}
.borderbox{
border-bottom: 1px solid white;
}
.navtitle{
width: 80px;
height: 40px;
/* background-color: blue; */
font-weight: bold;
text-align: center;
margin-left: 50px;
line-height: 40px;
font-size: 18px;
color: white;
position: absolute;
top: 130px;
}
.positioning{
width: 80px;
height: 40px;
/* background-color: blue; */
font-weight: bold;
text-align: center;
margin-left: 50px;
line-height: 40px;
font-size: 14px;
color: white;
position: absolute;
top: 180px;
}
.bannertitle{
margin-top: 50px;
width: 280px;
height: 40px;
/* background-color: blue; */
font-weight: bold;
text-align: center;
margin-left: 50px;
line-height: 40px;
font-size: 20px;
color: black;
}
.bannerswiper{
/* margin-top: 20px; */
width: 1520px;
height: 500px;
/* background-color: aqua; */
}
/* 图片展示 */
.all {
position: relative;
line-height: 424px;
width: 1000px;
height: 424px;
margin-top: 100px;
margin-left: 200px;
margin-right: 200px;
/* background-color: yellow; */
}
.all > div {
position: absolute;
border: 1px solid silver;
background: #ebffc6;
top: 0;
bottom: 0;
margin: auto;
}
.all>div>span{
position: absolute;
display: inline-block;
width: 100%;;
text-align: center;
}
img {
position: absolute;
width: 100%;
height: 0;
top: 50%;
}
/* 美食推荐 */
.foodrecommend{
position: relative;
width:1200px;
height: 650px;
margin: 20px auto;
/* background-color: tomato; */
}
.recommend{
position: absolute;
clear: both;
left: 420px;
width: 280px;
height: 40px;
/* background-color: blue; */
font-weight: bold;
text-align: center;
margin-left: 50px;
line-height: 40px;
font-size: 20px;
color: black;
}
.recommedimg{
position: absolute;
top: 60px;
width: 100%;
height: 580px;
/* background-color: aquamarine; */
}
.recommedimg ul li{
list-style: none;
width: 270px;
height: 250px;
/* background-color: blue; */
float: left;
margin-right: 20px;
margin-top: 20px;
}
.topimg{
width: 100%;
height: 200px;
/* background-color: tomato; */
}
.topimg img{
width: 100%;
height: 100%;
position: inherit;
}
.bottomtext{
width: 100%;
height: 50px;
/* background-color: thistle; */
text-align: center;
font-weight: bold;
line-height: 50px;
}
/* 底部 */
.foot{
position: relative;
width: 100%;
height: 150px;
background-color: black;
}
.footlogo{
position: absolute;
left: 200px;
width: 130px;
height: 80px;
/* background-color: rgb(8, 84, 84); */
font-weight: bold;
font-size: 25px;
line-height: 80px;
/* margin-left: 30px; */
color: white;
float: left;
}
.nickname{
position: absolute;
top: 100px;
left: 190px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 16px;
color: white;
/* background-color: aquamarine; */
}
.Companyaddress{
position: absolute;
top: 50px;
left: 600px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
.Customerservicehotline{
position: absolute;
top: 100px;
left: 600px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
.OfficialWeibo{
position: absolute;
top: 100px;
left: 1000px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
.WeChatpublicaccount{
position: absolute;
top: 50px;
left: 1000px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
</style>
</html>
|
2202_75337835/Jiangnan
|
delicacies.html
|
HTML
|
unknown
| 12,003
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>烟雨江南</title>
</head>
<body>
<!-- 头部 -->
<div class="nav">
<div class="logo">
烟 雨 江 南
</div>
<div class="navright">
<ul>
<li ><a href="index.html">主页</a></li>
<li><a href="delicacies.html">美食</a></li>
<li><a href="tourism.html">旅游</a></li>
<li ><a href="login.html">登录</a></li>
<li class="borderbox"><a href="enroll.html">注册</a></li>
<li><a href="Aboutwebsite.html">关于网站</a></li>
</ul>
</div>
<div class="navtitle">
注册
</div>
<div class="positioning">
主页 > 注册
</div>
</div>
<div class="banner">
<div class="auto">
<div class="logintext">
注 册
</div>
<div class="loginfrom">
<div class="loginname">用 户 名 / 手 机 号</div>
<input type="text" class="username" placeholder="">
<div class="loginname">密码</div>
<input type="password" class="username" placeholder="">
<div class="loginname">再次输入密码</div>
<input type="password" class="username" placeholder="">
<div class="submit">注 册</div>
<div class="gologin">
已有账号 去<a href="login.html">登录</a>
</div>
</div>
</div>
</div>
<!-- 底部 -->
<div class="foot">
<div class="footlogo">
烟 雨 江 南
</div>
<div class="nickname">
“我本无意入江南,奈何江南入我心”
</div>
<div class="Companyaddress">
公司地址:烟雨江南
</div>
<div class="Customerservicehotline">
客服热线:+ 010 854 6578
</div>
<div class="OfficialWeibo">
官方微博:烟雨江南
</div>
<div class="WeChatpublicaccount">
微信公众号:烟雨江南
</div>
</div>
</body>
<script src="/js/jquery-3.7.1.js"></script>
<script>
//导航下划线
$lis = $('.navright ul li')
$lis.hover(function() {
$(this).addClass('borderbox'); // 添加样式类
$(this).siblings().removeClass('borderbox'); // 移除兄弟元素的样式类
}, function() {
$(this).removeClass('borderbox'); // 移除样式类
});
//鼠标离开头部显示导航下划线
//鼠标触摸头部显示透明色
$nav=$('.nav')
$nav.hover(function() {
}, function() {
$lis.eq(4).addClass('borderbox')
});
</script>
<style>
.nav{
position: relative;
width: 100%;
height: 250px;
background-color: rgb(159, 10, 14);
}
.logo{
width: 130px;
height: 80px;
/* background-color: rgb(8, 84, 84); */
font-weight: bold;
font-size: 25px;
line-height: 80px;
margin-left: 30px;
color: white;
float: left;
}
.navright{
float: right;
width: 600px;
height: 80px;
/* background-color: yellow; */
margin-right: 10px;
}
.navright ul li{
list-style: none;
float: left;
margin-right: 10px;
line-height: 45px;
font-weight: bold;
font-size: 16px;
width: 80px;
height: 40px;
margin-top: 20px;
text-align: center;
/* background-color: aquamarine; */
}
.navright ul li a{
color: white;
text-decoration: none;
}
.borderbox{
border-bottom: 1px solid white;
}
.navtitle{
width: 80px;
height: 40px;
/* background-color: blue; */
font-weight: bold;
text-align: center;
margin-left: 50px;
line-height: 40px;
font-size: 18px;
color: white;
position: absolute;
top: 130px;
}
.positioning{
width: 80px;
height: 40px;
/* background-color: blue; */
font-weight: bold;
text-align: center;
margin-left: 50px;
line-height: 40px;
font-size: 14px;
color: white;
position: absolute;
top: 180px;
}
.banner{
margin-top: 20px;
width: 100%;
height: 400px;
/* background-color: tomato; */
margin-bottom: 50px;
}
.auto{
margin: 0 auto;
width: 80%;
height: 100%;
/* background-color: violet; */
}
.logintext{
width: 100%;
height: 40px;
line-height: 40px;
/* background-color: aqua; */
text-align: center;
font-size: 28px;
font-weight: bold;
}
.loginfrom{
margin-top: 20px;
margin-left: 405px;
width: 400px;
height: 340px;
/* background-color: blue; */
}
.loginname{
width: 150px;
line-height: 30px;
font-size: 14px;
font-weight: bold;
color: #979899;
margin-left: 80px;
margin-bottom: 5px;
/* background-color: aquamarine; */
}
.username{
width: 200px;
height: 20px;
margin-left: 80px;
border-radius: 5px;
padding: 5px;
margin-bottom: 10px;
}
.submit{
margin-left: 80px;
width: 210px;
height: 35px;
background-color: orangered;
text-align: center;
line-height: 35px;
font-weight: bold;
color: white;
border-radius: 5px;
margin-top: 10px;
}
.gologin{
width: 210px;
line-height: 30px;
/* background-color: aqua; */
text-align: center;
margin-top: 20px;
font-size: 13px;
margin-left: 80px;
}
.gologin a{
color: red;
text-decoration: none;
}
/* 底部 */
.foot{
position: relative;
width: 100%;
height: 150px;
background-color: black;
}
.footlogo{
position: absolute;
left: 200px;
width: 130px;
height: 80px;
/* background-color: rgb(8, 84, 84); */
font-weight: bold;
font-size: 25px;
line-height: 80px;
/* margin-left: 30px; */
color: white;
float: left;
}
.nickname{
position: absolute;
top: 100px;
left: 190px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 16px;
color: white;
/* background-color: aquamarine; */
}
.Companyaddress{
position: absolute;
top: 50px;
left: 600px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
.Customerservicehotline{
position: absolute;
top: 100px;
left: 600px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
.OfficialWeibo{
position: absolute;
top: 100px;
left: 1000px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
.WeChatpublicaccount{
position: absolute;
top: 50px;
left: 1000px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
</style>
</html>
|
2202_75337835/Jiangnan
|
enroll.html
|
HTML
|
unknown
| 6,987
|
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>烟雨江南</title>
<link rel="stylesheet" type="text/css" href="https://www.jq22.com/jquery/bootstrap-3.3.4.css">
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<div id="top-image">
<!-- 头部 -->
<div class="nav">
<div class="logo">
烟 雨 江 南
</div>
<div class="navright">
<ul>
<li class="borderbox"><a href="index.html">主页</a></li>
<li><a href="delicacies.html">美食</a></li>
<li><a href="tourism.html">旅游</a></li>
<li><a href="login.html">登录</a></li>
<li><a href="enroll.html">注册</a></li>
<li><a href="Aboutwebsite.html">关于网站</a></li>
</ul>
</div>
</div>
<!-- 内容 -->
<div class="banner">
<div class="nickname">
“小巷深深梦徽州,白墙黛瓦见江南”
</div>
<div class="name">
这 里 是 江 南
</div>
<div class="welecome">
Welcome to Gangnam
</div>
<div class="login" data-url="login.html">
登录
</div>
<div class="enroll" data-url="enroll.html">
注册
</div>
</div>
</div>
</div>
<script src="https://www.jq22.com/jquery/jquery-1.10.2.js"></script>
<script src="js/ios-parallax.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#top-image').iosParallax({
movementFactor: 50
});
});
//导航下划线
$lis=$('.navright ul li')
$lis.hover(function() {
$(this).addClass('borderbox'); // 添加样式类
$(this).siblings().removeClass('borderbox'); // 移除兄弟元素的样式类
}, function() {
$(this).removeClass('borderbox'); // 移除样式类
});
//鼠标触摸头部显示透明色
$nav=$('.nav')
$nav.hover(function() {
$(this).addClass('bgc'); // 添加样式类
}, function() {
$(this).removeClass('bgc'); // 移除样式类
$lis.eq(0).addClass('borderbox')
});
//按钮触摸变色
$enroll =$('.enroll')
$enroll.hover(function(){
$(this).addClass('hoverbtn')
},function(){
$(this).removeClass('hoverbtn')
})
//点击按钮体跳转至登录页
$login = $('.login')
$login.click(function(){
var url = $(this).data('url');
// 使用 JavaScript 跳转到指定页面
window.location.href = url;
})
//点击按钮体跳转至注册页
$enroll = $('.enroll')
$enroll.click(function(){
var url = $(this).data('url');
// 使用 JavaScript 跳转到指定页面
window.location.href = url;
})
</script>
</body>
<style>
.nav{
width: 100%;
height: 80px;
}
.bgc{
background-color: rgb(0,0,0,0.2);
}
.logo{
width: 130px;
height: 100%;
/* background-color: rgb(8, 84, 84); */
font-weight: bold;
font-size: 25px;
line-height: 80px;
margin-left: 30px;
color: white;
float: left;
}
.navright{
float: right;
width: 600px;
height: 100%;
/* background-color: yellow; */
margin-right: 10px;
}
.navright ul li{
list-style: none;
float: left;
margin-right: 10px;
line-height: 45px;
font-weight: bold;
font-size: 16px;
width: 80px;
height: 40px;
margin-top: 20px;
text-align: center;
/* background-color: aquamarine; */
}
.navright ul li a{
color: white;
text-decoration: none;
}
.borderbox{
border-bottom: 1px solid white;
}
.banner{
margin-left: 60px;
width: 500px;
height: 400px;
/* background-color: blueviolet; */
margin-top: 180px;
}
.nickname{
width: 500px;
text-align: center;
height:50px;
line-height: 50px;
font-weight: bold;
font-size: 25px;
color: white;
/* background-color: aquamarine; */
}
.name{
margin-left: 55px;
width: 250px;
height:50px;
line-height: 50px;
font-weight: bold;
font-size: 40px;
color: white;
/* background-color: rgb(5, 83, 179); */
}
.welecome{
margin-left: 55px;
width: 250px;
height:50px;
line-height: 50px;
color: white;
/* background-color: rgb(145, 6, 148); */
}
.login{
margin-left: 55px;
margin-top: 40px;
width: 150px;
height: 40px;
background-color: white;
font-weight: bold;
color: rgb(108, 110, 146);
border-radius: 5px;
text-align: center;
line-height: 40px;
float: left;
}
.enroll{
margin-left: 10px;
margin-top: 40px;
width: 150px;
height: 40px;
background-color: rgb(0,0,0,0.2);
font-weight: bold;
color:white;
border-radius: 5px;
text-align: center;
line-height: 40px;
float: left;
border:1px solid white
}
.hoverbtn{
background-color: white;
color: rgb(108, 110, 146);
}
</style>
</html>
|
2202_75337835/Jiangnan
|
index.html
|
HTML
|
unknown
| 5,275
|
(function($){
$.iosParallax = function(el, options){
// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
// Add a reverse reference to the DOM object
base.$el.data("iosParallax", base);
var centerCoordinates = {x: 0, y: 0};
var targetCoordinates = {x: 0, y: 0};
var transitionCoordinates = {x: 0, y: 0};
function getBackgroundImageUrl(){
var backgroundImage = base.$el.css('background-image').match(/url\(.*\)/ig);
if ( ! backgroundImage || backgroundImage.length < 1) {
throw 'No background image found';
}
return backgroundImage[0].replace(/url\(|'|"|'|"|\)$/ig, "");
}
function getBackgroundImageSize(){
var img = new Image;
img.src = getBackgroundImageUrl();
return {width: img.width, height: img.height};
}
function setCenterCoordinates(){
var bgImgSize = getBackgroundImageSize();
centerCoordinates.x = -1 * Math.abs(bgImgSize.width - base.$el.width()) / 2;
centerCoordinates.y = -1 * Math.abs(bgImgSize.height - base.$el.height()) / 2;
targetCoordinates.x = centerCoordinates.x;
targetCoordinates.y = centerCoordinates.y;
transitionCoordinates.x = centerCoordinates.x;
transitionCoordinates.y = centerCoordinates.y;
}
function bindEvents(){
base.$el.mousemove(function(e){
var width = base.options.movementFactor / base.$el.width();
var height = base.options.movementFactor / base.$el.height();
var cursorX = e.pageX - ($(window).width() / 2);
var cursorY = e.pageY - ($(window).height() / 2);
targetCoordinates.x = width * cursorX * -1 + centerCoordinates.x;
targetCoordinates.y = height * cursorY * -1 + centerCoordinates.y;
});
// Slowly converge the background image position to the target coordinates in 60 FPS
var loop = setInterval(function(){
transitionCoordinates.x += ((targetCoordinates.x - transitionCoordinates.x) / base.options.dampenFactor);
transitionCoordinates.y += ((targetCoordinates.y - transitionCoordinates.y) / base.options.dampenFactor);
base.$el.css("background-position", transitionCoordinates.x+"px "+transitionCoordinates.y+"px");
}, 16);
$(window).resize(function(){
// Re-center the image
setCenterCoordinates();
});
// There's a problem with getting image height and width when the image isn't loaded.
var img = new Image;
img.src = getBackgroundImageUrl();
$(img).load(function(){
setCenterCoordinates();
});
};
base.init = function(){
base.options = $.extend({}, $.iosParallax.defaultOptions, options);
bindEvents();
};
base.init();
};
$.iosParallax.defaultOptions = {
// How fast the background moves
movementFactor: 50,
// How much to dampen the movement (higher is slower)
dampenFactor: 36
};
$.fn.iosParallax = function(options){
return this.each(function(){
(new $.iosParallax(this, options));
});
};
})(jQuery);
|
2202_75337835/Jiangnan
|
js/ios-parallax.js
|
JavaScript
|
unknown
| 3,240
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>烟雨江南</title>
</head>
<body>
<!-- 头部 -->
<div class="nav">
<div class="logo">
烟 雨 江 南
</div>
<div class="navright">
<ul>
<li ><a href="index.html">主页</a></li>
<li><a href="delicacies.html">美食</a></li>
<li><a href="tourism.html">旅游</a></li>
<li class="borderbox"><a href="login.html">登录</a></li>
<li><a href="enroll.html">注册</a></li>
<li><a href="Aboutwebsite.html">关于网站</a></li>
</ul>
</div>
<div class="navtitle">
登录
</div>
<div class="positioning">
主页 > 登录
</div>
</div>
<div class="banner">
<div class="auto">
<div class="logintext">
登 录
</div>
<div class="loginfrom">
<div class="loginname">用 户 名 / 手 机 号</div>
<input type="text" class="username" placeholder="">
<div class="loginname">密码</div>
<input type="text" class="username" placeholder="">
<div class="submit">登 录</div>
<div class="gologin">
没有账号? 去<a href="enroll.html">注册</a>
</div>
</div>
</div>
</div>
<!-- 底部 -->
<div class="foot">
<div class="footlogo">
烟 雨 江 南
</div>
<div class="nickname">
“我本无意入江南,奈何江南入我心”
</div>
<div class="Companyaddress">
公司地址:烟雨江南
</div>
<div class="Customerservicehotline">
客服热线:+ 010 854 6578
</div>
<div class="OfficialWeibo">
官方微博:烟雨江南
</div>
<div class="WeChatpublicaccount">
微信公众号:烟雨江南
</div>
</div>
</body>
<script src="/js/jquery-3.7.1.js"></script>
<script>
//导航下划线
$lis = $('.navright ul li')
$lis.hover(function() {
$(this).addClass('borderbox'); // 添加样式类
$(this).siblings().removeClass('borderbox'); // 移除兄弟元素的样式类
}, function() {
$(this).removeClass('borderbox'); // 移除样式类
});
//鼠标离开头部显示导航下划线
//鼠标触摸头部显示透明色
$nav=$('.nav')
$nav.hover(function() {
}, function() {
$lis.eq(3).addClass('borderbox')
});
</script>
<style>
.nav{
position: relative;
width: 100%;
height: 250px;
background-color: rgb(159, 10, 14);
}
.logo{
width: 130px;
height: 80px;
/* background-color: rgb(8, 84, 84); */
font-weight: bold;
font-size: 25px;
line-height: 80px;
margin-left: 30px;
color: white;
float: left;
}
.navright{
float: right;
width: 600px;
height: 80px;
/* background-color: yellow; */
margin-right: 10px;
}
.navright ul li{
list-style: none;
float: left;
margin-right: 10px;
line-height: 45px;
font-weight: bold;
font-size: 16px;
width: 80px;
height: 40px;
margin-top: 20px;
text-align: center;
/* background-color: aquamarine; */
}
.navright ul li a{
color: white;
text-decoration: none;
}
.borderbox{
border-bottom: 1px solid white;
}
.navtitle{
width: 80px;
height: 40px;
/* background-color: blue; */
font-weight: bold;
text-align: center;
margin-left: 50px;
line-height: 40px;
font-size: 18px;
color: white;
position: absolute;
top: 130px;
}
.positioning{
width: 80px;
height: 40px;
/* background-color: blue; */
font-weight: bold;
text-align: center;
margin-left: 50px;
line-height: 40px;
font-size: 14px;
color: white;
position: absolute;
top: 180px;
}
.banner{
margin-top: 20px;
width: 100%;
height: 350px;
/* background-color: tomato; */
margin-bottom: 50px;
}
.auto{
margin: 0 auto;
width: 80%;
height: 100%;
/* background-color: violet; */
}
.logintext{
width: 100%;
height: 40px;
line-height: 40px;
/* background-color: aqua; */
text-align: center;
font-size: 28px;
font-weight: bold;
}
.loginfrom{
margin-top: 20px;
margin-left: 405px;
width: 400px;
height: 280px;
/* background-color: blue; */
}
.loginname{
width: 150px;
line-height: 30px;
font-size: 14px;
font-weight: bold;
color: #979899;
margin-left: 80px;
margin-bottom: 5px;
/* background-color: aquamarine; */
}
.username{
width: 200px;
height: 20px;
margin-left: 80px;
border-radius: 5px;
padding: 5px;
margin-bottom: 10px;
}
.submit{
margin-left: 80px;
width: 210px;
height: 35px;
background-color: orangered;
text-align: center;
line-height: 35px;
font-weight: bold;
color: white;
border-radius: 5px;
margin-top: 10px;
}
.gologin{
width: 210px;
line-height: 30px;
/* background-color: aqua; */
text-align: center;
margin-top: 20px;
font-size: 13px;
margin-left: 80px;
}
.gologin a{
color: red;
text-decoration: none;
}
/* 底部 */
.foot{
position: relative;
width: 100%;
height: 150px;
background-color: black;
}
.footlogo{
position: absolute;
left: 200px;
width: 130px;
height: 80px;
/* background-color: rgb(8, 84, 84); */
font-weight: bold;
font-size: 25px;
line-height: 80px;
/* margin-left: 30px; */
color: white;
float: left;
}
.nickname{
position: absolute;
top: 100px;
left: 190px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 16px;
color: white;
/* background-color: aquamarine; */
}
.Companyaddress{
position: absolute;
top: 50px;
left: 600px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
.Customerservicehotline{
position: absolute;
top: 100px;
left: 600px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
.OfficialWeibo{
position: absolute;
top: 100px;
left: 1000px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
.WeChatpublicaccount{
position: absolute;
top: 50px;
left: 1000px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
</style>
</html>
|
2202_75337835/Jiangnan
|
login.html
|
HTML
|
unknown
| 6,858
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>烟雨江南</title>
</head>
<body>
<!-- 头部 -->
<div class="nav">
<div class="logo">
烟 雨 江 南
</div>
<div class="navright">
<ul>
<li ><a href="index.html">主页</a></li>
<li ><a href="delicacies.html">美食</a></li>
<li class="borderbox"><a href="tourism.html">旅游</a></li>
<li><a href="login.html">登录</a></li>
<li><a href="enroll.html">注册</a></li>
<li><a href="Aboutwebsite.html">关于网站</a></li>
</ul>
</div>
<div class="navtitle">
旅游
</div>
<div class="positioning">
主页 > 旅游
</div>
</div>
<!-- 内容 -->
<div class="bannertitle">
旅游热门
</div>
<div class="banner">
<ul class="tabs">
<li class="active">目的地</li>
<li >景点</li>
<li >住宿</li>
</ul>
<div class="boxs">
<div class="tabBox boxOne">
<ul class="destination">
<li>
<div class="destinationleft">
<img src="images/scenery/destination/0.jpg" alt="">
</div>
<div class="destinationright">
<h4>杭州</h4>
<p>Hangzhou</p>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/destination/1.jpg" alt="">
</div>
<div class="destinationright">
<h4>上海</h4>
<p>Shanghai</p>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/destination/2.jpg" alt="">
</div>
<div class="destinationright">
<h4>苏州</h4>
<p>Suzhou</p>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/destination/3.jpg" alt="">
</div>
<div class="destinationright">
<h4>南京</h4>
<p>Nanjing</p>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/destination/4.jpg" alt="">
</div>
<div class="destinationright">
<h4>无锡</h4>
<p>Wuxi</p>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/destination/5.jpg" alt="">
</div>
<div class="destinationright">
<h4>宁波</h4>
<p>Ningbo</p>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/destination/6.jpg" alt="">
</div>
<div class="destinationright">
<h4>扬州</h4>
<p>Yangzhou</p>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/destination/7.jpg" alt="">
</div>
<div class="destinationright">
<h4>黄山风景区</h4>
<p>Huangshan Scenic Area</p>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/destination/8.jpg" alt="">
</div>
<div class="destinationright">
<h4>绍兴</h4>
<p>Shaoxing</p>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/destination/9.jpg" alt="">
</div>
<div class="destinationright">
<h4>乌镇</h4>
<p>Wuzhen</p>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/destination/10.jpg" alt="">
</div>
<div class="destinationright">
<h4>浙江</h4>
<p>Zhejiang</p>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/destination/11.jpg" alt="">
</div>
<div class="destinationright">
<h4>西塘</h4>
<p>Ningbo</p>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/destination/12.jpg" alt="">
</div>
<div class="destinationright">
<h4>江苏</h4>
<p>Jiangsu</p>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/destination/13.jpg" alt="">
</div>
<div class="destinationright">
<h4>舟山</h4>
<p>Zhoushan</p>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/destination/14.jpg" alt="">
</div>
<div class="destinationright">
<h4>安徽</h4>
<p>Anhui</p>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/destination/15.jpg" alt="">
</div>
<div class="destinationright">
<h4>江西</h4>
<p>Jiangxi</p>
</div>
</li>
</ul>
</div>
<div class="tabBox ">
<ul class="destination">
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/0.jpg" alt="">
</div>
<div class="destinationright">
<h4>豫园</h4>
<p>Yu Garden</p>
<span class="fraction">4.7分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/1.jpg" alt="">
</div>
<div class="destinationright">
<h4>瘦西湖</h4>
<p>Slender West Lake</p>
<span class="fraction">4.6分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/2.jpg" alt="">
</div>
<div class="destinationright">
<h4>拙政园</h4>
<p>Humble Administrator's Garden</p>
<span class="fraction">4.7分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/3.jpg" alt="">
</div>
<div class="destinationright">
<h4>宏村景区</h4>
<p>Hongcun Village</p>
<span class="fraction">4.5分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/4.jpg" alt="">
</div>
<div class="destinationright">
<h4>西湖风景名胜区</h4>
<p>The West Lake</p>
<span class="fraction">4.7分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/5.jpg" alt="">
</div>
<div class="destinationright">
<h4>普陀山风景区</h4>
<p>Putuo Mountain Scenic Area</p>
<span class="fraction">4.7分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/6.jpg" alt="">
</div>
<div class="destinationright">
<h4>杭州宋城</h4>
<p>Hangzhou Songcheng Park</p>
<span class="fraction">4.6分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/7.jpg" alt="">
</div>
<div class="destinationright">
<h4>乌镇</h4>
<p>Zhouzhuang</p>
<span class="fraction">4.6分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/8.jpg" alt="">
</div>
<div class="destinationright">
<h4>周庄</h4>
<p>Wuzhen Water Town</p>
<span class="fraction">4.5分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/9.jpg" alt="">
</div>
<div class="destinationright">
<h4>寒山寺</h4>
<p>Hanshan Temple</p>
<span class="fraction">4.6分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/10.jpg" alt="">
</div>
<div class="destinationright">
<h4>南浔古镇</h4>
<p>Nanxun Ancient Town</p>
<span class="fraction">4.6分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/11.jpg" alt="">
</div>
<div class="destinationright">
<h4>婺源篁岭</h4>
<p>Wuyuan Huangling</p>
<span class="fraction">4.6分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/12.jpg" alt="">
</div>
<div class="destinationright">
<h4>西栅</h4>
<p>West Gate</p>
<span class="fraction">4.6分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/13.jpg" alt="">
</div>
<div class="destinationright">
<h4>同里古镇</h4>
<p>Tongli Ancient Town</p>
<span class="fraction">4.5分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/14.jpg" alt="">
</div>
<div class="destinationright">
<h4>留园</h4>
<p>Lingering Garden</p>
<span class="fraction">4.7分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/Attractions/15.jpg" alt="">
</div>
<div class="destinationright">
<h4>山塘街</h4>
<p>Shantang Street</p>
<span class="fraction">4.5分</span>
<span class="comments">999+条评论</span>
</div>
</li>
</ul>
</div>
<div class="tabBox ">
<ul class="destination">
<li>
<div class="destinationleft">
<img src="images/scenery/lodging/0.jpg" alt="">
</div>
<div class="destinationright">
<h4>周庄忆江南清禅客栈</h4>
<p>Zhouzhuang's recollection of Jiangnan Qingchan Inn</p>
<span class="fraction">4.8分</span>
<span class="comments">133条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/lodging/1.jpg" alt="">
</div>
<div class="destinationright">
<h4>乌镇禅意江南竹二民宿</h4>
<p>Wuzhen jiangnan zhuer hotel</p>
<span class="fraction">4.8分</span>
<span class="comments">199条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/lodging/2.jpg" alt="">
</div>
<div class="destinationright">
<h4>苏州山塘江南织造漫心府</h4>
<p>Manxin Suzhou Shantang Jiangnan Weaving House Hotel</p>
<span class="fraction">4.7分</span>
<span class="comments">999+条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/lodging/3.jpg" alt="">
</div>
<div class="destinationright">
<h4>尧歌里精品民宿</h4>
<p>Yao Homestay Inn (Taihu Rongchuang Branch)</p>
<span class="fraction">4.6分</span>
<span class="comments">58条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/lodging/4.jpg" alt="">
</div>
<div class="destinationright">
<h4>苏州叙姑苏忆江南民宿</h4>
<p>Suzhou Xugusu Yijiangnan Boutique Hotel</p>
<span class="fraction">4.9分</span>
<span class="comments">170条评论</span>
</div>
</li>
<li>
<div class="destinationleft">
<img src="images/scenery/lodging/5.jpg" alt="">
</div>
<div class="destinationright">
<h4>维也纳国际酒店</h4>
<p>Vienna International Hotel (Nanning Baisha Shizhuling Metro Station)</p>
<span class="fraction">4.7分</span>
<span class="comments">399条评论</span>
</div>
</li>
</ul>
</div>
</div>
</div>
<div class="bannertitle">
旅游跟团
</div>
<div class="Withgroup">
<div class="groupbanner">
<div class="groupleft">
<img src="images/scenery/group/0.jpg" alt="">
<div class="imgtags">
<span class="imgSold">跟团游</span>
<span class="imgbars">|</span>
<span class="imgSold">从合肥出发</span>
</div>
</div>
<div class="groupright">
<h4>杭州+乌镇+西塘3日2晚跟团游</h4>
<p>精品纯玩 1车到底『1晚乌镇品牌5钻 1晚杭州5星开元』赠200元古镇双游船+汉服游园 门票价超600【经典5A3水乡 乌镇+南浔+西塘】5星自助早 50元御茶宴 高端优选 交通任选</p>
<span class="label">无购物</span>
<span class="label">成团保障</span>
<span class="label">古镇古村</span>
<span class="label">西湖游船</span>
<span class="label">东坡宴</span>
<span class="label">乾隆御茶宴</span>
<!-- 评分 -->
<span class="Star">4.9分</span>
<div class="solidbanner">
<span class="Sold">已售6889人</span>
<span class="bars">|</span>
<span class="Sold">1606条点评</span>
<div class="price">
<span class="spanname">¥</span>
<span class="toprice">696</span>
<span class="spanname">起</span>
</div>
<div class="salespromotion">
<span>限时促销</span>
<span>已减250</span>
</div>
</div>
</div>
</div>
<div class="groupbanner">
<div class="groupleft">
<img src="images/scenery/group/1.jpg" alt="">
<div class="imgtags">
<span class="imgSold">跟团游</span>
<span class="imgbars">|</span>
<span class="imgSold">从合肥出发</span>
</div>
</div>
<div class="groupright">
<h4>上海+苏州+杭州+乌镇5日4晚跟团游</h4>
<p>【漫游江南Classic】自营爆品 金牌导游·5月“程”意巨惠 狂减50,宿西栅内外任选,好导游伴游5A 拙政园专题+VIP入西塘·赠汉服+乌镇,50元特色宴 水乡+御茶·交通任选</p>
<span class="label">无购物</span>
<span class="label">成团保障</span>
<span class="label">3期免息</span>
<span class="label">古镇古村</span>
<!-- 评分 -->
<span class="Star">4.9分</span>
<div class="solidbanner">
<span class="Sold">已售14709人</span>
<span class="bars">|</span>
<span class="Sold">4463条点评</span>
<div class="price">
<span class="spanname">¥</span>
<span class="toprice">778</span>
<span class="spanname">起</span>
</div>
<div class="salespromotion">
<span>限时促销</span>
<span>已减50</span>
</div>
</div>
</div>
</div>
<div class="groupbanner">
<div class="groupleft">
<img src="images/scenery/group/2.jpg" alt="">
<div class="imgtags">
<span class="imgSold">跟团游</span>
<span class="imgbars">|</span>
<span class="imgSold">从合肥出发</span>
</div>
</div>
<div class="groupright">
<h4>苏州3日2晚跟团游</h4>
<p>五星旅行社『本地玩法』两晚连住【品牌5钻酒店 5星自助早餐】世遗园林【拙政园or狮子林】走进博物馆【苏博or园博 探索国家宝藏】千年古镇【周庄古镇 深度闲逛】打卡网红【金鸡湖 诚品书店】</p>
<span class="label">无购物</span>
<span class="label">成团保障</span>
<span class="label">动车高铁游</span>
<span class="label">古镇古村</span>
<span class="label">博物馆</span>
<span class="label">寺院祈福</span>
<!-- 评分 -->
<span class="Star">4.7分</span>
<div class="solidbanner">
<span class="Sold">已售39人</span>
<span class="bars">|</span>
<span class="Sold">23条点评</span>
<div class="price">
<span class="spanname">¥</span>
<span class="toprice">965</span>
<span class="spanname">起</span>
</div>
<!-- <div class="salespromotion">
<span>限时促销</span>
<span>已减50</span>
</div> -->
</div>
</div>
</div>
</div>
<div class="bannertitle">
游客打卡
</div>
<div class="Withgroup">
<div class="groupswiper">
<div class="carousel" id="carousel">
<ul id="unit">
<li><a href=""><img src="images/scenery/Clock/0.jpg" /></a></li>
<li><a href=""><img src="images/scenery/Clock/1.jpg" /></a></li>
<li><a href=""><img src="images/scenery/Clock/2.jpg" /></a></li>
<li><a href=""><img src="images/scenery/Clock/3.jpg" /></a></li>
<li><a href=""><img src="images/scenery/Clock/4.jpg" /></a></li>
</ul>
<div class="btns">
<a id="leftBtn" class="leftBtn" href="javascript:void(0);"><</a>
<a id="rightBtn" class="rightBtn" href="javascript:void(0);">></a>
</div>
<div class="circles" id="circles">
<ol>
<li class="cur"></li>
<li></li>
<li></li>
<li></li>
<li class="last"></li>
</ol>
</div>
</div>
</div>
</div>
<!-- 底部 -->
<div class="foot">
<div class="footlogo">
烟 雨 江 南
</div>
<div class="nickname">
“我本无意入江南,奈何江南入我心”
</div>
<div class="Companyaddress">
公司地址:烟雨江南
</div>
<div class="Customerservicehotline">
客服热线:+ 010 854 6578
</div>
<div class="OfficialWeibo">
官方微博:烟雨江南
</div>
<div class="WeChatpublicaccount">
微信公众号:烟雨江南
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
//导航下划线
$lis = $('.navright ul li')
$lis.hover(function() {
$(this).addClass('borderbox'); // 添加样式类
$(this).siblings().removeClass('borderbox'); // 移除兄弟元素的样式类
}, function() {
$(this).removeClass('borderbox'); // 移除样式类
});
//鼠标离开头部显示导航下划线
//鼠标触摸头部显示透明色
$nav=$('.nav')
$nav.hover(function() {
}, function() {
$lis.eq(2).addClass('borderbox')
});
//tab栏切换
$tablis=$('.tabs li')
$tablis.on('click', function () {
// 给当前选中的li添加一个选中的样式,除了点击当前的这个样式其他的删除样式
$(this).addClass('active').siblings().removeClass('active');
// siblings:除自己以外
// 当前指向的上级父元素的下一个子元素的索引下标出现,让其他的消失
$(this).parent().next().children().eq($(this).index()).css('display', 'block').siblings().css('display', 'none');
})
//轮播图
// 得到DOM元素
var $carousel = $("#carousel"); // 大盒子
var $unit = $("#unit"); // “小火车”
var $leftBtn = $("#leftBtn"); // 左按钮
var $rightBtn = $("#rightBtn"); // 右按钮
var $circlesLis = $("#circles li"); // 小圆点
// 图片个数
var amount =$unit.children("li").length;
//克隆第一张图片
$unit.children("li:first").clone().appendTo($unit);
// 定时器
var timer = setInterval(rightBtnHandler,2000);
// 鼠标进入停止定时器
$carousel.mouseenter(function(){
clearInterval(timer);
});
// 鼠标离开重新开启定时器
$carousel.mouseleave(function(){
clearInterval(timer);
timer = setInterval(rightBtnHandler,2000);
});
//信号量,表示当前第几张图片。0、1、2、3、4
var idx = 0;
//右按钮的事件监听
$rightBtn.click(rightBtnHandler);
function rightBtnHandler(){
// 防止多次点击
if($unit.is(":animated")){
return;
}
// 先改变信号量,在回调函数中验证
idx++;
$unit.animate({"left":idx * -1100},400,function(){
if(idx > amount - 1){
idx = 0;
$unit.css("left",0); //瞬间移动
}
});
//改变小圆点
var i = idx <= amount - 1 ? idx : 0;
$circlesLis.eq(i).addClass("cur").siblings().removeClass("cur");
}
//左按钮的事件监听
$leftBtn.click(function(){
// 防止多次点击
if($unit.is(":animated")){
return;
}
// 改变信号量
idx --;
// 先判断
if(idx < 0){
// 如果信号量小于0,则瞬间移动到被克隆的图片,信号量为最后一张真实图片序号
idx = amount - 1;
$unit.css("left" , amount * -1100);
}
// 拉动“小火车”
$unit.animate({"left":idx * -1100},400);
// 小圆点
$circlesLis.eq(idx).addClass("cur").siblings().removeClass("cur");
});
// 小圆点事件监听
$circlesLis.mouseenter(function(){
idx = $(this).index();
$unit.stop(true).animate({"left":idx * -1100},400);
$circlesLis.eq(idx).addClass("cur").siblings().removeClass("cur");
});
</script>
<style>
*{
margin: 0;
padding: 0;
}
.nav{
position: relative;
width: 100%;
height: 250px;
background-color: rgb(159, 10, 14);
}
.logo{
width: 130px;
height: 80px;
/* background-color: rgb(8, 84, 84); */
font-weight: bold;
font-size: 25px;
line-height: 80px;
margin-left: 30px;
color: white;
float: left;
}
.navright{
float: right;
width: 600px;
height: 80px;
/* background-color: yellow; */
margin-right: 10px;
}
.navright ul li{
list-style: none;
float: left;
margin-right: 10px;
line-height: 45px;
font-weight: bold;
font-size: 16px;
width: 80px;
height: 40px;
margin-top: 20px;
text-align: center;
/* background-color: aquamarine; */
}
.navright ul li a{
color: white;
text-decoration: none;
}
.borderbox{
border-bottom: 1px solid white;
}
.navtitle{
width: 80px;
height: 40px;
/* background-color: blue; */
font-weight: bold;
text-align: center;
margin-left: 50px;
line-height: 40px;
font-size: 18px;
color: white;
position: absolute;
top: 130px;
}
.positioning{
width: 80px;
height: 40px;
/* background-color: blue; */
font-weight: bold;
text-align: center;
margin-left: 50px;
line-height: 40px;
font-size: 14px;
color: white;
position: absolute;
top: 180px;
}
.bannertitle{
margin-top: 50px;
width: 280px;
height: 40px;
/* background-color: blue; */
font-weight: bold;
text-align: center;
margin-left: 50px;
line-height: 40px;
font-size: 20px;
color: black;
}
.banner{
margin: 0px auto;
margin-right: 10px;
width:90%;
height: 730px;
/* background-color: tomato; */
}
/* tab栏切换 */
.tabs {
width: 600px;
height: 70px;
/* background-color: yellow; */
}
.tabs li {
float: left;
margin-left: 5px;
list-style: none;
width: 100px;
height: 40px;
line-height: 40px;
font-weight: bold;
text-align: center;
margin-top: 20px;
}
.tabBox {
width: 100%;
/* background-color: rgb(45, 111, 245); */
height: 650px;
display: none;
}
.active {
background-color: rgb(159, 10, 14);
color: white;
}
.boxOne {
display: block;
}
.destination li{
float: left;
list-style: none;
margin-top: 10px;
margin-right: 5px;
width: 320px;
height: 141px;
/* background-color: yellowgreen; */
}
.destinationleft{
width:45%;
height: 100%;
background-color: teal;
border-radius: 10px;
float: left;
}
.destinationleft img{
width: 100%;
height: 100%;
border-radius: 10px;
}
.destinationright{
float: left;
width: 55%;
height: 100%;
/* background-color: tomato; */
}
.destinationright h4{
margin-top: 10px;
margin-left: 10px;
}
.destinationright p{
margin-left: 10px;
margin-top: 10px;
font-size: 14px;
color: #979899;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.fraction{
font-weight: bold;
color:rgb(86, 120, 168) ;
margin-left: 10px;
}
.comments{
color: #979899;
font-size: 13px;
}
.Withgroup{
padding-top: 10px;
margin: 0px auto;
margin-right: 10px;
width:90%;
height: 620px;
/* background-color: tomato; */
margin-bottom: 40px;
}
.groupbanner{
margin-top: 20px;
position: relative;
width: 100%;
height: 180px;
/* background-color: turquoise; */
}
.groupleft{
width: 200px;
border-radius: 10px;
height: 100%;
/* background-color: violet; */
float: left;
}
.groupleft img{
width: 100%;
height: 100%;
border-radius: 10px;
}
.groupright{
float: left;
width: 60%;
height: 100%;
/* background-color: yellow; */
}
.groupright h4{
margin-left: 10px;
}
.groupright p{
margin-top: 5px;
margin-left: 10px;
font-size: 13px;
}
.label{
display: block;
float: left;
margin-left: 5px;
margin-top: 5px;
font-size: 12px;
width: 70px;
line-height: 20px;
text-align: center;
color:rgb(61, 174, 249) ;
font-weight: bold;
border:1px solid rgb(109, 189, 242);
}
.Star{
clear: both;
display: block;
background-color: rgb(0, 134, 246);
width: 50px;
text-align: center;
margin-top: 35px;
line-height: 30px;
margin-left: 10px;
color: white;
font-size: 13px;
}
.solidbanner{
position: absolute;
top: 98px;
left: 270px;
}
.Sold{
font-size: 12px;
}
.bars{
font-size: 12px;
}
.price{
position: absolute;
left: 670px;
top: 20px;
width: 80px;
height: 30px;
/* background-color: violet; */
}
.price .spanname{
font-size: 14px;
color: orangered;
}
.toprice{
font-weight: bold;
font-size: 20px;
color: orangered;
}
.salespromotion{
position: absolute;
top: 55px;
left: 640px;
width: 115px;
height: 25px;
/* background-color: springgreen; */
}
.salespromotion span{
display: block;
float: left;
width: 50px;
height: 20px;
margin-right: 5px;
line-height: 20px;
text-align: center;
background-color: white;
font-size: 12px;
color: orangered;
border: 1px solid orangered;
}
.imgtags{
position: absolute;
top: 0px;
padding-left:5px;
text-align:left;
line-height: 30px;
width: 120px;
height: 30px;
background-color: rgb(0,0,0,0.6);
border-radius: 0px 0px 15px 0px;
}
.imgSold{
color: white;
font-size: 12px;
}
.imgbars{
color: white;
font-size: 12px;
}
.groupswiper{
width: 100%;
height: 90%;
/* background-color: turquoise; */
}
/* 轮播图 */
.carousel{
margin-top: 10px;
width: 1100px;
height: 500px;
/* border: 1px solid #9e9e9e; */
border-radius: 15px;
position: relative;
overflow: hidden;
}
.carousel ul{
list-style: none;
width: 8000px;
position: relative;
}
.carousel ul li{
width: 1100px;
height: 500px;
float: left;
}
.carousel ul li img{
border-radius: 15px;
width: 100%;
height: 100%;
}
.carousel .btns a{
position: absolute;
width: 30px;
height: 70px;
top: 50%;
margin-top: -35px;
background-color: rgba(0, 0, 0, 0.73);
text-align: center;
line-height: 70px;
text-decoration: none;
font-size: 24px;
color: white;
font-family: serif;
border-radius: 4px;
}
.carousel .btns a.leftBtn{
left: 10px;
}
.carousel .btns a.rightBtn{
right: 10px;
}
.circles{
position: absolute;
bottom: 10px;
left: 50%;
width: 120px;
height: 20px;
margin-left: -60px;
}
.circles ol{
list-style: none;
}
.circles ol li{
float: left;
width: 16px;
height: 16px;
margin-right: 10px;
background-color: rgb(0,0,0,0.6);
border-radius: 50%;
}
.circles ol li.cur{
background-color: white;
}
.circles ol li.last{
margin-right: 0;
}
/* 底部 */
.foot{
position: relative;
width: 100%;
height: 150px;
background-color: black;
}
.footlogo{
position: absolute;
left: 200px;
width: 130px;
height: 80px;
/* background-color: rgb(8, 84, 84); */
font-weight: bold;
font-size: 25px;
line-height: 80px;
/* margin-left: 30px; */
color: white;
float: left;
}
.nickname{
position: absolute;
top: 100px;
left: 190px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 16px;
color: white;
/* background-color: aquamarine; */
}
.Companyaddress{
position: absolute;
top: 50px;
left: 600px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
.Customerservicehotline{
position: absolute;
top: 100px;
left: 600px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
.OfficialWeibo{
position: absolute;
top: 100px;
left: 1000px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
.WeChatpublicaccount{
position: absolute;
top: 50px;
left: 1000px;
width: 310px;
height:30px;
font-weight: bold;
font-size: 14px;
color: white;
/* background-color: aquamarine; */
}
</style>
</html>
|
2202_75337835/Jiangnan
|
tourism.html
|
HTML
|
unknown
| 33,758
|
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>匿名空间</title>
<link rel="shortcut icon" href="./img/ico.jpg" type="image/x-icon">
<link rel="stylesheet" href="./css/css.css">
<style>
</style>
</head>
<body>
<video id="bg-video" autoplay muted loop>
<source src="img/35.mp4" type="video/mp4">
<source src="img/35.webm" type="video/webm">
您的浏览器不支持 HTML5 video 标签。
</video>
<div class="header">
<ul class="daohang">
<li><button onclick="navigate('1.html')">首页</button></li>
<li><button onclick="navigate('2.html')">课程</button></li>
<li><button onclick="navigate('3.html')">代码</button></li>
<li><button onclick="navigate('4.html')">关于</button></li>
<li><button onclick="navigate('5.html')">更多</button></li>
</ul>
</div>
<div class="time-weather-container">
<h2 id="current-time"></h2>
<p id="current-city"></p>
<p id="current-weather"></p>
</div>
<div class="search-form">
<form action="https://www.baidu.com/s" method="get" target="_self">
<span><input type="text" name="wd" placeholder="搜索内容"></span>
<span><button type="submit">百度一下</button></span>
</form>
</div>
<script>
document.addEventListener('contextmenu', function (event) {
event.preventDefault();
});
function navigate(href) {
window.location.href = href;
}
function updateTime() {
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
document.getElementById('current-time').innerText = `${hours}:${minutes}:${seconds}`;
}
setInterval(updateTime, 1000);
updateTime(); // 初始化显示时间
</script>
<div class="q">本网站纯属个人网站,不得盗用或用于非法目的</div>
</body>
</html>
|
2302_81108167/niming
|
index.html
|
HTML
|
apache-2.0
| 2,331
|
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
pnpm lint-staged
|
2302_81331056/big-event
|
.husky/pre-commit
|
Shell
|
unknown
| 70
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
|
2302_81331056/big-event
|
index.html
|
HTML
|
unknown
| 331
|
<script setup>
import zh from 'element-plus/es/locale/lang/zh-cn.mjs'
</script>
<template>
<div>
<el-config-provider :locale="zh">
<router-view></router-view>
</el-config-provider>
</div>
</template>
<style scoped></style>
|
2302_81331056/big-event
|
src/App.vue
|
Vue
|
unknown
| 243
|
import request from '@/utils/request'
// 获取文章分类
export const artGetChannelsService = () => request.get('/my/cate/list')
// 添加分类
export const artAddChannelService = (data) => request.post('/my/cate/add', data)
// 编辑分类
export const artEditChannelService = (data) =>
request.put('/my/cate/info', data)
// 删除文章分类
export const artDelChannelService = (id) =>
request.delete('/my/cate/del', {
params: { id }
})
// 获取文章列表
export const artGetListService = (params) =>
request.get('/my/article/list', { params })
// 发布文章
export const artPublishService = (data) => request.post('/my/article/add', data)
// 获取文章详情
export const artGetDetailService = (id) =>
request.get('my/article/info', { params: { id } })
// 删除文章
export const artDelService = (id) =>
request.delete('/my/article/info', { params: { id } })
|
2302_81331056/big-event
|
src/api/article.js
|
JavaScript
|
unknown
| 900
|