All files / owid-grapher/adminSiteServer apiRouter.ts

12.16% Statements 203/1670
100% Branches 0/0
0% Functions 0/6
12.16% Lines 203/1670

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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 23751x 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 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 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                             1x 1x 1x                                 1x 1x                                         1x 1x                                                                   1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
/* eslint @typescript-eslint/no-unused-vars: [ "warn", { argsIgnorePattern: "^(res|req)$" } ] */
 
import * as lodash from "lodash"
import { getConnection } from "typeorm"
import * as bodyParser from "body-parser"
import * as db from "../db/db"
import * as wpdb from "../db/wpdb"
import {
    UNCATEGORIZED_TAG_ID,
    BAKE_ON_CHANGE,
    BAKED_BASE_URL,
    ADMIN_BASE_URL,
} from "../settings/serverSettings"
import { expectInt, isValidSlug, absoluteUrl } from "../serverUtils/serverUtil"
import { sendMail } from "./mail"
import { OldChart, Chart, getGrapherById } from "../db/model/Chart"
import { UserInvitation } from "../db/model/UserInvitation"
import { Request, Response, CurrentUser } from "./authentication"
import { getVariableData } from "../db/model/Variable"
import { applyPatch } from "../clientUtils/patchHelper"
import {
    GrapherInterface,
    grapherKeysToSerialize,
} from "../grapher/core/GrapherInterface"
import { SuggestedChartRevisionStatus } from "../adminSiteClient/SuggestedChartRevision"
import {
    VariableAnnotationsResponse,
    VariableAnnotationPatch,
} from "../clientUtils/AdminSessionTypes"
import {
    CountryNameFormat,
    CountryDefByKey,
} from "../adminSiteClient/CountryNameFormat"
import { Dataset } from "../db/model/Dataset"
import { User } from "../db/model/User"
import { syncDatasetToGitRepo, removeDatasetFromGitRepo } from "./gitDataExport"
import { ChartRevision } from "../db/model/ChartRevision"
import { SuggestedChartRevision } from "../db/model/SuggestedChartRevision"
import { Post } from "../db/model/Post"
import { camelCaseProperties } from "../clientUtils/string"
import { logErrorAndMaybeSendToSlack } from "../serverUtils/slackLog"
import { denormalizeLatestCountryData } from "../baker/countryProfiles"
import { PostReference, ChartRedirect } from "../adminSiteClient/ChartEditor"
import { DeployQueueServer } from "../baker/DeployQueueServer"
import { FunctionalRouter } from "./FunctionalRouter"
import { JsonError, PostRow } from "../clientUtils/owidTypes"
import { escape } from "mysql"
import Papa from "papaparse"
 
// import {
//     BinaryLogicOperation,
//     BinaryLogicOperators,
//     EqualityComparision,
//     EqualityOperator,
//     parseToOperation,
//     SqlColumnName,
//     StringAtom,
// } from "../clientUtils/SqlFilterSExpression"
import { parseToOperation } from "../clientUtils/SqlFilterSExpression"
import { parseIntOrUndefined } from "../clientUtils/Util"
//import parse = require("s-expression")
const apiRouter = new FunctionalRouter()
 
// Call this to trigger build and deployment of static charts on change
const triggerStaticBuild = async (user: CurrentUser, commitMessage: string) => {
    if (!BAKE_ON_CHANGE) {
        console.log(
            "Not triggering static build because BAKE_ON_CHANGE is false"
        )
        return
    }

    new DeployQueueServer().enqueueChange({
        timeISOString: new Date().toISOString(),
        authorName: user.fullName,
        authorEmail: user.email,
        message: commitMessage,
    })
}
 
async function getLogsByChartId(chartId: number): Promise<ChartRevision[]> {
    const logs = await db.queryMysql(
        `SELECT userId, config, fullName as userName, l.createdAt
        FROM chart_revisions l
        LEFT JOIN users u on u.id = userId
        WHERE chartId = ?
        ORDER BY l.id DESC
        LIMIT 50`,
        [chartId]
    )
    return logs
}
 
const getReferencesByChartId = async (
    chartId: number
): Promise<PostReference[]> => {
    if (!wpdb.isWordpressDBEnabled) return []

    const rows = await db.queryMysql(
        `
        SELECT config->"$.slug" AS slug
        FROM charts
        WHERE id = ?
        UNION
        SELECT slug AS slug
        FROM chart_slug_redirects
        WHERE chart_id = ?
    `,
        [chartId, chartId]
    )

    const slugs = rows.map(
        (row: { slug?: string }) => row.slug && row.slug.replace(/^"|"$/g, "")
    )

    if (!slugs || slugs.length === 0) return []

    let posts = []
    // Hacky approach to find all the references to a chart by searching for
    // the chart URL through the Wordpress database.
    // The Grapher should work without the Wordpress database, so we need to
    // handle failures gracefully.
    // NOTE: Sometimes slugs can be substrings of other slugs, e.g.
    // `grapher/gdp` is a substring of `grapher/gdp-maddison`. We need to be
    // careful not to erroneously match those, which is why we switched to a
    // REGEXP.
    try {
        posts = await wpdb.singleton.query(
            `
                SELECT ID, post_title, post_name
                FROM wp_posts
                WHERE
                    (post_type='page' OR post_type='post' OR post_type='wp_block')
                    AND post_status='publish'
                    AND (
                        ${slugs
                            .map(
                                () =>
                                    `post_content REGEXP CONCAT('grapher/', ?, '[^a-zA-Z_\-]')`
                            )
                            .join(" OR ")}
                    )
            `,
            slugs.map(lodash.escapeRegExp)
        )
    } catch (error) {
        console.warn(`Error in getReferencesByChartId`)
        console.error(error)
        // We can ignore errors due to not being able to connect.
    }
    const permalinks = await wpdb.getPermalinks()
    return posts.map((post) => {
        const slug = permalinks.get(post.ID, post.post_name)
        return {
            id: post.ID,
            title: post.post_title,
            slug: slug,
            url: `${BAKED_BASE_URL}/${slug}`,
        }
    })
}
 
const getRedirectsByChartId = async (
    chartId: number
): Promise<ChartRedirect[]> =>
    await db.queryMysql(
        `
        SELECT id, slug, chart_id as chartId
        FROM chart_slug_redirects
        WHERE chart_id = ?
        ORDER BY id ASC`,
        [chartId]
    )
 
const expectChartById = async (chartId: any): Promise<GrapherInterface> => {
    const chart = await getGrapherById(expectInt(chartId))
    if (chart) return chart

    throw new JsonError(`No chart found for id ${chartId}`, 404)
}
 
const saveGrapher = async (
    transactionContext: db.TransactionContext,
    user: CurrentUser,
    newConfig: GrapherInterface,
    existingConfig?: GrapherInterface
) => {
    // Slugs need some special logic to ensure public urls remain consistent whenever possible
    async function isSlugUsedInRedirect() {
        const rows = await transactionContext.query(
            `SELECT * FROM chart_slug_redirects WHERE chart_id != ? AND slug = ?`,
            [existingConfig ? existingConfig.id : undefined, newConfig.slug]
        )
        return rows.length > 0
    }

    async function isSlugUsedInOtherGrapher() {
        const rows = await transactionContext.query(
            `SELECT * FROM charts WHERE id != ? AND JSON_EXTRACT(config, "$.isPublished") IS TRUE AND JSON_EXTRACT(config, "$.slug") = ?`,
            [existingConfig ? existingConfig.id : undefined, newConfig.slug]
        )
        return rows.length > 0
    }

    // When a chart is published, check for conflicts
    if (newConfig.isPublished) {
        if (!isValidSlug(newConfig.slug))
            throw new JsonError(`Invalid chart slug ${newConfig.slug}`)
        else if (await isSlugUsedInRedirect())
            throw new JsonError(
                `This chart slug was previously used by another chart: ${newConfig.slug}`
            )
        else if (await isSlugUsedInOtherGrapher())
            throw new JsonError(
                `This chart slug is in use by another published chart: ${newConfig.slug}`
            )
        else if (
            existingConfig &&
            existingConfig.isPublished &&
            existingConfig.slug !== newConfig.slug
        ) {
            // Changing slug of an existing chart, delete any old redirect and create new one
            await transactionContext.execute(
                `DELETE FROM chart_slug_redirects WHERE chart_id = ? AND slug = ?`,
                [existingConfig.id, existingConfig.slug]
            )
            await transactionContext.execute(
                `INSERT INTO chart_slug_redirects (chart_id, slug) VALUES (?, ?)`,
                [existingConfig.id, existingConfig.slug]
            )
        }
    }

    if (existingConfig)
        // Bump chart version, very important for cachebusting
        newConfig.version = existingConfig.version! + 1
    else if (newConfig.version)
        // If a chart is republished, we want to keep incrementing the old version number,
        // otherwise it can lead to clients receiving cached versions of the old data.
        newConfig.version += 1
    else newConfig.version = 1

    // Execute the actual database update or creation
    const now = new Date()
    let chartId = existingConfig && existingConfig.id
    const newJsonConfig = JSON.stringify(newConfig)
    // todo: drop "isExplorable"
    if (existingConfig)
        await transactionContext.query(
            `UPDATE charts SET config=?, updatedAt=?, lastEditedAt=?, lastEditedByUserId=?, isExplorable=? WHERE id = ?`,
            [newJsonConfig, now, now, user.id, false, chartId]
        )
    else {
        const result = await transactionContext.execute(
            `INSERT INTO charts (config, createdAt, updatedAt, lastEditedAt, lastEditedByUserId, starred, isExplorable) VALUES (?)`,
            [[newJsonConfig, now, now, now, user.id, false, false]]
        )
        chartId = result.insertId
    }

    // Record this change in version history
    const log = new ChartRevision()
    log.chartId = chartId as number
    log.userId = user.id
    log.config = newConfig
    // TODO: the orm needs to support this but it does not :(
    log.createdAt = new Date()
    log.updatedAt = new Date()
    await transactionContext.manager.save(log)

    // Remove any old dimensions and store the new ones
    // We only note that a relationship exists between the chart and variable in the database; the actual dimension configuration is left to the json
    await transactionContext.execute(
        `DELETE FROM chart_dimensions WHERE chartId=?`,
        [chartId]
    )
    for (let i = 0; i < newConfig.dimensions!.length; i++) {
        const dim = newConfig.dimensions![i]
        await transactionContext.execute(
            `INSERT INTO chart_dimensions (chartId, variableId, property, \`order\`) VALUES (?)`,
            [[chartId, dim.variableId, dim.property, i]]
        )
    }

    // So we can generate country profiles including this chart data
    if (newConfig.isPublished)
        await denormalizeLatestCountryData(
            newConfig.dimensions!.map((d) => d.variableId)
        )

    if (
        newConfig.isPublished &&
        (!existingConfig || !existingConfig.isPublished)
    ) {
        // Newly published, set publication info
        await transactionContext.execute(
            `UPDATE charts SET publishedAt=?, publishedByUserId=? WHERE id = ? `,
            [now, user.id, chartId]
        )
        await triggerStaticBuild(user, `Publishing chart ${newConfig.slug}`)
    } else if (
        !newConfig.isPublished &&
        existingConfig &&
        existingConfig.isPublished
    ) {
        // Unpublishing chart, delete any existing redirects to it
        await transactionContext.execute(
            `DELETE FROM chart_slug_redirects WHERE chart_id = ?`,
            [existingConfig.id]
        )
        await triggerStaticBuild(user, `Unpublishing chart ${newConfig.slug}`)
    } else if (newConfig.isPublished)
        await triggerStaticBuild(user, `Updating chart ${newConfig.slug}`)

    return chartId
}
 
