All files / owid-grapher/db/model Chart.ts

56.49% Statements 135/239
100% Branches 0/0
0% Functions 0/9
56.49% Lines 135/239

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 1971x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                         1x 1x       1x 1x                                                 1x 1x                                       1x 1x                 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x             1x 1x           1x 1x 1x                         1x
import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    BaseEntity,
    ManyToOne,
    OneToMany,
} from "typeorm"
import * as lodash from "lodash"
import * as db from "../db"
import { getVariableData } from "./Variable"
import { User } from "./User"
import { ChartRevision } from "./ChartRevision"
 
// XXX hardcoded filtering to public parent tags
const PUBLIC_TAG_PARENT_IDS = [
    1515, 1507, 1513, 1504, 1502, 1509, 1506, 1501, 1514, 1511, 1500, 1503,
    1505, 1508, 1512, 1510,
]
 
@Entity("charts")
export class Chart extends BaseEntity {
    @PrimaryGeneratedColumn() id!: number
    @Column({ type: "json" }) config: any
    @Column() lastEditedAt!: Date
    @Column({ nullable: true }) lastEditedByUserId!: number
    @Column({ nullable: true }) publishedAt!: Date
    @Column({ nullable: true }) publishedByUserId!: number
    @Column() createdAt!: Date
    @Column() updatedAt!: Date
    @Column() starred!: boolean
    @Column() isExplorable!: boolean
 
    @ManyToOne(() => User, (user) => user.lastEditedCharts)
    lastEditedByUser!: User
    @ManyToOne(() => User, (user) => user.publishedCharts)
    publishedByUser!: User
    @OneToMany(() => ChartRevision, (rev) => rev.chart)
    logs!: ChartRevision[]
 
    static table: string = "charts"
 
    // Only considers published charts, because only in that case the mapping slug -> id is unique
    static async mapSlugsToIds(): Promise<{ [slug: string]: number }> {
        const redirects = await db.queryMysql(
            `SELECT chart_id, slug FROM chart_slug_redirects`
        )
        const rows = await db.queryMysql(`
            SELECT
                id,
                JSON_UNQUOTE(JSON_EXTRACT(config, "$.slug")) AS slug
            FROM charts
            WHERE JSON_EXTRACT(config, "$.isPublished") IS TRUE
        `)

        const slugToId: { [slug: string]: number } = {}
        for (const row of redirects) {
            slugToId[row.slug] = row.chart_id
        }
        for (const row of rows) {
            slugToId[row.slug] = row.id
        }
        return slugToId
    }
 
    static async getBySlug(slug: string): Promise<Chart | undefined> {
        const slugsById = await this.mapSlugsToIds()
        return await Chart.findOne({ id: slugsById[slug] })
    }
 
    static async setTags(chartId: number, tagIds: number[]): Promise<void> {
        await db.transaction(async (t) => {
            const tagRows = tagIds.map((tagId) => [tagId, chartId])
            await t.execute(`DELETE FROM chart_tags WHERE chartId=?`, [chartId])
            if (tagRows.length)
                await t.execute(
                    `INSERT INTO chart_tags (tagId, chartId) VALUES ?`,
                    [tagRows]
                )

            const tags = tagIds.length
                ? ((await t.query("select parentId from tags where id in (?)", [
                      tagIds,
                  ])) as { parentId: number }[])
                : []
            const isIndexable = tags.some((t) =>
                PUBLIC_TAG_PARENT_IDS.includes(t.parentId)
            )

            await t.execute("update charts set is_indexable = ? where id = ?", [
                isIndexable,
                chartId,
            ])
        })
    }
 
    static async assignTagsForCharts(
        charts: { id: number; tags: any[] }[]
    ): Promise<void> {
        const chartTags = await db.queryMysql(`
            SELECT ct.chartId, ct.tagId, t.name as tagName FROM chart_tags ct
            JOIN charts c ON c.id=ct.chartId
            JOIN tags t ON t.id=ct.tagId
        `)

        for (const chart of charts) {
            chart.tags = []
        }

        const chartsById = lodash.keyBy(charts, (c) => c.id)

        for (const ct of chartTags) {
            const chart = chartsById[ct.chartId]
            if (chart) chart.tags.push({ id: ct.tagId, name: ct.tagName })
        }
    }
 
    static async all(): Promise<ChartRow[]> {
        const rows = await db.knexTable(Chart.table)

        for (const row of rows) {
            row.config = JSON.parse(row.config)
        }

        return rows as ChartRow[] // This cast might be a lie?
    }
}
 
interface ChartRow {
    id: number
    config: any
}
 
// TODO integrate this old logic with typeorm
export class OldChart {
    static listFields = `
        charts.id,
        charts.config->>"$.title" AS title,
        charts.config->>"$.slug" AS slug,
        charts.config->>"$.type" AS type,
        charts.config->>"$.internalNotes" AS internalNotes,
        charts.config->>"$.variantName" AS variantName,
        charts.config->>"$.isPublished" AS isPublished,
        charts.config->>"$.tab" AS tab,
        JSON_EXTRACT(charts.config, "$.hasChartTab") = true AS hasChartTab,
        JSON_EXTRACT(charts.config, "$.hasMapTab") = true AS hasMapTab,
        charts.starred AS isStarred,
        charts.lastEditedAt,
        charts.lastEditedByUserId,
        lastEditedByUser.fullName AS lastEditedBy,
        charts.publishedAt,
        charts.publishedByUserId,
        publishedByUser.fullName AS publishedBy,
        charts.isExplorable AS isExplorable
    `
 
    static async getBySlug(slug: string): Promise<OldChart> {
        const row = await db.mysqlFirst(
            `SELECT id, config FROM charts WHERE JSON_EXTRACT(config, "$.slug") = ?`,
            [slug]
        )

        return new OldChart(row.id, JSON.parse(row.config))
    }
 
    id: number
    config: any
    constructor(id: number, config: any) {
        this.id = id
        this.config = config

        // XXX todo make the relationship between chart models and chart configuration more defined
        this.config.id = id
    }
 
    async getVariableData(): Promise<any> {
        const variableIds = lodash.uniq(
            this.config.dimensions!.map((d: any) => d.variableId)
        )
        return getVariableData(variableIds as number[])
    }
}
 
export const getGrapherById = async (grapherId: number): Promise<any> => {
    const grapher = (
        await db.queryMysql(`SELECT id, config FROM charts WHERE id=?`, [
            grapherId,
        ])
    )[0]

    if (!grapher) return undefined

    const config = JSON.parse(grapher.config)
    config.id = grapher.id
    return config
}