Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding support for custom actions per table #244

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion admin_ui/src/components/MessagePopup.vue
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export default Vue.extend({
if (now - app.timeLastAppeared >= 3000) {
app.visible = false
}
}, 3000)
}, this.$store.state.apiResponseMessage.timeout ? this.$store.state.apiResponseMessage.timeout : 3000)
}
}
})
Expand Down
12 changes: 12 additions & 0 deletions admin_ui/src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ export interface DeleteRow {
rowID: number
}

export interface ExecuteAction {
tableName: string
rowIDs: number
actionId: number
}

export interface UpdateRow {
tableName: string
rowID: number
Expand All @@ -34,6 +40,7 @@ export interface FetchSingleRowConfig {
export interface APIResponseMessage {
contents: string
type: string
timeout?: number
}

export interface SortByConfig {
Expand Down Expand Up @@ -143,3 +150,8 @@ export interface FormConfig {
slug: string
description: string
}

export interface Action {
actionID: number
actionName: string
}
23 changes: 22 additions & 1 deletion admin_ui/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ export default new Vuex.Store({
tableNames: [],
formConfigs: [] as i.FormConfig[],
user: undefined,
loadingStatus: false
loadingStatus: false,
actions: [] as i.Action[]
},
mutations: {
updateTableNames(state, value) {
Expand Down Expand Up @@ -66,6 +67,9 @@ export default new Vuex.Store({
updateSortBy(state, config: i.SortByConfig) {
state.sortBy = config
},
updateActions(state, actions) {
state.actions = actions
},
reset(state) {
state.sortBy = null
state.filterParams = {}
Expand Down Expand Up @@ -229,6 +233,23 @@ export default new Vuex.Store({
)
return response
},
async fetchActions(context, tableName: string) {
const response = await axios.get(
`${BASE_URL}tables/${tableName}/actions`
)
context.commit("updateActions", response.data)
return response
},
async executeAction(context, config: i.ExecuteAction) {
const response = await axios.post(
`${BASE_URL}tables/${config.tableName}/actions/${config.actionId}/execute`,
{
table_name: config.tableName,
row_ids: config.rowIDs
}
)
return response
},
async updateRow(context, config: i.UpdateRow) {
const response = await axios.patch(
`${BASE_URL}tables/${config.tableName}/${config.rowID}/`,
Expand Down
62 changes: 57 additions & 5 deletions admin_ui/src/views/RowListing.vue
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,20 @@
/>
</div>
<div class="buttons">
<a class="button" v-on:click.prevent="showActionDropDown = !showActionDropDown">
<font-awesome-icon icon="angle-right" v-if="!showActionDropDown"/>
<font-awesome-icon icon="angle-down" v-if="showActionDropDown"/>
Actions
<a class="actions-dropdown">
<DropDownMenu v-if="showActionDropDown">
<li v-for="action in allActions">
<a href="#" class="button" v-on:click="executeAction(action.action_id)">
<span>{{ action.action_name }}</span>
</a>
</li>
</DropDownMenu>
</a>
</a>
<a
class="button"
href="#"
Expand All @@ -27,7 +41,8 @@
v-if="selectedRows.length > 0"
v-on:triggered="deleteRows"
/>



<router-link
:to="{
name: 'addRow',
Expand All @@ -40,6 +55,7 @@
<span>{{ $t("Add Row") }}</span>
</router-link>


<a
class="button"
href="#"
Expand Down Expand Up @@ -397,7 +413,8 @@ export default Vue.extend({
showUpdateModal: false,
visibleDropdown: null,
showMediaViewer: false,
mediaViewerConfig: null as MediaViewerConfig
mediaViewerConfig: null as MediaViewerConfig,
showActionDropDown: false,
}
},
components: {
Expand Down Expand Up @@ -435,6 +452,9 @@ export default Vue.extend({
schema() {
return this.$store.state.schema
},
allActions() {
return this.$store.state.actions
},
rowCount() {
return this.$store.state.rowCount
},
Expand Down Expand Up @@ -538,10 +558,11 @@ export default Vue.extend({
this.selectedRows = []
}
},
showSuccess(contents: string) {
showSuccess(contents: string, timeout?: number) {
var message: APIResponseMessage = {
contents: contents,
type: "success"
type: "success",
timeout: timeout ? timeout : 3000
}
this.$store.commit("updateApiResponseMessage", message)
},
Expand All @@ -565,6 +586,30 @@ export default Vue.extend({
this.showSuccess("Successfully deleted row")
}
},
async executeAction(action_id) {
if (confirm(`Are you sure you want to run action for this row?`)) {
try {
let response = await this.$store.dispatch("executeAction", {
tableName: this.tableName,
rowIDs: this.selectedRows,
actionId: action_id
})
this.showSuccess(`Successfully ran action and got response: ${response.data}`, 10000)
} catch (error) {
if (error.response.status == 404) {
this.$store.commit("updateApiResponseMessage", {
contents: "This table is not configured for any actions",
type: "error"
})
} else {
this.$store.commit("updateApiResponseMessage", {
contents: "Something went wrong",
type: "error"
})
}
}
}
},
async deleteRows() {
if (confirm(`Are you sure you want to delete the selected rows?`)) {
console.log("Deleting rows!")
Expand All @@ -583,6 +628,9 @@ export default Vue.extend({
},
async fetchSchema() {
await this.$store.dispatch("fetchSchema", this.tableName)
},
async fetchActions() {
await this.$store.dispatch("fetchActions", this.tableName)
}
},
watch: {
Expand Down Expand Up @@ -610,7 +658,7 @@ export default Vue.extend({
this.$router.currentRoute.query
)

await Promise.all([this.fetchRows(), this.fetchSchema()])
await Promise.all([this.fetchRows(), this.fetchSchema(), this.fetchActions()])
}
})
</script>
Expand Down Expand Up @@ -687,6 +735,10 @@ div.wrapper {
&:first-child {
margin-left: 0;
}

a.actions-dropdown {
position: relative;
}
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions piccolo_admin/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ async def manager_only(
validators=Validators(post_single=manager_only)
)
)
:param custom_actions: Optional list of custom actions handler function

"""

Expand All @@ -164,6 +165,7 @@ async def manager_only(
hooks: t.Optional[t.List[Hook]] = None
media_storage: t.Optional[t.Sequence[MediaStorage]] = None
validators: t.Optional[Validators] = None
custom_actions: t.Optional[t.List[t.Callable]] = None

def __post_init__(self):
if self.visible_columns and self.exclude_visible_columns:
Expand Down Expand Up @@ -463,6 +465,7 @@ def __init__(
"tags": [f"{table_class._meta.tablename.capitalize()}"]
},
),
actions=table_config.custom_actions,
)

private_app.add_api_route(
Expand Down
17 changes: 17 additions & 0 deletions piccolo_admin/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
from piccolo_api.media.s3 import S3MediaStorage
from piccolo_api.session_auth.tables import SessionsBase
from pydantic import BaseModel, validator
from starlette.responses import JSONResponse
from piccolo_api.fastapi.endpoints import TableRowDataSchema

from piccolo_admin.endpoints import FormConfig, TableConfig, create_admin
from piccolo_admin.example_data import (
Expand Down Expand Up @@ -163,6 +165,7 @@ class Genre(int, enum.Enum):
romance = 7
musical = 8

id = BigInt
name = Varchar(length=300)
rating = Real(help_text="The rating on IMDB.")
duration = Interval()
Expand Down Expand Up @@ -269,6 +272,19 @@ async def booking_endpoint(request, data):
)


# CUSTOM ACTIONS
async def my_custom_action(data: TableRowDataSchema) -> JSONResponse:
row_ids = data.row_ids

# Use the selected row ids to fetch rows from db
movies = await Movie.select().where(Movie.id == row_ids[0])

Check notice

Code scanning / CodeQL

Unused local variable

Variable movies is not used.

# Return a JSONResponse which can be displayed back to the frontend
return JSONResponse(f"My API received the row_id: {row_ids}")

async def custom_action_2(data) -> JSONResponse:
return JSONResponse("This is the second action")

movie_config = TableConfig(
table_class=Movie,
visible_columns=[
Expand Down Expand Up @@ -301,6 +317,7 @@ async def booking_endpoint(request, data):
media_path=os.path.join(MEDIA_ROOT, "movie_screenshots"),
),
),
custom_actions=[my_custom_action, custom_action_2]
)

director_config = TableConfig(
Expand Down