apiRouter.get("/charts.json", async (req: Request, res: Response) => {
    const limit =
        req.query.limit !== undefined ? parseInt(req.query.limit) : 10000
    const charts = await db.queryMysql(
        `
        SELECT ${OldChart.listFields} FROM charts
        JOIN users lastEditedByUser ON lastEditedByUser.id = charts.lastEditedByUserId
        LEFT JOIN users publishedByUser ON publishedByUser.id = charts.publishedByUserId
        ORDER BY charts.lastEditedAt DESC LIMIT ?
    `,
        [limit]
    )

    await Chart.assignTagsForCharts(charts)

    return { charts }
})
 
apiRouter.get("/charts.csv", async (req: Request, res: Response) => {
    const limit =
        req.query.limit !== undefined ? parseInt(req.query.limit) : 10000

    // note: this query is extended from OldChart.listFields.
    const charts = await db.queryMysql(
        `
        SELECT
            charts.id,
            charts.config->>"$.version" AS version,
            CONCAT("${BAKED_BASE_URL}/grapher/", charts.config->>"$.slug") AS url,
            CONCAT("${ADMIN_BASE_URL}", "/admin/charts/", charts.id, "/edit") AS editUrl,
            charts.config->>"$.slug" AS slug,
            charts.config->>"$.title" AS title,
            charts.config->>"$.subtitle" AS subtitle,
            charts.config->>"$.sourceDesc" AS sourceDesc,
            charts.config->>"$.note" AS note,
            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.config->>"$.originUrl" AS originUrl,
            charts.starred AS isStarred,
            charts.lastEditedAt,
            charts.lastEditedByUserId,
            lastEditedByUser.fullName AS lastEditedBy,
            charts.publishedAt,
            charts.publishedByUserId,
            publishedByUser.fullName AS publishedBy,
            charts.isExplorable AS isExplorable
        FROM charts
        JOIN users lastEditedByUser ON lastEditedByUser.id = charts.lastEditedByUserId
        LEFT JOIN users publishedByUser ON publishedByUser.id = charts.publishedByUserId
        ORDER BY charts.lastEditedAt DESC
        LIMIT ?
    `,
        [limit]
    )
    // note: retrieving references is VERY slow.
    // await Promise.all(
    //     charts.map(async (chart: any) => {
    //         const references = await getReferencesByChartId(chart.id)
    //         chart.references = references.length
    //             ? references.map((ref) => ref.url)
    //             : ""
    //     })
    // )
    // await Chart.assignTagsForCharts(charts)
    res.setHeader("Content-disposition", "attachment; filename=charts.csv")
    res.setHeader("content-type", "text/csv")
    const csv = Papa.unparse(charts)
    return csv
})
 
apiRouter.get(
    "/charts/:chartId.config.json",
    async (req: Request, res: Response) => expectChartById(req.params.chartId)
)
 
apiRouter.get(
    "/editorData/namespaces.json",
    async (req: Request, res: Response) => {
        const rows = (await db.queryMysql(
            `SELECT DISTINCT
                namespace AS name,
                namespaces.description AS description,
                namespaces.isArchived AS isArchived
            FROM datasets
            JOIN namespaces ON namespaces.name = datasets.namespace`
        )) as { name: string; description?: string; isArchived: boolean }[]

        return {
            namespaces: lodash
                .sortBy(rows, (row) => row.description)
                .map((namespace) => ({
                    ...namespace,
                    isArchived: !!namespace.isArchived,
                })),
        }
    }
)
 
apiRouter.get(
    "/charts/:chartId.logs.json",
    async (req: Request, res: Response) => ({
        logs: await getLogsByChartId(req.params.chartId),
    })
)
 
apiRouter.get(
    "/charts/:chartId.references.json",
    async (req: Request, res: Response) => ({
        references: await getReferencesByChartId(req.params.chartId),
    })
)
 
apiRouter.get(
    "/charts/:chartId.redirects.json",
    async (req: Request, res: Response) => ({
        redirects: await getRedirectsByChartId(req.params.chartId),
    })
)
 
apiRouter.get("/countries.json", async (req: Request, res: Response) => {
    let rows = []

    const input = req.query.input
    const output = req.query.output

    if (input === CountryNameFormat.NonStandardCountryName) {
        const outputColumn = CountryDefByKey[output].column_name

        rows = await db.queryMysql(`
            SELECT country_name as input, ${outputColumn} as output
            FROM country_name_tool_countryname ccn
            LEFT JOIN country_name_tool_countrydata ccd on ccn.owid_country = ccd.id
            LEFT JOIN country_name_tool_continent con on con.id = ccd.continent`)
    } else {
        const inputColumn = CountryDefByKey[input].column_name
        const outputColumn = CountryDefByKey[output].column_name

        rows = await db.queryMysql(
            `SELECT ${inputColumn} as input, ${outputColumn} as output
            FROM country_name_tool_countrydata ccd
            LEFT JOIN country_name_tool_continent con on con.id = ccd.continent`
        )
    }

    return {
        countries: rows,
    }
})
 
apiRouter.post("/countries", async (req: Request, res: Response) => {
    const countries = req.body.countries

    const mapOwidNameToId: any = {}
    let owidRows = []

    // find owid ID
    const owidNames = Object.keys(countries).map((key) => countries[key])
    owidRows = await db.queryMysql(
        `SELECT id, owid_name
        FROM country_name_tool_countrydata
        WHERE owid_name in (?)
        `,
        [owidNames]
    )
    for (const row of owidRows) {
        mapOwidNameToId[row.owid_name] = row.id
    }

    // insert one by one (ideally do a bulk insert)
    for (const country of Object.keys(countries)) {
        const owidName = countries[country]

        console.log(
            `adding ${country}, ${mapOwidNameToId[owidName]}, ${owidName}`
        )

        await db.execute(
            `INSERT INTO country_name_tool_countryname (country_name, owid_country)
            VALUES (?, ?)`,
            [country, mapOwidNameToId[owidName]]
        )
    }

    return { success: true }
})
 
apiRouter.get(
    "/editorData/:namespace.json",
    async (req: Request, res: Response) => {
        const datasets = []
        const rows = await db.queryMysql(
            `SELECT
                v.name,
                v.id,
                d.name as datasetName,
                d.namespace,
                d.isPrivate,
                d.nonRedistributable
            FROM variables as v JOIN datasets as d ON v.datasetId = d.id
            WHERE namespace=?
            ORDER BY d.updatedAt DESC
            `,
            [req.params.namespace]
        )

        let dataset:
            | {
                  name: string
                  namespace: string
                  isPrivate: boolean
                  nonRedistributable: boolean
                  variables: { id: number; name: string }[]
              }
            | undefined
        for (const row of rows) {
            if (!dataset || row.datasetName !== dataset.name) {
                if (dataset) datasets.push(dataset)

                dataset = {
                    name: row.datasetName,
                    namespace: row.namespace,
                    isPrivate: row.isPrivate,
                    nonRedistributable: row.nonRedistributable,
                    variables: [],
                }
            }

            dataset.variables.push({
                id: row.id,
                name: row.name,
            })
        }

        if (dataset) datasets.push(dataset)

        return { datasets: datasets }
    }
)
 
