@ozguraltan/strapi-content-input 1.0.22 → 1.0.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/README.md +14 -9
  2. package/dist/admin/{AnalyticsHubPage-B1_chQkG.js → AnalyticsHubPage-ByOrVZCl.js} +555 -59
  3. package/dist/admin/{AnalyticsHubPage-DUj3D2kA.mjs → AnalyticsHubPage-O-7pF2E5.mjs} +537 -59
  4. package/dist/admin/{ContentInputField-BrtpTCDd.mjs → ContentInputField-BoZHf0Ka.mjs} +6 -236
  5. package/dist/admin/{ContentInputField-CQFQxxgm.js → ContentInputField-DK97AIG0.js} +22 -252
  6. package/dist/admin/{SurveyWidgetEditor-C5Uvyf_h.js → SurveyWidgetEditor-D3KiAotu.js} +6133 -514
  7. package/dist/admin/{SurveyWidgetEditor-DGSwgTzR.mjs → SurveyWidgetEditor-Y5BR-NWE.mjs} +6157 -539
  8. package/dist/admin/{index-Dc7AFLOj.mjs → index-C5Uj5YV9.mjs} +2 -2
  9. package/dist/admin/{index-i0NfSYto.js → index-CHtB_Fa5.js} +2 -2
  10. package/dist/admin/index.js +1 -1
  11. package/dist/admin/index.mjs +1 -1
  12. package/dist/admin/src/components/widgets/SurveyLivePreviewPane.d.ts +9 -0
  13. package/dist/admin/src/components/widgets/SurveyTransferCleanupModal.d.ts +35 -0
  14. package/dist/admin/src/components/widgets/SurveyWidgetEditor.d.ts +3 -1
  15. package/dist/admin/src/components/widgets/surveyStepTreeOps.d.ts +54 -0
  16. package/dist/server/index.js +796 -32
  17. package/dist/server/index.mjs +778 -32
  18. package/dist/server/src/controllers/ci-survey.d.ts +4 -0
  19. package/dist/server/src/controllers/index.d.ts +4 -0
  20. package/dist/server/src/index.d.ts +56 -2
  21. package/dist/server/src/services/ci-form.d.ts +5 -1
  22. package/dist/server/src/services/ci-survey.d.ts +47 -1
  23. package/dist/server/src/services/index.d.ts +52 -2
  24. package/dist/server/src/utils/demoSeedState.d.ts +14 -0
  25. package/dist/server/src/utils/surveyEngine.d.ts +5 -0
  26. package/package.json +1 -1
@@ -5,11 +5,30 @@ const fs = require("fs");
5
5
  const module$1 = require("module");
6
6
  const os = require("os");
7
7
  const path = require("path");
8
+ const XLSXNs = require("xlsx");
8
9
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
10
+ function _interopNamespace(e) {
11
+ if (e && e.__esModule) return e;
12
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
13
+ if (e) {
14
+ for (const k in e) {
15
+ if (k !== "default") {
16
+ const d = Object.getOwnPropertyDescriptor(e, k);
17
+ Object.defineProperty(n, k, d.get ? d : {
18
+ enumerable: true,
19
+ get: () => e[k]
20
+ });
21
+ }
22
+ }
23
+ }
24
+ n.default = e;
25
+ return Object.freeze(n);
26
+ }
9
27
  const crypto__default = /* @__PURE__ */ _interopDefault(crypto);
10
28
  const fs__default = /* @__PURE__ */ _interopDefault(fs);
11
29
  const os__default = /* @__PURE__ */ _interopDefault(os);
12
30
  const path__default = /* @__PURE__ */ _interopDefault(path);