apiRouter.get(
    "/data/variables/:variableStr.json",
    async (req: Request, res: Response) => {
        const variableIds: number[] = req.params.variableStr
            .split("+")
            .map((v: string) => parseInt(v))
        return getVariableData(variableIds)
    }
)
 
// Mark a chart for display on the front page
apiRouter.post("/charts/:chartId/star", async (req: Request, res: Response) => {
    const chart = await expectChartById(req.params.chartId)

    await db.execute(`UPDATE charts SET starred=(charts.id=?)`, [chart.id])
    await triggerStaticBuild(
        res.locals.user,
        `Setting front page chart to ${chart.slug}`
    )

    return { success: true }
})
 
apiRouter.post("/charts", async (req: Request, res: Response) => {
    const chartId = await db.transaction(async (t) => {
        return saveGrapher(t, res.locals.user, req.body)
    })
    return { success: true, chartId: chartId }
})
 
apiRouter.post(
    "/charts/:chartId/setTags",
    async (req: Request, res: Response) => {
        const chartId = expectInt(req.params.chartId)

        await Chart.setTags(chartId, req.body.tagIds)

        return { success: true }
    }
)
 
apiRouter.put("/charts/:chartId", async (req: Request, res: Response) => {
    const existingConfig = await expectChartById(req.params.chartId)

    await db.transaction(async (t) => {
        await saveGrapher(t, res.locals.user, req.body, existingConfig)
    })

    const logs = await getLogsByChartId(existingConfig.id as number)
    return { success: true, chartId: existingConfig.id, newLog: logs[0] }
})
 
apiRouter.delete("/charts/:chartId", async (req: Request, res: Response) => {
    const chart = await expectChartById(req.params.chartId)

    await db.transaction(async (t) => {
        await t.execute(`DELETE FROM chart_dimensions WHERE chartId=?`, [
            chart.id,
        ])
        await t.execute(`DELETE FROM chart_slug_redirects WHERE chart_id=?`, [
            chart.id,
        ])
        await t.execute(
            `DELETE FROM suggested_chart_revisions WHERE chartId=?`,
            [chart.id]
        )
        await t.execute(`DELETE FROM charts WHERE id=?`, [chart.id])
    })

    if (chart.isPublished)
        await triggerStaticBuild(
            res.locals.user,
            `Deleting chart ${chart.slug}`
        )

    return { success: true }
})
 
apiRouter.get(
    "/suggested-chart-revisions",
    async (req: Request, res: Response) => {
        const isValidSortBy = (sortBy: string) => {
            return [
                "updatedAt",
                "createdAt",
                "suggestedReason",
                "id",
                "chartId",
                "status",
                "variableId",
                "chartUpdatedAt",
                "chartCreatedAt",
            ].includes(sortBy)
        }
        const isValidSortOrder = (sortOrder: string) => {
            return (
                sortOrder !== undefined &&
                sortOrder !== null &&
                ["ASC", "DESC"].includes(sortOrder.toUpperCase())
            )
        }
        const limit =
            req.query.limit !== undefined ? expectInt(req.query.limit) : 10000
        const offset =
            req.query.offset !== undefined ? expectInt(req.query.offset) : 0
        const sortBy = isValidSortBy(req.query.sortBy)
            ? req.query.sortBy
            : "updatedAt"
        const sortOrder = isValidSortOrder(req.query.sortOrder)
            ? req.query.sortOrder.toUpperCase()
            : "DESC"
        const status = SuggestedChartRevision.isValidStatus(req.query.status)
            ? req.query.status
            : null

        let orderBy
        if (sortBy === "variableId") {
            orderBy =
                "CAST(scr.suggestedConfig->>'$.dimensions[0].variableId' as SIGNED)"
        } else if (sortBy === "chartUpdatedAt") {
            orderBy = "c.updatedAt"
        } else if (sortBy === "chartCreatedAt") {
            orderBy = "c.createdAt"
        } else {
            orderBy = `scr.${sortBy}`
        }

        const suggestedChartRevisions = await db.queryMysql(
            `
            SELECT scr.id, scr.chartId, scr.updatedAt, scr.createdAt,
                scr.suggestedReason, scr.decisionReason, scr.status,
                scr.suggestedConfig, scr.originalConfig,
                createdByUser.id as createdById,
                updatedByUser.id as updatedById,
                createdByUser.fullName as createdByFullName,
                updatedByUser.fullName as updatedByFullName,
                c.config as existingConfig, c.updatedAt as chartUpdatedAt,
                c.createdAt as chartCreatedAt
            FROM suggested_chart_revisions as scr
            LEFT JOIN charts c on c.id = scr.chartId
            LEFT JOIN users createdByUser on createdByUser.id = scr.createdBy
            LEFT JOIN users updatedByUser on updatedByUser.id = scr.updatedBy
            ${status ? "WHERE scr.status = ?" : ""}
            ORDER BY ${orderBy} ${sortOrder}
            LIMIT ? OFFSET ?
        `,
            status ? [status, limit, offset] : [limit, offset]
        )

        let numTotalRows = (
            await db.queryMysql(
                `
                SELECT COUNT(*) as count
                FROM suggested_chart_revisions
                ${status ? "WHERE status = ?" : ""}
            `,
                status ? [status] : []
            )
        )[0].count
        numTotalRows = numTotalRows ? parseInt(numTotalRows) : numTotalRows

        suggestedChartRevisions.map(
            (suggestedChartRevision: SuggestedChartRevision) => {
                suggestedChartRevision.suggestedConfig = JSON.parse(
                    suggestedChartRevision.suggestedConfig
                )
                suggestedChartRevision.existingConfig = JSON.parse(
                    suggestedChartRevision.existingConfig
                )
                suggestedChartRevision.originalConfig = JSON.parse(
                    suggestedChartRevision.originalConfig
                )
                suggestedChartRevision.canApprove =
                    SuggestedChartRevision.checkCanApprove(
                        suggestedChartRevision
                    )
                suggestedChartRevision.canReject =
                    SuggestedChartRevision.checkCanReject(
                        suggestedChartRevision
                    )
                suggestedChartRevision.canFlag =
                    SuggestedChartRevision.checkCanFlag(suggestedChartRevision)
                suggestedChartRevision.canPending =
                    SuggestedChartRevision.checkCanPending(
                        suggestedChartRevision
                    )
            }
        )

        return {
            suggestedChartRevisions: suggestedChartRevisions,
            numTotalRows: numTotalRows,
        }
    }
)
 
apiRouter.post(
    "/suggested-chart-revisions",
    async (req: Request, res: Response) => {
        const messages: any[] = []
        const status = SuggestedChartRevisionStatus.pending
        const suggestedReason = req.body.suggestedReason
            ? String(req.body.suggestedReason)
            : null
        const convertStringsToNull =
            typeof req.body.convertStringsToNull == "boolean"
                ? req.body.convertStringsToNull
                : true
        const suggestedConfigs = req.body.suggestedConfigs as any[]

        // suggestedConfigs must be an array of length > 0
        if (!(Array.isArray(suggestedConfigs) && suggestedConfigs.length > 0)) {
            throw new JsonError(
                "POST body must contain a `suggestedConfigs` property, which must be an Array with length > 0."
            )
        }

        // tries to convert each config field to json (e.g. the `map` field
        // should be converted to json if it is present).
        suggestedConfigs.map((config) => {
            Object.keys(config).map((k) => {
                try {
                    const json = JSON.parse(config[k])
                    config[k] = json
                } catch (error) {
                    // do nothing.
                }
            })
        })

        // checks for required keys
        const requiredKeys = ["id", "version"]
        suggestedConfigs.map((config) => {
            requiredKeys.map((k) => {
                if (!config.hasOwnProperty(k)) {
                    throw new JsonError(
                        `The "${k}" field is required, but one or more chart configs in the POST body does not contain it.`
                    )
                }
            })
        })

        // safely sets types of keys that are used in db queries below.
        const typeConversions = [
            { key: "id", expectedType: "number", f: expectInt },
            { key: "version", expectedType: "number", f: expectInt },
        ]
        suggestedConfigs.map((config) => {
            typeConversions.map((obj) => {
                config[obj.key] = obj.f(config[obj.key])
                if (
                    config[obj.key] !== null &&
                    config[obj.key] !== undefined &&
                    typeof config[obj.key] !== obj.expectedType
                ) {
                    throw new JsonError(
                        `Expected all "${obj.key}" values to be non-null and of ` +
                            `type "${obj.expectedType}", but one or more chart ` +
                            `configs contains a "${obj.key}" value that does ` +
                            `not meet this criteria.`
                    )
                }
            })
        })

        // checks for invalid keys
        const uniqKeys = new Set()
        suggestedConfigs.map((config) => {
            Object.keys(config).forEach((item) => {
                uniqKeys.add(item)
            })
        })
        const invalidKeys = [...uniqKeys].filter(
            (v) => !grapherKeysToSerialize.includes(v as string)
        )
        if (invalidKeys.length > 0) {
            throw new JsonError(
                `The following fields are not valid chart config fields: ${invalidKeys}`
            )
        }

        // checks that no duplicate chart ids are present.
        const chartIds = suggestedConfigs.map((config) => config.id)
        if (new Set(chartIds).size !== chartIds.length) {
            throw new JsonError(
                `Found one or more duplicate chart ids in POST body.`
            )
        }

        // converts some strings to null
        if (convertStringsToNull) {
            const isNullString = (value: string): boolean => {
                const nullStrings = ["nan", "na"]
                return nullStrings.includes(value.toLowerCase())
            }
            suggestedConfigs.map((config) => {
                for (const key of Object.keys(config)) {
                    if (
                        typeof config[key] == "string" &&
                        isNullString(config[key])
                    ) {
                        config[key] = null
                    }
                }
            })
        }

        // empty strings mean that the field should NOT be overwritten, so we
        // remove key-value pairs where value === ""
        suggestedConfigs.map((config) => {
            for (const key of Object.keys(config)) {
                if (config[key] === "") {
                    delete config[key]
                }
            }
        })

        await db.transaction(async (t) => {
            const whereCond1 = suggestedConfigs
                .map(
                    (config) =>
                        `(id = ${escape(
                            config.id
                        )} AND config->"$.version" = ${escape(config.version)})`
                )
                .join(" OR ")
            const whereCond2 = suggestedConfigs
                .map(
                    (config) =>
                        `(chartId = ${escape(
                            config.id
                        )} AND config->"$.version" = ${escape(config.version)})`
                )
                .join(" OR ")
            // retrieves original chart configs
            let rows: any[] = await t.query(
                `
                SELECT id, config, 1 as priority
                FROM charts
                WHERE ${whereCond1}

                UNION

                SELECT chartId as id, config, 2 as priority
                FROM chart_revisions
                WHERE ${whereCond2}

                ORDER BY priority
                `
            )

            rows.map((row) => {
                row.config = JSON.parse(row.config)
            })

            // drops duplicate id-version rows (keeping the row from the
            // `charts` table when available).
            rows = rows.filter(
                (v, i, a) =>
                    a.findIndex(
                        (el) =>
                            el.id === v.id &&
                            el.config.version === v.config.version
                    ) === i
            )
            if (rows.length < suggestedConfigs.length) {
                // identifies which particular chartId-version combinations have
                // not been found in the DB
                const missingConfigs = suggestedConfigs.filter((config) => {
                    const i = rows.findIndex((row) => {
                        return (
                            row.id === config.id &&
                            row.config.version === config.version
                        )
                    })
                    return i === -1
                })
                throw new JsonError(
                    `Failed to retrieve the following chartId-version combinations:\n${missingConfigs
                        .map((c) => {
                            return JSON.stringify({
                                id: c.id,
                                version: c.version,
                            })
                        })
                        .join(
                            "\n"
                        )}\nPlease check that each chartId and version exists.`
                )
            } else if (rows.length > suggestedConfigs.length) {
                throw new JsonError(
                    "Retrieved more chart configs than expected. This may be due to a bug on the server."
                )
            }
            const originalConfigs: Record<string, GrapherInterface> =
                rows.reduce(
                    (obj: any, row: any) => ({
                        ...obj,
                        [row.id]: row.config,
                    }),
                    {}
                )

            // some chart configs do not have an `id` field, so we check for it
            // and insert the id here as needed. This is important for the
            // lodash.isEqual condition later on.
            for (const [id, config] of Object.entries(originalConfigs)) {
                if (config.id === null || config.id === undefined) {
                    config.id = parseInt(id)
                }
            }

            // sanity check that each original config also has the required keys.
            Object.values(originalConfigs).map((config) => {
                requiredKeys.map((k) => {
                    if (!config.hasOwnProperty(k)) {
                        throw new JsonError(
                            `The "${k}" field is required, but one or more ` +
                                `chart configs in the database does not ` +
                                `contain it. Please report this issue to a ` +
                                `developer.`
                        )
                    }
                })
            })

            // if a field is null in the suggested config and the field does not
            // exist in the original config, then we can delete the field from
            // the suggested config b/c the non-existence of the field on the
            // original config is equivalent to null.
            suggestedConfigs.map((config: any) => {
                const chartId = config.id as number
                const originalConfig = originalConfigs[chartId]
                for (const key of Object.keys(config)) {
                    if (
                        config[key] === null &&
                        !originalConfig.hasOwnProperty(key)
                    ) {
                        delete config[key]
                    }
                }
            })

            // constructs array of suggested chart revisions to insert.
            const values: any[] = []
            suggestedConfigs.map((config) => {
                const chartId = config.id as number
                const originalConfig = originalConfigs[chartId]
                const suggestedConfig: GrapherInterface = Object.assign(
                    {},
                    JSON.parse(JSON.stringify(originalConfig)),
                    config
                )
                if (!lodash.isEqual(suggestedConfig, originalConfig)) {
                    if (suggestedConfig.version) {
                        suggestedConfig.version += 1
                    }
                    values.push([
                        chartId,
                        JSON.stringify(suggestedConfig),
                        JSON.stringify(originalConfig),
                        suggestedReason,
                        status,
                        res.locals.user.id,
                        new Date(),
                        new Date(),
                    ])
                }
            })

            // inserts suggested chart revisions
            const result = await t.execute(
                `
                INSERT INTO suggested_chart_revisions
                (chartId, suggestedConfig, originalConfig, suggestedReason, status, createdBy, createdAt, updatedAt)
                VALUES
                ?
                `,
                [values]
            )
            if (result.affectedRows > 0) {
                messages.push({
                    type: "success",
                    text: `${result.affectedRows} chart revisions have been queued for approval.`,
                })
            }
            if (suggestedConfigs.length - result.affectedRows > 0) {
                messages.push({
                    type: "warning",
                    text: `${
                        suggestedConfigs.length - result.affectedRows
                    } chart revisions have not been queued for approval (e.g. because the chart revision does not contain any changes).`,
                })
            }
        })

        return { success: true, messages }
    }
)
 
apiRouter.get(
    "/suggested-chart-revisions/:suggestedChartRevisionId",
    async (req: Request, res: Response) => {
        const suggestedChartRevisionId = expectInt(
            req.params.suggestedChartRevisionId
        )

        const suggestedChartRevision = await db.mysqlFirst(
            `
            SELECT scr.id, scr.chartId, scr.updatedAt, scr.createdAt,
                scr.suggestedReason, scr.decisionReason, scr.status,
                scr.suggestedConfig, scr.originalConfig,
                createdByUser.id as createdById,
                updatedByUser.id as updatedById,
                createdByUser.fullName as createdByFullName,
                updatedByUser.fullName as updatedByFullName,
                c.config as existingConfig, c.updatedAt as chartUpdatedAt,
                c.createdAt as chartCreatedAt
            FROM suggested_chart_revisions as scr
            LEFT JOIN charts c on c.id = scr.chartId
            LEFT JOIN users createdByUser on createdByUser.id = scr.createdBy
            LEFT JOIN users updatedByUser on updatedByUser.id = scr.updatedBy
            WHERE scr.id = ?
        `,
            [suggestedChartRevisionId]
        )

        if (!suggestedChartRevision) {
            throw new JsonError(
                `No suggested chart revision by id '${suggestedChartRevisionId}'`,
                404
            )
        }

        suggestedChartRevision.suggestedConfig = JSON.parse(
            suggestedChartRevision.suggestedConfig
        )
        suggestedChartRevision.originalConfig = JSON.parse(
            suggestedChartRevision.originalConfig
        )
        suggestedChartRevision.existingConfig = JSON.parse(
            suggestedChartRevision.existingConfig
        )
        suggestedChartRevision.canApprove =
            SuggestedChartRevision.checkCanApprove(suggestedChartRevision)
        suggestedChartRevision.canReject =
            SuggestedChartRevision.checkCanReject(suggestedChartRevision)
        suggestedChartRevision.canFlag = SuggestedChartRevision.checkCanFlag(
            suggestedChartRevision
        )
        suggestedChartRevision.canPending =
            SuggestedChartRevision.checkCanPending(suggestedChartRevision)

        return {
            suggestedChartRevision: suggestedChartRevision,
        }
    }
)
 