31
+ const XLSXNs__namespace = /* @__PURE__ */ _interopNamespace(XLSXNs);
13
32
  const register = ({ strapi }) => {
14
33
  strapi.customFields.register({
15
34
  name: "content-input",
@@ -1915,18 +1934,31 @@ const ciSurveyController = ({ strapi }) => ({
1915
1934
  async exportResponses(ctx) {
1916
1935
  try {
1917
1936
  const { id } = ctx.params;
1918
- const format = String(ctx.query?.format || "csv").toLowerCase() === "json" ? "json" : "csv";
1937
+ const rawFmt = String(ctx.query?.format || "xlsx").toLowerCase();
1938
+ const format = rawFmt === "json" ? "json" : rawFmt === "csv" ? "csv" : "xlsx";
1919
1939
  const locale = String(ctx.query?.locale || "en").trim();
1920
1940
  const from = ctx.query?.from ? String(ctx.query.from) : void 0;
1921
1941
  const to = ctx.query?.to ? String(ctx.query.to) : void 0;
1942
+ const encoding = String(ctx.query?.encoding || "").toLowerCase();
1922
1943
  const exported = await strapi.plugin("content-input").service("ci-survey").exportResponses(id, { format, locale, from, to });
1923
1944
  if (!exported) {
1924
1945
  return ctx.notFound("Survey not found");
1925
1946
  }
1947
+ if (encoding === "base64") {
1948
+ const buf = Buffer.isBuffer(exported.body) ? exported.body : Buffer.from(String(exported.body), "utf8");
1949
+ ctx.status = 200;
1950
+ ctx.body = {
1951
+ filename: exported.filename,
1952
+ contentType: exported.contentType,
1953
+ base64: buf.toString("base64")
1954
+ };
1955
+ return;
1956
+ }
1957
+ ctx.body = exported.body;
1958
+ ctx.type = exported.contentType;
1926
1959
  ctx.set("Content-Type", exported.contentType);
1927
1960
  ctx.set("Content-Disposition", `attachment; filename="${exported.filename}"`);
1928
1961
  ctx.status = 200;
1929
- ctx.body = exported.body;
1930
1962
  } catch (err) {
1931
1963
  ctx.throw(500, err);
1932
1964
  }
@@ -1938,6 +1970,79 @@ const ciSurveyController = ({ strapi }) => ({
1938
1970
  } catch (err) {
1939
1971
  ctx.throw(500, err);
1940
1972
  }
1973
+ },
1974
+ async purgeDemo(ctx) {
1975
+ try {
1976
+ const res = await strapi.plugin("content-input").service("ci-survey").purgeDemoData();
1977
+ ctx.status = 200;
1978
+ ctx.body = res;
1979
+ } catch (err) {
1980
+ ctx.throw(500, err);
1981
+ }
1982
+ },
1983
+ async clearResponses(ctx) {
1984
+ try {
1985
+ const { id } = ctx.params;
1986
+ const res = await strapi.plugin("content-input").service("ci-survey").clearResponses(id);
1987
+ if (!res) {
1988
+ return ctx.notFound("Survey not found");
1989
+ }
1990
+ ctx.status = 200;
1991
+ ctx.body = res;
1992
+ } catch (err) {
1993
+ ctx.throw(500, err);
1994
+ }
1995
+ },
1996
+ async exportBundle(ctx) {
1997
+ try {
1998
+ const target = String(ctx.query?.target || "all").trim();
1999
+ const rawMode = String(ctx.query?.mode || "structure").trim().toLowerCase();
2000
+ const mode = rawMode === "full" ? "full" : "structure";
2001
+ const directDownload = String(ctx.query?.download || "") === "1";
2002
+ const exported = await strapi.plugin("content-input").service("ci-survey").exportBundle(target, mode);
2003
+ if (!exported) {
2004
+ return ctx.notFound("Survey not found");
2005
+ }
2006
+ if (directDownload) {
2007
+ ctx.body = JSON.stringify(exported.bundle, null, 2);
2008
+ ctx.type = exported.contentType;
2009
+ ctx.set("Content-Type", exported.contentType);
2010
+ ctx.set("Content-Disposition", `attachment; filename="${exported.filename}"`);
2011
+ ctx.status = 200;
2012
+ return;
2013
+ }
2014
+ ctx.status = 200;
2015
+ ctx.body = {
2016
+ filename: exported.filename,
2017
+ bundle: exported.bundle
2018
+ };
2019
+ } catch (err) {
2020
+ ctx.throw(500, err);
2021
+ }
2022
+ },
2023
+ async importBundle(ctx) {
2024
+ try {
2025
+ const rawBody = ctx.request.body || {};
2026
+ const hasEnvelope = rawBody && typeof rawBody === "object" && !Array.isArray(rawBody) && rawBody.bundle !== void 0;
2027
+ const bundlePayload = hasEnvelope ? rawBody.bundle : rawBody;
2028
+ const rawStrategy = String(
2029
+ (hasEnvelope ? rawBody.conflictStrategy : ctx.query?.conflictStrategy) || "duplicate"
2030
+ ).trim().toLowerCase();
2031
+ const conflictStrategy = rawStrategy === "overwrite" ? "overwrite" : "duplicate";
2032
+ const rawInclude = hasEnvelope ? rawBody.includeResponses : ctx.query?.includeResponses;
2033
+ const includeResponses = rawInclude === void 0 ? true : rawInclude !== false && String(rawInclude).toLowerCase() !== "false";
2034
+ const res = await strapi.plugin("content-input").service("ci-survey").importBundle(bundlePayload, {
2035
+ conflictStrategy,
2036
+ includeResponses
2037
+ });
2038
+ ctx.status = 200;
2039
+ ctx.body = res;
2040
+ } catch (err) {
2041
+ if (err?.status === 400) {
2042
+ return ctx.badRequest(err.message || "Invalid survey bundle");
2043
+ }
2044
+ ctx.throw(500, err);
2045
+ }
1941
2046
  }
1942
2047
  });
1943
2048
  const ciColorController = ({ strapi }) => ({
@@ -2251,6 +2356,46 @@ const routes = {
2251
2356
  policies: []
2252
2357
  }
2253
2358
  },
2359
+ {
2360
+ method: "POST",
2361
+ path: "/surveys/purge-demo",
2362
+ handler: "ci-survey.purgeDemo",
2363
+ config: {
2364
+ policies: []
2365
+ }
2366
+ },
2367
+ {
2368
+ method: "GET",
2369
+ path: "/survey-bundle/export",
2370
+ handler: "ci-survey.exportBundle",
2371
+ config: {
2372
+ policies: []
2373
+ }
2374
+ },
2375
+ {
2376
+ method: "POST",
2377
+ path: "/survey-bundle/import",
2378
+ handler: "ci-survey.importBundle",
2379
+ config: {
2380
+ policies: []
2381
+ }
2382
+ },
2383
+ {
2384
+ method: "GET",
2385
+ path: "/surveys/bundle/export",
2386
+ handler: "ci-survey.exportBundle",
2387
+ config: {
2388
+ policies: []
2389
+ }
2390
+ },
2391
+ {
2392
+ method: "POST",
2393
+ path: "/surveys/bundle/import",
2394
+ handler: "ci-survey.importBundle",
2395
+ config: {
2396
+ policies: []
2397
+ }
2398
+ },
2254
2399
  {
2255
2400
  method: "POST",
2256
2401
  path: "/surveys",
@@ -2275,6 +2420,14 @@ const routes = {
2275
2420
  policies: []
2276
2421
  }
2277
2422
  },
2423
+ {
2424
+ method: "DELETE",
2425
+ path: "/surveys/:id/responses",
2426
+ handler: "ci-survey.clearResponses",
2427
+ config: {
2428
+ policies: []
2429
+ }
2430
+ },
2278
2431
  {
2279
2432
  method: "GET",
2280
2433
  path: "/surveys/:id/analytics",
@@ -4496,6 +4649,84 @@ function generateSampleFormSubmissions(formEntry) {
4496
4649
  }
4497
4650
  return list;
4498
4651
  }
4652
+ const DEMO_SEED_STORE_KEY = "demo_seed_state";
4653
+ const fallbackStore = /* @__PURE__ */ new WeakMap();
4654
+ function isDemoSeedDisabledByEnv() {
4655
+ const raw = String(process.env.CI_DISABLE_DEMO_SEED || "").trim().toLowerCase();
4656
+ return raw === "true" || raw === "1" || raw === "yes";
4657
+ }
4658
+ function getPluginStore(strapi) {
4659
+ if (strapi && typeof strapi.store === "function") {
4660
+ return strapi.store({
4661
+ type: "plugin",
4662
+ name: "content-input"
4663
+ });
4664
+ }
4665
+ return null;
4666
+ }
4667
+ async function getDemoSeedState(strapi) {
4668
+ const disabledByEnv = isDemoSeedDisabledByEnv();
4669
+ let stored = null;
4670
+ try {
4671
+ const store = getPluginStore(strapi);
4672
+ if (store && typeof store.get === "function") {
4673
+ const val = await store.get({ key: DEMO_SEED_STORE_KEY });
4674
+ if (val && typeof val === "object") {
4675
+ stored = val;
4676
+ }
4677
+ } else if (strapi && typeof strapi === "object") {
4678
+ stored = fallbackStore.get(strapi) || null;
4679
+ }
4680
+ } catch {
4681
+ if (strapi && typeof strapi === "object") {
4682
+ stored = fallbackStore.get(strapi) || null;
4683
+ }
4684
+ }
4685
+ return {
4686
+ cleared: Boolean(stored?.cleared),
4687
+ surveysInitialized: Boolean(stored?.surveysInitialized),
4688
+ formsInitialized: Boolean(stored?.formsInitialized),
4689
+ updatedAt: stored?.updatedAt || "",
4690
+ disabledByEnv
4691
+ };
4692
+ }
4693
+ async function updateDemoSeedState(strapi, patch) {
4694
+ const current = await getDemoSeedState(strapi);
4695
+ const next = {
4696
+ cleared: patch.cleared !== void 0 ? Boolean(patch.cleared) : current.cleared,
4697
+ surveysInitialized: patch.surveysInitialized !== void 0 ? Boolean(patch.surveysInitialized) : Boolean(current.surveysInitialized),
4698
+ formsInitialized: patch.formsInitialized !== void 0 ? Boolean(patch.formsInitialized) : Boolean(current.formsInitialized),
4699
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
4700
+ };
4701
+ if (strapi && typeof strapi === "object") {
4702
+ fallbackStore.set(strapi, next);
4703
+ }
4704
+ try {
4705
+ const store = getPluginStore(strapi);
4706
+ if (store && typeof store.set === "function") {
4707
+ await store.set({
4708
+ key: DEMO_SEED_STORE_KEY,
4709
+ value: next
4710
+ });
4711
+ }
4712
+ } catch {
4713
+ }
4714
+ return next;
4715
+ }
4716
+ async function isDemoSeedBlocked(strapi, domain) {
4717
+ const state = await getDemoSeedState(strapi);
4718
+ if (state.disabledByEnv || state.cleared) return true;
4719
+ if (domain === "surveys" && state.surveysInitialized) return true;
4720
+ if (domain === "forms" && state.formsInitialized) return true;
4721
+ return false;
4722
+ }
4723
+ async function setDemoSeedCleared(strapi, cleared) {
4724
+ return updateDemoSeedState(strapi, {
4725
+ cleared,
4726
+ surveysInitialized: true,
4727
+ formsInitialized: true
4728
+ });
4729
+ }
4499
4730
  const FORM_UID = "plugin::content-input.ci-form";
4500
4731
  const SUBMISSION_UID = "plugin::content-input.ci-form-submission";
4501
4732
  function slugifyIdentifier$1(text) {
@@ -4824,11 +5055,20 @@ const ciFormService = ({ strapi }) => ({
4824
5055
  },
4825
5056
  async ensureSampleSubmissions(force = false) {
4826
5057
  try {
5058
+ if (!force && await isDemoSeedBlocked(strapi, "forms")) {
5059
+ return;
5060
+ }
4827
5061
  const subCount = await strapi.db.query(SUBMISSION_UID).count();
4828
5062
  if (subCount > 0 && !force) return;
4829
- const showcaseForm = await strapi.db.query(FORM_UID).findOne({
5063
+ let showcaseForm = await strapi.db.query(FORM_UID).findOne({
4830
5064
  where: { slug: "showcase_contact_form" }
4831
5065
  });
5066
+ if (!showcaseForm && force) {
5067
+ const seedDef = DEFAULT_SEED_FORMS.find((s) => s.slug === "showcase_contact_form");
5068
+ if (seedDef) {
5069
+ showcaseForm = await strapi.db.query(FORM_UID).create({ data: seedDef });
5070
+ }
5071
+ }
4832
5072
  if (!showcaseForm) return;
4833
5073
  if (force) {
4834
5074
  await strapi.db.query(SUBMISSION_UID).deleteMany({
@@ -4842,16 +5082,24 @@ const ciFormService = ({ strapi }) => ({
4842
5082
  } catch {
4843
5083
  }
4844
5084
  },
4845
- async ensureSeeded() {
5085
+ async ensureSeeded(force = false) {
5086
+ if (!force && await isDemoSeedBlocked(strapi, "forms")) {
5087
+ return;
5088
+ }
4846
5089
  let count = 0;
4847
5090
  try {
4848
5091
  count = await strapi.db.query(FORM_UID).count();
4849
5092
  } catch {
4850
5093
  return;
4851
5094
  }
4852
- if (count === 0) {
5095
+ if (count === 0 || force) {
4853
5096
  for (const seed of DEFAULT_SEED_FORMS) {
4854
- await strapi.db.query(FORM_UID).create({ data: seed });
5097
+ const existingSeed = await strapi.db.query(FORM_UID).findOne({
5098
+ where: { slug: seed.slug }
5099
+ });
5100
+ if (!existingSeed) {
5101
+ await strapi.db.query(FORM_UID).create({ data: seed });
5102
+ }
4855
5103
  }
4856
5104
  } else {
4857
5105
  try {
@@ -4870,7 +5118,52 @@ const ciFormService = ({ strapi }) => ({
4870
5118
  } catch {
4871
5119
  }
4872
5120
  }
4873
- await this.ensureSampleSubmissions(false);
5121
+ await this.ensureSampleSubmissions(force);
5122
+ await updateDemoSeedState(strapi, { formsInitialized: true });
5123
+ },
5124
+ async purgeDemoForms() {
5125
+ let deletedForms = 0;
5126
+ let deletedFormSubmissions = 0;
5127
+ const demoSlugs = DEFAULT_SEED_FORMS.map((f) => f.slug);
5128
+ for (const slug of demoSlugs) {
5129
+ try {
5130
+ const existingForm = await strapi.db.query(FORM_UID).findOne({
5131
+ where: { slug }
5132
+ });
5133
+ const matchingSubs = await strapi.db.query(SUBMISSION_UID).findMany({
5134
+ where: existingForm ? {
5135
+ $or: [
5136
+ { formSlug: slug },
5137
+ { formId: String(existingForm.documentId || existingForm.id) },
5138
+ { formId: String(existingForm.id) }
5139
+ ]
5140
+ } : { formSlug: slug }
5141
+ }) || [];
5142
+ if (matchingSubs.length > 0) {
5143
+ const subIds = matchingSubs.map((s) => s.id).filter((id) => id !== void 0 && id !== null);
5144
+ if (subIds.length > 0) {
5145
+ await strapi.db.query(SUBMISSION_UID).deleteMany({
5146
+ where: { id: { $in: subIds } }
5147
+ });
5148
+ }
5149
+ await strapi.db.query(SUBMISSION_UID).deleteMany({
5150
+ where: { formSlug: slug }
5151
+ });
5152
+ deletedFormSubmissions += matchingSubs.length;
5153
+ }
5154
+ if (existingForm) {
5155
+ await strapi.db.query(FORM_UID).delete({
5156
+ where: { id: existingForm.id }
5157
+ });
5158
+ deletedForms += 1;
5159
+ }
5160
+ } catch {
5161
+ }
5162
+ }
5163
+ return {
5164
+ deletedForms,
5165
+ deletedFormSubmissions
5166
+ };
4874
5167
  },
4875
5168
  async findRawByIdOrSlug(idOrSlug) {
4876
5169
  await this.ensureSeeded();
@@ -5274,6 +5567,7 @@ const ciFormService = ({ strapi }) => ({
5274
5567
  };
5275
5568
  }
5276
5569
  });
5570
+ const XLSX = XLSXNs__namespace?.utils ? XLSXNs__namespace : XLSXNs__namespace?.default || XLSXNs__namespace;
5277
5571
  function evalSingleRule(rule, answers) {
5278
5572
  const targetVal = answers ? answers[rule.questionKey] : void 0;
5279
5573
  const op = rule.operator;
@@ -5650,6 +5944,7 @@ function computeSurveyAnalytics(survey, rawResponses, filter = {}) {
5650
5944
  }
5651
5945
  const distribution = Object.keys(distMap).map(Number).sort((a, b) => a - b).map((value) => ({
5652
5946
  value,
5947
+ labels: q.scaleLabels ? q.scaleLabels[String(value)] : void 0,
5653
5948
  count: distMap[value] || 0,
5654
5949
  percentage: answeredCount > 0 ? Math.round((distMap[value] || 0) / answeredCount * 1e3) / 10 : 0
5655
5950
  }));
@@ -5660,6 +5955,7 @@ function computeSurveyAnalytics(survey, rawResponses, filter = {}) {
5660
5955
  max: maxVal,
5661
5956
  lowLabel: q.lowLabel,
5662
5957
  highLabel: q.highLabel,
5958
+ scaleLabels: q.scaleLabels,
5663
5959
  average: answeredCount > 0 ? Math.round(sum / answeredCount * 100) / 100 : 0,
5664
5960
  distribution,
5665
5961
  npsBreakdown: q.type === "nps" ? {
@@ -5848,6 +6144,7 @@ function computePublicSurveyResults(survey, rawResponses) {
5848
6144
  optionsBreakdown: qs.optionsBreakdown,
5849
6145
  average: qs.average,
5850
6146
  distribution: qs.distribution,
6147
+ scaleLabels: qs.scaleLabels,
5851
6148
  npsBreakdown: qs.npsBreakdown,
5852
6149
  rankingBreakdown: qs.rankingBreakdown
5853
6150
  }))
@@ -5860,9 +6157,17 @@ function escapeCsvCell(val) {
5860
6157
  }
5861
6158
  return str;
5862
6159
  }
5863
- function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
6160
+ function buildSurveyResponseExportAoA(survey, rawResponses, locale = "en") {
6161
+ const tr = String(locale || "").toLowerCase().startsWith("tr");
5864
6162
  const activeQuestions = (survey.questions || []).filter((q) => q && q.type !== "statement");
5865
- const headers = [
6163
+ const headers = tr ? [
6164
+ "Yanıt ID",
6165
+ "Gönderim Tarihi",
6166
+ "Dil",
6167
+ "Süre (sn)",
6168
+ "NPS Puanı",
6169
+ "NPS Kategorisi"
6170
+ ] : [
5866
6171
  "Response ID",
5867
6172
  "Submitted At",
5868
6173
  "Locale",
@@ -5880,18 +6185,18 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
5880
6185
  } else {
5881
6186
  headers.push(`${qTitle} (${q.key})`);
5882
6187
  if (q.allowOther) {
5883
- headers.push(`${qTitle} [Other Text]`);
6188
+ headers.push(`${qTitle} [${tr ? "Diğer Açıklama" : "Other Text"}]`);
5884
6189
  }
5885
6190
  }
5886
6191
  }
5887
- const lines = [headers.map(escapeCsvCell).join(",")];
6192
+ const rows = [];
5888
6193
  for (const r of rawResponses || []) {
5889
6194
  const rowCells = [
5890
6195
  String(r.id || r.documentId || ""),
5891
6196
  String(r.submittedAt || r.createdAt || ""),
5892
6197
  String(r.locale || ""),
5893
- String(r.durationSeconds ?? ""),
5894
- r.npsValue !== null && r.npsValue !== void 0 ? String(r.npsValue) : "",
6198
+ typeof r.durationSeconds === "number" ? r.durationSeconds : String(r.durationSeconds ?? ""),
6199
+ typeof r.npsValue === "number" ? r.npsValue : r.npsValue !== null && r.npsValue !== void 0 && r.npsValue !== "" ? Number(r.npsValue) : "",
5895
6200
  String(r.npsCategory || "")
5896
6201
  ];
5897
6202
  for (const q of activeQuestions) {
@@ -5908,7 +6213,7 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
5908
6213
  } else if (Array.isArray(q.options) && q.options.length > 0) {
5909
6214
  if (Array.isArray(ans)) {
5910
6215
  const mapped = ans.map((optId) => {
5911
- if (optId === "__other__") return locale === "tr" ? "Diğer" : "Other";
6216
+ if (optId === "__other__") return tr ? "Diğer" : "Other";
5912
6217
  const found = q.options.find((o) => o.id === optId);
5913
6218
  return found ? resolveLocalizedText(found.labels, locale, optId) : optId;
5914
6219
  });
@@ -5916,7 +6221,7 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
5916
6221
  } else if (ans !== void 0 && ans !== null && ans !== "") {
5917
6222
  const strAns = String(ans);
5918
6223
  if (strAns === "__other__") {
5919
- rowCells.push(locale === "tr" ? "Diğer" : "Other");
6224
+ rowCells.push(tr ? "Diğer" : "Other");
5920
6225
  } else {
5921
6226
  const found = q.options.find((o) => o.id === strAns);
5922
6227
  rowCells.push(found ? resolveLocalizedText(found.labels, locale, strAns) : strAns);
@@ -5928,16 +6233,131 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
5928
6233
  rowCells.push(String(r.otherTexts?.[q.key] || ""));
5929
6234
  }
5930
6235
  } else {
5931
- rowCells.push(ans === void 0 || ans === null ? "" : String(ans));
6236
+ if (q.type === "likert_scale" && q.scaleLabels && ans !== void 0 && ans !== null && ans !== "") {
6237
+ const ptLbl = resolveLocalizedText(q.scaleLabels[String(ans)], locale, "");
6238
+ rowCells.push(ptLbl ? `${ans} - ${ptLbl}` : Number.isNaN(Number(ans)) ? String(ans) : Number(ans));
6239
+ } else if ((q.type === "nps" || q.type === "star_rating" || q.type === "likert_scale") && ans !== void 0 && ans !== null && ans !== "" && !Number.isNaN(Number(ans))) {
6240
+ rowCells.push(Number(ans));
6241
+ } else {
6242
+ rowCells.push(ans === void 0 || ans === null ? "" : String(ans));
6243
+ }
5932
6244
  if (q.allowOther) {
5933
6245
  rowCells.push(String(r.otherTexts?.[q.key] || ""));
5934
6246
  }
5935
6247
  }
5936
6248
  }
5937
- lines.push(rowCells.map(escapeCsvCell).join(","));
6249
+ rows.push(rowCells);
6250
+ }
6251
+ return { headers, rows };
6252
+ }
6253
+ function computeAutoColWidths(aoa) {
6254
+ const colCount = aoa.reduce((m, r) => Math.max(m, r.length), 0);
6255
+ const widths = [];
6256
+ for (let c = 0; c < colCount; c++) {
6257
+ let maxLen = 12;
6258
+ for (let r = 0; r < Math.min(aoa.length, 300); r++) {
6259
+ const cell = aoa[r]?.[c];
6260
+ const str = cell === null || cell === void 0 ? "" : String(cell);
6261
+ if (str.length > maxLen) maxLen = str.length;
6262
+ }
6263
+ widths.push({ wch: Math.min(54, maxLen + 3) });
6264
+ }
6265
+ return widths;
6266
+ }
6267
+ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
6268
+ const { headers, rows } = buildSurveyResponseExportAoA(survey, rawResponses, locale);
6269
+ const lines = [headers.map(escapeCsvCell).join(",")];
6270
+ for (const r of rows) {
6271
+ lines.push(r.map(escapeCsvCell).join(","));
5938
6272
  }
5939
6273
  return `\uFEFF${lines.join("\r\n")}`;
5940
6274
  }
6275
+ function exportSurveyResponsesToXlsxBuffer(survey, rawResponses, locale = "en") {
6276
+ const tr = String(locale || "").toLowerCase().startsWith("tr");
6277
+ const { headers, rows } = buildSurveyResponseExportAoA(survey, rawResponses, locale);
6278
+ const responsesAoA = [headers, ...rows];
6279
+ const wb = XLSX.utils.book_new();
6280
+ const wsResponses = XLSX.utils.aoa_to_sheet(responsesAoA);
6281
+ wsResponses["!cols"] = computeAutoColWidths(responsesAoA);
6282
+ XLSX.utils.book_append_sheet(wb, wsResponses, tr ? "Yanitlar" : "Responses");
6283
+ const analytics = computeSurveyAnalytics(survey, rawResponses);
6284
+ const s = analytics.summary;
6285
+ const summaryAoA = [
6286
+ [tr ? "Anket Başlığı" : "Survey Title", resolveLocalizedText(survey.titleI18n, locale, survey.title)],
6287
+ ["Survey Slug", survey.slug],
6288
+ [tr ? "Dışa Aktarım Tarihi" : "Exported At", (/* @__PURE__ */ new Date()).toISOString()],
6289
+ [tr ? "Toplam Yanıt" : "Total Responses", s.totalResponses],
6290
+ [tr ? "Ortalama Süre (sn)" : "Average Duration (s)", s.avgDurationSeconds],
6291
+ [tr ? "Medyan Süre (sn)" : "Median Duration (s)", s.medianDurationSeconds]
6292
+ ];
6293
+ if (s.nps?.hasNps) {
6294
+ summaryAoA.push(
6295
+ ["Net Promoter Score (NPS)", s.nps.score ?? 0],
6296
+ [
6297
+ tr ? "NPS Dağılımı" : "NPS Breakdown",
6298
+ `Promoters: ${s.nps.promoters} (${s.nps.promotersPct}%) | Passives: ${s.nps.passives} (${s.nps.passivesPct}%) | Detractors: ${s.nps.detractors} (${s.nps.detractorsPct}%)`
6299
+ ]
6300
+ );
6301
+ }
6302
+ summaryAoA.push(
6303
+ [],
6304
+ tr ? ["Soru Anahtarı", "Soru Başlığı", "Tip", "Seçenek / Kriter", "Adet / Ort.", "Yüzde (%)"] : ["Question Key", "Question Title", "Type", "Option / Metric", "Count / Avg", "Share (%)"]
6305
+ );
6306
+ for (const qs of analytics.questionStats) {
6307
+ const qTitle = resolveLocalizedText(qs.title, locale, qs.key);
6308
+ if (Array.isArray(qs.optionsBreakdown)) {
6309
+ for (const opt of qs.optionsBreakdown) {
6310
+ const optLbl = opt.id === "__other__" ? tr ? "Diğer" : "Other" : resolveLocalizedText(opt.labels, locale, opt.id);
6311
+ summaryAoA.push([qs.key, qTitle, qs.type, optLbl, opt.count, opt.percentage]);
6312
+ }
6313
+ } else if (Array.isArray(qs.distribution)) {
6314
+ summaryAoA.push([
6315
+ qs.key,
6316
+ qTitle,
6317
+ qs.type,
6318
+ tr ? "Ortalama Puan" : "Average Score",
6319
+ qs.average,
6320
+ ""
6321
+ ]);
6322
+ for (const d of qs.distribution) {
6323
+ const ptLbl = d.labels ? resolveLocalizedText(d.labels, locale, "") : "";
6324
+ summaryAoA.push([
6325
+ qs.key,
6326
+ qTitle,
6327
+ qs.type,
6328
+ ptLbl ? `${d.value} - ${ptLbl}` : String(d.value),
6329
+ d.count,
6330
+ d.percentage
6331
+ ]);
6332
+ }
6333
+ } else if (Array.isArray(qs.rankingBreakdown)) {
6334
+ for (const rk of qs.rankingBreakdown) {
6335
+ summaryAoA.push([
6336
+ qs.key,
6337
+ qTitle,
6338
+ qs.type,
6339
+ resolveLocalizedText(rk.labels, locale, rk.id),
6340
+ rk.averageRank,
6341
+ rk.scorePercentage
6342
+ ]);
6343
+ }
6344
+ } else {
6345
+ summaryAoA.push([
6346
+ qs.key,
6347
+ qTitle,
6348
+ qs.type,
6349
+ tr ? "Toplam Yanıt" : "Answered Count",
6350
+ qs.answeredCount || 0,
6351
+ ""
6352
+ ]);
6353
+ }
6354
+ }
6355
+ const wsSummary = XLSX.utils.aoa_to_sheet(summaryAoA);
6356
+ wsSummary["!cols"] = computeAutoColWidths(summaryAoA);
6357
+ XLSX.utils.book_append_sheet(wb, wsSummary, tr ? "Ozet_Istatistik" : "Summary");
6358
+ const out = XLSX.write(wb, { type: "buffer", bookType: "xlsx" });
6359
+ return Buffer.isBuffer(out) ? out : Buffer.from(out);
6360
+ }
5941
6361
  const SURVEY_UID = "plugin::content-input.ci-survey";
5942
6362
  const SURVEY_RESPONSE_UID = "plugin::content-input.ci-survey-response";
5943
6363
  let activeSeedPromise = null;
@@ -6023,38 +6443,126 @@ function sanitizeSurveyForPublic(entry, extra = {}) {
6023
6443
  publicResults: extra.publicResults || null
6024
6444
  };
6025
6445
  }
6446
+ function sanitizeSurveyForBundle(entry, rawResponses) {
6447
+ const cleanTitle = String(entry?.title || "Untitled Survey").trim();
6448
+ const cleanSlug = String(entry?.slug || slugifyIdentifier(cleanTitle) || "survey").trim();
6449
+ const sortedResponses = Array.isArray(rawResponses) ? [...rawResponses].sort((a, b) => {
6450
+ const ta = new Date(a?.submittedAt || a?.createdAt || 0).getTime();
6451
+ const tb = new Date(b?.submittedAt || b?.createdAt || 0).getTime();
6452
+ return ta - tb;
6453
+ }) : [];
6454
+ return {
6455
+ title: cleanTitle,
6456
+ titleI18n: entry?.titleI18n || { tr: cleanTitle, en: cleanTitle },
6457
+ slug: cleanSlug,
6458
+ description: entry?.description ?? { tr: "", en: "" },
6459
+ status: entry?.status || "published",
6460
+ displayMode: entry?.displayMode || "single_page",
6461
+ startsAt: entry?.startsAt || null,
6462
+ endsAt: entry?.endsAt || null,
6463
+ quotaLimit: entry?.quotaLimit ? Number(entry.quotaLimit) : null,
6464
+ submissionPolicy: entry?.submissionPolicy || "one_per_voter",
6465
+ anonymizeIp: entry?.anonymizeIp !== void 0 ? Boolean(entry.anonymizeIp) : true,
6466
+ showPublicResults: entry?.showPublicResults || "after_vote",
6467
+ allowBackNavigation: entry?.allowBackNavigation !== void 0 ? Boolean(entry.allowBackNavigation) : true,
6468
+ showProgressBar: entry?.showProgressBar !== void 0 ? Boolean(entry.showProgressBar) : true,
6469
+ useRecaptcha: entry?.useRecaptcha !== void 0 ? Boolean(entry.useRecaptcha) : false,
6470
+ recaptchaSiteKey: entry?.recaptchaSiteKey ? String(entry.recaptchaSiteKey) : "",
6471
+ steps: Array.isArray(entry?.steps) ? entry.steps : [],
6472
+ questions: Array.isArray(entry?.questions) ? entry.questions : [],
6473
+ settings: entry?.settings && typeof entry.settings === "object" ? entry.settings : {},
6474
+ version: Number(entry?.version || 1),
6475
+ responses: sortedResponses.map((r) => ({
6476
+ answers: r?.answers && typeof r.answers === "object" && !Array.isArray(r.answers) ? r.answers : {},
6477
+ otherTexts: r?.otherTexts && typeof r.otherTexts === "object" && !Array.isArray(r.otherTexts) ? r.otherTexts : {},
6478
+ score: typeof r?.score === "number" ? r.score : null,
6479
+ npsValue: typeof r?.npsValue === "number" ? r.npsValue : null,
6480
+ npsCategory: r?.npsCategory || null,
6481
+ locale: String(r?.locale || "en"),
6482
+ durationSeconds: Math.max(0, Number(r?.durationSeconds || 0) || 0),
6483
+ voterHash: r?.voterHash || null,
6484
+ respondentToken: r?.respondentToken || null,
6485
+ submittedAt: r?.submittedAt || r?.createdAt || (/* @__PURE__ */ new Date()).toISOString()
6486
+ }))
6487
+ };
6488
+ }
6489
+ function makeUniqueSlug(baseSlug, usedSlugs) {
6490
+ const cleanBase = slugifyIdentifier(baseSlug) || "survey";
6491
+ if (!usedSlugs.has(cleanBase)) {
6492
+ usedSlugs.add(cleanBase);
6493
+ return cleanBase;
6494
+ }
6495
+ let candidate = `${cleanBase}_copy`;
6496
+ let counter = 2;
6497
+ while (usedSlugs.has(candidate)) {
6498
+ candidate = `${cleanBase}_copy_${counter}`;
6499
+ counter += 1;
6500
+ }
6501
+ usedSlugs.add(candidate);
6502
+ return candidate;
6503
+ }
6026
6504
  const ciSurveyService = ({ strapi }) => ({
6505
+ async deleteResponsesForSurveyRecord(survey) {
6506
+ if (!survey) return 0;
6507
+ const existing = await this.getResponsesForSurvey(survey);
6508
+ const count = existing.length;
6509
+ if (count > 0) {
6510
+ const ids = existing.map((r) => r.id).filter((id) => id !== void 0 && id !== null);
6511
+ if (ids.length > 0) {
6512
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6513
+ where: { id: { $in: ids } }
6514
+ });
6515
+ }
6516
+ }
6517
+ if (survey.slug) {
6518
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6519
+ where: { surveySlug: survey.slug }
6520
+ });
6521
+ }
6522
+ return count;
6523
+ },
6027
6524
  async ensureSeeded(forceReseedResponses = false) {
6028
6525
  if (activeSeedPromise && !forceReseedResponses) {
6029
6526
  return activeSeedPromise;
6030
6527
  }
6031
6528
  const runSeed = async () => {
6529
+ if (!forceReseedResponses && await isDemoSeedBlocked(strapi, "surveys")) {
6530
+ return;
6531
+ }
6032
6532
  let existingSurveys = [];
6033
6533
  try {
6034
6534
  existingSurveys = await strapi.db.query(SURVEY_UID).findMany() || [];
6035
6535
  } catch {
6036
6536
  return;
6037
6537
  }
6538
+ const isFreshEmptyDb = existingSurveys.length === 0;
6038
6539
  const bySlug = {};
6039
6540
  for (const s of existingSurveys) {
6040
6541
  if (s?.slug) bySlug[s.slug] = s;
6041
6542
  }
6042
- for (const seed of DEFAULT_SEED_SURVEYS) {
6043
- if (!bySlug[seed.slug]) {
6044
- const created = await strapi.db.query(SURVEY_UID).create({
6045
- data: seed
6046
- });
6047
- bySlug[seed.slug] = created;
6543
+ if (isFreshEmptyDb || forceReseedResponses) {
6544
+ for (const seed of DEFAULT_SEED_SURVEYS) {
6545
+ if (!bySlug[seed.slug]) {
6546
+ const created = await strapi.db.query(SURVEY_UID).create({
6547
+ data: seed
6548
+ });
6549
+ bySlug[seed.slug] = created;
6550
+ }
6048
6551
  }
6049
6552
  }
6050
6553
  const totalResponses = await strapi.db.query(SURVEY_RESPONSE_UID).count();
6051
- if (totalResponses === 0 || forceReseedResponses) {
6554
+ if (isFreshEmptyDb && totalResponses === 0 || forceReseedResponses) {
6052
6555
  if (forceReseedResponses) {
6053
6556
  const demoSlugs = DEFAULT_SEED_SURVEYS.map((s) => s.slug);
6054
6557
  for (const slug of demoSlugs) {
6055
- await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6056
- where: { surveySlug: slug }
6057
- });
6558
+ const demoSrv = bySlug[slug];
6559
+ if (demoSrv) {
6560
+ await this.deleteResponsesForSurveyRecord(demoSrv);
6561
+ } else {
6562
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6563
+ where: { surveySlug: slug }
6564
+ });
6565
+ }
6058
6566
  }
6059
6567
  }
6060
6568
  const rows = generateSeedSurveyResponses(bySlug);
@@ -6070,6 +6578,7 @@ const ciSurveyService = ({ strapi }) => ({
6070
6578
  );
6071
6579
  }
6072
6580
  }
6581
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6073
6582
  };
6074
6583
  activeSeedPromise = runSeed().finally(() => {
6075
6584
  activeSeedPromise = null;
@@ -6077,9 +6586,10 @@ const ciSurveyService = ({ strapi }) => ({
6077
6586
  return activeSeedPromise;
6078
6587
  },
6079
6588
  async reseedSampleData() {
6589
+ await setDemoSeedCleared(strapi, false);
6080
6590
  await this.ensureSeeded(true);
6081
6591
  try {
6082
- await strapi.plugin("content-input").service("ci-form").ensureSampleSubmissions(true);
6592
+ await strapi.plugin("content-input").service("ci-form").ensureSeeded(true);
6083
6593
  } catch {
6084
6594
  }
6085
6595
  const totalSurveyResponses = await strapi.db.query(SURVEY_RESPONSE_UID).count();
@@ -6088,6 +6598,47 @@ const ciSurveyService = ({ strapi }) => ({
6088
6598
  totalSurveyResponses
6089
6599
  };
6090
6600
  },
6601
+ async purgeDemoData() {
6602
+ await setDemoSeedCleared(strapi, true);
6603
+ const demoSlugs = DEFAULT_SEED_SURVEYS.map((s) => s.slug);
6604
+ let deletedSurveys = 0;
6605
+ let deletedSurveyResponses = 0;
6606
+ for (const slug of demoSlugs) {
6607
+ const found = await strapi.db.query(SURVEY_UID).findOne({
6608
+ where: { slug }
6609
+ });
6610
+ if (found) {
6611
+ deletedSurveyResponses += await this.deleteResponsesForSurveyRecord(found);
6612
+ await strapi.db.query(SURVEY_UID).delete({ where: { id: found.id } });
6613
+ deletedSurveys += 1;
6614
+ } else {
6615
+ const orphanRows = await strapi.db.query(SURVEY_RESPONSE_UID).findMany({
6616
+ where: { surveySlug: slug }
6617
+ }) || [];
6618
+ if (orphanRows.length > 0) {
6619
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6620
+ where: { surveySlug: slug }
6621
+ });
6622
+ deletedSurveyResponses += orphanRows.length;
6623
+ }
6624
+ }
6625
+ }
6626
+ let deletedForms = 0;
6627
+ let deletedFormSubmissions = 0;
6628
+ try {
6629
+ const formRes = await strapi.plugin("content-input").service("ci-form").purgeDemoForms();
6630
+ deletedForms = Number(formRes?.deletedForms || 0);
6631
+ deletedFormSubmissions = Number(formRes?.deletedFormSubmissions || 0);
6632
+ } catch {
6633
+ }
6634
+ return {
6635
+ ok: true,
6636
+ deletedSurveys,
6637
+ deletedSurveyResponses,
6638
+ deletedForms,
6639
+ deletedFormSubmissions
6640
+ };
6641
+ },
6091
6642
  async findRawByIdOrSlug(idOrSlug) {
6092
6643
  await this.ensureSeeded(false);
6093
6644
  const raw = String(idOrSlug || "").trim();
@@ -6260,17 +6811,36 @@ const ciSurveyService = ({ strapi }) => ({
6260
6811
  const created = await strapi.db.query(SURVEY_UID).create({
6261
6812
  data: recordData
6262
6813
  });
6814
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6263
6815
  return formatSurveyForAdmin(created, { responseCount: 0 });
6264
6816
  },
6265
6817
  async remove(idOrSlug) {
6266
6818
  const found = await this.findRawByIdOrSlug(idOrSlug);
6819
+ let deletedResponses = 0;
6267
6820
  if (found) {
6268
- await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6269
- where: { surveySlug: found.slug }
6270
- });
6821
+ deletedResponses = await this.deleteResponsesForSurveyRecord(found);
6271
6822
  await strapi.db.query(SURVEY_UID).delete({ where: { id: found.id } });
6823
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6272
6824
  }
6273
- return { success: true };
6825
+ return { success: true, deletedResponses };
6826
+ },
6827
+ async clearResponses(idOrSlug) {
6828
+ const found = await this.findRawByIdOrSlug(idOrSlug);
6829
+ if (!found) {
6830
+ return null;
6831
+ }
6832
+ const deletedCount = await this.deleteResponsesForSurveyRecord(found);
6833
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6834
+ return {
6835
+ ok: true,
6836
+ slug: found.slug,
6837
+ deletedCount,
6838
+ survey: formatSurveyForAdmin(found, {
6839
+ responseCount: 0,
6840
+ npsScore: null,
6841
+ lastSubmittedAt: null
6842
+ })
6843
+ };
6274
6844
  },
6275
6845
  async submitSurvey(idOrSlug, rawBody, meta = {}) {
6276
6846
  const survey = await this.findRawByIdOrSlug(idOrSlug);
@@ -6509,6 +7079,18 @@ const ciSurveyService = ({ strapi }) => ({
6509
7079
  return true;
6510
7080
  });
6511
7081
  }
7082
+ if (options2.format === "xlsx") {
7083
+ const xlsxBuf = exportSurveyResponsesToXlsxBuffer(
7084
+ survey,
7085
+ responses,
7086
+ options2.locale || "en"
7087
+ );
7088
+ return {
7089
+ filename: `${survey.slug}-responses.xlsx`,
7090
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
7091
+ body: xlsxBuf
7092
+ };
7093
+ }
6512
7094
  if (options2.format === "json") {
6513
7095
  return {
6514
7096
  filename: `${survey.slug}-responses.json`,
@@ -6538,6 +7120,188 @@ const ciSurveyService = ({ strapi }) => ({
6538
7120
  contentType: "text/csv; charset=utf-8",
6539
7121
  body: csv
6540
7122
  };
7123
+ },
7124
+ async exportBundle(targetIdOrAll = "all", mode = "structure") {
7125
+ await this.ensureSeeded(false);
7126
+ const cleanTarget = String(targetIdOrAll || "all").trim();
7127
+ const exportMode = mode === "full" ? "full" : "structure";
7128
+ let targetSurveys = [];
7129
+ if (!cleanTarget || cleanTarget === "all") {
7130
+ targetSurveys = await strapi.db.query(SURVEY_UID).findMany({
7131
+ orderBy: { id: "asc" }
7132
+ }) || [];
7133
+ } else {
7134
+ const single = await this.findRawByIdOrSlug(cleanTarget);
7135
+ if (!single) {
7136
+ return null;
7137
+ }
7138
+ targetSurveys = [single];
7139
+ }
7140
+ const portableSurveys = [];
7141
+ let totalResponses = 0;
7142
+ for (const srv of targetSurveys) {
7143
+ const rawResps = exportMode === "full" ? await this.getResponsesForSurvey(srv) : [];
7144
+ const item = sanitizeSurveyForBundle(srv, rawResps);
7145
+ totalResponses += item.responses.length;
7146
+ portableSurveys.push(item);
7147
+ }
7148
+ const dateStamp = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
7149
+ const modeSuffix = exportMode === "full" ? "full-backup" : "structure";
7150
+ const filename = cleanTarget && cleanTarget !== "all" && portableSurveys[0]?.slug ? `${portableSurveys[0].slug}-${modeSuffix}.ci-survey.json` : `ci-surveys-all-${modeSuffix}-${dateStamp}.ci-survey.json`;
7151
+ const bundle = {
7152
+ packageType: "strapi-content-input-survey-bundle",
7153
+ schemaVersion: 1,
7154
+ mode: exportMode,
7155
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
7156
+ surveyCount: portableSurveys.length,
7157
+ totalResponses,
7158
+ surveys: portableSurveys
7159
+ };
7160
+ return {
7161
+ filename,
7162
+ contentType: "application/json; charset=utf-8",
7163
+ bundle
7164
+ };
7165
+ },
7166
+ async importBundle(rawPayload, options2 = {}) {
7167
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
7168
+ let parsed = rawPayload;
7169
+ if (typeof parsed === "string") {
7170
+ try {
7171
+ parsed = JSON.parse(parsed);
7172
+ } catch {
7173
+ const err = new Error("Invalid JSON bundle payload");
7174
+ err.status = 400;
7175
+ throw err;
7176
+ }
7177
+ }
7178
+ let rawItems = [];
7179
+ if (Array.isArray(parsed)) {
7180
+ rawItems = parsed;
7181
+ } else if (parsed && typeof parsed === "object") {
7182
+ if (Array.isArray(parsed.surveys)) {
7183
+ rawItems = parsed.surveys;
7184
+ } else if (Array.isArray(parsed.questions) || parsed.title || parsed.slug) {
7185
+ rawItems = [parsed];
7186
+ }
7187
+ }
7188
+ const validItems = rawItems.filter(
7189
+ (it) => it && typeof it === "object" && (Array.isArray(it.questions) || it.title)
7190
+ );
7191
+ if (validItems.length === 0) {
7192
+ const err = new Error(
7193
+ "No valid survey definitions found in the provided JSON package."
7194
+ );
7195
+ err.status = 400;
7196
+ throw err;
7197
+ }
7198
+ const conflictStrategy = options2.conflictStrategy === "overwrite" ? "overwrite" : "duplicate";
7199
+ const includeResponses = options2.includeResponses !== false;
7200
+ const existingSurveys = await strapi.db.query(SURVEY_UID).findMany() || [];
7201
+ const usedSlugs = new Set(
7202
+ existingSurveys.map((s) => String(s?.slug || "").trim()).filter(Boolean)
7203
+ );
7204
+ const importedSurveys = [];
7205
+ let importedResponsesCount = 0;
7206
+ for (const item of validItems) {
7207
+ const cleanTitle = String(item.title || "Imported Survey").trim();
7208
+ const baseSlug = slugifyIdentifier(String(item.slug || cleanTitle)) || "imported_survey";
7209
+ const existing = await strapi.db.query(SURVEY_UID).findOne({ where: { slug: baseSlug } });
7210
+ const isOverwriting = Boolean(existing && conflictStrategy === "overwrite");
7211
+ const isDuplicatingCollision = Boolean(
7212
+ existing && conflictStrategy === "duplicate"
7213
+ );
7214
+ const finalSlug = isOverwriting ? baseSlug : makeUniqueSlug(baseSlug, usedSlugs);
7215
+ const finalTitle = isDuplicatingCollision ? `${cleanTitle} (Copy)` : cleanTitle;
7216
+ const rawTitleI18n = item.titleI18n && typeof item.titleI18n === "object" ? { ...item.titleI18n } : { tr: cleanTitle, en: cleanTitle };
7217
+ if (isDuplicatingCollision) {
7218
+ for (const k of Object.keys(rawTitleI18n)) {
7219
+ if (rawTitleI18n[k]) {
7220
+ rawTitleI18n[k] = `${rawTitleI18n[k]} (${k === "tr" ? "Kopya" : "Copy"})`;
7221
+ }
7222
+ }
7223
+ }
7224
+ const savePayload = {
7225
+ ...isOverwriting ? { id: existing.documentId || existing.id } : {},
7226
+ title: finalTitle,
7227
+ titleI18n: rawTitleI18n,
7228
+ slug: finalSlug,
7229
+ description: item.description ?? { tr: "", en: "" },
7230
+ status: item.status || "published",
7231
+ displayMode: item.displayMode || "single_page",
7232
+ startsAt: item.startsAt || null,
7233
+ endsAt: item.endsAt || null,
7234
+ quotaLimit: item.quotaLimit ? Number(item.quotaLimit) : null,
7235
+ submissionPolicy: item.submissionPolicy || "one_per_voter",
7236
+ anonymizeIp: item.anonymizeIp !== void 0 ? Boolean(item.anonymizeIp) : true,
7237
+ showPublicResults: item.showPublicResults || "after_vote",
7238
+ allowBackNavigation: item.allowBackNavigation !== void 0 ? Boolean(item.allowBackNavigation) : true,
7239
+ showProgressBar: item.showProgressBar !== void 0 ? Boolean(item.showProgressBar) : true,
7240
+ useRecaptcha: item.useRecaptcha !== void 0 ? Boolean(item.useRecaptcha) : false,
7241
+ recaptchaSiteKey: item.recaptchaSiteKey ? String(item.recaptchaSiteKey) : "",
7242
+ steps: Array.isArray(item.steps) ? item.steps : [],
7243
+ questions: Array.isArray(item.questions) ? item.questions : [],
7244
+ settings: item.settings && typeof item.settings === "object" ? item.settings : {}
7245
+ };
7246
+ await this.save(savePayload);
7247
+ const savedRaw = await strapi.db.query(SURVEY_UID).findOne({ where: { slug: finalSlug } });
7248
+ if (!savedRaw) continue;
7249
+ const rawResponses = Array.isArray(item.responses) ? item.responses : [];
7250
+ if (includeResponses) {
7251
+ if (isOverwriting) {
7252
+ await this.deleteResponsesForSurveyRecord(savedRaw);
7253
+ }
7254
+ if (rawResponses.length > 0) {
7255
+ const surveyDocOrId = String(savedRaw.documentId || savedRaw.id);
7256
+ const batchSize = 50;
7257
+ for (let i = 0; i < rawResponses.length; i += batchSize) {
7258
+ const chunk = rawResponses.slice(i, i + batchSize);
7259
+ await Promise.all(
7260
+ chunk.map((r) => {
7261
+ const answers = r?.answers && typeof r.answers === "object" && !Array.isArray(r.answers) ? r.answers : {};
7262
+ const otherTexts = r?.otherTexts && typeof r.otherTexts === "object" && !Array.isArray(r.otherTexts) ? r.otherTexts : {};
7263
+ const metrics = computeResponseMetrics(
7264
+ savedRaw,
7265
+ answers
7266
+ );
7267
+ const durationSeconds = typeof r?.durationSeconds === "number" ? Math.max(0, Math.round(r.durationSeconds)) : typeof r?.durationMs === "number" ? Math.max(0, Math.round(r.durationMs / 1e3)) : 0;
7268
+ return strapi.db.query(SURVEY_RESPONSE_UID).create({
7269
+ data: {
7270
+ surveyId: surveyDocOrId,
7271
+ surveySlug: savedRaw.slug,
7272
+ surveyTitle: savedRaw.title,
7273
+ surveyVersion: Number(savedRaw.version || 1),
7274
+ answers,
7275
+ otherTexts,
7276
+ score: typeof r?.score === "number" ? r.score : metrics.score,
7277
+ npsValue: typeof r?.npsValue === "number" ? r.npsValue : metrics.npsValue,
7278
+ npsCategory: r?.npsCategory || metrics.npsCategory,
7279
+ locale: String(r?.locale || "en"),
7280
+ durationSeconds,
7281
+ voterHash: r?.voterHash || null,
7282
+ respondentToken: r?.respondentToken || null,
7283
+ ip: null,
7284
+ userAgent: String(r?.userAgent || "imported"),
7285
+ submittedAt: r?.submittedAt || r?.createdAt || (/* @__PURE__ */ new Date()).toISOString()
7286
+ }
7287
+ });
7288
+ })
7289
+ );
7290
+ }
7291
+ importedResponsesCount += rawResponses.length;
7292
+ }
7293
+ }
7294
+ const finalAdminObj = await this.findOneAdmin(finalSlug);
7295
+ if (finalAdminObj) {
7296
+ importedSurveys.push(finalAdminObj);
7297
+ }
7298
+ }
7299
+ return {
7300
+ ok: true,
7301
+ importedCount: importedSurveys.length,
7302
+ importedResponsesCount,
7303
+ importedSurveys
7304
+ };
6541
7305
  }
6542
7306
  });
6543
7307
  const PALETTE_UID = "plugin::content-input.ci-color-palette";