apiRouter.post(
    "/suggested-chart-revisions/:suggestedChartRevisionId/update",
    async (req: Request, res: Response) => {
        const suggestedChartRevisionId = expectInt(
            req.params.suggestedChartRevisionId
        )
        const { status, decisionReason } = req.body as {
            status: string
            decisionReason: string
        }

        await db.transaction(async (t) => {
            const suggestedChartRevision = await db.mysqlFirst(
                `SELECT id, chartId, suggestedConfig, originalConfig, status FROM suggested_chart_revisions WHERE id=?`,
                [suggestedChartRevisionId]
            )
            if (!suggestedChartRevision) {
                throw new JsonError(
                    `No suggested chart revision found for id '${suggestedChartRevisionId}'`,
                    404
                )
            }

            suggestedChartRevision.suggestedConfig = JSON.parse(
                suggestedChartRevision.suggestedConfig
            )
            suggestedChartRevision.originalConfig = JSON.parse(
                suggestedChartRevision.originalConfig
            )
            suggestedChartRevision.existingConfig = await expectChartById(
                suggestedChartRevision.chartId
            )

            const canApprove = SuggestedChartRevision.checkCanApprove(
                suggestedChartRevision
            )
            const canReject = SuggestedChartRevision.checkCanReject(
                suggestedChartRevision
            )
            const canFlag = SuggestedChartRevision.checkCanFlag(
                suggestedChartRevision
            )
            const canPending = SuggestedChartRevision.checkCanPending(
                suggestedChartRevision
            )

            const canUpdate =
                (status === "approved" && canApprove) ||
                (status === "rejected" && canReject) ||
                (status === "pending" && canPending) ||
                (status === "flagged" && canFlag)
            if (!canUpdate) {
                throw new JsonError(
                    `Suggest chart revision ${suggestedChartRevisionId} cannot be ` +
                        `updated with status="${status}".`,
                    404
                )
            }

            await t.execute(
                `
                UPDATE suggested_chart_revisions
                SET status=?, decisionReason=?, updatedAt=?, updatedBy=?
                WHERE id = ?
                `,
                [
                    status,
                    decisionReason,
                    new Date(),
                    res.locals.user.id,
                    suggestedChartRevisionId,
                ]
            )
            // note: the calls to saveGrapher() below will never overwrite a config
            // that has been changed since the suggestedConfig was created, because
            // if the config has been changed since the suggestedConfig was created
            // then canUpdate will be false (so an error would have been raised
            // above).
            if (status === "approved" && canApprove) {
                await saveGrapher(
                    t,
                    res.locals.user,
                    suggestedChartRevision.suggestedConfig,
                    suggestedChartRevision.existingConfig
                )
            } else if (
                status === "rejected" &&
                canReject &&
                suggestedChartRevision.status === "approved"
            ) {
                await saveGrapher(
                    t,
                    res.locals.user,
                    suggestedChartRevision.originalConfig,
                    suggestedChartRevision.existingConfig
                )
            }
        })

        return { success: true }
    }
)
 
apiRouter.get("/users.json", async (req: Request, res: Response) => ({
    users: await User.find({
        select: [
            "id",
            "email",
            "fullName",
            "isActive",
            "isSuperuser",
            "createdAt",
            "updatedAt",
            "lastLogin",
            "lastSeen",
        ],
        order: { lastSeen: "DESC" },
    }),
}))
 
apiRouter.get("/users/:userId.json", async (req: Request, res: Response) => ({
    user: await User.findOne(req.params.userId, {
        select: [
            "id",
            "email",
            "fullName",
            "isActive",
            "isSuperuser",
            "createdAt",
            "updatedAt",
            "lastLogin",
            "lastSeen",
        ],
    }),
}))
 
apiRouter.delete("/users/:userId", async (req: Request, res: Response) => {
    if (!res.locals.user.isSuperuser)
        throw new JsonError("Permission denied", 403)

    const userId = expectInt(req.params.userId)
    await db.transaction(async (t) => {
        await t.execute(`DELETE FROM users WHERE id=?`, [userId])
    })

    return { success: true }
})
 
apiRouter.put("/users/:userId", async (req: Request, res: Response) => {
    if (!res.locals.user.isSuperuser)
        throw new JsonError("Permission denied", 403)

    const user = await User.findOne(req.params.userId)
    if (!user) throw new JsonError("No such user", 404)

    user.fullName = req.body.fullName
    user.isActive = req.body.isActive
    await user.save()

    return { success: true }
})
 
apiRouter.post("/users/invite", async (req: Request, res: Response) => {
    if (!res.locals.user.isSuperuser)
        throw new JsonError("Permission denied", 403)

    const { email } = req.body

    await getConnection().transaction(async (manager) => {
        // Remove any previous invites for this email address to avoid duplicate accounts
        const repo = manager.getRepository(UserInvitation)
        await repo
            .createQueryBuilder()
            .where(`email = :email`, { email })
            .delete()
            .execute()

        const invite = new UserInvitation()
        invite.email = email
        invite.code = UserInvitation.makeInviteCode()
        invite.validTill = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
        invite.createdAt = new Date()
        invite.updatedAt = new Date()
        await repo.save(invite)

        const inviteLink = absoluteUrl(`/admin/register?code=${invite.code}`)

        await sendMail({
            from: "no-reply@ourworldindata.org",
            to: email,
            subject: "Invitation to join owid-admin",
            text: `Hi, please follow this link to register on owid-admin: ${inviteLink}`,
        })
    })

    return { success: true }
})
 
apiRouter.get("/variables.json", async (req) => {
    const limit = req.query.limit !== undefined ? parseInt(req.query.limit) : 50
    const searchStr = req.query.search

    const query = `
        SELECT
            v.id,
            v.name,
            d.id AS datasetId,
            d.name AS datasetName,
            d.isPrivate AS isPrivate,
            d.nonRedistributable AS nonRedistributable,
            d.dataEditedAt AS uploadedAt,
            u.fullName AS uploadedBy
        FROM variables AS v
        JOIN datasets d ON d.id=v.datasetId
        JOIN users u ON u.id=d.dataEditedByUserId
        ${searchStr ? "WHERE v.name LIKE ?" : ""}
        ORDER BY d.dataEditedAt DESC
        LIMIT ?
    `

    const rows = await db.queryMysql(
        query,
        searchStr ? [`%${searchStr}%`, limit] : [limit]
    )

    const numTotalRows = (
        await db.queryMysql(`SELECT COUNT(*) as count FROM variables`)
    )[0].count

    return { variables: rows, numTotalRows: numTotalRows }
})
 
apiRouter.get(
    "/variable-annotations",
    async (req): Promise<VariableAnnotationsResponse> => {
        const filterSExpr =
            req.query.filter !== undefined
                ? parseToOperation(req.query.filter)
                : undefined

        const offset = parseIntOrUndefined(req.query.offset) ?? 0

        // Note that our DSL generates sql here that we splice directly into the SQL as text
        // This is a potential for a SQL injection attack but we control the DSL and are
        // careful there to only allow carefully guarded vocabularies from being used, not
        // arbitrary user input
        const whereClause = filterSExpr?.toSql() ?? "true"
        const resultsWithStringGrapherConfigs =
            await db.queryMysql(`SELECT variables.id as id, variables.name as name, variables.grapherConfig as grapherConfig, datasets.name as datasetname, namespaces.name as namespace
FROM variables
LEFT JOIN datasets on variables.datasetId = datasets.id
LEFT JOIN namespaces on datasets.namespace = namespaces.name
WHERE ${whereClause}
ORDER BY variables.id DESC
LIMIT 50
OFFSET ${offset.toString()}`)

        const results = resultsWithStringGrapherConfigs.map((row: any) => ({
            ...row,
            grapherConfig: lodash.isNil(row.grapherConfig)
                ? null
                : JSON.parse(row.grapherConfig),
        }))
        const resultCount = await db.queryMysql(`SELECT count(*) as count
FROM variables
LEFT JOIN datasets on variables.datasetId = datasets.id
LEFT JOIN namespaces on datasets.namespace = namespaces.name
WHERE ${whereClause}`)
        return { variables: results, numTotalRows: resultCount[0].count }
    }
)
 
apiRouter.patch("/variable-annotations", async (req) => {
    const patchesList = req.body as VariableAnnotationPatch[]
    const variableIds = new Set(patchesList.map((patch) => patch.variableId))

    await db.transaction(async (manager) => {
        const configsAndIds = await manager.query(
            `SELECT id, grapherConfig FROM variables where id IN (?)`,
            [[...variableIds.values()]]
        )
        const configMap = new Map(
            configsAndIds.map((item: any) => [
                item.id,
                item.grapherConfig ? JSON.parse(item.grapherConfig) : {},
            ])
        )
        // console.log("ids", configsAndIds.map((item : any) => item.id))
        for (const patchSet of patchesList) {
            const config = configMap.get(patchSet.variableId)
            configMap.set(patchSet.variableId, applyPatch(patchSet, config))
        }

        for (const [variableId, newConfig] of configMap.entries()) {
            await manager.execute(
                `UPDATE variables SET grapherConfig = ? where id = ?`,
                [JSON.stringify(newConfig), variableId]
            )
        }
    })

    return { success: true }
})
 
apiRouter.get("/variables.usages.json", async (req) => {
    const query = `SELECT variableId, COUNT(DISTINCT chartId) AS usageCount
FROM chart_dimensions
GROUP BY variableId
ORDER BY usageCount DESC`

    const rows = await db.queryMysql(query)

    return rows
})
 
interface VariableSingleMeta {
    id: number
    name: string
    unit: string
    shortUnit: string
    description: string
 
    datasetId: number
    datasetName: string
    datasetNamespace: string
 
    vardata: string
    display: any
}
 
// TODO where is this used? can we get rid of VariableSingleMeta type?
apiRouter.get(
    "/variables/:variableId.json",
    async (req: Request, res: Response) => {
        const variableId = expectInt(req.params.variableId)

        const variable = await db.mysqlFirst(
            `
        SELECT v.id, v.name, v.unit, v.shortUnit, v.description, v.sourceId, u.fullName AS uploadedBy,
               v.display, d.id AS datasetId, d.name AS datasetName, d.namespace AS datasetNamespace
        FROM variables v
        JOIN datasets d ON d.id=v.datasetId
        JOIN users u ON u.id=d.dataEditedByUserId
        WHERE v.id = ?
    `,
            [variableId]
        )

        if (!variable) {
            throw new JsonError(`No variable by id '${variableId}'`, 404)
        }

        variable.display = JSON.parse(variable.display)

        variable.source = await db.mysqlFirst(
            `SELECT id, name FROM sources AS s WHERE id = ?`,
            variable.sourceId
        )

        const charts = await db.queryMysql(
            `
        SELECT ${OldChart.listFields}
        FROM charts
        JOIN users lastEditedByUser ON lastEditedByUser.id = charts.lastEditedByUserId
        LEFT JOIN users publishedByUser ON publishedByUser.id = charts.publishedByUserId
        JOIN chart_dimensions cd ON cd.chartId = charts.id
        WHERE cd.variableId = ?
        GROUP BY charts.id
    `,
            [variableId]
        )

        await Chart.assignTagsForCharts(charts)

        variable.charts = charts

        return {
            variable: variable as VariableSingleMeta,
        } /*, vardata: await getVariableData([variableId]) }*/
    }
)
 
apiRouter.put("/variables/:variableId", async (req: Request) => {
    const variableId = expectInt(req.params.variableId)
    const variable = (req.body as { variable: VariableSingleMeta }).variable

    await db.execute(
        `UPDATE variables SET name=?, description=?, updatedAt=?, display=? WHERE id = ?`,
        [
            variable.name,
            variable.description,
            new Date(),
            JSON.stringify(variable.display),
            variableId,
        ]
    )

    return { success: true }
})
 
apiRouter.delete("/variables/:variableId", async (req: Request) => {
    const variableId = expectInt(req.params.variableId)

    const variable = await db.mysqlFirst(
        `SELECT datasets.namespace FROM variables JOIN datasets ON variables.datasetId=datasets.id WHERE variables.id=?`,
        [variableId]
    )

    if (!variable) throw new JsonError(`No variable by id ${variableId}`, 404)
    else if (variable.namespace !== "owid")
        throw new JsonError(`Cannot delete bulk import variable`, 400)

    await db.transaction(async (t) => {
        await t.execute(`DELETE FROM data_values WHERE variableId=?`, [
            variableId,
        ])
        await t.execute(`DELETE FROM variables WHERE id=?`, [variableId])
    })

    return { success: true }
})
 
apiRouter.get("/datasets.json", async (req) => {
    const datasets = await db.queryMysql(`
        SELECT
            d.id,
            d.namespace,
            d.name,
            d.description,
            d.dataEditedAt,
            du.fullName AS dataEditedByUserName,
            d.metadataEditedAt,
            mu.fullName AS metadataEditedByUserName,
            d.isPrivate,
            d.nonRedistributable
        FROM datasets d
        JOIN users du ON du.id=d.dataEditedByUserId
        JOIN users mu ON mu.id=d.metadataEditedByUserId
        ORDER BY d.dataEditedAt DESC
    `)

    const tags = await db.queryMysql(`
        SELECT dt.datasetId, t.id, t.name FROM dataset_tags dt
        JOIN tags t ON dt.tagId = t.id
    `)
    const tagsByDatasetId = lodash.groupBy(tags, (t) => t.datasetId)
    for (const dataset of datasets) {
        dataset.tags = (tagsByDatasetId[dataset.id] || []).map((t) =>
            lodash.omit(t, "datasetId")
        )
    }
    /*LEFT JOIN variables AS v ON v.datasetId=d.id
    GROUP BY d.id*/

    return { datasets: datasets }
})
 
apiRouter.get("/datasets/:datasetId.json", async (req: Request) => {
    const datasetId = expectInt(req.params.datasetId)

    const dataset = await db.mysqlFirst(
        `
        SELECT d.id,
            d.namespace,
            d.name,
            d.description,
            d.updatedAt,
            d.dataEditedAt,
            d.dataEditedByUserId,
            du.fullName AS dataEditedByUserName,
            d.metadataEditedAt,
            d.metadataEditedByUserId,
            mu.fullName AS metadataEditedByUserName,
            d.isPrivate,
            d.nonRedistributable
        FROM datasets AS d
        JOIN users du ON du.id=d.dataEditedByUserId
        JOIN users mu ON mu.id=d.metadataEditedByUserId
        WHERE d.id = ?
    `,
        [datasetId]
    )

    if (!dataset) throw new JsonError(`No dataset by id '${datasetId}'`, 404)

    const zipFile = await db.mysqlFirst(
        `SELECT filename FROM dataset_files WHERE datasetId=?`,
        [datasetId]
    )
    if (zipFile) dataset.zipFile = zipFile

    const variables = await db.queryMysql(
        `
        SELECT v.id, v.name, v.description, v.display
        FROM variables AS v
        WHERE v.datasetId = ?
    `,
        [datasetId]
    )

    for (const v of variables) {
        v.display = JSON.parse(v.display)
    }

    dataset.variables = variables

    // Currently for backwards compatibility datasets can still have multiple sources
    // but the UI presents only a single item of source metadata, we use the first source
    const sources = await db.queryMysql(
        `
        SELECT s.id, s.name, s.description
        FROM sources AS s
        WHERE s.datasetId = ?
        ORDER BY s.id ASC
    `,
        [datasetId]
    )

    dataset.source = JSON.parse(sources[0].description)
    dataset.source.id = sources[0].id
    dataset.source.name = sources[0].name

    const charts = await db.queryMysql(
        `
        SELECT ${OldChart.listFields}
        FROM charts
        JOIN chart_dimensions AS cd ON cd.chartId = charts.id
        JOIN variables AS v ON cd.variableId = v.id
        JOIN users lastEditedByUser ON lastEditedByUser.id = charts.lastEditedByUserId
        LEFT JOIN users publishedByUser ON publishedByUser.id = charts.publishedByUserId
        WHERE v.datasetId = ?
        GROUP BY charts.id
    `,
        [datasetId]
    )

    dataset.charts = charts

    await Chart.assignTagsForCharts(charts)

    const tags = await db.queryMysql(
        `
        SELECT t.id, t.name
        FROM tags t
        JOIN dataset_tags dt ON dt.tagId = t.id
        WHERE dt.datasetId = ?
    `,
        [datasetId]
    )
    dataset.tags = tags
 
    const availableTags = await db.queryMysql(`
        SELECT t.id, t.name, p.name AS parentName
        FROM tags AS t
        JOIN tags AS p ON t.parentId=p.id
        WHERE p.isBulkImport IS FALSE
    `)
    dataset.availableTags = availableTags
 
    return { dataset: dataset }
})
 
apiRouter.put("/datasets/:datasetId", async (req: Request, res: Response) => {
    const datasetId = expectInt(req.params.datasetId)
    const dataset = await Dataset.findOne({ id: datasetId })
    if (!dataset) throw new JsonError(`No dataset by id ${datasetId}`, 404)
 
    await db.transaction(async (t) => {
        const newDataset = (req.body as { dataset: any }).dataset
        await t.execute(
            `
            UPDATE datasets
            SET
                name=?,
                description=?,
                isPrivate=?,
                nonRedistributable=?,
                metadataEditedAt=?,
                metadataEditedByUserId=?
            WHERE id=?
            `,
            [
                newDataset.name,
                newDataset.description || "",
                newDataset.isPrivate,
                newDataset.nonRedistributable,
                new Date(),
                res.locals.user.id,
                datasetId,
            ]
        )
 
        const tagRows = newDataset.tags.map((tag: any) => [tag.id, datasetId])
        await t.execute(`DELETE FROM dataset_tags WHERE datasetId=?`, [
            datasetId,
        ])
        if (tagRows.length)
            await t.execute(
                `INSERT INTO dataset_tags (tagId, datasetId) VALUES ?`,
                [tagRows]
            )
 
        const source = newDataset.source
        const description = lodash.omit(source, ["name", "id"])
        await t.execute(`UPDATE sources SET name=?, description=? WHERE id=?`, [
            source.name,
            JSON.stringify(description),
            source.id,
        ])
    })
 
    // Note: not currently in transaction
    try {
        await syncDatasetToGitRepo(datasetId, {
            oldDatasetName: dataset.name,
            commitName: res.locals.user.fullName,
            commitEmail: res.locals.user.email,
        })
    } catch (err) {
        logErrorAndMaybeSendToSlack(err)
        // Continue
    }
 
    return { success: true }
})
 
apiRouter.post(
    "/datasets/:datasetId/setTags",
    async (req: Request, res: Response) => {
        const datasetId = expectInt(req.params.datasetId)
 
        await Dataset.setTags(datasetId, req.body.tagIds)
 
        return { success: true }
    }
)
 
apiRouter.router.put(
    "/datasets/:datasetId/uploadZip",
    bodyParser.raw({ type: "application/zip", limit: "50mb" }),
    async (req: Request, res: Response) => {
        const datasetId = expectInt(req.params.datasetId)
 
        await db.transaction(async (t) => {
            await t.execute(`DELETE FROM dataset_files WHERE datasetId=?`, [
                datasetId,
            ])
            await t.execute(
                `INSERT INTO dataset_files (datasetId, filename, file) VALUES (?, ?, ?)`,
                [datasetId, "additional-material.zip", req.body]
            )
        })
 
        res.send({ success: true })
    }
)
 
apiRouter.delete(
    "/datasets/:datasetId",
    async (req: Request, res: Response) => {
        const datasetId = expectInt(req.params.datasetId)
 
        const dataset = await Dataset.findOne({ id: datasetId })
        if (!dataset) throw new JsonError(`No dataset by id ${datasetId}`, 404)
 
        await db.transaction(async (t) => {
            await t.execute(
                `DELETE d FROM data_values AS d JOIN variables AS v ON d.variableId=v.id WHERE v.datasetId=?`,
                [datasetId]
            )
            await t.execute(
                `DELETE d FROM country_latest_data AS d JOIN variables AS v ON d.variable_id=v.id WHERE v.datasetId=?`,
                [datasetId]
            )
            await t.execute(`DELETE FROM dataset_files WHERE datasetId=?`, [
                datasetId,
            ])
            await t.execute(`DELETE FROM variables WHERE datasetId=?`, [
                datasetId,
            ])
            await t.execute(`DELETE FROM sources WHERE datasetId=?`, [
                datasetId,
            ])
            await t.execute(`DELETE FROM datasets WHERE id=?`, [datasetId])
        })
 
        try {
            await removeDatasetFromGitRepo(dataset.name, dataset.namespace, {
                commitName: res.locals.user.fullName,
                commitEmail: res.locals.user.email,
            })
        } catch (err) {
            logErrorAndMaybeSendToSlack(err)
            // Continue
        }
 
        return { success: true }
    }
)
 
apiRouter.post(
    "/datasets/:datasetId/charts",
    async (req: Request, res: Response) => {
        const datasetId = expectInt(req.params.datasetId)
 
        const dataset = await Dataset.findOne({ id: datasetId })
        if (!dataset) throw new JsonError(`No dataset by id ${datasetId}`, 404)
 
        if (req.body.republish) {
            await db.transaction(async (t) => {
                await t.execute(
                    `
            UPDATE charts
            SET config = JSON_SET(config, "$.version", config->"$.version" + 1)
            WHERE id IN (
                SELECT DISTINCT chart_dimensions.chartId
                FROM chart_dimensions
                JOIN variables ON variables.id = chart_dimensions.variableId
                WHERE variables.datasetId = ?
            )
            `,
                    [datasetId]
                )
            })
        }
 
        await triggerStaticBuild(
            res.locals.user,
            `Republishing all charts in dataset ${dataset.name} (${dataset.id})`
        )
 
        return { success: true }
    }
)
 
// Get a list of redirects that map old slugs to charts
apiRouter.get("/redirects.json", async (req: Request, res: Response) => ({
    redirects: await db.queryMysql(`
        SELECT r.id, r.slug, r.chart_id as chartId, JSON_UNQUOTE(JSON_EXTRACT(charts.config, "$.slug")) AS chartSlug
        FROM chart_slug_redirects AS r JOIN charts ON charts.id = r.chart_id
        ORDER BY r.id DESC`),
}))
 
apiRouter.get("/tags/:tagId.json", async (req: Request, res: Response) => {
    const tagId = expectInt(req.params.tagId) as number | null
 
    // NOTE (Mispy): The "uncategorized" tag is special -- it represents all untagged stuff
    // Bit fiddly to handle here but more true to normalized schema than having to remember to add the special tag
    // every time we create a new chart etcs
    const uncategorized = tagId === UNCATEGORIZED_TAG_ID
 
    const tag = await db.mysqlFirst(
        `
        SELECT t.id, t.name, t.specialType, t.updatedAt, t.parentId, p.isBulkImport
        FROM tags t LEFT JOIN tags p ON t.parentId=p.id
        WHERE t.id = ?
    `,
        [tagId]
    )
 
    // Datasets tagged with this tag
    const datasets = await db.queryMysql(
        `
        SELECT
            d.id,
            d.namespace,
            d.name,
            d.description,
            d.createdAt,
            d.updatedAt,
            d.dataEditedAt,
            du.fullName AS dataEditedByUserName,
            d.isPrivate,
            d.nonRedistributable
        FROM datasets d
        JOIN users du ON du.id=d.dataEditedByUserId
        LEFT JOIN dataset_tags dt ON dt.datasetId = d.id
        WHERE dt.tagId ${uncategorized ? "IS NULL" : "= ?"}
        ORDER BY d.dataEditedAt DESC
    `,
        uncategorized ? [] : [tagId]
    )
    tag.datasets = datasets
 
    // The other tags for those datasets
    if (tag.datasets.length) {
        if (uncategorized) {
            for (const dataset of tag.datasets) dataset.tags = []
        } else {
            const datasetTags = await db.queryMysql(
                `
                SELECT dt.datasetId, t.id, t.name FROM dataset_tags dt
                JOIN tags t ON dt.tagId = t.id
                WHERE dt.datasetId IN (?)
            `,
                [tag.datasets.map((d: any) => d.id)]
            )
            const tagsByDatasetId = lodash.groupBy(
                datasetTags,
                (t) => t.datasetId
            )
            for (const dataset of tag.datasets) {
                dataset.tags = tagsByDatasetId[dataset.id].map((t) =>
                    lodash.omit(t, "datasetId")
                )
            }
        }
    }
 
    // Charts using datasets under this tag
    const charts = await db.queryMysql(
        `
        SELECT ${OldChart.listFields} FROM charts
        LEFT JOIN chart_tags ct ON ct.chartId=charts.id
        JOIN users lastEditedByUser ON lastEditedByUser.id = charts.lastEditedByUserId
        LEFT JOIN users publishedByUser ON publishedByUser.id = charts.publishedByUserId
        WHERE ct.tagId ${tagId === UNCATEGORIZED_TAG_ID ? "IS NULL" : "= ?"}
        GROUP BY charts.id
        ORDER BY charts.updatedAt DESC
    `,
        uncategorized ? [] : [tagId]
    )
    tag.charts = charts
 
    await Chart.assignTagsForCharts(charts)
 
    // Subcategories
    const children = await db.queryMysql(
        `
        SELECT t.id, t.name FROM tags t
        WHERE t.parentId = ?
    `,
        [tag.id]
    )
    tag.children = children
 
    // Possible parents to choose from
    const possibleParents = await db.queryMysql(`
        SELECT t.id, t.name FROM tags t
        WHERE t.parentId IS NULL AND t.isBulkImport IS FALSE
    `)
    tag.possibleParents = possibleParents
 
    return {
        tag,
    }
})
 
apiRouter.put("/tags/:tagId", async (req: Request) => {
    const tagId = expectInt(req.params.tagId)
    const tag = (req.body as { tag: any }).tag
    await db.execute(
        `UPDATE tags SET name=?, updatedAt=?, parentId=? WHERE id=?`,
        [tag.name, new Date(), tag.parentId, tagId]
    )
    return { success: true }
})
 
apiRouter.post("/tags/new", async (req: Request) => {
    const tag = (req.body as { tag: any }).tag
    const now = new Date()
    const result = await db.execute(
        `INSERT INTO tags (parentId, name, createdAt, updatedAt) VALUES (?, ?, ?, ?)`,
        [tag.parentId, tag.name, now, now]
    )
    return { success: true, tagId: result.insertId }
})
 
apiRouter.get("/tags.json", async (req: Request, res: Response) => {
    const tags = await db.queryMysql(`
        SELECT t.id, t.name, t.parentId, t.specialType
        FROM tags t LEFT JOIN tags p ON t.parentId=p.id
        WHERE t.isBulkImport IS FALSE AND (t.parentId IS NULL OR p.isBulkImport IS FALSE)
        ORDER BY t.name ASC
    `)
 
    return {
        tags,
    }
})
 
apiRouter.delete("/tags/:tagId/delete", async (req: Request, res: Response) => {
    const tagId = expectInt(req.params.tagId)
 
    await db.transaction(async (t) => {
        await t.execute(`DELETE FROM tags WHERE id=?`, [tagId])
    })
 
    return { success: true }
})
 
apiRouter.post("/charts/:chartId/redirects/new", async (req: Request) => {
    const chartId = expectInt(req.params.chartId)
    const fields = req.body as { slug: string }
    const result = await db.execute(
        `INSERT INTO chart_slug_redirects (chart_id, slug) VALUES (?, ?)`,
        [chartId, fields.slug]
    )
    const redirectId = result.insertId
    const redirect = await db.mysqlFirst(
        `SELECT * FROM chart_slug_redirects WHERE id = ?`,
        [redirectId]
    )
    return { success: true, redirect: redirect }
})
 
apiRouter.delete("/redirects/:id", async (req: Request, res: Response) => {
    const id = expectInt(req.params.id)
 
    const redirect = await db.mysqlFirst(
        `SELECT * FROM chart_slug_redirects WHERE id = ?`,
        [id]
    )
 
    if (!redirect) throw new JsonError(`No redirect found for id ${id}`, 404)
 
    await db.execute(`DELETE FROM chart_slug_redirects WHERE id=?`, [id])
    await triggerStaticBuild(
        res.locals.user,
        `Deleting redirect from ${redirect.slug}`
    )
 
    return { success: true }
})
 
apiRouter.get("/posts.json", async (req) => {
    const rows = await Post.select(
        "id",
        "title",
        "type",
        "status",
        "updated_at"
    ).from(db.knexInstance().from(Post.table).orderBy("updated_at", "desc"))
 
    const tagsByPostId = await Post.tagsByPostId()
 
    const authorship = await wpdb.getAuthorship()
 
    for (const post of rows) {
        const postAsAny = post as any
        postAsAny.authors = authorship.get(post.id) || []
        postAsAny.tags = tagsByPostId.get(post.id) || []
    }
 
    return { posts: rows.map((r) => camelCaseProperties(r)) }
})
 
apiRouter.get("/newsletterPosts.json", async (req) => {
    const rows = await wpdb.singleton.query(`
        SELECT
            ID AS id,
            post_name AS name,
            post_title AS title,
            post_modified_gmt AS updatedAt,
            post_date_gmt AS publishedAt,
            post_type AS type,
            post_status AS status,
            post_excerpt AS excerpt
        FROM wp_posts
        WHERE (post_type='post' OR post_type='page') AND post_status='publish'
        ORDER BY post_date_gmt DESC`)
 
    const permalinks = await wpdb.getPermalinks()
    const featuresImages = await wpdb.getFeaturedImages()
 
    const posts = rows.map((row) => {
        const slug = permalinks.get(row.id, row.name)
        return {
            id: row.id,
            title: row.title,
            updatedAt: row.updatedAt,
            publishedAt: row.publishedAt,
            type: row.type,
            status: row.status,
            excerpt: row.excerpt,
            slug: slug,
            imageUrl: featuresImages.get(row.id),
            url: `${BAKED_BASE_URL}/${slug}`,
        }
    })
 
    return { posts }
})
 
apiRouter.post(
    "/posts/:postId/setTags",
    async (req: Request, res: Response) => {
        const postId = expectInt(req.params.postId)
 
        await Post.setTags(postId, req.body.tagIds)
 
        return { success: true }
    }
)
 
apiRouter.get("/posts/:postId.json", async (req: Request, res: Response) => {
    const postId = expectInt(req.params.postId)
    const post = (await db
        .knexTable(Post.table)
        .where({ id: postId })
        .select("*")
        .first()) as PostRow | undefined
    return camelCaseProperties(post)
})
 
apiRouter.get("/importData.json", async (req) => {
    // Get all datasets from the importable namespace to match against
    const datasets = await db.queryMysql(
        `SELECT id, name FROM datasets WHERE namespace='owid' ORDER BY name ASC`
    )
 
    // Get a unique list of all entities in the database (probably this won't scale indefinitely)
    const existingEntities = (
        await db.queryMysql(`SELECT name FROM entities`)
    ).map((e: any) => e.name)
 
    return { datasets, existingEntities }
})
 
apiRouter.get("/importData/datasets/:datasetId.json", async (req) => {
    const datasetId = expectInt(req.params.datasetId)
 
    const dataset = await db.mysqlFirst(
        `
        SELECT d.id, d.namespace, d.name, d.description, d.updatedAt
        FROM datasets AS d
        WHERE d.id = ?
    `,
        [datasetId]
    )
 
    if (!dataset) throw new JsonError(`No dataset by id '${datasetId}'`, 404)
 
    const variables = await db.queryMysql(
        `
        SELECT v.id, v.name
        FROM variables AS v
        WHERE v.datasetId = ?
    `,
        [datasetId]
    )
 
    dataset.variables = variables
 
    return { dataset }
})
 
interface ImportPostData {
    dataset: {
        id?: number
        name: string
    }
    entities: string[]
    years: number[]
    variables: {
        name: string
        overwriteId?: number
        values: string[]
    }[]
}
 
apiRouter.post("/importDataset", async (req: Request, res: Response) => {
    const userId = res.locals.user.id
    const { dataset, entities, years, variables } = req.body as ImportPostData
 
    const newDatasetId = await db.transaction(async (t) => {
        const now = new Date()
 
        let datasetId: number
 
        if (dataset.id) {
            // Updating existing dataset
            datasetId = dataset.id
            await t.execute(
                `UPDATE datasets SET dataEditedAt=?, dataEditedByUserId=? WHERE id=?`,
                [now, userId, datasetId]
            )
        } else {
            // Creating new dataset
            const row = [
                dataset.name,
                "owid",
                "",
                now,
                now,
                now,
                userId,
                now,
                userId,
                userId,
                true,
            ]
            const datasetResult = await t.execute(
                `INSERT INTO datasets (name, namespace, description, createdAt, updatedAt, dataEditedAt, dataEditedByUserId, metadataEditedAt, metadataEditedByUserId, createdByUserId, isPrivate) VALUES (?)`,
                [row]
            )
            datasetId = datasetResult.insertId
        }
 
        // Find or create the dataset source
        // TODO probably merge source info into dataset table
        let sourceId: number | undefined
        if (datasetId) {
            // Use first source (if any)
            const rows = await t.query(
                `SELECT id FROM sources WHERE datasetId=? ORDER BY id ASC LIMIT 1`,
                [datasetId]
            )
            if (rows[0]) sourceId = rows[0].id
        }
 
        if (!sourceId) {
            // Insert default source
            const sourceRow = [dataset.name, "{}", now, now, datasetId]
            const sourceResult = await t.execute(
                `INSERT INTO sources (name, description, createdAt, updatedAt, datasetId) VALUES (?)`,
                [sourceRow]
            )
            sourceId = sourceResult.insertId
        }
 
        // Insert any new entities into the db
        const entitiesUniq = lodash.uniq(entities)
        const importEntityRows = entitiesUniq.map((e) => [
            e,
            false,
            now,
            now,
            "",
        ])
        await t.execute(
            `INSERT IGNORE entities (name, validated, createdAt, updatedAt, displayName) VALUES ?`,
            [importEntityRows]
        )
 
        // Map entities to entityIds
        const entityRows = await t.query(
            `SELECT id, name FROM entities WHERE name IN (?)`,
            [entitiesUniq]
        )
        const entityIdLookup: { [key: string]: number } = {}
        console.log(
            lodash.difference(lodash.keys(entityIdLookup), entitiesUniq)
        )
        for (const row of entityRows) {
            entityIdLookup[row.name] = row.id
        }
 
        // Remove all existing variables not matched by overwriteId
        const existingVariables = await t.query(
            `SELECT id FROM variables v WHERE v.datasetId=?`,
            [datasetId]
        )
        const removingVariables = existingVariables.filter(
            (v: any) => !variables.some((v2) => v2.overwriteId === v.id)
        )
        const removingVariableIds = removingVariables.map(
            (v: any) => v.id
        ) as number[]
        if (removingVariableIds.length) {
            await t.execute(`DELETE FROM data_values WHERE variableId IN (?)`, [
                removingVariableIds,
            ])
            await t.execute(`DELETE FROM variables WHERE id IN (?)`, [
                removingVariableIds,
            ])
        }
 
        // Overwrite old variables and insert new variables
        for (const variable of variables) {
            let variableId: number
            if (variable.overwriteId) {
                // Remove any existing data values
                await t.execute(`DELETE FROM data_values WHERE variableId=?`, [
                    variable.overwriteId,
                ])
 
                variableId = variable.overwriteId
            } else {
                const variableRow = [
                    variable.name,
                    datasetId,
                    sourceId,
                    now,
                    now,
                    "",
                    "",
                    "",
                    "{}",
                ]
 
                // Create a new variable
                // TODO migrate to clean up these fields
                const result = await t.execute(
                    `INSERT INTO variables (name, datasetId, sourceId, createdAt, updatedAt, unit, coverage, timespan, display) VALUES (?)`,
                    [variableRow]
                )
                variableId = result.insertId
            }
 
            const valueRows = []
            for (let i = 0; i < variable.values.length; i++) {
                const value = variable.values[i]
                if (value !== "") {
                    valueRows.push([
                        value,
                        years[i],
                        entityIdLookup[entities[i]],
                        variableId,
                    ])
                }
            }
 
            if (valueRows.length) {
                await t.execute(
                    `INSERT INTO data_values (value, year, entityId, variableId) VALUES ?`,
                    [valueRows]
                )
            }
        }
 
        return datasetId
    })
 
    // Don't sync to git repo on import-- dataset is initially private
    //await syncDatasetToGitRepo(newDatasetId, { oldDatasetName: oldDatasetName, commitName: res.locals.user.fullName, commitEmail: res.locals.user.email })
 
    return { success: true, datasetId: newDatasetId }
})
 
apiRouter.get("/sources/:sourceId.json", async (req: Request) => {
    const sourceId = expectInt(req.params.sourceId)
    const source = await db.mysqlFirst(
        `
        SELECT s.id, s.name, s.description, s.createdAt, s.updatedAt, d.namespace
        FROM sources AS s
        JOIN datasets AS d ON d.id=s.datasetId
        WHERE s.id=?`,
        [sourceId]
    )
    source.description = JSON.parse(source.description)
    source.variables = await db.queryMysql(
        `SELECT id, name, updatedAt FROM variables WHERE variables.sourceId=?`,
        [sourceId]
    )
 
    return { source: source }
})
 
apiRouter.get("/deploys.json", async () => ({
    deploys: await new DeployQueueServer().getDeploys(),
}))
 
export { apiRouter }